439 lines
2.1 MiB
439 lines
2.1 MiB
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/PersonalizationDrawer.js","assets/index.js","assets/CloseButton.js","assets/_plugin-vue_export-helper.js","assets/CloseButton.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/SandboxSetupDialog.js","assets/SandboxSetupDialog.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 VB=Object.defineProperty;var qM=s=>{throw TypeError(s)};var GB=(s,e,t)=>e in s?VB(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var Se=(s,e,t)=>GB(s,typeof e!="symbol"?e+"":e,t),Qk=(s,e,t)=>e.has(s)||qM("Cannot "+t);var f=(s,e,t)=>(Qk(s,e,"read from private field"),t?t.call(s):e.get(s)),B=(s,e,t)=>e.has(s)?qM("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(s):e.set(s,t),R=(s,e,t,n)=>(Qk(s,e,"write to private field"),n?n.call(s,t):e.set(s,t),t),H=(s,e,t)=>(Qk(s,e,"access private method"),t);var Ls=(s,e,t,n)=>({set _(i){R(s,e,i,t)},get _(){return f(s,e,n)}});import{k as be,E as ry,G as kE,H as KB,I as UP,j as ge,J as CE,K as WP,L as zP,M as qB,N as QB,O as XB,y as oy,P as ft,Q as YB,w as Ke,l as S,D as lt,R as JB,S as jP,a as Rn,d as ct,o as dn,U as QM,s as We,V as VP,W as ZB,m as F,c as U,n as Ce,f as M,z as qe,t as Q,e as me,x as Gt,F as Ie,r as Ze,X as ay,Y as Mi,Z as PT,b as Ft,h as cn,_ as eF,B as De,$ as Tf,u as Ne,a0 as tF,T as gs,g as Ov,A as Dv,i as yw,a1 as sF,a2 as nF,a3 as iF,a4 as rF,a5 as oF,a6 as aF,a7 as rr,p as GP,a8 as lF,a9 as Hs,aa as cF,q as uF}from"./index.js";import{_ as qt}from"./_plugin-vue_export-helper.js";import{P as PS,p as dF,a as hF,b as fF,r as KP,k as pF}from"./useMarkdownRenderer.js";import{C as ml,F as mF,T as gF,I as vF,a as yF}from"./CloseButton.js";/*!
|
||
* pinia v3.0.4
|
||
* (c) 2025 Eduardo San Martin Morote
|
||
* @license MIT
|
||
*/let qP;const ak=s=>qP=s,QP=Symbol();function LT(s){return s&&typeof s=="object"&&Object.prototype.toString.call(s)==="[object Object]"&&typeof s.toJSON!="function"}var Nv;(function(s){s.direct="direct",s.patchObject="patch object",s.patchFunction="patch function"})(Nv||(Nv={}));function bF(){const s=UP(!0),e=s.run(()=>ge({}));let t=[],n=[];const i=CE({install(r){ak(i),i._a=r,r.provide(QP,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 XP=()=>{};function XM(s,e,t,n=XP){s.add(e);const i=()=>{s.delete(e)&&n()};return!t&&QB()&&XB(i),i}function Qf(s,...e){s.forEach(t=>{t(...e)})}const _F=s=>s(),YM=Symbol(),Xk=Symbol();function OT(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];LT(i)&<(n)&&s.hasOwnProperty(t)&&!ry(n)&&!kE(n)?s[t]=OT(i,n):s[t]=n}return s}const wF=Symbol();function SF(s){return!LT(s)||!Object.prototype.hasOwnProperty.call(s,wF)}const{assign:qc}=Object;function kF(s){return!!(ry(s)&&s.effect)}function CF(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=YB(t.state.value[s]);return qc(u,r,Object.keys(o||{}).reduce((d,h)=>(d[h]=CE(be(()=>{ak(t);const p=t._s.get(s);return o[h].call(p,p)})),d),{}))}return c=YP(s,l,e,t,n,!0),c}function YP(s,e,t={},n,i,r){let o;const a=qc({actions:{}},t),c={deep:!0};let l,u,d=new Set,h=new Set,p;const g=n.state.value[s];!r&&!g&&(n.state.value[s]={});let v;function m(C){let E;l=u=!1,typeof C=="function"?(C(n.state.value[s]),E={type:Nv.patchFunction,storeId:s,events:p}):(OT(n.state.value[s],C),E={type:Nv.patchObject,payload:C,storeId:s,events:p});const x=v=Symbol();ft().then(()=>{v===x&&(l=!0)}),u=!0,Qf(d,E,n.state.value[s])}const y=r?function(){const{state:E}=t,x=E?E():{};this.$patch(D=>{qc(D,x)})}:XP;function _(){o.stop(),d.clear(),h.clear(),n._s.delete(s)}const b=(C,E="")=>{if(YM in C)return C[Xk]=E,C;const x=function(){ak(n);const D=Array.from(arguments),N=new Set,O=new Set;function G(V){N.add(V)}function Z(V){O.add(V)}Qf(h,{args:D,name:x[Xk],store:w,after:G,onError:Z});let q;try{q=C.apply(this&&this.$id===s?this:w,D)}catch(V){throw Qf(O,V),V}return q instanceof Promise?q.then(V=>(Qf(N,V),V)).catch(V=>(Qf(O,V),Promise.reject(V))):(Qf(N,q),q)};return x[YM]=!0,x[Xk]=E,x},k={_p:n,$id:s,$onAction:XM.bind(null,h),$patch:m,$reset:y,$subscribe(C,E={}){const x=XM(d,C,E.detached,()=>D()),D=o.run(()=>Ke(()=>n.state.value[s],N=>{(E.flush==="sync"?u:l)&&C({storeId:s,type:Nv.direct,events:p},N)},qc({},c,E)));return x},$dispose:_},w=oy(k);n._s.set(s,w);const A=(n._a&&n._a.runWithContext||_F)(()=>n._e.run(()=>(o=UP()).run(()=>e({action:b}))));for(const C in A){const E=A[C];if(ry(E)&&!kF(E)||kE(E))r||(g&&SF(E)&&(ry(E)?E.value=g[C]:OT(E,g[C])),n.state.value[s][C]=E);else if(typeof E=="function"){const x=b(E,C);A[C]=x,a.actions[C]=E}}return qc(w,A),qc(WP(w),A),Object.defineProperty(w,"$state",{get:()=>n.state.value[s],set:C=>{m(E=>{qc(E,C)})}}),n._p.forEach(C=>{qc(w,o.run(()=>C({store:w,app:n._a,pinia:n,options:a})))}),g&&r&&t.hydrate&&t.hydrate(w.$state,g),l=!0,u=!0,w}/*! #__NO_SIDE_EFFECTS__ */function hn(s,e,t){let n;const i=typeof e=="function";n=i?t:e;function r(o,a){const c=qB();return o=o||(c?zP(QP,null):null),o&&ak(o),o=qP,o._s.has(s)||(i?YP(s,e,n,o):CF(s,n,o)),o._s.get(s)}return r.$id=s,r}function O_(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 Pr(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 Zo(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 xi(s){const e=WP(s),t={};for(const n in e){const i=e[n];i.effect?t[n]=be({get:()=>s[n],set(r){s[n]=r}}):(ry(i)||kE(i))&&(t[n]=KB(s,n))}return t}const TF="modulepreload",AF=function(s){return"/static/dist/"+s},JM={},St=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=AF(c),c in JM)return;JM[c]=!0;const l=c.endsWith(".css"),u=l?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${c}"]${u}`))return;const d=document.createElement("link");if(d.rel=l?"stylesheet":TF,l||(d.as="script"),d.crossOrigin="",d.href=c,a&&d.setAttribute("nonce",a),document.head.appendChild(d),l)return new Promise((h,p)=>{d.addEventListener("load",h),d.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)})},EF=typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia("(max-width: 768px)").matches:!1,Is=hn("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:EF,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||S("stores.confirmAction"),message:s.message||S("stores.confirmOperation"),confirmText:s.confirmText||S("common.confirm"),cancelText:s.cancelText||S("common.cancel"),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}}}}),MF=Object.freeze(Object.defineProperty({__proto__:null,useUiStore:Is},Symbol.toStringTag,{value:"Module"})),xF=new Set(["chat","compact","hidden"]),RF=new Set(["user","presend"]),IF=new Set(["guidance","goal_review","compression","compression_handoff","sub_agent","background_command","workflow"]);function DT(s){return String(s||"").trim().toLowerCase()}function JP(s){return String((s==null?void 0:s.content)||(s==null?void 0:s.message)||"").trim()}function PF(s){const e=JP(s);return e.includes("【目标模式已开启】")||e.includes(`[系统通知|goal]
|
||
【目标模式已开启】`)}function ZP(s){return JP(s).includes("审核智能体对于你的工作结束给出了以下内容")}function Fd(s){var i;const e=(s==null?void 0:s.metadata)||{},t=DT(e.visibility||((i=e.ui)==null?void 0:i.visibility)||(s==null?void 0:s.visibility));if(xF.has(t))return t;if(e.hidden===!0||e.system_injected_image||e.system_injected_video)return"hidden";const n=DT(e.message_source||e.source||(s==null?void 0:s.message_source)||(s==null?void 0:s.source));return n==="skill"||n==="goal_prompt"||PF(s)||n==="notify"&&(e.runtime_mode_notice||s!=null&&s.runtime_mode_notice)?"hidden":IF.has(n)||ZP(s)?"compact":"chat"}function $v(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(Fd(s)==="hidden")return!1;const t=DT(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"||ZP(s)?!0:t==="compression"||t==="compression_handoff"?!1:RF.has(t||"user")}const Yk=["stores.generatingBrainstorming","stores.generatingPreparing","stores.generatingPreparingTools","stores.generatingThink","stores.generatingAnswerSoon","stores.generatingLoadingInspiration","stores.generatingAssemblingIdeas","stores.generatingBestApproach","stores.generatingBrainMeeting","stores.generatingOrganizing","stores.generatingPolishing","stores.generatingContext","stores.generatingMemorySearch","stores.generatingAlmostDone","stores.generatingDomainExpand","stores.generatingToolchain","stores.generatingSentence","stores.generatingRethinking","stores.generatingKnowledgeSearch"],LF=/<show_html\b[\s\S]*?<\/show_html>/i;function OF(s){return s?LF.test(s):!1}function DF(){if(!Yk.length)return"";const s=Math.floor(Math.random()*Yk.length);return S(Yk[s])}function Jk(){return{role:"assistant",actions:[],streamingThinking:"",streamingText:"",currentStreamingType:null,activeThinkingId:null,awaitingFirstContent:!1,generatingLabel:DF()}}function D_(s){return`${s}-${Date.now()}-${Math.random().toString(36).slice(2)}`}function Zk(s){return new Set(Array.from(s))}function NF(s){return new Map(Array.from(s.entries()))}function eC(s){s&&s.awaitingFirstContent&&(s.awaitingFirstContent=!1)}const tC=(...s)=>{},TE=hn("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=Zk(this.expandedBlocks);e.has(s)?e.delete(s):e.add(s),this.expandedBlocks=e},expandBlock(s){const e=Zk(this.expandedBlocks);e.add(s),this.expandedBlocks=e},collapseBlock(s){const e=Zk(this.expandedBlocks);e.delete(s),this.expandedBlocks=e},clearExpandedBlocks(){this.expandedBlocks=new Set},setThinkingLock(s,e){const t=NF(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=Jk();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=Fd({content:s,metadata:c}),c.starts_work=$v({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=Jk();return this.messages.push(s),this.currentMessageIndex=this.messages.length-1,this.streamingMessage=!0,s.awaitingFirstContent=!0,s},startThinkingAction(){const s=this.ensureAssistantMessage();eC(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=D_("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;eC(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:D_("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:D_("text"),type:"text",content:"",streaming:!0,timestamp:Date.now(),continuation:!0},e.actions.push(t)),t.content+=s,t.streaming&&OF(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},clearStreamingResidualState(){for(const s of this.messages)if(!(!s||s.role!=="assistant")&&(s.currentStreamingType=null,s.activeThinkingId=null,s.streamingThinking="",s.streamingText="",s.awaitingFirstContent=!1,s.generatingLabel="",Array.isArray(s.actions)))for(const e of s.actions)e&&(e.type==="thinking"||e.type==="text")&&e.streaming===!0&&(e.streaming=!1)},resetStreamingAttemptActions(s=""){var n,i,r;const e=[];let t=null;if(this.currentMessageIndex>=0&&((n=this.messages[this.currentMessageIndex])==null?void 0:n.role)==="assistant")t=this.messages[this.currentMessageIndex];else for(let o=this.messages.length-1;o>=0;o--)if(((i=this.messages[o])==null?void 0:i.role)==="assistant"){t=this.messages[o];break}if(!t||!Array.isArray(t.actions))return e;for(;t.actions.length;){const o=t.actions[t.actions.length-1],a=(o==null?void 0:o.type)==="thinking",c=(o==null?void 0:o.type)==="text",l=(o==null?void 0:o.type)==="tool"&&String(((r=o==null?void 0:o.tool)==null?void 0:r.status)||"").toLowerCase()==="preparing";if(!a&&!c&&!l)break;e.push(o),t.actions.pop()}return t.currentStreamingType=null,t.activeThinkingId=null,t.streamingThinking="",t.streamingText="",t.actions.length===0?(t.awaitingFirstContent=!0,t.generatingLabel=s):(t.awaitingFirstContent=!1,t.generatingLabel=""),e},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)&&(tC("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?Jk():this.ensureAssistantMessage();eC(n),tC("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:D_("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),tC("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()}}}),lk=hn("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}}}),eL=hn("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()}}}),sC=()=>({count:0,limit:0,reset_at:null,window_start:null}),ZM=()=>({fast:sC(),thinking:sC(),search:sC(),role:"user"}),N_=6e4,$F=3e5,Ig=5e3,BF=3e4,tL=hn("resource",{state:()=>({tokenPanelCollapsed:!0,currentContextTokens:0,currentConversationTokens:{cumulative_input_tokens:0,cumulative_output_tokens:0,cumulative_total_tokens:0,cumulative_cached_input_tokens:0,cache_exempt_input_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:Ig,containerStatsTimer:null,projectStorageTimer:null,projectStorageInFlight:!1,projectStorageFailCount:0,projectStorageIntervalMs:N_,usageQuota:ZM(),usageQuotaTimer:null}),actions:{resetTokenStatistics(){this.currentContextTokens=0,this.currentConversationTokens={cumulative_input_tokens:0,cumulative_output_tokens:0,cumulative_total_tokens:0,cumulative_cached_input_tokens:0,cache_exempt_input_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,this.currentConversationTokens.cumulative_cached_input_tokens=t.data.total_cached_input_tokens||0,this.currentConversationTokens.cache_exempt_input_tokens=t.data.cache_exempt_input_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`:S("stores.unlimited")),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>Ig&&this._restartContainerStatsTimer(Ig)}catch(t){if(console.warn("获取容器状态异常:",t),this.containerStatsFailCount+=1,this.containerStatsFailCount>=3){const n=Math.min(this.containerStatsIntervalMs*2,BF);this._restartContainerStatsTimer(n)}}finally{this.containerStatsInFlight=!1,e&&clearTimeout(e)}},startContainerStatsPolling(){this.containerStatsTimer||this.tokenPanelCollapsed||(this.containerStatsFailCount=0,this.containerStatsIntervalMs=Ig,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=Ig,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||S("stores.requestFailed"));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>N_&&this._restartProjectStorageTimer(N_))}catch(s){if(this.projectStorageFailCount+=1,console.warn("获取存储信息失败:",s),this.projectStorageFailCount>=3){const e=Math.min(this.projectStorageIntervalMs*2,$F);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=N_},_restartProjectStorageTimer(s){this.projectStorageTimer&&clearInterval(this.projectStorageTimer),this.projectStorageIntervalMs=Math.max(s,1e4),this.projectStorageTimer=setInterval(()=>{this.pollProjectStorage()},this.projectStorageIntervalMs)},normalizeUsageQuota(s){const e=ZM(),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||S("stores.requestFailed"));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)}}}),sL="agents_sidebar_conversation_type",FF=()=>{try{return window.localStorage.getItem(sL)==="multi_agent"?"multi_agent":"normal"}catch{return"normal"}},HF=s=>{try{window.localStorage.setItem(sL,s)}catch{}},nL=()=>({conversationsByType:{normal:[],multi_agent:[]},pagingByType:{normal:{offset:0,hasMore:!1,loaded:!1},multi_agent:{offset:0,hasMore:!1,loaded:!1}}}),kr=hn("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:FF(),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,HF(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=nL();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(d=>d.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 d=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}${d}`)).json();if(p.success){const g=(((l=p.data)==null?void 0:l.conversations)||[]).map(m=>({id:m.id,title:m.title,updated_at:m.updated_at,total_messages:m.total_messages,total_tools:m.total_tools}));if(t){const m=o.slice(g.length);o.splice(0,o.length,...g,...m)}else c===0?o.splice(0,o.length,...g):o.push(...g);a.hasMore=!!((u=p.data)!=null&&u.has_more),a.loaded=!0,t||(a.offset=c+g.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(d){console.error("加载工作区对话异常:",d)}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",d=await(await fetch(`/api/conversations?workspace_id=${encodeURIComponent(s)}&limit=${t.bufferLimit}&offset=${c}${l}`)).json();if(d.success){const h=(((i=d.data)==null?void 0:i.conversations)||[]).map(g=>({id:g.id,title:g.title,updated_at:g.updated_at,total_messages:g.total_messages,total_tools:g.total_tools}));t.conversations.push(...h),t.hasMore=!!((r=d.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}}}}),Ti=Object.freeze(Object.defineProperty({__proto__:null,createEmptyGroupTypeCache:nL,useConversationStore:kr},Symbol.toStringTag,{value:"Module"}));function UF(...s){}function iL(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:iL(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 Pc=hn("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();UF("[FileTree] fetch result",e),this.setFileTreeFromResponse(e)}catch(s){console.error("获取文件树失败:",s)}},markFileTreeUnavailable(s){this.fileTreeUnavailable=!0,this.fileTreeMessage=s||S("stores.fileTreeUnavailableHostMode"),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=iL(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=kr().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})}}}),WF={categories:{},forced_category_states:{},disabled_models:[],ui_blocks:{}},zo=hn("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||S("stores.loadPolicyFailed"));this.policy=e.data||WF,this.loaded=!0}catch(s){this.error=(s==null?void 0:s.message)||S("stores.loadPolicyFailed")}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 zF(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 rL=hn("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=zo().uiBlocks)!=null&&c.block_upload)return Is().pushToast({title:S("stores.uploadDisabled"),message:S("stores.uploadDisabledByAdmin"),type:"warning"}),[];const o=Pc(),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=zo();if(!i&&((u=r.uiBlocks)!=null&&u.block_upload))return Is().pushToast({title:S("stores.uploadDisabled"),message:S("stores.uploadDisabledByAdmin"),type:"warning"}),null;const o=Is(),a=Pc();(s.type&&s.type.startsWith("video/")||/\.(mp4|mov|m4v|webm|avi|mkv|flv|mpg|mpeg)$/i.test(s.name||""))&&o.pushToast({title:S("stores.videoProcessing"),message:S("stores.videoProcessingSlow"),type:"info",duration:5e3}),t&&this.setUploading(!0);const l=o.pushToast({title:S("stores.uploadingFileTitle"),message:S("stores.uploadingFile",{name:s.name}),type:"info",duration:null});try{const d=s.name||zF(s.type)||`upload_${Date.now()}`,h=new FormData;h.append("file",s),h.append("filename",d);const p=await fetch("/api/upload",{method:"POST",body:h});l&&o.updateToast(l,{message:S("stores.uploadingScanning"),type:"info"});let g={};try{g=await p.json()}catch{throw new Error(S("stores.serverResponseUnparseable"))}if(!p.ok||!g.success){const m=g.error||g.message||S("stores.uploadFailed");throw new Error(m)}n&&await a.fetchFileTree();const v=S("stores.uploadSuccess",{name:g.path||s.name});return l?o.updateToast(l,{title:S("stores.uploadComplete"),message:v,type:"success",duration:4500}):o.pushToast({title:S("stores.uploadComplete"),message:v,type:"success"}),g!=null&&g.path?{path:g.path,filename:g.filename||s.name||g.path}:null}catch(d){const h=d&&d.message?String(d.message):"",p=s&&s.name?s.name:S("stores.genericFile");let g=h||S("common.retryLater");/(?:\u5b89\u5168\u5ba1\u6838\u672a\u901a\u8fc7|Security check failed)/.test(h)||/Eicar/i.test(h)?g=S("stores.uploadSecurityRejected",{name:p}):/(?:\u6587\u4ef6\u7c7b\u578b\u4e0d\u5728\u5141\u8bb8\u5217\u8868\u4e2d|File type is not in the allowed list)/.test(h)?g=S("stores.uploadTypeNotAllowed",{name:p}):g?g=S("stores.uploadFailedWithReason",{name:p,reason:g}):g=S("stores.uploadFailedRetryLater",{name:p});const v=Is();return l?v.updateToast(l,{title:S("stores.uploadFailed"),message:g,type:"error",duration:5e3}):v.pushToast({title:S("stores.uploadFailed"),message:g,type:"error"}),null}finally{t&&this.setUploading(!1)}}}}),jF=new Set(["completed","failed","timeout","terminated"]),dd=hn("subAgent",{state:()=>({subAgents:[],activityTimer:null,activeAgent:null,silentActivityTaskId:null,stoppingTaskIds:{},activityEntries:[],activityLoading:!1,activityError:null}),actions:{async fetchSubAgents(){var s;try{const e=kr(),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=kr().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();jF.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:S("stores.taskIdRequired")};this.stoppingTaskIds={...this.stoppingTaskIds,[e]:!0};try{const i=kr().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=kr().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`}}}),VF=Object.freeze(Object.defineProperty({__proto__:null,useSubAgentStore:dd},Symbol.toStringTag,{value:"Module"}));function nC(){const s=kr().currentConversationId;return s?`conversation_id=${encodeURIComponent(s)}`:""}const GF=new Set(["completed","failed","timeout","cancelled"]),vg=hn("backgroundCommand",{state:()=>({commands:[],detailPollTimer:null,activeCommand:null,silentDetailCommandId:null,stoppingCommandIds:{},activeDetail:null,detailLoading:!1,detailError:null}),actions:{async fetchCommands(){var s;try{const e=kr().currentConversationId;if(!e){this.commands=[];return}const t=nC();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=nC(),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();GF.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:S("stores.commandIdRequired")};this.stoppingCommandIds={...this.stoppingCommandIds,[e]:!0};try{const n=nC(),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)}}}}}),oL=hn("focus",{state:()=>({focusedFiles:{}}),actions:{async fetchFocusedFiles(){try{const s=await fetch("/api/focused");if(!s.ok)throw new Error(s.statusText||S("stores.requestFailed"));const e=await s.json();this.focusedFiles=e||{}}catch(s){console.error("获取聚焦文件失败:",s)}},setFocusedFiles(s){this.focusedFiles=s||{}},clearFocusedFiles(){this.focusedFiles={}}}}),er=hn("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)||S("stores.loadModelListFailed"));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)}}}),KF=["stores.toneChatty","stores.toneHumorous","stores.toneBlunt","stores.toneEncouraging","stores.tonePoetic","stores.toneCorporate","stores.toneUnconventional","stores.toneEmpathetic"],aL=()=>({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}}),qF=s=>{const e=aL(),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},NT=10,Xf={min:1,max:30},bw=20,$_=5,QF=8e4,XF=15e4,ex=["fast","thinking"],tx=["low","medium","high","xhigh","max"],AE="agents_personalization_experiments",$T="agents_ui_theme",lL="agents_stacked_hide_borders",cL="agents_minimal_expand_height_limited",EE="agents_quick_dock_auto_expand",uL=()=>{if(typeof window>"u"||!window.localStorage)return"classic";const s=window.localStorage.getItem($T);return s==="light"||s==="dark"||s==="classic"?s:"classic"},YF=()=>typeof window>"u"||!window.localStorage?!1:window.localStorage.getItem(lL)==="true",JF=()=>{if(typeof window>"u"||!window.localStorage)return"minimal";try{const s=window.localStorage.getItem(AE);if(!s)return"minimal";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"minimal"},sx=s=>{if(!(typeof window>"u"||!window.localStorage))try{window.localStorage.setItem(lL,s?"true":"false")}catch(e){console.warn("写入堆叠块边线设置失败:",e)}},dL=()=>{if(typeof window>"u"||!window.localStorage)return!0;const s=window.localStorage.getItem(EE);return s===null?!0:s==="true"},hL=()=>typeof window>"u"||!window.localStorage?!1:window.localStorage.getItem(EE)!==null,ZF=s=>{if(!(typeof window>"u"||!window.localStorage))try{window.localStorage.setItem(EE,s?"true":"false")}catch(e){console.warn("写入快捷窗口自动展开设置缓存失败:",e)}},e3=()=>{if(typeof window>"u"||!window.localStorage)return!0;const s=window.localStorage.getItem(cL);return s===null?!0:s==="true"},nx=s=>{if(!(typeof window>"u"||!window.localStorage))try{window.localStorage.setItem(cL,s?"true":"false")}catch(e){console.warn("写入极简展开高度限制设置失败:",e)}},t3=()=>({enabled:!1,communication_style:"default",conversation_continuity:"medium",auto_generate_title:!0,title_model:"",recent_conversations_prompt_enabled:!1,recent_conversations_prompt_limit:NT,project_memory_inject_limit:bw,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:JF(),show_status_avatar:!0,show_git_status_bar:!0,auto_open_terminal_panel:!0,quick_dock_auto_expand:dL(),file_preview_auto_wrap:!1,edit_summary_live_display:!1,modify_history_enabled:!0,stacked_hide_borders:YF(),minimal_expand_height_limited:e3(),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:"approval",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,claude_md_auto_inject:!1,agents_skills_scan_enabled:!0,new_chat_button_behavior:"route",group_sidebar_by_workspace:!1,sidebar_pinned_workspaces:[],sidebar_workspace_order:[],theme:uL(),ui_locale:"zh-CN",goal_review_mode:"readonly",goal_end_conditions:["max_turns"],goal_max_turns:5,goal_max_tokens:null,review_agents:aL()}),Pg=()=>({blockDisplayMode:"minimal",compactMessageDisplay:"full"}),s3=()=>{if(typeof window>"u"||!window.localStorage)return Pg();try{const s=window.localStorage.getItem(AE);if(!s)return Pg();const e=JSON.parse(s);let t=Pg().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=Pg().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),Pg()}};let B_=null;const Js=hn("personalization",{state:()=>({visible:!1,loading:!1,saving:!1,loaded:!1,status:"",error:"",toggleUpdating:!1,overlayPressActive:!1,form:t3(),toolCategories:[],skillsCatalog:[],recentConversationsPromptLimitRange:{...Xf},projectMemoryInjectLimitMin:$_,experiments:s3()}),getters:{tonePresets:()=>(lt.value,KF.map(s=>S(s)))},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||S("common.loadFailed"));this.applyPersonalizationData(e.data||{}),this.applyPersonalizationMeta(e),this.loaded=!0}catch(s){this.error=(s==null?void 0:s.message)||S("common.loadFailed")}finally{this.loading=!1}},applyPersonalizationData(s){var o,a;const e=this.form&&typeof this.form.default_model=="string"?this.form.default_model:null,t=((o=this.form)==null?void 0:o.theme)||uL();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,title_model:typeof s.title_model=="string"?s.title_model:"",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:"minimal",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(c=>typeof c=="string"):[],enabled_skills:Array.isArray(s.enabled_skills)?s.enabled_skills.filter(c=>typeof c=="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(c=>typeof c=="string").join(`
|
||
`):"",disabled_tool_categories:Array.isArray(s.disabled_tool_categories)?s.disabled_tool_categories.filter(c=>typeof c=="string"):[],default_run_mode:(()=>{const c=s.default_run_mode==="deep"?"thinking":s.default_run_mode;return typeof c=="string"&&ex.includes(c)?c:null})(),default_reasoning_effort:typeof s.default_reasoning_effort=="string"&&tx.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:"approval",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,claude_md_auto_inject:!!s.claude_md_auto_inject,agents_skills_scan_enabled:s.agents_skills_scan_enabled===void 0?!0:!!s.agents_skills_scan_enabled,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(c=>typeof c=="string"):[],sidebar_workspace_order:Array.isArray(s.sidebar_workspace_order)?s.sidebar_workspace_order.filter(c=>typeof c=="string"):[],theme:["classic","light","dark"].includes(s.theme)?s.theme:t,ui_locale:["zh-CN","en-US"].includes(s.ui_locale)?s.ui_locale:((a=this.form)==null?void 0:a.ui_locale)||"zh-CN",goal_review_mode:s.goal_review_mode==="active"?"active":"readonly",goal_end_conditions:Array.isArray(s.goal_end_conditions)?s.goal_end_conditions.filter(c=>c==="max_turns"||c==="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:qF(s.review_agents)};const n=typeof window<"u"&&window.localStorage?window.localStorage.getItem($T):null;this.form.theme!==n&&this.applyTheme(this.form.theme),this.form.ui_locale&&this.form.ui_locale!==lt.value&&JB(this.form.ui_locale),sx(this.form.stacked_hide_borders),nx(this.form.minimal_expand_height_limited),ZF(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==="minimal"&&r!=="minimal"&&(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($T,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??Xf.min,n=this.recentConversationsPromptLimitRange.max??Xf.max;return Number.isFinite(e)?Math.max(t,Math.min(n,Math.round(e))):NT},normalizeProjectMemoryInjectLimit(s){if(typeof s>"u")return bw;if(s===null||s==="")return null;const e=Number(s);if(!Number.isFinite(e))return bw;const t=Math.round(e);if(t<=0)return null;const n=this.projectMemoryInjectLimitMin??$_;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:Xf.min,max:typeof t=="number"?t:Xf.max}}else this.recentConversationsPromptLimitRange={...Xf};if(s&&s.project_memory_inject_limit_range){const{min:e}=s.project_memory_inject_limit_range;this.projectMemoryInjectLimitMin=typeof e=="number"?e:$_}else this.projectMemoryInjectLimitMin=$_;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||S("stores.updateFailed"));n.data&&this.applyPersonalizationData(n.data),this.applyPersonalizationMeta(n);const i=s?S("stores.enabled"):S("stores.disabled");this.status=i,setTimeout(()=>{this.status===i&&(this.status="")},2e3)}catch(t){this.form.enabled=e,this.error=(t==null?void 0:t.message)||S("stores.updateFailed")}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)??QF;if((this.normalizeCompressionNumber(this.form.deep_compress_trigger_tokens)??XF)<=s)throw new Error(S("stores.deepCompressMustExceedShallow"));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||S("stores.saveFailed"));this.applyPersonalizationData(n.data||{}),this.applyPersonalizationMeta(n);const i=S("stores.saved");this.status=i,setTimeout(()=>{this.status===i&&(this.status="")},3e3)}catch(s){this.error=(s==null?void 0:s.message)||S("stores.saveFailed")}finally{this.saving=!1}}},updateField(s){!s||!s.key||(this.form={...this.form,[s.key]:s.value},s.key==="stacked_hide_borders"&&sx(!!s.value),s.key==="minimal_expand_height_limited"&&nx(!!s.value),this.clearFeedback(),this.scheduleAutoSave())},scheduleAutoSave(){B_&&clearTimeout(B_),B_=setTimeout(()=>{B_=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||S("stores.autoSaveFailed"))}catch(s){this.error=(s==null?void 0:s.message)||S("stores.autoSaveFailed")}finally{this.saving=!1}}},setRecentConversationsPromptLimit(s){const e=s===null||typeof s>"u"?NT: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:bw},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"&&ex.includes(s)&&(e=s),this.form={...this.form,default_run_mode:e},this.clearFeedback(),this.scheduleAutoSave()},setDefaultReasoningEffort(s){let e=null;typeof s=="string"&&tx.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=er(),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)||S("stores.logoutFailedRetry"),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()}}}),n3=Object.freeze(Object.defineProperty({__proto__:null,hasCachedQuickDockAutoExpand:hL,loadCachedQuickDockAutoExpand:dL,usePersonalizationStore:Js},Symbol.toStringTag,{value:"Module"})),i3={browserSearch:"chat.progressBrowserSearch",webExtract:"chat.progressWebExtract",webSave:"chat.progressWebSave",appendFile:"chat.progressAppendFile",modifyFile:"chat.progressModifyFile",createFile:"chat.progressCreateFile",deleteFile:"chat.progressDeleteFile",readFile:"chat.progressReadFile",reader:"chat.progressReader",focus:"chat.progressFocus",unfocus:"chat.progressUnfocus",runCommand:"chat.progressRunCommand",terminalSession:"chat.progressTerminalSession",terminalInput:"chat.progressTerminalInput",terminalSnapshot:"chat.progressTerminalSnapshot",memoryUpdate:"chat.progressMemoryUpdate",todoCreate:"chat.progressTodoCreate",todoUpdate:"chat.progressTodoUpdate",todoFinish:"chat.progressTodoFinish",todoFinishConfirm:"chat.progressTodoFinishConfirm",todoDelete:"chat.progressTodoDelete",wait:"chat.progressWait",sleep:"chat.progressSleep",createFolder:"chat.progressCreateFolder",renameFile:"chat.progressRenameFile",terminalReset:"chat.progressTerminalReset",terminalSleep:"chat.progressTerminalSleep",terminalRun:"chat.progressTerminalRun",ocr:"chat.progressOcr",memory:"chat.progressMemory",todo:"chat.progressTodo",genericTool:"chat.progressGenericTool"};function ix(s){const e=i3[s];return e?S(e):null}const fL=hn("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}}}),iC=(...s)=>{},Yf=(...s)=>{},Td=(...s)=>{},rC=["__pycache__","config","core","data","doc","docker","logs","modules","node_modules","project","prompts","scratch_test","scripts","static","sub_agent","test","users","utils"],r3=32,rx={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"},o3=(s="evt")=>`${s}-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,pL=hn("monitor",{state:()=>({statusLabel:S("stores.idle"),queue:[],playing:!1,awaitingTools:{},lastTreeSnapshot:[...rC],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&&(Yf("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=[...rC],(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:[...rC],(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=S("stores.idle"),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},Yf("progress-indicator:set",this.progressIndicator)},previewToolIntent(s){this.bubbleActive&&this.hideBubble(`tool-intent:${(s==null?void 0:s.name)||"unknown"}`),this.speechBuffer="";const e=rx[s.name]||"genericTool",t=ix(e);t&&(this.setStatus(t),this.progressIndicator={id:null,label:t,scene:e},Yf("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||(Yf("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&&(iC("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(S("stores.idle")),this.driver&&typeof this.driver.showWaitingBubble=="function"){this.driver.showWaitingBubble(S("stores.waitingReply")),this.bubbleActive=!0;return}(s=this.driver)==null||s.showSpeechBubble(S("stores.waitingReplyEllipsis"),{variant:"info",duration:0}),this.bubbleActive=!0},enqueueModelSpeech(s){if(s){if(this.setStatus(S("stores.planning")),this.speechBuffer=`${this.speechBuffer}${s}`,this.lastSpeechAt=Date.now(),iC("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=fL();s.runMode==="fast"||s.thinkingMode===!1||this.playing||!this.driver||this.thinkingActive||(this.setStatus(S("stores.thinking")),(t=this.driver)==null||t.showThinkingBubble(),this.bubbleActive=!0,this.thinkingActive=!0)},endModelOutput(){this.setStatus(S("stores.idle")),this.thinkingActive=!1},enqueueToolEvent(s){var c,l,u,d,h;const t=Date.now()-this.lastSpeechAt,n=480,i=rx[s.name]||"genericTool",r=ix(i);r&&this.setStatus(r);const o=s.executionId||s.id||o3("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)||((d=s==null?void 0:s.argumentSnapshot)==null?void 0:d.path)||((h=s==null?void 0:s.argumentSnapshot)==null?void 0:h.target_path);this.driver.preparePendingCreation(p)}Td("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?(Yf("enqueueToolEvent:preview-now",{tool:s.name,script:i,id:o}),this.driver.previewSceneProgress(i)):(Yf("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;Td("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],Td("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||S("stores.toolExecFailed");(t=this.driver)==null||t.showSpeechBubble(n,{variant:"error",icon:"✖",duration:2800}),this.setStatus(S("stores.abnormal")),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>r3){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),Td("queue-start",{size:this.queue.length});this.queue.length&&this.driver;){const s=this.queue.shift();s&&(iC("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(S("stores.idle"))}},async runScript(s){var a,c,l,u,d;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;Td("runScript:start",{script:s.script,waitKey:e,payloadTool:(u=s.payload)==null?void 0:u.name,payloadId:(d=s.payload)==null?void 0:d.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(h){console.warn("monitor waitForResult error",h),t=null}finally{n=!0}return t},r=h=>{const p=typeof h=="string"&&h.trim().length?h.trim():S("stores.inProgress");return p.startsWith("正在")?S("stores.playbackStatus",{label:p.slice(2)}):p},o={waitForResult:()=>i(),setStatus:h=>this.setStatus(r(h)),statusPhase:"playback"};this.setStatus(S("stores.toolPlayback")),Td("runScript:playback",{script:s.script,waitKey:e,status:this.statusLabel});try{await this.driver.playScene(s.script,s.payload||{},o)}catch(h){console.warn("Monitor scene error",h)}finally{Td("runScript:end",{script:s.script,waitKey:e})}}}}),oC={damping:.7,stiffness:.05,mass:1.25},a3=70,l3=1e3/60,c3=350;let _w=!1,ox=!1;function u3(){ox||typeof document>"u"||(document.addEventListener("mousedown",()=>{_w=!0}),document.addEventListener("mouseup",()=>{_w=!1}),document.addEventListener("click",()=>{_w=!1}),ox=!0)}const aC=new Map;function lC(...s){const e={damping:oC.damping,stiffness:oC.stiffness,mass:oC.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 aC.has(n)||aC.set(n,Object.freeze({...e})),t?"instant":aC.get(n)}function d3(s={}){u3();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 x=r();for(const D of t)D(x)}function r(){return{isAtBottom:n.isAtBottom||n.isNearBottom,isNearBottom:n.isNearBottom,escapedFromLock:n.escapedFromLock}}function o(){var x;return((x=n.scrollElement)==null?void 0:x.scrollTop)??0}function a(x){n.scrollElement&&(n.scrollElement.scrollTop=x,n.ignoreScrollToTop=n.scrollElement.scrollTop)}function c(){const x=n.scrollElement,D=n.contentElement;return!x||!D?0:x.scrollHeight-1-x.clientHeight}let l;function u(){const x=n.scrollElement,D=n.contentElement;if(!x||!D)return 0;const N=c();if(!e.targetScrollTop)return N;if((l==null?void 0:l.targetScrollTop)===N)return l.calculatedScrollTop;const O=Math.max(Math.min(e.targetScrollTop(N,{scrollElement:x,contentElement:D}),N),0);return l={targetScrollTop:N,calculatedScrollTop:O},typeof requestAnimationFrame<"u"&&requestAnimationFrame(()=>{l=void 0}),O}function d(){return u()-o()}function h(){return d()<=a3}function p(x){n.isAtBottom=x,i()}function g(x){n.escapedFromLock=x,i()}function v(x){n.isNearBottom=x,i()}function m(){var G;if(!_w||typeof window>"u")return!1;const x=(G=window.getSelection)==null?void 0:G.call(window);if(!x||!x.rangeCount)return!1;const D=x.getRangeAt(0),N=n.scrollElement;if(!N)return!1;const O=D.commonAncestorContainer;return!!(O&&(N.contains(O)||O.contains(N)))}const y=x=>{if(x.target!==n.scrollElement)return;const D=o(),N=n.ignoreScrollToTop;let O=n.lastScrollTop??D;n.lastScrollTop=D,n.ignoreScrollToTop=void 0,N&&N>D&&(O=N),v(h()),setTimeout(()=>{var q;if(n.resizeDifference||D===N)return;if(m()){g(!0),p(!1);return}const G=D>O,Z=D<O;if((q=n.animation)!=null&&q.ignoreEscapes){a(O);return}Z&&(g(!0),p(!1)),G&&g(!1),!n.escapedFromLock&&h()&&p(!0)},1)},_=x=>{var O;const D=n.scrollElement;if(!D)return;let N=x.target;for(;N&&!["scroll","auto"].includes(getComputedStyle(N).overflow);){if(!N.parentElement)return;N=N.parentElement}N===D&&x.deltaY<0&&D.scrollHeight>D.clientHeight&&!((O=n.animation)!=null&&O.ignoreEscapes)&&(g(!0),p(!1))};function b(x,D){k(),n.scrollElement=x,n.contentElement=D,getComputedStyle(x).overflow==="visible"&&(x.style.overflow="auto"),x.addEventListener("scroll",y,{passive:!0}),x.addEventListener("wheel",_,{passive:!0});let N;n.resizeObserver=new ResizeObserver(O=>{const G=O[0];if(!G)return;const{height:Z}=G.contentRect,q=Z-(N??Z);if(n.resizeDifference=q,o()>c()&&a(c()),v(h()),q>=0){const V=lC(e,N?e.resize:e.initial);A({animation:V,wait:!0,preserveScrollPosition:!0,duration:V==="instant"?void 0:c3})}else h()&&(g(!1),p(!0));N=Z,typeof requestAnimationFrame<"u"&&requestAnimationFrame(()=>{setTimeout(()=>{n.resizeDifference===q&&(n.resizeDifference=0)},1)})}),n.resizeObserver.observe(D)}function k(){var x;n.scrollElement&&(n.scrollElement.removeEventListener("scroll",y),n.scrollElement.removeEventListener("wheel",_)),(x=n.resizeObserver)==null||x.disconnect(),n.resizeObserver=void 0,n.scrollElement=void 0,n.contentElement=void 0}function w(){k(),t.clear()}function T(x){e={...e,...x}}function A(x={}){var I;const D=typeof x=="string"?{animation:x}:x;D.preserveScrollPosition||p(!0);const N=Date.now()+(Number(D.wait)||0),O=lC(e,D.animation),{ignoreEscapes:G=!1}=D;let Z,q=u();D.duration instanceof Promise?D.duration.finally(()=>{Z=Date.now()}):Z=N+(D.duration??0);const V=async()=>{const $=new Promise(L=>{if(typeof requestAnimationFrame>"u"){L(!1);return}requestAnimationFrame(()=>L(!0))}).then(()=>{var oe;if(!n.isAtBottom)return n.animation=void 0,!1;const L=o(),K=typeof performance<"u"?performance.now():Date.now(),se=(K-(n.lastTick??K))/l3;if(n.animation||(n.animation={behavior:O,promise:$,ignoreEscapes:G}),n.animation.behavior===O&&(n.lastTick=K),m()||N>Date.now())return V();if(L<Math.min(q,u())){if(((oe=n.animation)==null?void 0:oe.behavior)===O){if(O==="instant")return a(u()),V();const ve=O;n.velocity=(ve.damping*n.velocity+ve.stiffness*d())/ve.mass,n.accumulated+=n.velocity*se;const le=o();a(le+n.accumulated),o()!==le&&(n.accumulated=0)}return V()}return Z>Date.now()?(q=u(),V()):(n.animation=void 0,o()<u()?A({animation:lC(e,e.resize),ignoreEscapes:G,duration:Math.max(0,Z-Date.now())||void 0}):n.isAtBottom)});return $.then(L=>(typeof requestAnimationFrame<"u"&&requestAnimationFrame(()=>{n.animation||(n.lastTick=void 0,n.velocity=0)}),L))};return D.wait!==!0&&(n.animation=void 0),((I=n.animation)==null?void 0:I.behavior)===O?n.animation.promise:V()}const C=()=>{g(!0),p(!1)};function E(x){return t.add(x),()=>t.delete(x)}return{attach:b,detach:k,destroy:w,setOptions:T,getState:r,onChange:E,scrollToBottom:A,stopScroll:C}}function h3(s={}){const e=ge(null),t=ge(null),n=ge(s.initial!==!1),i=ge(!1),r=ge(!1),o=d3(s);let a=null;return jP(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()}))}),Rn(()=>{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 ly=null,{min:Hd,max:sa,abs:ax,floor:f3}=Math,mL=(s,e,t)=>Hd(t,sa(e,s)),gL=s=>[...s].sort((e,t)=>e-t),p3=typeof queueMicrotask=="function"?queueMicrotask:s=>{Promise.resolve().then(s)},BT=()=>{let s;return[new Promise(e=>{s=e}),s]},vL=s=>{let e;return()=>(s&&(e=s(),s=void 0),e)},Bv=(s,e,t)=>{const n=t?"unshift":"push";for(let i=0;i<e;i++)s[n](-1);return s},yL=(s,e)=>{const t=s.t[e];return t===-1?s.o:t},m3=(s,e,t)=>{const n=s.t[e]===-1;return s.t[e]=t,s.i=Hd(e,s.i),n},ww=(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+=yL(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=f3((t+n)/2);ww(s,r)<=e?(i=r,t=r+1):n=r-1}return mL(i,0,s.l-1)},lx=(s,e,t)=>{const n=e-s.l;return s.i=t?-1:Hd(e-1,s.i),s.l=e,n>0?(Bv(s.u,n),Bv(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))},g3=s=>s.documentElement,v3=s=>s.ownerDocument,y3=s=>s.defaultView,bL=vL(()=>!!/iP(hone|od|ad)/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>0),b3=vL(()=>"scrollBehavior"in g3(document).style),_3=(s,e=40,t=0,n,i=!1)=>{let r=!!t,o=1,a=0,c=0,l=0,u=0,d=0,h=0,p=0,g=0,v=ly,m=[0,r?sa(t-1,0):-1],y=0,_=!1;const b=((O,G,Z)=>({o:G,t:Z?Bv(Z.slice(0,Hd(O,Z.length)),sa(0,O-Z.length)):Bv([],O),l:O,i:-1,u:Bv([],O+1)}))(s,n?n[1]:e,n&&n[0]),k=new Set,w=()=>l-c,T=()=>w()+d+u,A=(O,G)=>((Z,q,V,I)=>{if(I=Hd(I,Z.l-1),ww(Z,I)<=q){const $=Jf(Z,V,I);return[Jf(Z,q,I,$),$]}{const $=Jf(Z,q,void 0,I);return[$,Jf(Z,V,$)]}})(b,O,G,m[0]),C=()=>ww(b,b.l),E=(O,G)=>{const Z=ww(b,O)-d;return G?C()-Z-x(O):Z},x=O=>yL(b,O),D=(O,G=-1)=>b.t[O]===G,N=O=>{O&&(bL()&&p!==0||v&&g===1?d+=O:u+=O)};return{p:()=>{k.clear()},m:()=>o,h:()=>(O=>[O.t.slice(),O.o])(b),v:(O=200)=>{if(!_||r)return m;let G,Z;if(h)[G,Z]=m;else{let q=sa(0,T()),V=q+a;i||(O=sa(0,O),p!==1&&(q-=O),p!==2&&(V+=O)),[G,Z]=m=A(sa(0,q),sa(0,V)),v&&(G=Hd(G,v[0]),Z=sa(Z,v[1]))}return[sa(G,0),Hd(Z,b.l-1)]},S:O=>Jf(b,O-c),I:D,O:E,k:x,j:()=>b.l,N:()=>l,B:()=>p!==0,T:()=>a,q:()=>c,M:C,P:()=>(h=u,u=0,[h,g===2]),R:(O,G)=>{const Z=[O,G];return k.add(Z),()=>{k.delete(Z)}},A:(O,G)=>{let Z,q,V=0;switch(O){case 1:{if(G===l&&g===0)break;const I=h;h=0;const $=G-l,L=ax($);I&&L<ax(I)+1||g!==0||(p=$<0?2:1),r&&(r=!1),l=G,V=4;const K=w();K>=-a&&K<=C()&&(V+=1,q=L>a);break}case 2:V=8,p!==0&&(Z=!0,V+=1),p=0,g=0,v=ly;break;case 3:{const I=G.filter(([$,L])=>!D($,L));if(!I.length)break;N(I.reduce(($,[L,K])=>{let se;if(g===2)se=!0;else if(v&&g===1)se=L<v[0];else{const oe=w(),ve=E(L),le=x(L);se=p!==1&&g===0?ve+le<=oe:ve<oe&&ve+le<oe+a}return se&&($+=K-x(L)),$},0));for(const[$,L]of I){const K=x($),se=m3(b,$,L);i&&(y+=se?L:L-K)}i&&a&&y>a&&(N((($,L)=>{let K=0;const se=[];$.t.forEach((X,J)=>{X!==-1&&(se.push(X),J<L&&K++)}),$.i=-1;const oe=gL(se),ve=oe.length,le=ve/2|0,ue=ve%2==0?(oe[le-1]+oe[le])/2:oe[le],P=$.o;return(($.o=ue)-P)*sa(L-K,0)})(b,Jf(b,T()))),i=!1),V=3,q=!0;break}case 4:a!==G&&(a||(_=q=!0),a=G,V=3);break;case 5:G[1]?(N(lx(b,G[0],!0)),g=2,V=1):(lx(b,G[0]),V=1);break;case 6:c=G;break;case 7:g=1;break;case 8:v=A(G,G+a),V=1}V&&(o=1+(2147483647&o),Z&&d&&(u+=d,d=0),k.forEach(([I,$])=>{V&I&&$(q)}))}}},ME=setTimeout,cC=(s,e)=>e?-s:s,w3=(s,e,t,n,i,r)=>{const o=Date.now;let a=0,c=!1,l=!1,u=!1,d=!1;const h=(()=>{let y;const _=()=>{y!=ly&&clearTimeout(y)},b=()=>{_(),y=ME(()=>{y=ly,(()=>{if(c||l)return c=!1,void h();u=!1,s.A(2)})()},150)};return b.C=_,b})(),p=()=>{a=o(),u&&(d=!0),s.A(1,n()),h()},g=y=>{if(c||!s.B()||y.ctrlKey)return;const _=o()-a;150>_&&50<_&&(t?y.deltaX:y.deltaY)&&(c=!0)},v=()=>{l=!0,u=d=!1},m=()=>{l=!1,bL()&&(u=!0)};return e.addEventListener("scroll",p),e.addEventListener("wheel",g,{passive:!0}),e.addEventListener("touchstart",v,{passive:!0}),e.addEventListener("touchend",m,{passive:!0}),{H:()=>{e.removeEventListener("scroll",p),e.removeEventListener("wheel",g),e.removeEventListener("touchstart",v),e.removeEventListener("touchend",m),h.C()},V:()=>{const[y,_]=s.P();y&&(i(y,_,d),d=!1,_&&s.T()>s.M()&&s.A(1,n()))}}},S3=(s,e,t)=>{let n;return[async(i,r)=>{if(!await e())return;n&&n();const o=()=>{const[a,c]=BT();return n=()=>{c(!1)},s.T()&&ME(n,150),[a,s.R(2,()=>{c(!0)})]};if(r&&b3())s.A(8,i()),p3(async()=>{for(;;){let a=!0;for(let[u,d]=s.v();u<=d;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()}]},k3=s=>{let e;return{F(t){(e||(e=new(y3(v3(t))).ResizeObserver(s))).observe(t)},J(t){e.unobserve(t)},H(){e&&e.disconnect()}}},C3=ct({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=ge(),t=be(()=>s.L.value&&s.W.O(s.D,s.K)),n=be(()=>s.L.value&&s.W.I(s.D));return Ke(()=>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??{},d={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&&(d.display="inline-flex"),We(a,ZB({ref:e,style:d},u),typeof(h=i)=="function"||Object.prototype.toString.call(h)==="[object Object]"&&!VP(h)?i:{default:()=>[i],_:2},16,["style"]);var h}}}),T3=(s,e)=>{if(s.length===1){const t=s[0].key;if(t!=null)return t}return"_"+e},A3=(s,e)=>s[0]===e[0]&&s[1]===e[1],E3=ct({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=ge(),a=_3(s.data.length,s.itemSize,s.ssrCount,s.cache,!s.itemSize),c=((g,v)=>{let m;const y=v?"width":"height",_=new WeakMap,b=k3(k=>{const w=[];for(const{target:T,contentRect:A}of k)if(T.offsetParent)if(T===m)g.A(4,A[y]);else{const C=_.get(T);C!=ly&&w.push([C,A[y]])}w.length&&g.A(3,w)});return{te(k){b.F(m=k)},re:(k,w)=>(_.set(k,w),b.F(k),()=>{_.delete(k),b.J(k)}),p:b.H}})(a,r),l=((g,v)=>{let m,y,_=BT(),b=!1;const k=v?"scrollLeft":"scrollTop",w=v?"overflowX":"overflowY",[T,A]=S3(g,()=>_[0],(C,E)=>{C=cC(C,b),E?m.scrollTo({[v?"left":"top"]:C,behavior:"smooth"}):m[k]=C});return{oe(C,E){m=E,v&&(b=getComputedStyle(E).direction==="rtl"),y=w3(g,E,v,()=>cC(E[k],b),(x,D,N)=>{if(N){const O=E.style,G=O[w];O[w]="hidden",ME(()=>{O[w]=G})}E[k]=cC(g.N()+x,b),D&&A()}),_[1](!0)},p(){y&&y.H(),_[1](!1),_=BT()},ne:()=>b,se(C){T(()=>C)},ie(C){C+=g.N(),T(()=>C)},le(C,{align:E,smooth:x,offset:D=0}={}){if(C=mL(C,0,g.j()-1),E==="nearest"){const N=g.O(C),O=g.N();if(N<O)E="start";else{if(!(N+g.k(C)>O+g.T()))return;E="end"}}T(()=>D+g.q()+g.O(C)+(E==="end"?g.k(C)-g.T():E==="center"?(g.k(C)-g.T())/2:0),x)},ce:()=>{y&&y.V()}}})(a,r),u=ge(a.m());a.R(1,()=>{u.value=a.m()}),a.R(4,()=>{e("scroll",a.N())}),a.R(8,()=>{e("scrollEnd")});const d=be(g=>{u.value;const v=a.v(s.bufferSize);return g&&A3(g,v)?g:v}),h=be(()=>u.value&&a.B()),p=be(()=>u.value&&a.M());return dn(()=>{i=!1;const g=o.value,v=requestAnimationFrame(()=>{const m=y=>{c.te(y),l.oe(g,y)};s.scrollRef?m(s.scrollRef):m(g.parentElement)});QM(()=>{cancelAnimationFrame(v)})}),QM(()=>{a.p(),c.p(),l.p()}),Ke(()=>s.data.length,g=>{a.A(5,[g,s.shift])}),Ke(()=>s.startMargin,g=>{a.A(6,g)},{immediate:!0}),Ke([u],()=>{l.ce()},{flush:"post"}),t({get cache(){return a.h()},get scrollOffset(){return a.N()},get scrollSize(){return(g=>sa(g.M(),g.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 g=s.as,v=s.item,m=p.value,y=l.ne(),_=[],b=w=>{var A;const T=n.default({item:s.data[w],index:w});return We(C3,{key:T3(T,w),L:u,W:a,Y:c.re,D:w,X:T,U:r,K:y,G:i,Z:v,ee:(A=s.itemProps)==null?void 0:A.call(s,{item:s.data[w],index:w})},null,8,["L","W","Y","D","X","U","K","G","Z","ee"])};if(s.keepMounted){const w=new Set(s.keepMounted);for(let[T,A]=d.value;T<=A;T++)w.add(T);gL([...w]).forEach(T=>{_.push(b(T))})}else for(let[w,T]=d.value;w<=T;w++)_.push(b(w));return We(g,{ref:o,style:{contain:"size style",overflowAnchor:"none",flex:"none",position:"relative",width:r?m+"px":"100%",height:r?"100%":m+"px",pointerEvents:h.value?"none":void 0}},typeof(k=_)=="function"||Object.prototype.toString.call(k)==="[object Object]"&&!VP(k)?_:{default:()=>[_],_:2},8,["style"]);var k}}});function M3(s,e){const{stopScroll:t,duration:n=300,defaultDirection:i="auto"}=e,r=new Map,o=new Map;let a=null;function c(h,p,g){const v=h.top-p.top,m=p.height/2;return v>m?"up":"down"}function l(){const h=s.value;if(!h){a=null;return}const p=h.getBoundingClientRect(),g=performance.now();let v=!1;for(const[m,y]of r){const _=g-y.startTime;if(!(document.body.contains(h)&&h.contains(y.element))){r.delete(m);continue}const k=y.element.getBoundingClientRect(),w=k.top-p.top,T=k.bottom-p.top;let A=0;y.mode==="up"?A=T-y.initialBottom:A=-(w-y.initialTop);const C=Math.abs(A)>1,E=y.extendOnGrowth&&C&&_>y.duration*.6;if(E&&(y.startTime=g-y.duration*.3),_>=y.duration&&!E){y.phase==="collapse"&&o.delete(m),r.delete(m);continue}v=!0,Math.abs(A)>.5&&(h.scrollTop+=A)}v?a=requestAnimationFrame(l):a=null}function u(h,p,g){const v=s.value;if(!v)return;const m=v.getBoundingClientRect(),y=h.getBoundingClientRect(),_=y.top-m.top,b=y.bottom-m.top;if(b<-50||_>m.height+50)return;const k=(g==null?void 0:g.phase)??"expand",w=(g==null?void 0:g.direction)??i;let T;w!=="auto"?T=w:k==="collapse"&&o.has(p)||k==="expand"&&o.has(p)?T=o.get(p):(T=c(y,m),o.set(p,T));const A=(g==null?void 0:g.extendOnGrowth)??!1;t();const C=r.get(p);r.set(p,{element:h,startTime:performance.now(),duration:(g==null?void 0:g.duration)??n,mode:T,initialTop:_,initialBottom:b,extendOnGrowth:A||(C==null?void 0:C.extendOnGrowth)||!1,phase:k}),a===null&&(a=requestAnimationFrame(l))}function d(){a!==null&&(cancelAnimationFrame(a),a=null),r.clear(),o.clear()}return{anchorBlockElement:u,stopAll:d}}function Y(s){const e=document.createElement("div");return e.textContent=s,e.innerHTML}function xE(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 x3(s){if(s<=0)return S("toolResults.duration.zero");if(s<60)return S("toolResults.duration.seconds",{seconds:s});const e=Math.floor(s/60),t=s%60;if(e<60)return t>0?S("toolResults.duration.minutesSeconds",{minutes:e,seconds:t}):S("toolResults.duration.minutes",{minutes:e});const n=Math.floor(e/60),i=e%60;return i===0&&t===0?S("toolResults.duration.hours",{hours:n}):S("toolResults.duration.hoursMinutesSeconds",{hours:n,minutes:i,seconds:t})}function ds(s,e,t=S("toolResults.status.failedMark")){const n=String((s==null?void 0:s.status)||"").toLowerCase();return n==="awaiting_user_answer"?S("toolResults.status.awaitingUserAnswer"):n==="awaiting_approval"||n==="pending_approval"||n==="pending"?S("toolResults.status.awaitingApproval"):n==="rejected"?S("toolResults.status.rejected"):n==="cancelled"?S("toolResults.status.cancelled"):s!=null&&s.success?e:t}function RE(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>${Y(r)}</pre></div>`:a==="web_search"?I3(r,o,e,t,n):a==="extract_webpage"?P3(r,o):a==="save_webpage"?L3(r,o):a==="create_file"||a==="create_folder"?O3(r,o):a==="write_file"?D3(r,o):a==="edit_file"?N3(r,o):a==="delete_file"?$3(r,o):a==="rename_file"?B3(r,o):a==="read_file"||a==="read_skill"?F3(r,o):a==="create_skill"?e5(r):a==="list_workflows"?t5(r,o):a==="save_workflow"?s5(r,o):a==="vlm_analyze"?H3(r,o):a==="ocr_image"?U3(r,o):a==="view_image"?W3(r,o):a==="terminal_session"?z3(r,o):a==="terminal_input"?j3(r,o):a==="terminal_snapshot"?V3(r,o):a==="sleep"?G3(r,o):a==="run_command"?K3(r,o):a==="update_memory"?q3(r,o):a==="recall_project_memory"?Q3(r,o):a==="search_project_memory"?X3(r,o):a==="update_project_memory"?Y3(r,o):a==="conversation_search"?J3(r,o):a==="conversation_review"?Z3(r,o):a==="ask_user"?o5(r,o):a==="manage_personalization"?a5(r,o):a==="todo_create"?l5(r,o):a==="todo_update_task"?c5(r):a==="trigger_easter_egg"?u5(r,o):a==="create_sub_agent"?d5(r,o):a==="terminate_sub_agent"?h5(r,o):a==="send_message_to_sub_agent"?p5(r,o):a==="answer_sub_agent_question"?m5(r,o):a==="create_custom_agent"?g5(r,o):a==="list_agents"?v5(r):a==="list_active_sub_agents"?y5(r):a==="get_sub_agent_status"?f5(r):R3(r,o,a):""}function R3(s,e,t){const n=ds(s,S("toolResults.status.completed"),S("toolResults.status.failedMark"));let i='<div class="tool-result-meta">';i+=`<div><strong>${Y(S("toolResults.labels.tool"))}</strong>${Y(t)}</div>`,i+=`<div><strong>${Y(S("toolResults.labels.status"))}</strong>${Y(n)}</div>`,["path","file_path","agent_id","target_agent_id","display_name","target_display_name","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:"toolResults.fields.path",file_path:"toolResults.fields.filePath",agent_id:"toolResults.fields.agentId",target_agent_id:"toolResults.fields.targetAgentId",display_name:"toolResults.fields.displayName",target_display_name:"toolResults.fields.targetDisplayName",question:"toolResults.fields.question",role_id:"toolResults.fields.roleId",url:"toolResults.fields.url"},u=typeof c=="string"?c:JSON.stringify(c),d=String(u).slice(0,200),h=String(u).length>200?"…":"",p=S("toolResults.values.colon"),g=l[a]?S(l[a])+p:a+p;i+=`<div><strong>${Y(g)}</strong>${Y(d+h)}</div>`}}),!(s!=null&&s.success)&&(s!=null&&s.error)&&(i+=`<div><strong>${Y(S("toolResults.labels.error"))}</strong>${Y(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>${Y(o.trim())}</pre>`,i+="</div>"):s!=null&&s.success&&(i+='<div class="tool-result-content scrollable">',i+=`<div class="tool-result-empty">${Y(S("toolResults.sentences.emptyResult"))}</div>`,i+="</div>"),i}function I3(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>${Y(S("toolResults.labels.query"))}</strong>${Y(r)}</div>`,l+=`<div><strong>${Y(S("toolResults.labels.topic"))}</strong>${Y(t(o))}</div>`,l+=`<div><strong>${Y(S("toolResults.labels.timeRange"))}</strong>${Y(n(o))}</div>`,l+=`<div><strong>${Y(S("toolResults.labels.domains"))}</strong>${Y(i(o))}</div>`,l+=`<div><strong>${Y(S("toolResults.labels.resultCount"))}</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">${Y(u.title||S("toolResults.values.noTitle"))}</div>`,l+='<div class="search-result-url">',u.url?l+=`<a href="${Y(u.url)}" target="_blank">${Y(u.url)}</a>`:l+=`<span>${Y(S("toolResults.values.noLink"))}</span>`,l+="</div></div>"}),l+="</div>"):l+=`<div class="tool-result-empty">${Y(S("toolResults.sentences.noSearchResults"))}</div>`,l}function P3(s,e){const t=e.url||s.url||"",n=ds(s,S("toolResults.status.successMark")),i=s.content||s.text||"";let r='<div class="tool-result-meta">';return r+=`<div><strong>${Y(S("toolResults.labels.url"))}</strong>${Y(t)}</div>`,r+=`<div><strong>${Y(S("toolResults.labels.status"))}</strong>${n}</div>`,r+="</div>",i&&(r+='<div class="tool-result-content scrollable">',r+=`<pre>${Y(i)}</pre>`,r+="</div>"),r}function L3(s,e){const t=e.url||s.url||"",n=s.path||e.save_path||"",i=ds(s,S("toolResults.status.saved"));let r='<div class="tool-result-meta">';return r+=`<div><strong>${Y(S("toolResults.labels.url"))}</strong>${Y(t)}</div>`,r+=`<div><strong>${Y(S("toolResults.labels.savePath"))}</strong>${Y(n)}</div>`,r+=`<div><strong>${Y(S("toolResults.labels.status"))}</strong>${i}</div>`,r+="</div>",r}function O3(s,e){const t=e.path||s.path||"",n=ds(s,S("toolResults.status.created"));let i='<div class="tool-result-meta">';return i+=`<div><strong>${Y(S("toolResults.labels.path"))}</strong>${Y(t)}</div>`,i+=`<div><strong>${Y(S("toolResults.labels.status"))}</strong>${n}</div>`,i+="</div>",i}function D3(s,e){const t=e.file_path||e.path||s.path||"",n=ds(s,S("toolResults.status.written")),i=typeof e.append=="boolean"?e.append:null,r=String(s.mode||"").toLowerCase(),o=i===!0||r==="a"?S("toolResults.values.append"):i===!1||r==="w"?S("toolResults.values.overwrite"):S("toolResults.values.none"),a=i===!0||r==="a"?e.content||"":s.new_file??e.content??"";let c='<div class="tool-result-meta">';return c+=`<div><strong>${Y(S("toolResults.labels.path"))}</strong>${Y(t)}</div>`,c+=`<div><strong>${Y(S("toolResults.labels.status"))}</strong>${n}</div>`,c+=`<div><strong>${Y(S("toolResults.labels.mode"))}</strong>${o}</div>`,!s.success&&s.error&&(c+=`<div><strong>${Y(S("toolResults.labels.error"))}</strong>${Y(String(s.error))}</div>`),c+="</div>",s.success&&a&&(c+='<div class="tool-result-diff scrollable">',a.split(`
|
||
`).forEach((u,d)=>{c+=`<div class="diff-line diff-add"><span class="diff-line-number">${d+1}</span><span class="diff-marker">+</span><span class="diff-content">${Y(u)}</span></div>`}),c+="</div>"),c}function N3(s,e){const t=e.file_path||e.path||s.path||"",n=ds(s,S("toolResults.status.edited")),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>${Y(S("toolResults.labels.path"))}</strong>${Y(t)}</div>`,a+=`<div><strong>${Y(S("toolResults.labels.status"))}</strong>${n}</div>`,a+=`<div><strong>${Y(S("toolResults.labels.replacementGroups"))}</strong>${Y((s.replacement_groups??o.length)||S("toolResults.values.none"))}</div>`,a+=`<div><strong>${Y(S("toolResults.labels.found"))}</strong>${Y(S("toolResults.counts.foundValue",{n:i??S("toolResults.values.none")}))}</div>`,a+=`<div><strong>${Y(S("toolResults.labels.replaced"))}</strong>${Y(S("toolResults.counts.replacedValue",{n:r??S("toolResults.values.none")}))}</div>`,!s.success&&s.error&&(a+=`<div><strong>${Y(S("toolResults.labels.error"))}</strong>${Y(String(s.error))}</div>`),a+="</div>",!s.success)return a;if(o.length>0){a+='<div class="tool-result-diff scrollable">';const c=(p,g,v,m="")=>{const y=typeof p=="number"&&Number.isFinite(p)?String(p):"";a+=`<div class="diff-line${m?` ${m}`:""}"><span class="diff-line-number">${Y(y)}</span><span class="diff-marker">${Y(g)}</span><span class="diff-content">${Y(v)}</span></div>`},l=[];o.forEach(p=>{const g=p.old_string||"",v=p.new_string||"",m=Array.isArray(p.contexts)?p.contexts:[],y=g?g.split(`
|
||
`):[],_=v?v.split(`
|
||
`):[],b=k=>{var C;const w=[],T=Number((k==null?void 0:k.old_start_line)??((C=p.matched_lines)==null?void 0:C[0])),A=Number.isFinite(T)?T:null;return g&&y.forEach((E,x)=>{w.push({lineNo:A===null?null:A+x,marker:"-",text:E,className:"diff-remove"})}),v&&_.forEach((E,x)=>{w.push({lineNo:A===null?null:A+x,marker:"+",text:E,className:"diff-add"})}),w};if(m.length>0)m.forEach(k=>{var q,V,I;const w=[],T=Array.isArray(k.before_lines)?k.before_lines:[],A=Array.isArray(k.after_lines)?k.after_lines:[],C=T.length>=2&&T.every($=>String(($==null?void 0:$.text)??"")==="")?[]:T.length>=2&&String(((q=T[0])==null?void 0:q.text)??"")===""?T.slice(1):T,E=A.length>=2&&A.every($=>String(($==null?void 0:$.text)??"")==="")?[]:A.length>=2&&String(((V=A[A.length-1])==null?void 0:V.text)??"")===""?A.slice(0,-1):A,x=Number((k==null?void 0:k.old_start_line)??((I=p.matched_lines)==null?void 0:I[0])),D=Number((k==null?void 0:k.old_end_line)??x),N=Number.isFinite(x)&&Number.isFinite(D)?Math.max(1,D-x+1):Math.max(1,g?g.split(`
|
||
`).length:1),G=(v===""?0:v.split(`
|
||
`).length)-N;C.forEach($=>{w.push({lineNo:Number($.line),marker:" ",text:String($.text??""),className:""})}),w.push(...b(k)),E.forEach($=>{const L=Number($.line),K=Number.isFinite(L)?L+G:L;w.push({lineNo:K,marker:" ",text:String($.text??""),className:""})});const Z=w.filter($=>typeof $.lineNo=="number"&&Number.isFinite($.lineNo));l.push({rows:w,minLine:Z.length?Math.min(...Z.map($=>$.lineNo)):null,maxLine:Z.length?Math.max(...Z.map($=>$.lineNo)):null})});else{const k=b(),w=k.filter(T=>typeof T.lineNo=="number"&&Number.isFinite(T.lineNo));l.push({rows:k,minLine:w.length?Math.min(...w.map(T=>T.lineNo)):null,maxLine:w.length?Math.max(...w.map(T=>T.lineNo)):null})}});const u=l.sort((p,g)=>(p.minLine??Number.MAX_SAFE_INTEGER)-(g.minLine??Number.MAX_SAFE_INTEGER)),d=[];u.forEach(p=>{const g=d[d.length-1];g&&p.minLine!==null&&g.maxLine!==null&&p.minLine<=g.maxLine+1?(g.rows.push(...p.rows),g.maxLine=Math.max(g.maxLine,p.maxLine??g.maxLine)):d.push({...p,rows:[...p.rows]})});const h={" ":0,"-":1,"+":2};d.forEach((p,g)=>{g>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,_)=>{const b=y.marker==="-"||y.marker==="+",k=_.marker==="-"||_.marker==="+";return b&&k?(h[y.marker]??9)-(h[_.marker]??9)||(y.lineNo??Number.MAX_SAFE_INTEGER)-(_.lineNo??Number.MAX_SAFE_INTEGER):(y.lineNo??Number.MAX_SAFE_INTEGER)-(_.lineNo??Number.MAX_SAFE_INTEGER)||(h[y.marker]??9)-(h[_.marker]??9)}).forEach(y=>c(y.lineNo,y.marker,y.text,y.className))}),a+="</div>"}return a}function $3(s,e){const t=e.path||s.path||"",n=ds(s,S("toolResults.status.deleted"));let i='<div class="tool-result-meta">';return i+=`<div><strong>${Y(S("toolResults.labels.path"))}</strong>${Y(t)}</div>`,i+=`<div><strong>${Y(S("toolResults.labels.status"))}</strong>${n}</div>`,i+="</div>",i}function B3(s,e){const t=e.old_path||e.source||s.old_path||"",n=e.new_path||e.destination||s.new_path||"",i=ds(s,S("toolResults.status.renamed"));let r='<div class="tool-result-meta">';return r+=`<div><strong>${Y(S("toolResults.labels.path"))}</strong>${Y(t)}</div>`,r+=`<div><strong>${Y(S("toolResults.labels.status"))}</strong>${i}</div>`,r+=`<div><strong>${Y(S("toolResults.labels.rename"))}</strong>${Y(t)} → ${Y(n)}</div>`,r+="</div>",r}function F3(s,e){const t=e.path||s.path||"",n=ds(s,S("toolResults.status.successMark")),i=s.size||s.file_size||0,r=s.type||"read";let o='<div class="tool-result-meta">';if(o+=`<div><strong>${Y(S("toolResults.labels.path"))}</strong>${Y(t)}</div>`,o+=`<div><strong>${Y(S("toolResults.labels.status"))}</strong>${n}</div>`,i>0&&(o+=`<div><strong>${Y(S("toolResults.labels.size"))}</strong>${xE(i)}</div>`),r!=="read"&&(o+=`<div><strong>${Y(S("toolResults.labels.mode"))}</strong>${Y(r)}</div>`),o+="</div>",r==="read"){const a=s.content||s.text||"";a&&(o+='<div class="tool-result-content scrollable">',o+=`<pre>${Y(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>${Y(S("toolResults.labels.searchKeyword"))}</strong>${Y(c)}</div>`,o+=`<div><strong>${Y(S("toolResults.labels.matchCount"))}</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 d=l.line_start===l.line_end?`${l.line_start}`:`${l.line_start}-${l.line_end}`;o+=`<div class="search-match-line">${Y(S("toolResults.values.line",{line:d}))}</div>`,o+=`<pre>${Y(l.snippet||l.content||"")}</pre>`,o+="</div>"}),o+="</div>"):o+=`<div class="tool-result-empty">${Y(S("toolResults.sentences.noMatches"))}</div>`}else if(r==="extract"){const a=s.segments||[];a.length>0?(o+='<div class="tool-result-meta">',o+=`<div><strong>${Y(S("toolResults.labels.segmentCount"))}</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||"?",d=c.end_line||c.line_end||"?";o+=`<div class="segment-range">${Y(S("toolResults.values.line",{line:`${u}-${d}`}))}</div>`,o+=`<pre>${Y(c.content||c.text||"")}</pre>`,o+="</div>"}),o+="</div>"):o+=`<div class="tool-result-empty">${Y(S("toolResults.sentences.noExtractedContent"))}</div>`}return o}function H3(s,e){const t=e.image_path||e.path||s.path||"",n=ds(s,S("toolResults.status.successMark")),i=s.analysis||s.result||"";let r='<div class="tool-result-meta">';return r+=`<div><strong>${Y(S("toolResults.labels.path"))}</strong>${Y(t)}</div>`,r+=`<div><strong>${Y(S("toolResults.labels.status"))}</strong>${n}</div>`,r+="</div>",i&&(r+='<div class="tool-result-content scrollable">',r+=`<div class="content-label">${Y(S("toolResults.labels.analysis"))}</div>`,r+=`<pre>${Y(i)}</pre>`,r+="</div>"),r}function U3(s,e){const t=e.image_path||e.path||s.path||"",n=ds(s,S("toolResults.status.successMark")),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>${Y(S("toolResults.labels.path"))}</strong>${Y(t)}</div>`,a+=`<div><strong>${Y(S("toolResults.labels.status"))}</strong>${n}</div>`,i>0&&(a+=`<div><strong>${Y(S("toolResults.labels.size"))}</strong>${xE(i)}</div>`),a+="</div>",o&&(a+=`<div class="tool-result-image"><img src="${Y(o)}" alt="${Y(S("toolResults.media.ocrImgAlt"))}" style="max-width: 100%; height: auto;" /></div>`),r&&(a+='<div class="tool-result-content scrollable">',a+=`<div class="content-label">${Y(S("toolResults.labels.ocrText"))}</div>`,a+=`<pre>${Y(r)}</pre>`,a+="</div>"),a}function W3(s,e){const t=e.image_path||e.path||s.path||"",n=ds(s,S("toolResults.status.successMark")),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>${Y(S("toolResults.labels.path"))}</strong>${Y(t)}</div>`,o+=`<div><strong>${Y(S("toolResults.labels.status"))}</strong>${n}</div>`,i>0&&(o+=`<div><strong>${Y(S("toolResults.labels.size"))}</strong>${xE(i)}</div>`),o+="</div>",r){const a=Y(r);o+=`<div class="tool-result-image"><img src="${a}" alt="${Y(S("toolResults.media.viewImgAlt"))}" loading="lazy" /></div>`}return o}function z3(s,e){const t=e.operation||e.action||"start",n=e.session_name||e.name||s.session_name||"",i=ds(s,S("toolResults.status.successMark"));let r='<div class="tool-result-meta">';return r+=`<div><strong>${Y(S("toolResults.labels.operation"))}</strong>${Y(t)}</div>`,r+=`<div><strong>${Y(S("toolResults.labels.terminalName"))}</strong>${Y(n)}</div>`,r+=`<div><strong>${Y(S("toolResults.labels.status"))}</strong>${i}</div>`,r+="</div>",r}function j3(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>${Y(S("toolResults.labels.command"))}</strong>${Y(t)}</div>`,r+=`<div><strong>${Y(S("toolResults.labels.waitTime"))}</strong>${Y(S("toolResults.duration.seconds",{seconds:n}))}</div>`,r+="</div>",i&&(r+='<div class="tool-result-content scrollable">',r+=`<div class="content-label">${Y(S("toolResults.labels.output"))}</div>`,r+=`<pre>${Y(i)}</pre>`,r+="</div>"),r}function V3(s,e){const t=e.session_name||e.name||s.session_name||"",n=ds(s,S("toolResults.status.successMark")),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>${Y(S("toolResults.labels.status"))}</strong>${n}</div>`,a+=`<div><strong>${Y(S("toolResults.labels.terminalName"))}</strong>${Y(t)}</div>`,(i||r)&&(a+=`<div><strong>${Y(S("toolResults.labels.lineRange"))}</strong>${i} - ${r}</div>`),a+="</div>",o&&(a+='<div class="tool-result-content scrollable">',a+=`<div class="content-label">${Y(S("toolResults.labels.fetchedContent"))}</div>`,a+=`<pre>${Y(o)}</pre>`,a+="</div>"),a}function G3(s,e){const t=ds(s,S("toolResults.status.completed")),n=(s==null?void 0:s.mode)||"seconds";let i='<div class="tool-result-meta">';if(i+=`<div><strong>${Y(S("toolResults.labels.status"))}</strong>${t}</div>`,i+=`<div><strong>${Y(S("toolResults.labels.mode"))}</strong>${Y(n)}</div>`,n==="seconds"||n===""||n===null){const r=e.seconds||e.duration||0;i+=`<div><strong>${Y(S("toolResults.labels.waitTime"))}</strong>${Y(S("toolResults.duration.seconds",{seconds:r}))}</div>`,e.reason&&(i+=`<div><strong>${Y(S("toolResults.labels.reason"))}</strong>${Y(String(e.reason))}</div>`)}else if(n==="wait_sub_agent_output"){const r=(s==null?void 0:s.display_name)??(e==null?void 0:e.wait_sub_agent_output)??"";r!==""&&(i+=`<div><strong>${Y(S("toolResults.labels.waitSubAgent"))}</strong>${Y(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>${Y(S("toolResults.labels.waitSubAgent"))}</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>${Y(S("toolResults.labels.taskId"))}</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>${Y(S("toolResults.labels.backgroundCommandId"))}</strong>${Y(String(r))}</div>`)}if(!(s!=null&&s.success)&&(s!=null&&s.error)&&(i+=`<div><strong>${Y(S("toolResults.labels.error"))}</strong>${Y(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">${Y(S("toolResults.labels.result"))}</div>`,i+=`<pre>${Y(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">${Y(S("toolResults.labels.subAgentOutput"))}</div>`,i+=`<pre>${Y(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">${Y(S("toolResults.labels.waitedSubAgents",{n: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">';const d=u?S("toolResults.status.successMark"):S("toolResults.status.failedMark");i+=`<div><strong>${Y(S("toolResults.sentences.subAgentResultName",{agentId:String(a)}))}</strong>${Y(S("toolResults.sentences.subAgentResultMeta",{taskId:String(c),status:String(l),outcome:d}))}</div>`;const h=o.message||o.error||"";if(h){const p=o.runtime_seconds??o.elapsed_seconds??null,g=p!==null?S("toolResults.duration.runtimeNote",{n:Math.round(Number(p))}):"",v=o.stats;if(g||v){if(i+='<div class="sub-agent-meta">',g&&(i+=`<span>${Y(g)}</span>`),v&&typeof v=="object"){const m=[];v.api_calls!=null&&m.push(S("toolResults.counts.statApiCalls",{n:v.api_calls})),v.files_read!=null&&m.push(S("toolResults.counts.statFilesRead",{n:v.files_read})),v.edit_files!=null&&m.push(S("toolResults.counts.statEditFiles",{n:v.edit_files})),v.searches!=null&&m.push(S("toolResults.counts.statSearches",{n:v.searches})),v.web_pages!=null&&m.push(S("toolResults.counts.statWebPages",{n:v.web_pages})),v.commands!=null&&m.push(S("toolResults.counts.statCommands",{n:v.commands})),m.length>0&&(i+=`<span>${Y(m.join(" | "))}</span>`)}i+="</div>"}i+=`<pre>${Y(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">${Y(S("toolResults.labels.backgroundCommandOutput"))}</div>`,a!==void 0&&(i+=`<div><strong>${Y(S("toolResults.labels.exitCode"))}</strong>${Y(String(a))}</div>`),o?i+=`<pre>${Y(String(o))}</pre>`:i+=`<div class="tool-result-empty">${Y(S("toolResults.sentences.noOutput"))}</div>`,i+="</div>"}}return i}function K3(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>${Y(S("toolResults.labels.command"))}</strong>${Y(t)}</div>`,o+=`<div><strong>${Y(S("toolResults.labels.timeout"))}</strong>${Y(S("toolResults.duration.seconds",{seconds:n}))}</div>`,r!==void 0&&(o+=`<div><strong>${Y(S("toolResults.labels.exitCode"))}</strong>${r}</div>`),o+="</div>",i&&(o+='<div class="tool-result-content scrollable">',o+=`<div class="content-label">${Y(S("toolResults.labels.output"))}</div>`,o+=`<pre>${Y(i)}</pre>`,o+="</div>"),o}function q3(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>${Y(S("toolResults.sentences.memoryAdd"))}</div>`,o+=`<div>${r}. ${Y(n)}</div>`):t==="replace"?(o+=`<div>${Y(S("toolResults.sentences.memoryUpdate"))}</div>`,o+=`<div>${i}. ${Y(n)}</div>`):t==="delete"&&(o+=`<div>${Y(S("toolResults.sentences.memoryDelete"))}</div>`,o+=`<div>${i}. ${Y(n||S("toolResults.values.deleted"))}</div>`),o+="</div>",o}function Q3(s,e){const t=e.name||s.memory_name||"",n=ds(s,S("toolResults.status.read")),i=s.content||s.text||"";let r='<div class="tool-result-meta">';return r+=`<div><strong>${Y(S("toolResults.labels.status"))}</strong>${n}</div>`,r+=`<div><strong>${Y(S("toolResults.labels.memory"))}</strong>${Y(t)}</div>`,r+="</div>",s.success&&i?(r+='<div class="tool-result-content scrollable">',r+=`<pre>${Y(i)}</pre>`,r+="</div>"):!s.success&&s.error&&(r+=`<div class="tool-result-error">${Y(String(s.error))}</div>`),r}function X3(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=ds(s,S("toolResults.status.completed"));let r='<div class="tool-result-meta">';return r+=`<div><strong>${Y(S("toolResults.labels.keywords"))}</strong>${Y(t.join(" / ")||S("toolResults.values.notSpecified"))}</div>`,r+=`<div><strong>${Y(S("toolResults.labels.status"))}</strong>${i}</div>`,r+=`<div>${Y(S("toolResults.counts.memoryHits",{n:n.length}))}</div>`,!(s!=null&&s.success)&&(s!=null&&s.error)&&(r+=`<div><strong>${Y(S("toolResults.labels.error"))}</strong>${Y(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">${Y(o.name||o.file||"")}</div>`,o.description&&(r+=`<div><strong>${Y(S("toolResults.labels.description"))}</strong>${Y(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=Y(l);r+=`<div class="search-match-snippet" title="${u.replace(/"/g,""")}">${u}</div>`}),r+="</div>"),r+="</div>"}),r+="</div>",r):(s!=null&&s.success&&(r+=`<div class="tool-result-empty">${Y(S("toolResults.sentences.noMatchesMemory"))}</div>`),r)}function Y3(s,e){const t=e.name||s.memory_name||"",n=e.description||"",i=e.content||"",r=ds(s,S("toolResults.status.updated"));let o='<div class="tool-result-meta">';return o+=`<div><strong>${Y(S("toolResults.labels.status"))}</strong>${r}</div>`,o+=`<div><strong>${Y(S("toolResults.labels.memory"))}</strong>${Y(t)}</div>`,n&&(o+=`<div><strong>${Y(S("toolResults.labels.description"))}</strong>${Y(n)}</div>`),!s.success&&s.error&&(o+=`<div><strong>${Y(S("toolResults.labels.error"))}</strong>${Y(String(s.error))}</div>`),o+="</div>",s.success&&i&&(o+='<div class="tool-result-content scrollable">',o+=`<div class="content-label">${Y(S("toolResults.labels.memoryContent"))}</div>`,o+=`<pre>${Y(i)}</pre>`,o+="</div>"),o}function J3(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)||S("toolResults.values.notSpecified");let r='<div class="tool-result-meta">';return r+=`<div><strong>${Y(S("toolResults.labels.keywords"))}</strong>${Y(i)}</div>`,r+=`<div><strong>${Y(S("toolResults.labels.dateRange"))}</strong>${Y((s==null?void 0:s.start_date)||(e==null?void 0:e.start_date)||S("toolResults.values.unlimited"))} ~ ${Y((s==null?void 0:s.end_date)||(e==null?void 0:e.end_date)||S("toolResults.values.unlimited"))}</div>`,r+=`<div><strong>${Y(S("toolResults.labels.scope"))}</strong>${Y(S("toolResults.sentences.conversationScope"))}</div>`,r+=`<div><strong>${Y(S("toolResults.labels.resultCount"))}</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">${Y(o.title||S("toolResults.values.unnamedConversation"))}</div>`,r+=`<div><strong>${Y(S("toolResults.labels.id"))}</strong>${Y(o.id||"")}</div>`,r+=`<div>${Y(S("toolResults.counts.conversationScale",{n:String(o.total_messages||0),m:String(o.total_tools||0)}))}</div>`,o.first_user_message&&(r+=`<div><strong>${Y(S("toolResults.labels.firstUserMessage"))}</strong>${Y(o.first_user_message)}</div>`),o.updated_at&&(r+=`<div><strong>${Y(S("toolResults.labels.updatedAt"))}</strong>${Y(o.updated_at)}</div>`),r+="</div>"}),r+="</div>",r):(r+=`<div class="tool-result-empty">${Y(S("toolResults.sentences.noMatchesConversation"))}</div>`,r)}function Z3(s,e){const t=ds(s,(s==null?void 0:s.mode)==="read"?S("toolResults.status.returned"):S("toolResults.status.generated"));let n='<div class="tool-result-meta">';return n+=`<div><strong>${Y(S("toolResults.labels.conversationId"))}</strong>${Y((s==null?void 0:s.conversation_id)||(e==null?void 0:e.conversation_id)||"")}</div>`,n+=`<div><strong>${Y(S("toolResults.labels.status"))}</strong>${t}</div>`,n+=`<div><strong>${Y(S("toolResults.labels.mode"))}</strong>${Y((s==null?void 0:s.mode)||(e==null?void 0:e.mode)||"")}</div>`,s!=null&&s.title&&(n+=`<div><strong>${Y(S("toolResults.labels.title"))}</strong>${Y(s.title)}</div>`),s!=null&&s.path&&(n+=`<div><strong>${Y(S("toolResults.labels.reviewFile"))}</strong>${Y(s.path)}</div>`),(s==null?void 0:s.char_count)!==void 0&&(n+=`<div><strong>${Y(S("toolResults.labels.charCount"))}</strong>${Y(String(s.char_count))}</div>`),n+="</div>",!(s!=null&&s.success)&&(s!=null&&s.error)&&(n+=`<div class="tool-result-error">${Y(s.error)}</div>`),s!=null&&s.too_long&&(s!=null&&s.path)&&(n+=`<div class="tool-result-warning">${Y(S("toolResults.sentences.tooLongSaved"))}</div>`),s!=null&&s.content&&(n+='<div class="tool-result-content scrollable">',n+=`<div class="content-label">${Y(S("toolResults.labels.reviewContent"))}</div>`,n+=`<pre>${Y(s.content)}</pre>`,n+="</div>"),n}function e5(s){const e=ds(s,S("toolResults.status.archived"));let t='<div class="tool-result-meta">';return t+=`<div><strong>${Y(S("toolResults.labels.status"))}</strong>${e}</div>`,s!=null&&s.skill_name&&(t+=`<div><strong>${Y(S("toolResults.labels.skill"))}</strong>${Y(s.skill_name)}</div>`),t+="</div>",!(s!=null&&s.success)&&(s!=null&&s.error)&&(t+=`<div class="tool-result-error">${Y(s.error)}</div>`),s!=null&&s.sync_warning&&(t+=`<div class="tool-result-warning">${Y(s.sync_warning)}</div>`),t}function t5(s,e){if(!(s!=null&&s.success)){const r=(s==null?void 0:s.error)??S("toolResults.sentences.queryFailed");return`<div class="tool-result-error">⚠️ ${Y(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>${Y(S("toolResults.labels.workflow"))}</strong>${Y(t)}</div>`,r+="</div>";const o=String((s==null?void 0:s.message)||"");return o&&(r+='<div class="tool-result-content scrollable">',r+=`<pre>${Y(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">${Y(S("toolResults.sentences.noWorkflows"))}</div>`;let i='<div class="tool-result-meta">';return i+=`<div><strong>${Y(S("toolResults.labels.workflowCount"))}</strong>${n.length}</div>`,i+="</div>",i+='<div class="search-result-list">',n.forEach(r=>{const o=Y(String((r==null?void 0:r.name)||S("toolResults.values.unnamed"))),a=Y(String((r==null?void 0:r.description)||S("toolResults.values.noDescription"))),c=(r==null?void 0:r.source)==="builtin"?S("toolResults.values.builtin"):S("toolResults.values.user"),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>${Y(S("toolResults.labels.source"))}</strong>${c} | <strong>${Y(S("toolResults.labels.nodeCount"))}</strong>${l}</div>`,i+="</div>"}),i+="</div>",i}function s5(s,e){const t=ds(s,S("toolResults.status.archived"));let n='<div class="tool-result-meta">';n+=`<div><strong>${Y(S("toolResults.labels.status"))}</strong>${t}</div>`;const i=String((e==null?void 0:e.source_dir)||"");return i&&(n+=`<div><strong>${Y(S("toolResults.labels.sourceDir"))}</strong>${Y(i)}</div>`),s!=null&&s.workflow_name&&(n+=`<div><strong>${Y(S("toolResults.labels.workflow"))}</strong>${Y(String(s.workflow_name))}</div>`),s!=null&&s.success&&typeof(s==null?void 0:s.node_count)=="number"&&(n+=`<div><strong>${Y(S("toolResults.labels.nodeCountTotal"))}</strong>${s.node_count}</div>`),s!=null&&s.success&&(s!=null&&s.overwritten)?n+=`<div><strong>${Y(S("toolResults.labels.mode"))}</strong>${Y(S("toolResults.sentences.overwrittenVersion"))}</div>`:s!=null&&s.success&&(s!=null&&s.shadows_builtin)&&(n+=`<div><strong>${Y(S("toolResults.labels.mode"))}</strong>${Y(S("toolResults.sentences.userCopyShadow"))}</div>`),n+="</div>",!(s!=null&&s.success)&&(s!=null&&s.error)&&(n+=`<div class="tool-result-error">${Y(String(s.error))}</div>`),s!=null&&s.success&&(s!=null&&s.summary)&&(n+='<div class="tool-result-content">',n+=Y(String(s.summary)),n+="</div>"),n}const n5={self_identify:"toolResults.personalization.fieldLabels.selfIdentify",user_name:"toolResults.personalization.fieldLabels.userName",profession:"toolResults.personalization.fieldLabels.profession",tone:"toolResults.personalization.fieldLabels.tone",considerations:"toolResults.personalization.fieldLabels.considerations",theme:"toolResults.personalization.fieldLabels.theme",communication_style:"toolResults.personalization.fieldLabels.communicationStyle",conversation_continuity:"toolResults.personalization.fieldLabels.conversationContinuity",enabled:"toolResults.personalization.fieldLabels.enabled"};function i5(s){const e=n5[s];return e?S(e):s}function r5(s,e){return e==null||e===""?S("common.unset"):s==="enabled"?e?S("toolResults.personalization.values.enabled"):S("toolResults.personalization.values.disabled"):s==="considerations"?typeof e!="string"||e.trim()===""?S("common.unset"):e.trim():s==="communication_style"?{default:S("toolResults.personalization.values.styleDefault"),human_like:S("toolResults.personalization.values.styleHumanLike"),auto:S("toolResults.personalization.values.styleAuto")}[String(e)]||String(e):s==="conversation_continuity"&&{low:S("toolResults.personalization.values.independenceLow"),medium:S("toolResults.personalization.values.independenceMedium"),high:S("toolResults.personalization.values.independenceHigh")}[String(e)]||String(e)}function o5(s,e){const t=e.question||s.question||"",n=e.context||s.context||"",i=ds(s,S("toolResults.status.answered")),r=s.status==="answered"?String(s.answer_text||s.message||"").trim():"";let o='<div class="tool-result-meta">';o+=`<div><strong>${Y(S("toolResults.labels.status"))}</strong>${Y(i)}</div>`,t&&(o+=`<div><strong>${Y(S("toolResults.labels.question"))}</strong>${Y(String(t))}</div>`),n&&(o+=`<div><strong>${Y(S("toolResults.labels.context"))}</strong>${Y(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>${Y(S("toolResults.labels.providedOptions"))}</strong></div>`,a.forEach((c,l)=>{const u=String((c==null?void 0:c.label)||(c==null?void 0:c.id)||S("toolResults.values.optionLabel",{n:l+1})),d=String((c==null?void 0:c.description)||"").trim();o+=`<div>${l+1}. ${Y(u)}${d?` — ${Y(d)}`:""}</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),d=c.slice(l+1);o+=`<div><strong>${Y(u)}</strong>${Y(d)}</div>`}else o+=`<div><strong>${Y(S("toolResults.labels.userAnswer"))}</strong>${Y(c)}</div>`}),o+="</div></div>"),o}function a5(s,e){const t=String(e.action||s.action||"read"),n=ds(s,t==="update"?S("toolResults.status.updated"):S("toolResults.status.read")),i=String(s.updated_field||e.field||""),r=s.updated_value??e.value;let o='<div class="tool-result-meta">';return o+=`<div><strong>${Y(S("toolResults.labels.operation"))}</strong>${Y(t==="update"?S("toolResults.personalization.actionUpdate"):S("toolResults.personalization.actionRead"))}</div>`,o+=`<div><strong>${Y(S("toolResults.labels.status"))}</strong>${n}</div>`,s!=null&&s.success?(t==="update"&&i&&(o+=`<div><strong>${Y(S("toolResults.labels.updatedField"))}</strong>${Y(i5(i))}</div>`,o+=`<div><strong>${Y(S("toolResults.labels.updatedValue"))}</strong>${Y(r5(i,r))}</div>`),o+="</div>",o):(s!=null&&s.error&&(o+=`<div><strong>${Y(S("toolResults.labels.error"))}</strong>${Y(String(s.error))}</div>`),Array.isArray(s==null?void 0:s.validation_errors)&&s.validation_errors.length>0&&(o+=`<div><strong>${Y(S("toolResults.labels.validation"))}</strong>${Y(s.validation_errors.join(";"))}</div>`),o+="</div>",o)}function l5(s,e){const t=ds(s,S("toolResults.status.created")),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>${Y(S("toolResults.labels.status"))}</strong>${t}</div>`,o+=`<div><strong>${Y(S("toolResults.labels.title"))}</strong>${Y(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 /> ${Y(c)}</div>`}),o+="</div>",o+="</div>"),o}function c5(s){const e=ds(s,S("toolResults.status.updated")),t=s.todo_list||{},n=t.title||"",i=t.tasks||[];let r='<div class="tool-result-meta">';return r+=`<div><strong>${Y(S("toolResults.labels.status"))}</strong>${e}</div>`,r+=`<div><strong>${Y(S("toolResults.labels.title"))}</strong>${Y(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 /> ${Y(a)}</div>`}),r+="</div>",r+="</div>"),r}function u5(s,e){const t=ds(s,S("toolResults.status.triggered")),n=s.type||e.type||"",i=s.content||s.message||"";let r='<div class="tool-result-meta">';return r+=`<div><strong>${Y(S("toolResults.labels.status"))}</strong>${t}</div>`,r+=`<div><strong>${Y(S("toolResults.labels.type"))}</strong>${Y(n)}</div>`,r+="</div>",i&&(r+='<div class="tool-result-content">',r+=`<div class="easter-egg-content">${Y(i)}</div>`,r+="</div>"),r}function d5(s,e){const t=ds(s,S("toolResults.status.created"),S("toolResults.status.createFailed")),n=s.agent_id??e.agent_id??"",i=s.display_name??"",r=s.task_id??"",o=s.deliverables_dir??"",a=e.task??"",c=s.message??s.summary??"",l=s.stats||{},u=s.runtime_seconds??s.elapsed_seconds??l.runtime_seconds??0,d=l.api_calls??l.turn_count??0,h=(l.files_read||0)+(l.write_files||0)+(l.edit_files||0)+(l.searches||0)+(l.web_pages||0)+(l.commands||0),p=u>0||d>0||h>0;let g='<div class="tool-result-meta">';if(g+=`<div><strong>${Y(S("toolResults.labels.status"))}</strong>${t}</div>`,i?g+=`<div><strong>${Y(S("toolResults.labels.subAgent"))}</strong>${Y(String(i))}</div>`:n!==""&&(g+=`<div><strong>${Y(S("toolResults.labels.subAgentId"))}</strong>${Y(String(n))}</div>`),r!==""&&!i&&(g+=`<div><strong>${Y(S("toolResults.labels.taskId"))}</strong>${Y(String(r))}</div>`),o!==""&&!i&&(g+=`<div><strong>${Y(S("toolResults.labels.deliverablesDir"))}</strong>${Y(String(o))}</div>`),a){const v=String(a).slice(0,200),m=String(a).length>200?"…":"";g+=`<div><strong>${Y(S("toolResults.labels.task"))}</strong>${Y(v+m)}</div>`}return g+="</div>",(c||p)&&(g+='<div class="tool-result-content scrollable">',p&&(g+=`<div class="content-label">${Y(S("toolResults.sectionLabels.executionStats"))}</div>`,u>0&&(g+=`<div><strong>${Y(S("toolResults.labels.workTime"))}</strong>${x3(u)}</div>`),d>0&&(g+=`<div>${Y(S("toolResults.counts.apiCalls",{n:d}))}</div>`),h>0&&(g+=`<div>${Y(S("toolResults.counts.toolCalls",{n:h}))}</div>`)),c&&(p&&(g+=`<div class="content-label">${Y(S("toolResults.sectionLabels.finalReply"))}</div>`),g+=`<div>${Y(String(c))}</div>`),g+="</div>"),g}function h5(s,e){const t=ds(s,S("toolResults.status.closed"),S("toolResults.status.closeFailed")),n=s.display_name??e.display_name??"",i=s.agent_id??e.agent_id??"",r=s.task_id??"",o=s.message??s.system_message??"";let a='<div class="tool-result-meta">';return a+=`<div><strong>${Y(S("toolResults.labels.status"))}</strong>${t}</div>`,n?a+=`<div><strong>${Y(S("toolResults.labels.subAgent"))}</strong>${Y(String(n))}</div>`:i!==""&&(a+=`<div><strong>${Y(S("toolResults.labels.subAgentId"))}</strong>${Y(String(i))}</div>`),r!==""&&!n&&(a+=`<div><strong>${Y(S("toolResults.labels.taskId"))}</strong>${Y(String(r))}</div>`),a+="</div>",o&&(a+='<div class="tool-result-content scrollable">',a+=`<div>${Y(String(o))}</div>`,a+="</div>"),a}function f5(s){if(!s.success){const n=s.error??S("toolResults.sentences.queryFailed");return`<div class="tool-result-error">⚠️ ${Y(String(n))}</div>`}const e=Array.isArray(s.results)?s.results:[];if(e.length===0)return`<div class="tool-result-empty">${Y(S("toolResults.sentences.noSubAgentStatus"))}</div>`;let t='<div class="sub-agent-status-list">';return e.forEach(n=>{var d,h;const i=n.agent_id??"",r=n.found!==!1,o=String(n.status||""),a=n.task_id??"",c=n.summary??((d=n.final_result)==null?void 0:d.message)??((h=n.final_result)==null?void 0:h.summary)??"";t+='<div class="sub-agent-status-item">';const l=n.display_name||"",u=l||S("toolResults.sentences.subAgentResultName",{agentId:String(i)});t+=`<div class="sub-agent-status-header">${Y(String(u))}</div>`,r?(t+='<div class="tool-result-meta">',o==="completed"?t+=`<div><strong>${Y(S("toolResults.labels.status"))}</strong>${Y(S("toolResults.status.done"))}</div>`:o==="terminated"?t+=`<div><strong>${Y(S("toolResults.labels.status"))}</strong>${Y(S("toolResults.status.terminated"))}</div>`:o==="running"?t+=`<div><strong>${Y(S("toolResults.labels.status"))}</strong>${Y(S("common.running"))}</div>`:o==="pending"?t+=`<div><strong>${Y(S("toolResults.labels.status"))}</strong>${Y(S("toolResults.status.waiting"))}</div>`:t+=`<div><strong>${Y(S("toolResults.labels.status"))}</strong>${Y(o||S("toolResults.values.unknown"))}</div>`,a!==""&&!l&&(t+=`<div><strong>${Y(S("toolResults.labels.taskId"))}</strong>${Y(String(a))}</div>`),t+="</div>",c&&(t+='<div class="tool-result-content scrollable">',t+=`<div>${Y(String(c))}</div>`,t+="</div>")):(t+='<div class="tool-result-meta">',t+=`<div><strong>${Y(S("toolResults.labels.status"))}</strong>${Y(S("toolResults.status.notFound"))}</div>`,t+="</div>"),t+="</div>"}),t+="</div>",t}function p5(s,e){const t=ds(s,S("toolResults.status.sent"),S("toolResults.status.sendFailed")),n=e.display_name??s.display_name??"",i=e.agent_id??s.agent_id??"";let r='<div class="tool-result-meta">';return r+=`<div><strong>${Y(S("toolResults.labels.status"))}</strong>${t}</div>`,n?r+=`<div><strong>${Y(S("toolResults.labels.subAgent"))}</strong>${Y(String(n))}</div>`:i!==""&&(r+=`<div><strong>${Y(S("toolResults.labels.subAgentId"))}</strong>${Y(String(i))}</div>`),!(s!=null&&s.success)&&(s!=null&&s.error)&&(r+=`<div><strong>${Y(S("toolResults.labels.error"))}</strong>${Y(String(s.error))}</div>`),r+="</div>",r}function m5(s,e){const t=ds(s,S("toolResults.status.replied"),S("toolResults.status.replyFailed")),n=e.question_id??s.question_id??"",i=e.answer??"";let r='<div class="tool-result-meta">';if(r+=`<div><strong>${Y(S("toolResults.labels.status"))}</strong>${t}</div>`,n&&(r+=`<div><strong>${Y(S("toolResults.labels.questionId"))}</strong>${Y(String(n))}</div>`),!(s!=null&&s.success)&&(s!=null&&s.error)&&(r+=`<div><strong>${Y(S("toolResults.labels.error"))}</strong>${Y(String(s.error))}</div>`),r+="</div>",i&&typeof i=="string"){r+='<div class="tool-result-content scrollable">',r+=`<div class="content-label">${Y(S("toolResults.sectionLabels.replyContent"))}</div>`;const o=String(i).slice(0,500),a=String(i).length>500?"…":"";r+=`<pre>${Y(o+a)}</pre>`,r+="</div>"}return r}function g5(s,e){const t=!!(s!=null&&s.overwritten),n=s!=null&&s.success?t?S("toolResults.status.overwrittenUpdated"):S("toolResults.status.created"):S("toolResults.status.createFailed"),i=e.role_id??s.role_id??"",r=e.name??s.name??i;let o='<div class="tool-result-meta">';return o+=`<div><strong>${Y(S("toolResults.labels.status"))}</strong>${n}</div>`,i!==""&&(o+=`<div><strong>${Y(S("toolResults.labels.roleId"))}</strong>${Y(String(i))}</div>`),r&&r!==i&&(o+=`<div><strong>${Y(S("toolResults.labels.roleName"))}</strong>${Y(String(r))}</div>`),!(s!=null&&s.success)&&(s!=null&&s.error)&&(o+=`<div><strong>${Y(S("toolResults.labels.error"))}</strong>${Y(String(s.error))}</div>`),o+="</div>",o}function v5(s){if(!(s!=null&&s.success)){const n=(s==null?void 0:s.error)??S("toolResults.sentences.queryFailed");return`<div class="tool-result-error">⚠️ ${Y(String(n))}</div>`}const e=Array.isArray(s.roles)?s.roles:[];if(e.length===0)return`<div class="tool-result-empty">${Y(S("toolResults.sentences.noRoles"))}</div>`;let t='<div class="tool-result-meta">';return t+=`<div><strong>${Y(S("toolResults.labels.roleCount"))}</strong>${e.length}</div>`,t+="</div>",t+='<div class="search-result-list">',e.forEach(n=>{const i=n.role_id||S("toolResults.values.unknown"),r=n.name||i,o=n.description||"",a=n.thinking_mode||"fast",c=n.is_custom?S("toolResults.values.yes"):S("toolResults.values.no");t+='<div class="search-result-item">',t+=`<div class="search-result-title">${Y(i)} — ${Y(r)}</div>`,o&&(t+=`<div>${Y(o)}</div>`),t+=`<div><strong>${Y(S("toolResults.labels.thinkingMode"))}</strong>${Y(a)} | <strong>${Y(S("toolResults.labels.custom"))}</strong>${Y(c)}</div>`,t+="</div>"}),t+="</div>",t}function y5(s){if(!(s!=null&&s.success)){const n=(s==null?void 0:s.error)??S("toolResults.sentences.queryFailed");return`<div class="tool-result-error">⚠️ ${Y(String(n))}</div>`}const e=Array.isArray(s.agents)?s.agents:[];if(e.length===0)return`<div class="tool-result-empty">${Y(S("toolResults.sentences.noActiveSubAgents"))}</div>`;let t='<div class="tool-result-meta">';return t+=`<div><strong>${Y(S("toolResults.labels.activeCount"))}</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">${Y(r)} [${Y(o)}]</div>`,t+='<div class="tool-result-meta">',a&&(t+=`<div><strong>${Y(S("toolResults.labels.task"))}</strong>${Y(String(a))}</div>`),c){const l=String(c).slice(0,120),u=String(c).length>120?"…":"";t+=`<div><strong>${Y(S("toolResults.labels.lastOutput"))}</strong>${Y(l+u)}</div>`}t+="</div>",t+="</div>"}),t+="</div>",t}const b5=["data-block-id"],_5={class:"status-icon"},w5={class:"status-text"},S5={class:"tool-desc"},k5={class:"content-inner"},C5=["innerHTML"],T5={key:0,class:"progress-indicator"},cx=ct({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 RE(e.action,e.formatSearchTopic,e.formatSearchTime,e.formatSearchDomains)}return(n,i)=>(F(),U("div",{class:Ce(["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"},[M("div",{class:"collapsible-header",onClick:i[0]||(i[0]=r=>n.$emit("toggle"))},[i[1]||(i[1]=M("div",{class:"arrow"},null,-1)),M("div",_5,[M("span",{class:Ce(["tool-icon icon icon-md",s.getToolAnimationClass(s.action.tool)]),style:qe(s.iconStyle(s.getToolIcon(s.action.tool))),"aria-hidden":"true"},null,6)]),M("span",w5,Q(s.getToolStatusText(s.action.tool)),1),M("span",S5,Q(s.getToolDescription(s.action.tool)),1)]),M("div",{class:"collapsible-content",ref:r=>s.registerCollapseContent&&s.registerCollapseContent(s.collapseKey||s.action.tool.id||s.action.id||"tool",r)},[M("div",k5,[M("div",{innerHTML:t()},null,8,C5)])],512),s.action.tool.status==="preparing"||s.action.tool.status==="running"?(F(),U("div",T5)):me("",!0)],10,b5))}}),A5="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",E5=["alt"],M5={class:"more-copy"},x5={class:"more-title"},R5={class:"more-desc"},I5=["data-block-id"],P5=["onClick"],L5={class:"status-icon"},O5={class:"status-text"},D5=["onScroll"],N5=["data-block-id"],$5=["onClick"],B5={class:"status-icon"},F5={class:"status-text"},H5={class:"tool-desc"},U5={class:"content-inner"},W5=["innerHTML"],z5={key:0,class:"progress-indicator"},uC=6,j5=600,V5=36,G5=ct({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=Js(),a=be(()=>o.form.stacked_hide_borders),c=J=>RE(J,t.formatSearchTopic,t.formatSearchTime,t.formatSearchDomains),l=ge(null),u=ge(null),d=ge(null),h=ge(!1),p=ge(0),g=ge(0),v=ge(0),m=ge(0),y=ge(!1),_=ge({}),b=new Map,k=be(()=>(t.actions||[]).filter(J=>J&&(J.type==="thinking"||J.type==="tool"))),w=be(()=>Math.max(0,k.value.length-uC)),T=be(()=>w.value>0||h.value),A=be(()=>k.value.length===1),C=be(()=>!!t.conversationRunning&&!!t.isLatestMessage),E=be(()=>k.value.length),x=be(()=>(lt.value,h.value?S("chat.allExpanded"):S("chat.more"))),D=be(()=>(lt.value,h.value?S("chat.stepsTotal",{n:E.value}):S("chat.stepsHidden",{n:w.value}))),N=(J,ne)=>(J==null?void 0:J.blockId)||(J==null?void 0:J.id)||`stacked-${ne}`,O=(J,ne)=>{var ce;return(ce=t.expandedBlocks)==null?void 0:ce.has(N(J,ne))},G=J=>{var ne;return(ne=t.expandedBlocks)==null?void 0:ne.has(J)},Z=J=>{const ne=Math.max(0,_.value[J]||0);return{maxHeight:G(J)?`${ne}px`:"0px"}},q=J=>{var ce;const ne=(ce=J==null?void 0:J.tool)==null?void 0:ce.status;return ne==="preparing"||ne==="running"},V=J=>{var ne;return((ne=J==null?void 0:J.tool)==null?void 0:ne.status)==="completed"},I=()=>{h.value=!h.value,le();const J=d.value;J instanceof HTMLElement&&n("more-toggle",{element:J,expanded:h.value,stackKey:r})},$=J=>{typeof t.toggleBlock=="function"&&(t.toggleBlock(J),le())},L=(J,ne)=>{ne instanceof HTMLElement?b.set(J,ne):b.delete(J),typeof t.registerThinkingRef=="function"&&t.registerThinkingRef(J,ne)},K=(J,ne)=>{typeof t.handleThinkingScroll=="function"&&t.handleThinkingScroll(J,ne)},se=J=>J?J instanceof HTMLElement?J:J.$el&&J.$el instanceof HTMLElement?J.$el:null:null,oe=()=>{const J=se(d.value);if(!J)return 56;const ne=J.querySelector(".more-title");return Math.max(48,Math.ceil((ne==null?void 0:ne.getBoundingClientRect().height)||56))},ve=()=>{const J=se(u.value);if(!se(l.value)||!J)return;const ce=Array.from(J.children),_e=k.value,Pe=[],it={};ce.forEach((he,ye)=>{const ke=_e[ye],Le=N(ke,ye),st=he.querySelector(".collapsible-header"),gt=he.querySelector(".content-inner"),Wt=st?Math.ceil(st.offsetHeight):V5,jt=gt?Math.min(Math.ceil(gt.offsetHeight),j5):0;it[Le]=jt;const ht=G(Le),Qt=a.value||ye===ce.length-1?0:1;Pe.push(Wt+(ht?jt:0)+Qt)}),_.value=it;const at=he=>he.length?he.reduce((ye,ke)=>ye+ke,0):0,rt=at(Pe),Oe=at(Pe.slice(0,Math.max(0,Pe.length-uC))),xe=at(Pe.slice(-uC));g.value=T.value?oe():0;const pe=g.value+(h.value||!T.value?rt:xe);p.value=pe+2,v.value=h.value||!T.value?0:-Oe,m.value=Math.max(0,pe-g.value)},le=()=>{ft(()=>{requestAnimationFrame(()=>{ve(),y.value||requestAnimationFrame(()=>{y.value=!0})})})};let ue=null,P=null;const X=()=>{ue&&(ue.disconnect(),b.forEach(J=>ue.observe(J)))};return dn(()=>{le(),typeof ResizeObserver<"u"&&(ue=new ResizeObserver(()=>{P&&cancelAnimationFrame(P),P=requestAnimationFrame(()=>ve())}),ft(()=>X()))}),Rn(()=>{ue&&(ue.disconnect(),ue=null),P&&(cancelAnimationFrame(P),P=null)}),Ke(()=>{var Pe,it,at,rt;const J=k.value,ne=((Pe=J[0])==null?void 0:Pe.blockId)||((it=J[0])==null?void 0:it.id)||"",ce=((at=J[J.length-1])==null?void 0:at.blockId)||((rt=J[J.length-1])==null?void 0:rt.id)||"",_e=J.map(Oe=>{var xe,pe,he;return(Oe==null?void 0:Oe.type)==="tool"?`T:${((xe=Oe==null?void 0:Oe.tool)==null?void 0:xe.status)||"?"}${(pe=Oe==null?void 0:Oe.tool)!=null&&pe.result?"R":"-"}`:(Oe==null?void 0:Oe.type)==="thinking"?`H:${Oe!=null&&Oe.streaming?"S":"-"}${Math.floor((((he=Oe==null?void 0:Oe.content)==null?void 0:he.length)||0)/48)}`:"?"}).join(",");return`${J.length}|${ne}|${ce}|${T.value}|${_e}`},()=>{ft(()=>{X(),le()})}),Ke(()=>t.expandedBlocks?t.expandedBlocks.size:0,()=>le()),Ke(a,()=>le()),(J,ne)=>(F(),U("div",{class:Ce(["stacked-shell",{"stacked-shell--single":A.value,"stacked-shell--not-ready":!y.value,"stacked-shell--no-borders":a.value}]),ref_key:"shell",ref:l,style:qe({height:`${p.value}px`,paddingTop:T.value?`${g.value}px`:"0px"})},[M("div",{class:Ce(["stacked-more-block",{visible:T.value}]),ref_key:"moreBlock",ref:d,style:qe({height:`${T.value?g.value:0}px`}),onClick:I},[M("img",{class:"more-icon",src:A5,alt:J.$t("chat.expand")},null,8,E5),M("div",M5,[M("span",x5,Q(x.value),1),M("span",R5,Q(D.value),1)])],6),M("div",{class:"stacked-viewport",style:qe({height:`${m.value}px`})},[We(ay,{name:"stacked",tag:"div",class:"stacked-inner",ref_key:"inner",ref:u,style:qe({transform:`translateY(${v.value}px)`}),appear:C.value,css:C.value},{default:Gt(()=>[(F(!0),U(Ie,null,Ze(k.value,(ce,_e)=>(F(),U("div",{key:N(ce,_e),class:"stacked-item"},[ce.type==="thinking"?(F(),U("div",{key:0,class:Ce(["collapsible-block thinking-block stacked-block",{expanded:O(ce,_e),processing:ce.streaming}]),"data-block-id":N(ce,_e)},[M("div",{class:"collapsible-header",onClick:Pe=>$(N(ce,_e))},[ne[0]||(ne[0]=M("div",{class:"arrow"},null,-1)),M("div",L5,[M("span",{class:Ce(["thinking-icon",{"thinking-animation":ce.streaming}])},[M("span",{class:"icon icon-sm",style:qe(s.iconStyle("brain")),"aria-hidden":"true"},null,4)],2)]),M("span",O5,Q(ce.streaming?J.$t("chat.thinkingRunning"):J.$t("chat.thinking")),1)],8,P5),M("div",{class:"collapsible-content",style:qe(Z(N(ce,_e)))},[M("div",{class:"content-inner thinking-content",ref_for:!0,ref:Pe=>L(N(ce,_e),Pe),onScroll:Pe=>K(N(ce,_e),Pe),style:{"max-height":"240px","overflow-y":"auto"}},Q(ce.content),41,D5)],4)],10,I5)):ce.type==="tool"?(F(),U("div",{key:1,class:Ce(["collapsible-block tool-block stacked-block",{expanded:O(ce,_e),processing:q(ce),completed:V(ce)}]),"data-block-id":N(ce,_e)},[M("div",{class:"collapsible-header",onClick:Pe=>$(N(ce,_e))},[ne[1]||(ne[1]=M("div",{class:"arrow"},null,-1)),M("div",B5,[M("span",{class:Ce(["tool-icon icon icon-md",s.getToolAnimationClass(ce.tool)]),style:qe(s.iconStyle(s.getToolIcon(ce.tool))),"aria-hidden":"true"},null,6)]),M("span",F5,Q(s.getToolStatusText(ce.tool)),1),M("span",H5,Q(s.getToolDescription(ce.tool)),1)],8,$5),M("div",{class:"collapsible-content",style:qe(Z(N(ce,_e)))},[M("div",U5,[M("div",{innerHTML:c(ce)},null,8,W5)])],4),q(ce)?(F(),U("div",z5)):me("",!0)],10,N5)):me("",!0)]))),128))]),_:1},8,["style","appear","css"])],4)],6))}}),K5=qt(G5,[["__scopeId","data-v-3241f026"]]),q5={class:"square-grid-loader"},Q5=ct({__name:"SquareGridLoader",setup(s){return(e,t)=>(F(),U("div",q5,[...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)])]))}}),X5=qt(Q5,[["__scopeId","data-v-afc6b5c3"]]),Y5={class:"rotating-squares-loader"},J5=ct({__name:"RotatingSquaresLoader",setup(s){return(e,t)=>(F(),U("div",Y5,[...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)])]))}}),Z5=qt(J5,[["__scopeId","data-v-db47acef"]]),e4={class:"dual-chase-loader"},t4=ct({__name:"DualChaseLoader",setup(s){return(e,t)=>(F(),U("div",e4))}}),s4=qt(t4,[["__scopeId","data-v-337256ff"]]),n4={class:"bouncing-squares-loader"},i4=ct({__name:"BouncingSquaresLoader",setup(s){return(e,t)=>(F(),U("div",n4,[...t[0]||(t[0]=[M("div",{class:"square"},null,-1),M("div",{class:"square"},null,-1),M("div",{class:"square"},null,-1)])]))}}),r4=qt(i4,[["__scopeId","data-v-502bc545"]]),o4={class:"five-squares-loader"},a4=ct({__name:"FiveSquaresLoader",setup(s){return(e,t)=>(F(),U("div",o4,[...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)])]))}}),l4=qt(a4,[["__scopeId","data-v-4ffc5a36"]]),c4={class:"nine-grid-loader"},u4=ct({__name:"NineGridLoader",setup(s){return(e,t)=>(F(),U("div",c4,[...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)])]))}}),d4=qt(u4,[["__scopeId","data-v-62be6033"]]),h4={class:"ripple-loader"},f4=ct({__name:"RippleLoader",setup(s){return(e,t)=>(F(),U("div",h4,[...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)])]))}}),p4=qt(f4,[["__scopeId","data-v-e8d9f3ef"]]),m4={class:"newton-loader"},g4=ct({__name:"NewtonCradleSquaresLoader",setup(s){return(e,t)=>(F(),U("div",m4,[...t[0]||(t[0]=[M("div",{class:"dot"},null,-1),M("div",{class:"dot"},null,-1),M("div",{class:"dot"},null,-1),M("div",{class:"dot"},null,-1)])]))}}),v4=qt(g4,[["__scopeId","data-v-4316d9b8"]]),y4={class:"dot-spinner-loader"},b4=ct({__name:"DotSpinnerSquaresLoader",setup(s){return(e,t)=>(F(),U("div",y4,[...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)])]))}}),_4=qt(b4,[["__scopeId","data-v-89be96b5"]]),w4={class:"orbit-loader"},S4=ct({__name:"OrbitBlurSquaresLoader",setup(s){return(e,t)=>(F(),U("div",w4,[...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)])]))}}),k4=qt(S4,[["__scopeId","data-v-19a87dd3"]]),C4={class:"shadow-rolling-loader"},T4=ct({__name:"ShadowRollingSquaresLoader",setup(s){return(e,t)=>(F(),U("div",C4))}}),A4=qt(T4,[["__scopeId","data-v-0934be8f"]]),E4={class:"jumping-seq-loader"},M4=ct({__name:"JumpingSequenceSquaresLoader",setup(s){return(e,t)=>(F(),U("div",E4,[...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)])]))}}),x4=qt(M4,[["__scopeId","data-v-bb2c052b"]]),R4={class:"chaotic-orbit-loader"},I4=ct({__name:"ChaoticOrbitSquaresLoader",setup(s){return(e,t)=>(F(),U("div",R4))}}),P4=qt(I4,[["__scopeId","data-v-c29a198e"]]),L4={class:"leap-frog-loader"},O4=ct({__name:"LeapFrogSquaresLoader",setup(s){return(e,t)=>(F(),U("div",L4,[...t[0]||(t[0]=[M("div",{class:"dot"},null,-1),M("div",{class:"dot"},null,-1),M("div",{class:"dot"},null,-1)])]))}}),D4=qt(O4,[["__scopeId","data-v-2e407c57"]]),N4={class:"wave-matrix-loader"},$4=ct({__name:"WaveMatrixSquaresLoader",setup(s){return(e,t)=>(F(),U("div",N4,[...t[0]||(t[0]=[M("div",{class:"sq"},null,-1),M("div",{class:"sq"},null,-1),M("div",{class:"sq"},null,-1),M("div",{class:"sq"},null,-1)])]))}}),B4=qt($4,[["__scopeId","data-v-c583d74c"]]),F4={class:"follow-track-loader"},H4=ct({__name:"FollowTrackSquaresLoader",setup(s){return(e,t)=>(F(),U("div",F4,[...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)])]))}}),U4=qt(H4,[["__scopeId","data-v-091a0000"]]),W4={class:"four-corner-loader"},z4=ct({__name:"FourCornerCycleSquaresLoader",setup(s){return(e,t)=>(F(),U("div",W4,[...t[0]||(t[0]=[M("div",{class:"sq"},null,-1),M("div",{class:"sq"},null,-1),M("div",{class:"sq"},null,-1),M("div",{class:"sq"},null,-1)])]))}}),j4=qt(z4,[["__scopeId","data-v-3a59d23d"]]),ux=[X5,Z5,s4,r4,l4,d4,p4,v4,_4,k4,A4,x4,P4,D4,B4,U4,j4],V4=4,Zf=[],G4=s=>{const e=Math.floor(Math.random()*s.length);return s[e]};function dC(){const s=ux.length;if(s===0)throw new Error(S("chatActions.loaderPoolEmpty"));const e=Math.max(0,Math.min(V4,s-1));let t=Array.from({length:s},(r,o)=>o);if(e>0&&Zf.length>0){const r=new Set(Zf.slice(-e)),o=t.filter(a=>!r.has(a));o.length>0&&(t=o)}const n=G4(t);Zf.push(n);const i=Math.max(s*2,e+1);return Zf.length>i&&Zf.splice(0,Zf.length-i),ux[n]}const K4=["data-streaming"],q4={class:"code-block-header"},Q4={class:"code-language"},X4=["title","aria-label"],Y4=ct({name:"CodeBlock",__name:"CodeBlock",props:{content:{},language:{},isStreaming:{type:Boolean}},setup(s){const e=s,t=ge(null),n=ge(!1),i=be(()=>e.language||"text"),r=be(()=>!e.language||e.language==="text"?"language-plain":`language-${e.language}`);function o(){ft(()=>{if(!(!t.value||typeof PS>"u"))try{PS.highlightElement(t.value)}catch(c){console.warn("代码高亮失败:",c)}})}Ke(()=>e.content,o,{immediate:!0}),dn(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(),U("div",{class:"code-block-wrapper","data-streaming":s.isStreaming?"1":void 0,"data-md-code-block":"1"},[M("div",q4,[M("span",Q4,Q(i.value),1),M("button",{class:Ce(["copy-code-btn",{copied:n.value}]),title:c.$t("chat.copyCode"),"aria-label":c.$t("chat.copyCode"),onClick:a},null,10,X4)]),M("pre",null,[M("code",{ref_key:"codeEl",ref:t,class:Ce(r.value)},Q(s.content),3)])],8,K4))}});function J4(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,"&").replace(/</g,"<").replace(/>/g,">")});continue}n.nodeType===Node.ELEMENT_NODE&&t.push({key:`c${t.length}`,html:n.outerHTML})}return t}const Z4=2e3,F_=[{trusted:!0,build:s=>`https://www.google.com/s2/favicons?domain=${encodeURIComponent(s)}&sz=64`},{trusted:!0,minSize:2,build:s=>`https://favicon.yandex.net/favicon/${encodeURIComponent(s)}`},{trusted:!1,build:s=>`https://icon.horse/icon/${encodeURIComponent(s)}`}],dx=new Map;function hx(s){return s.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function _L(s){const e=(s||"").replace(/^www\./,""),t=hx((e[0]||"?").toUpperCase());return`<span class="chip-letter" data-favicon-domain="${hx(e)}">${t}</span>`}function eH(s){const e=dx.get(s);if(e)return e;const t=new Promise(n=>{const i=F_.map(()=>({status:"pending"})),r=new Set;let o=!1;const a=()=>{if(o)return;o=!0,clearTimeout(c),r.forEach(d=>{d.onload=null,d.onerror=null,d.src=""}),r.clear();const l=F_.findIndex((d,h)=>d.trusted&&i[h].status==="ok"),u=F_.findIndex((d,h)=>!d.trusted&&i[h].status==="ok");l>=0&&u>=0?n(i[u].url):l>=0?n(i[l].url):n(null)},c=setTimeout(a,Z4);F_.forEach((l,u)=>{const d=l.build(s),h=new Image;r.add(h),h.onload=()=>{r.delete(h);const p=l.minSize??1;i[u]=h.naturalWidth>=p&&h.naturalHeight>=p?{status:"ok",url:d}:{status:"fail"},r.size||a()},h.onerror=()=>{r.delete(h),i[u]={status:"fail"},r.size||a()},h.src=d})});return dx.set(s,t),t}function FT(s){s.querySelectorAll(".chip-letter[data-favicon-domain]:not([data-favicon-racing])").forEach(t=>{const n=t.dataset.faviconDomain||"";n&&(t.dataset.faviconRacing="1",eH(n).then(i=>{if(!i||!t.isConnected)return;const r=document.createElement("img");r.className="chip-favicon",r.alt="",r.src=i,t.replaceWith(r)}))})}const ts=oy({visible:!1,pinned:!1,anchor:null,annotations:[]}),tH=250,sH=300;let Fv,rg;function wL(){clearTimeout(Fv),clearTimeout(rg),Fv=void 0,rg=void 0}function fx(s,e,t){Nl(),ts.anchor=s,ts.annotations=e,ts.pinned=t,ts.visible=!0,s.classList.add("is-open")}function Nl(){wL(),ts.anchor&&ts.anchor.classList.remove("is-open"),ts.visible=!1,ts.pinned=!1,ts.anchor=null,ts.annotations=[]}function SL(){clearTimeout(rg),rg=setTimeout(()=>{ts.pinned||Nl()},sH)}function px(){clearTimeout(rg)}function mx(){ts.pinned||SL()}function nH(s){const e=()=>s._citationAnnotations||[];s.addEventListener("mouseenter",()=>{clearTimeout(rg),!(ts.anchor===s&&ts.visible)&&(clearTimeout(Fv),Fv=setTimeout(()=>fx(s,e(),!1),tH))}),s.addEventListener("mouseleave",()=>{clearTimeout(Fv),ts.visible&&ts.anchor===s&&!ts.pinned&&SL()}),s.addEventListener("click",t=>{t.stopPropagation(),wL(),ts.anchor===s&&ts.visible&&ts.pinned?Nl():fx(s,e(),!0)})}function iH(s){const e=(s||"").trim();if(!e||/^src_/i.test(e))return null;const t=e.match(/^(.*?)#(?:L(\d+)(?:-L?(\d+))?|p(\d+))$/i);let n=(t?t[1]:e).trim();if(n.startsWith("./")&&(n=n.slice(2)),!n)return null;const i={id:s,type:"file_citation",file_path:n,file_name:n.split("/").pop()||n};return t&&(t[4]&&(i.page=parseInt(t[4],10)),t[2]&&(i.line_start=parseInt(t[2],10),t[3]&&(i.line_end=parseInt(t[3],10)))),i}function rH(s){var t,n;const e=new Map;for(const i of s||[])for(const r of(i==null?void 0:i.actions)||[]){const o=(n=(t=r==null?void 0:r.tool)==null?void 0:t.result)==null?void 0:n.citations;if(Array.isArray(o))for(const a of o)a&&typeof a.id=="string"&&!e.has(a.id)&&e.set(a.id,a)}return[...e.values()]}function oH(s){return(s||"").replace(/^www\./,"")}function aH(s){return s.type==="file_citation"?s.file_name||s.file_path||"":oH(s.domain)}const lH='<svg class="chip-file-icon" viewBox="0 0 16 16" fill="none"><path d="M4 1.5h5.5L13 5v9.5H4z" stroke="currentColor" stroke-width="1.2" stroke-linejoin="round"/><path d="M9.5 1.5V5H13" stroke="currentColor" stroke-width="1.2" stroke-linejoin="round"/></svg>';function cH(s){return s.type==="file_citation"?lH:_L(s.domain||"")}function uH(s,e,t={}){const n=s.querySelectorAll(".md-citation-chip");if(!n.length)return;const i=!!t.final,r=new Map((e||[]).map(o=>[o.id,o]));n.forEach(o=>{const a=(o.dataset.citationIds||"").split(",").map(d=>d.trim()).filter(Boolean);if(o.dataset.citeEnhanced==="1"&&o.dataset.citeLoaded==="1"){if(i){const d=a.map(h=>r.get(h)).filter(h=>!!h);d.length&&(o._citationAnnotations=d)}return}let c=a.map(d=>r.get(d)).filter(d=>!!d);if(!c.length&&!i){const d=a.map(h=>iH(h)).filter(h=>!!h);d.length&&(c=d)}if(!c.length){if(i){o.remove();return}o.dataset.citeEnhanced!=="1"&&(o.dataset.citeEnhanced="1",o.classList.add("is-pending"),o.innerHTML='<span class="chip-pending-dot"></span>');return}const l=c.slice(0,2).map(cH).join(""),u=c.length>1?`<span class="chip-count">+${c.length-1}</span>`:"";o.innerHTML=`<span class="chip-icons">${l}</span><span class="chip-label">${dH(aH(c[0]))}</span>`+u,o.classList.remove("is-pending"),o.classList.add(c[0].type==="file_citation"?"is-file":"is-url"),o.dataset.citeEnhanced="1",o.dataset.citeLoaded="1",o._citationAnnotations=c,nH(o)}),FT(s)}function dH(s){return s.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}const hH={key:0,class:"markdown-text-segment"},fH=["innerHTML"],pH=40,mH=ct({name:"MarkdownRenderer",__name:"MarkdownRenderer",props:{content:{},isStreaming:{type:Boolean},citations:{},citationsFinal:{type:Boolean},enableCitations:{type:Boolean}},setup(s){const e=s,t=ge(null),n=zP("mathRenderedCallback",()=>{}),i=be(()=>dF(e.content||"",e.isStreaming));function r(u){return fF(u,e.isStreaming,e.enableCitations)}const o=new Map;function a(u){const d=o.get(u.key);if(d&&d.content===u.content)return d.chunks;const h=J4(r(u.content));if(o.set(u.key,{content:u.content,chunks:h}),o.size>pH){const p=o.keys().next().value;p!==void 0&&o.delete(p)}return h}function c(){ft(()=>{t.value&&(hF(t.value),n())})}dn(c),PT(c),Ke(()=>e.content,c,{immediate:!0});function l(){e.enableCitations&&ft(()=>{t.value&&uH(t.value,e.citations,{final:e.citationsFinal})})}return dn(l),PT(l),Ke(()=>[e.citations,e.citationsFinal],l),(u,d)=>(F(),U("div",{ref_key:"containerRef",ref:t,class:"markdown-renderer"},[(F(!0),U(Ie,null,Ze(i.value,h=>(F(),U(Ie,{key:h.key},[h.type==="text"?(F(),U("div",hH,[(F(!0),U(Ie,null,Ze(a(h),p=>(F(),U("div",{key:p.key,class:"md-html-chunk",innerHTML:p.html},null,8,fH))),128))])):(F(),Ft(Y4,{key:1,content:h.content,language:h.language,"is-streaming":!h.closed},null,8,["content","language","is-streaming"]))],64))),128))],512))}}),zg=qt(mH,[["__scopeId","data-v-733b1a98"]]),gH={class:"minimal-blocks-container"},vH={key:0,class:"summary-group"},yH=["data-group-id","onClick"],bH={class:"summary-content-wrapper"},_H={class:"summary-preview"},wH={key:0,class:"summary-tool-reel-window"},SH={class:"summary-status-icon"},kH={key:0,class:"summary-icon-inner"},CH={key:1,class:"check-icon",width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2"},TH={class:"step-timeline"},AH={class:"step-content"},EH={key:0,class:"step-body"},MH=["onScroll","innerHTML"],xH={key:1,class:"step-body"},RH={class:"step-header"},IH={key:0,class:"tool-intent"},PH={key:1,class:"tool-result"},LH=["innerHTML"],OH={key:2,class:"tool-result"},DH={class:"result-item"},NH={key:2,class:"summary-group sub-agent-system-group"},$H={class:"summary-line-text sub-agent-system-summary-line"},BH={class:"summary-content-wrapper"},FH={class:"summary-preview"},HH=20,hC=26,UH=1450,fC=520,gx=170,vx=2,WH=ct({__name:"MinimalBlocks",props:{actions:{},citations:{},citationsFinal:{type:Boolean},enableCitations:{type:Boolean},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=Js(),n=be(()=>t.form.minimal_expand_height_limited),i=s,r=e,o=ge(new Set),a=new Map,c=new Map,l=new Map,u=new Map,d=oy({}),h=new Map,p=new Map,g=pe=>Array.from(pe||""),v=pe=>{const he=typeof pe=="string"?pe:"",ye=he.indexOf(`
|
||
`);return ye>0?he.substring(0,ye):he},m=pe=>{lt.value;const he=pe.tool;if(!he)return"";const ye=t.form.tool_intent_enabled,ke=he.intent_rendered||he.intent_full||"";return ye&&ke?v(ke):he.status==="preparing"?S("toolResults.sentences.preparing",{name:he.name||S("common.tool")}):he.status==="running"?S("chat.callingTool",{name:he.name||S("common.tool")}):he.status==="completed"?he.display_name||he.name||S("chat.toolCompleted"):pe.streaming?S("chat.executingTool"):he.display_name||he.name||S("chat.runTool")},y=pe=>{var ye;if(pe.type!=="tool")return!1;if(pe.streaming)return!0;const he=String(((ye=pe.tool)==null?void 0:ye.status)||"").toLowerCase();return["hinted","preparing","running","pending","pending_approval","awaiting_approval","awaiting_user_answer"].includes(he)},_=pe=>{let he=-1;for(let ke=pe.length-1;ke>=0;ke--){if(pe[ke].type==="tool"){he=ke;break}if(pe[ke].type==="thinking")break}if(he<0)return[];let ye=he;for(;ye>0&&pe[ye-1].type==="tool";)ye--;return pe.slice(ye,he+1)},b=pe=>{const he=_(pe);return he.some(y)?he:[]},k=pe=>b(pe).map(m).filter(he=>he.trim().length>0),w=(pe,he)=>{var Le;const ye=(Le=d[he])!=null&&Le.completing?d[he].items:null;if(ye!=null&&ye.length)return ye;const ke=k(pe);return ke.length>0?[...ke,ke[0]]:[]},T=(pe,he)=>{var ye;return!!((ye=d[he])!=null&&ye.completing)||ve(pe,he)&&k(pe).length>1},A=(pe,he)=>{var ye;return ve(pe,he)||!!((ye=d[he])!=null&&ye.completing)},C=pe=>{var he;return((he=d[pe])==null?void 0:he.phase)||"idle"},E=pe=>{var he;return{transform:`translateY(${((he=d[pe])==null?void 0:he.offsetPx)||0}px)`}},x=pe=>{const he=h.get(pe);he&&(window.clearInterval(he),h.delete(pe)),(p.get(pe)||[]).forEach(ke=>window.clearTimeout(ke)),p.delete(pe)},D=(pe,he)=>{const ye=p.get(pe)||[];ye.push(he),p.set(pe,ye)},N=(pe,he)=>{const ye=d[pe];if(!ye||ye.completing||he<2)return;const ke=(ye.index+1)%he,st=-(ke===0?he:ke)*hC;ye.phase="rolling",ye.offsetPx=st-vx;const gt=window.setTimeout(()=>{if(ye.phase="settle",ye.offsetPx=st,ye.index=ke,ke===0){const Wt=window.setTimeout(()=>{ye.phase="idle",ye.offsetPx=0},gx);D(pe,Wt)}},fC);D(pe,gt)},O=(pe,he)=>{const ye=d[pe];if(!ye||ye.completing)return;const ke=ye.items.length>1?ye.items:_(he).map(m).filter(Wt=>Wt.trim().length>0);if(ke.length<2){x(pe),delete d[pe];return}x(pe),ye.items=ke,ye.signature=ke.join(""),ye.completing=!0;const Le=ke.length-1,st=-ye.index*hC,gt=-Le*hC;ye.phase="idle",ye.offsetPx=st,window.requestAnimationFrame(()=>{ye.phase="rolling",ye.offsetPx=gt-vx;const Wt=window.setTimeout(()=>{ye.phase="settle",ye.offsetPx=gt,ye.index=Le},fC);D(pe,Wt);const jt=window.setTimeout(()=>{x(pe),delete d[pe]},fC+gx+260);D(pe,jt)})},G=()=>{const pe=new Set;q.value.forEach(he=>{if(he.type!=="summary"||!he.actions||!T(he.actions,he.id))return;const ye=k(he.actions),ke=ye.join("");if(pe.add(he.id),!d[he.id]||d[he.id].signature!==ke?(x(he.id),d[he.id]={index:0,offsetPx:0,phase:"idle",signature:ke,items:ye}):d[he.id].items=ye,!h.has(he.id)){const Le=window.setInterval(()=>N(he.id,ye.length),UH);h.set(he.id,Le)}}),Object.keys(d).forEach(he=>{if(!pe.has(he)){const ye=q.value.find(ke=>ke.id===he);if((ye==null?void 0:ye.type)==="summary"&&ye.actions&&!d[he].completing){pe.add(he),O(he,ye.actions);return}d[he].completing||(x(he),delete d[he])}})},Z=pe=>{const he=q.value.find(jt=>jt.id===pe);if(!he||!he.actions)return dC();const ke=he.actions.find(jt=>jt.streaming)||he.actions[he.actions.length-1];if(!ke)return dC();const Le=he.actions.indexOf(ke);let st=-1;for(let jt=Le-1;jt>=0;jt--)if(he.actions[jt].type!==ke.type){st=jt;break}const gt=st>=0?`${he.actions[st].id}-${ke.type}`:`start-${ke.type}`,Wt=`${pe}-${gt}`;return u.has(Wt)||u.set(Wt,dC()),u.get(Wt)},q=be(()=>{const pe=[];let he=[],ye=0;if(i.actions.forEach((ke,Le)=>{if(ke.type==="thinking"||ke.type==="tool")he.push(ke);else if(ke.type==="text"||ke.type==="system"){if(he.length>0){const st=he[0].id||he[0].blockId||`summary-${ye}`;pe.push({type:"summary",id:`summary-${st}`,actions:he}),ye++,he=[]}if(ke.type==="text"){const st=typeof ke.content=="string"?ke.content:"";if(!st.trim())return;pe.push({type:"text",id:`text-${Le}`,content:st,streaming:ke.streaming})}else pe.push({type:"system",id:`system-${Le}`,content:ke.content})}}),he.length>0){const ke=he[0].id||he[0].blockId||`summary-${ye}`;pe.push({type:"summary",id:`summary-${ke}`,actions:he})}return pe}),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"},I={read:"chat.summaryRead",command:"chat.summaryCommand",edit:"chat.summaryEdit",search:"chat.summarySearch",webpage:"chat.summaryWebpage",mcp:"chat.summaryMcp",workflow_activate:"chat.summaryWorkflowActivate",workflow_advance:"chat.summaryWorkflowAdvance",workflow:"chat.summaryWorkflow",todo_create:"chat.summaryTodoCreate",todo_update:"chat.summaryTodoUpdate",memory_update:"chat.summaryMemoryUpdate",memory_read:"chat.summaryMemoryRead",conversation:"chat.summaryConversation",sub_agent:"chat.summarySubAgent",sub_agent_manage:"chat.summarySubAgentManage",wait:"chat.summaryWait",ask:"chat.summaryAsk",plan:"chat.summaryPlan",skill:"chat.summarySkill",settings:"chat.summarySettings",easter_egg:"chat.summaryEasterEgg",other:"chat.summaryOther"},$=["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"],L=pe=>{var ye;const he=(ye=pe.tool)==null?void 0:ye.name;return typeof he!="string"?"other":he.startsWith("mcp__")?"mcp":V[he]||"other"},K=pe=>{lt.value;const he=pe.filter(ke=>ke.streaming);let ye;if(he.length>0)ye=he[he.length-1];else{const ke=pe.filter(Le=>Le.type==="tool");ke.length>0?ye=ke[ke.length-1]:ye=pe[pe.length-1]}if(!ye)return"";if(ye.type==="thinking"){const ke=ye.content||"";return v(ke)}if(ye.type==="tool"){const ke=ye.tool;if(!ke)return"";const Le=t.form.tool_intent_enabled,st=ke.intent_rendered||ke.intent_full||"";return Le&&st?v(st):ke.status==="preparing"?S("toolResults.sentences.preparing",{name:ke.name||S("common.tool")}):ke.status==="running"?S("chat.callingTool",{name:ke.name||S("common.tool")}):ke.status==="completed"?ke.display_name||ke.name||S("chat.toolCompleted"):ye.streaming?S("chat.executingTool"):ke.display_name||ke.name||S("chat.runTool")}return""},se=pe=>{lt.value;const he=pe.filter(Le=>Le.type==="tool");if(he.length===0){const Le=pe.filter(st=>st.type==="thinking").pop();return Le?v(Le.content||""):""}if(he.length===1)return m(he[0]);const ye=Object.fromEntries($.map(Le=>[Le,0]));he.forEach(Le=>{ye[L(Le)]++});const ke=[];return $.forEach(Le=>{const st=ye[Le];st>0&&ke.push(S(I[Le],{n:st}))}),ke.join(",")},oe=(pe,he)=>ve(pe,he)?K(pe):se(pe),ve=(pe,he)=>{if(!i.conversationRunning||!i.isLatestMessage)return!1;const ye=q.value.findIndex(Le=>Le.id===he);return ye===-1?!1:!q.value.slice(ye+1).some(Le=>Le.type==="text")},le=pe=>pe.map((he,ye)=>({id:he.id||he.blockId||`step-${ye}`,type:he.type,content:he.content||"",streaming:he.streaming||!1,action:he})),ue=pe=>pe.scrollHeight-pe.scrollTop-pe.clientHeight<=HH,P=(pe,he)=>{const ye=he.target;if(!ye)return;const ke=!ue(ye);l.set(pe,ke)},X=(pe,he)=>{const ye=c.get(pe);ye&&ye.removeEventListener("scroll",P),he instanceof HTMLElement?(c.set(pe,he),he.addEventListener("scroll",ke=>P(pe,ke))):(c.delete(pe),l.delete(pe))},J=pe=>{const he=c.get(pe);he&&!l.get(pe)&&(he.scrollTop=he.scrollHeight)},ne=pe=>{o.value.has(pe)?(o.value.delete(pe),r("group-toggle",{groupId:pe,expanded:!1}),ft(()=>{const he=q.value.find(ye=>ye.id===pe);he&&he.actions&&he.actions.forEach(ye=>{if(ye.type==="thinking"){const ke=ye.id||ye.blockId;ke&&typeof i.registerThinkingRef=="function"&&i.registerThinkingRef(ke,null)}})})):(o.value.add(pe),r("group-toggle",{groupId:pe,expanded:!0}),ft(()=>{const he=q.value.find(ye=>ye.id===pe);he&&he.actions&&(l.set(pe,!1),ve(he.actions,pe)&&J(pe),he.actions.forEach(ye=>{if(ye.type==="thinking"){const ke=ye.id||ye.blockId;if(ke){const Le=a.get(ke);Le&&typeof i.registerThinkingRef=="function"&&(i.registerThinkingRef(ke,Le),ye.streaming&&(Le.scrollTop=Le.scrollHeight))}}}))}))},ce=pe=>{if(pe.type==="thinking")return i.iconStyle?i.iconStyle("brain"):{};if(pe.type==="tool"&&pe.action.tool){const he=i.getToolIcon?i.getToolIcon(pe.action.tool):"terminal";return i.iconStyle?i.iconStyle(he):{}}return i.iconStyle?i.iconStyle("terminal"):{}},_e=pe=>{lt.value;const he=pe.tool;if(!he)return S("chat.runTool");const ye=t.form.tool_intent_enabled,ke=he.intent_rendered||he.intent_full||"";return ye&&ke?ke:he.status==="preparing"?S("toolResults.sentences.preparing",{name:he.name||S("common.tool")}):he.status==="running"?S("chat.callingTool",{name:he.name||S("common.tool")}):he.status==="completed"?S("chat.toolCompleted"):he.name||S("chat.runTool")},Pe=pe=>{var he;return((he=pe.tool)==null?void 0:he.intent)||""},it=pe=>{var ke;lt.value;const he=RE(pe,i.formatSearchTopic||(()=>""),i.formatSearchTime||(()=>""),i.formatSearchDomains||(()=>""));if(he)return he;const ye=(ke=pe.tool)==null?void 0:ke.result;return ye?typeof ye=="string"?`<div class="result-item"><pre>${rt(ye)}</pre></div>`:`<div class="result-item"><pre>${rt(JSON.stringify(ye,null,2))}</pre></div>`:`<div class="result-item">${rt(S("chat.executing"))}</div>`},at=pe=>pe?rt(pe).replace(/\n/g,"<br>"):"",rt=pe=>{const he=document.createElement("div");return he.textContent=pe,he.innerHTML},Oe=(pe,he)=>{he instanceof HTMLElement?a.set(pe,he):a.delete(pe);const ye=q.value.find(ke=>ke.type==="summary"&&ke.actions&&ke.actions.some(Le=>Le.id===pe||Le.blockId===pe));ye&&o.value.has(ye.id)&&typeof i.registerThinkingRef=="function"&&i.registerThinkingRef(pe,he)},xe=(pe,he)=>{typeof i.handleThinkingScroll=="function"&&i.handleThinkingScroll(pe,he)};return Ke(()=>i.actions,()=>{G(),ft(()=>{q.value.forEach(pe=>{pe.type==="summary"&&pe.actions&&o.value.has(pe.id)&&ve(pe.actions,pe.id)&&J(pe.id)})})},{deep:!0,immediate:!0}),Ke(()=>[i.conversationRunning,i.isLatestMessage],()=>{G()}),Rn(()=>{Object.keys(d).forEach(x),c.forEach(pe=>{pe.removeEventListener("scroll",P)}),c.clear(),l.clear()}),(pe,he)=>(F(),U("div",gH,[(F(!0),U(Ie,null,Ze(q.value,ye=>(F(),U(Ie,{key:ye.id},[ye.type==="summary"&&ye.actions?(F(),U("div",vH,[M("div",{class:Ce(["summary-line-text",{running:ve(ye.actions,ye.id)}]),"data-group-id":ye.id,onClick:ke=>ne(ye.id)},[M("div",bH,[M("span",_H,[A(ye.actions,ye.id)?(F(),U(Ie,{key:0},[T(ye.actions,ye.id)?(F(),U("span",wH,[M("span",{class:Ce(["summary-tool-reel-track",C(ye.id)]),style:qe(E(ye.id))},[(F(!0),U(Ie,null,Ze(w(ye.actions,ye.id),(ke,Le)=>(F(),U("span",{key:`${ye.id}-tool-reel-${Le}-${ke}`,class:"summary-tool-reel-item"},Q(ke),1))),128))],6)])):(F(!0),U(Ie,{key:1},Ze(g(oe(ye.actions,ye.id)),(ke,Le)=>(F(),U("span",{key:`${ye.id}-${Le}`,class:"summary-char",style:qe({animationDelay:`${(Le+1)*.12}s`})},Q(ke===" "?" ":ke),5))),128))],64)):(F(),U(Ie,{key:1},[cn(Q(oe(ye.actions,ye.id)),1)],64))])]),M("div",SH,[ve(ye.actions,ye.id)?(F(),U("div",kH,[(F(),Ft(eF(Z(ye.id))))])):(F(),U("svg",CH,[...he[0]||(he[0]=[M("circle",{cx:"12",cy:"12",r:"10"},null,-1),M("polyline",{points:"7.5 12 10.5 15 16.5 9"},null,-1)])]))])],10,yH),M("div",{class:Ce(["steps-container",{show:o.value.has(ye.id)}])},[M("div",{class:Ce(["steps-wrapper",{"height-limited":n.value}]),ref_for:!0,ref:ke=>X(ye.id,ke)},[(F(!0),U(Ie,null,Ze(le(ye.actions),ke=>{var Le;return F(),U("div",{key:ke.id,class:"step-item"},[M("div",TH,[M("span",{class:"step-icon icon icon-sm",style:qe(ce(ke)),"aria-hidden":"true"},null,4),he[1]||(he[1]=M("div",{class:"step-line"},null,-1))]),M("div",AH,[ke.type==="thinking"?(F(),U("div",EH,[M("div",{class:"thinking-content",ref_for:!0,ref:st=>Oe(ke.id,st),onScroll:st=>xe(ke.id,st),innerHTML:at(ke.content)},null,40,MH)])):ke.type==="tool"?(F(),U("div",xH,[M("div",RH,Q(_e(ke.action)),1),Pe(ke.action)?(F(),U("div",IH,Q(Pe(ke.action)),1)):me("",!0),(Le=ke.action.tool)!=null&&Le.result?(F(),U("div",PH,[M("div",{innerHTML:it(ke.action)},null,8,LH)])):(F(),U("div",OH,[M("div",DH,Q(pe.$t("chat.executing")),1)]))])):me("",!0)])])}),128))],2)],2)])):ye.type==="text"?(F(),U("div",{key:1,class:Ce(["text-output",{"streaming-text":ye.streaming}])},[M("div",{class:Ce(["text-content",{"streaming-text":ye.streaming}])},[We(zg,{content:ye.content||"","is-streaming":ye.streaming,citations:s.citations,"citations-final":s.citationsFinal,"enable-citations":s.enableCitations},null,8,["content","is-streaming","citations","citations-final","enable-citations"])],2)],2)):ye.type==="system"?(F(),U("div",NH,[M("div",$H,[M("div",BH,[M("span",FH,Q(ye.content||""),1)]),he[2]||(he[2]=M("div",{class:"summary-status-icon"},[M("svg",{class:"check-icon",width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2"},[M("circle",{cx:"12",cy:"12",r:"10"}),M("polyline",{points:"7.5 12 10.5 15 16.5 9"})])],-1))])])):me("",!0)],64))),128))]))}}),zH=qt(WH,[["__scopeId","data-v-ba476c38"]]),jH={class:"edit-summary-card__header"},VH={class:"edit-summary-card__title"},GH={class:"edit-summary-card__totals"},KH={class:"edit-summary-plus"},qH={class:"edit-summary-minus"},QH={class:"edit-summary-card__list"},XH=["onMouseenter","onClick"],YH=["title"],JH={class:"edit-summary-card__delta"},ZH={class:"edit-summary-plus"},e6={class:"edit-summary-minus"},t6={key:0,class:"es-modal"},s6=["aria-label"],n6={class:"es-modal__header"},i6=["title"],r6={class:"es-modal__delta"},o6={class:"edit-summary-plus"},a6={class:"edit-summary-minus"},l6={class:"es-modal__body"},c6={key:0,class:"es-diff-sep","aria-hidden":"true"},u6={class:"es-diff-line-number"},d6={class:"es-diff-marker"},h6={class:"es-diff-content"},f6={key:0,class:"es-diff-note"},p6={key:1,class:"es-diff-empty"},m6=720,ea=16,yx=140,g6=.7,v6=640,y6=260,b6=600,_6=ct({__name:"EditSummaryCard",props:{summary:{},iconStyle:{type:Function}},setup(s){const e=s,t=Is(),n=be(()=>!!t.isMobileViewport),i=be(()=>{var I;const V=(I=e.summary)==null?void 0:I.files;return Array.isArray(V)?V.filter($=>$&&$.path):[]}),r=be(()=>{let V=0,I=0;for(const $ of i.value)V+=Number($.added)||0,I+=Number($.removed)||0;return{added:V,removed:I}}),o=ge(null),a=ge(!1),c=ge(null),l=ge(null),u=ge({});let d=null,h=null;const p=be(()=>o.value&&i.value.find(V=>V.path===o.value)||null);function g(){if(n.value||!c.value||!l.value){u.value={};return}const V=window.innerWidth,I=window.innerHeight,$=Math.min(m6,V-ea*2),L=c.value.getBoundingClientRect(),K=L.left+L.width/2,se=Math.min(Math.max(K-$/2,ea),V-$-ea),oe=Math.min(I*g6,v6),ve=l.value.getBoundingClientRect(),le=ve.top-ve.height/2,ue=ve.bottom+ve.height/2,P=le-ea,X=I-ea-ue,J=P>=y6||P>=X,ne={left:`${Math.round(se)}px`,width:`${Math.round($)}px`,transform:"none"};if(J){const ce=Math.min(Math.max(le,ea+yx),I-ea);u.value={...ne,top:"auto",bottom:`${Math.round(I-ce)}px`,maxHeight:`${Math.round(Math.min(ce-ea,oe))}px`}}else{const ce=Math.min(Math.max(ue,ea),I-ea-yx);u.value={...ne,top:`${Math.round(ce)}px`,bottom:"auto",maxHeight:`${Math.round(Math.min(I-ea-ce,oe))}px`}}}let v=0;function m(V){if(!o.value)return;const I=V.target;I instanceof Element&&I.closest(".es-modal")&&a.value||(v=Date.now()+250,N())}function y(){o.value&&(v=Date.now()+250,N())}function _(){d&&(clearTimeout(d),d=null)}function b(){h&&(clearTimeout(h),h=null)}function k(V,I,$=null){_(),b(),o.value=V,a.value=I,l.value=$,g()}function w(V,I){if(_(),!(Date.now()<v)){if(o.value){k(V,!1,I);return}d=setTimeout(()=>k(V,!1,I),b6)}}function T(){a.value||(b(),h=setTimeout(()=>{o.value=null},200))}function A(V,I){n.value||(b(),w(V,I.currentTarget||null))}function C(){n.value||(_(),T())}function E(){n.value||b()}function x(){n.value||T()}function D(V,I){k(V,!0,I.currentTarget||null)}function N(){_(),b(),a.value=!1,o.value=null,l.value=null}function O(V){V.key==="Escape"&&o.value&&N()}Ke(o,V=>{V?(window.addEventListener("keydown",O),window.addEventListener("resize",y),window.addEventListener("scroll",m,!0)):(window.removeEventListener("keydown",O),window.removeEventListener("resize",y),window.removeEventListener("scroll",m,!0))}),Rn(()=>{_(),b(),window.removeEventListener("keydown",O),window.removeEventListener("resize",y),window.removeEventListener("scroll",m,!0)});function G(V){return V.type==="add"?"es-diff-add":V.type==="remove"?"es-diff-remove":"es-diff-context"}function Z(V){return V.type==="add"?"+":V.type==="remove"?"-":""}function q(V){const I=V.type==="remove"?V.old_no:V.new_no;return typeof I=="number"&&Number.isFinite(I)?String(I):""}return(V,I)=>i.value.length?(F(),U("div",{key:0,class:"edit-summary-card",ref_key:"cardRef",ref:c},[M("div",jH,[M("span",{class:"icon icon-sm edit-summary-card__icon",style:qe(e.iconStyle("filePen")),"aria-hidden":"true"},null,4),M("span",VH,Q(V.$t("chat.filesEdited",{n:i.value.length})),1),M("span",GH,[M("span",KH,"+"+Q(r.value.added),1),M("span",qH,"-"+Q(r.value.removed),1)])]),M("div",QH,[(F(!0),U(Ie,null,Ze(i.value,$=>(F(),U("div",{key:$.path,class:Ce(["edit-summary-card__row",{"is-active":a.value&&o.value===$.path}]),onMouseenter:L=>A($.path,L),onMouseleave:C,onClick:De(L=>D($.path,L),["stop"])},[M("span",{class:"edit-summary-card__path",title:$.path},Q($.path),9,YH),M("span",JH,[M("span",ZH,"+"+Q($.added||0),1),M("span",e6,"-"+Q($.removed||0),1)])],42,XH))),128))]),(F(),Ft(Tf,{to:"body"},[p.value?(F(),U("div",t6,[a.value||n.value?(F(),U("div",{key:0,class:"es-modal__overlay","aria-hidden":"true",onClick:N})):me("",!0),M("div",{class:"es-modal__panel",style:qe(u.value),role:"dialog","aria-label":V.$t("chat.fileChanges",{path:p.value.path}),onMouseenter:E,onMouseleave:x},[M("div",n6,[M("span",{class:"icon icon-sm es-modal__header-icon",style:qe(e.iconStyle("filePen")),"aria-hidden":"true"},null,4),M("span",{class:"es-modal__path",title:p.value.path},Q(p.value.path),9,i6),M("span",r6,[M("span",o6,"+"+Q(p.value.added||0),1),M("span",a6,"-"+Q(p.value.removed||0),1)]),a.value||n.value?(F(),Ft(ml,{key:0,label:V.$t("common.close"),size:"sm",onClick:De(N,["stop"])},null,8,["label"])):me("",!0)]),M("div",l6,[(p.value.lines||[]).length?(F(),U(Ie,{key:0},[(F(!0),U(Ie,null,Ze(p.value.lines,($,L)=>(F(),U(Ie,{key:L},[$.type==="sep"?(F(),U("div",c6,"⋮")):(F(),U("div",{key:1,class:Ce(["es-diff-line",G($)])},[M("span",u6,Q(q($)),1),M("span",d6,Q(Z($)),1),M("span",h6,Q($.content),1)],2))],64))),128)),p.value.truncated?(F(),U("div",f6,Q(V.$t("chat.diffTruncated")),1)):me("",!0)],64)):(F(),U("div",p6,Q(V.$t("chat.diffEmpty")),1))])],44,s6)])):me("",!0)]))],512)):me("",!0)}}),ep=()=>({active:!1,name:"",status:null,history:[],current:null,next:null,reviewing:!1,footnote:null}),yg=hn("workflow",{state:()=>({snapshot:ep(),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=ep());return}if(e&&this.snapshot.active){this.exiting=!0;return}this.snapshot=ep();return}this.exiting=!1,this.snapshot={...ep(),...s,active:!0}},finishExit(){this.exiting=!1,this.live=!1,this.snapshot=ep()},reset(){this.snapshot=ep(),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()}}}}),kL="agents_quick_dock_had_content",w6=()=>{if(typeof window>"u"||!window.localStorage)return!1;try{return window.localStorage.getItem(kL)==="1"}catch{return!1}},S6=s=>{if(!(typeof window>"u"||!window.localStorage))try{window.localStorage.setItem(kL,s?"1":"0")}catch(e){console.warn("写入快捷窗口内容状态缓存失败:",e)}},CL="agents_quick_dock_conv_content",bx=50,TL=()=>{if(typeof window>"u"||!window.localStorage)return{};try{const s=window.localStorage.getItem(CL),e=s?JSON.parse(s):{};return e&&typeof e=="object"?e:{}}catch{return{}}},k6=s=>TL()[s]===!0,C6=(s,e)=>{if(!(typeof window>"u"||!window.localStorage||!s))try{const t=TL();delete t[s],t[s]=e;const n=Object.keys(t);if(n.length>bx)for(const i of n.slice(0,n.length-bx))delete t[i];window.localStorage.setItem(CL,JSON.stringify(t))}catch(t){console.warn("写入快捷窗口对话内容缓存失败:",t)}},_x=()=>{if(typeof window<"u"){const s=window.location.pathname.replace(/\/+$/,"")||"/";if(s==="/"||s==="/new")return!1}return w6()},oo=hn("quickDock",{state:()=>({editedFiles:[],editedFilesLive:!1,detail:null,previewPath:null,menu:null,userCollapsed:!1,assumedContent:_x(),assumedActive:_x(),filesSyncSeq:0}),getters:{hasContent(s){var a,c;const e=Pc(),t=dd(),n=vg(),i=yg(),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?k6(s):!1,this.assumedActive=!0}}}),T6={class:"file-chip-row",role:"list"},A6=["title","onClick"],E6={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"},M6={class:"file-chip-meta"},x6={class:"file-chip-name"},R6={class:"file-chip-type"},I6=["aria-label","onClick"],P6="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",L6=ct({__name:"FileChips",props:{files:{default:()=>[]},removable:{type:Boolean,default:!1}},emits:["remove"],setup(s){const e={doc:{kind:"word",labelKey:"chat.fileTypeDoc"},docx:{kind:"word",labelKey:"chat.fileTypeDoc"},xls:{kind:"excel",labelKey:"chat.fileTypeSheet"},xlsx:{kind:"excel",labelKey:"chat.fileTypeSheet"},csv:{kind:"excel",labelKey:"chat.fileTypeSheet"},ppt:{kind:"ppt",labelKey:"chat.fileTypeSlides"},pptx:{kind:"ppt",labelKey:"chat.fileTypeSlides"},pdf:{kind:"pdf",labelKey:"chat.fileTypePdf"},txt:{kind:"text",labelKey:"chat.fileTypeText"},md:{kind:"text",labelKey:"chat.fileTypeText"},log:{kind:"text",labelKey:"chat.fileTypeText"},zip:{kind:"archive",labelKey:"chat.fileTypeArchive"},tar:{kind:"archive",labelKey:"chat.fileTypeArchive"},gz:{kind:"archive",labelKey:"chat.fileTypeArchive"},tgz:{kind:"archive",labelKey:"chat.fileTypeArchive"},bz2:{kind:"archive",labelKey:"chat.fileTypeArchive"},xz:{kind:"archive",labelKey:"chat.fileTypeArchive"},"7z":{kind:"archive",labelKey:"chat.fileTypeArchive"},rar:{kind:"archive",labelKey:"chat.fileTypeArchive"}},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=d=>{const h=String(d||"").split(/[/\\]/).filter(Boolean);return h.length?h[h.length-1]:String(d||"")},r=d=>{const h=(d.includes(".")&&d.split(".").pop()||"").trim().toLowerCase();return h&&e[h]?e[h]:h&&t.has(h)?{kind:"code",labelKey:"chat.fileTypeCode"}:{kind:"generic",labelKey:"chat.fileTypeGeneric"}},o=be(()=>(n.files||[]).map(d=>{const h=typeof d=="string"?d:String((d==null?void 0:d.path)||"");if(!h)return null;const p=typeof d=="object"&&d&&typeof d.name=="string"&&d.name||i(h),{kind:g,labelKey:v}=r(p);return{path:h,name:p,kind:g,labelKey:v}}).filter(d=>!!d)),a=oo(),c=Is(),l=be(()=>!c.isMobileViewport),u=d=>{l.value&&a.previewPath!==d.path&&a.openPreview(d.path)};return(d,h)=>(F(),U("div",T6,[(F(!0),U(Ie,null,Ze(o.value,p=>(F(),U("div",{key:p.path,class:Ce(["file-chip",{"is-clickable":l.value,"is-previewing":l.value&&Ne(a).previewPath===p.path}]),role:"listitem",title:p.name,onClick:g=>u(p)},[M("span",{class:"file-chip-icon",style:qe({background:`var(--file-kind-${p.kind})`})},[(F(),U("svg",E6,[M("path",{d:P6}),h[16]||(h[16]=M("path",{d:"M14 2v5a1 1 0 0 0 1 1h5"},null,-1)),p.kind==="word"?(F(),U(Ie,{key:0},[h[0]||(h[0]=M("path",{d:"M9 13h6"},null,-1)),h[1]||(h[1]=M("path",{d:"M9 16.5h6"},null,-1))],64)):p.kind==="excel"?(F(),U(Ie,{key:1},[h[2]||(h[2]=M("path",{d:"M9 12h6v5H9z"},null,-1)),h[3]||(h[3]=M("path",{d:"M9 14.5h6"},null,-1)),h[4]||(h[4]=M("path",{d:"M12 12v5"},null,-1))],64)):p.kind==="ppt"?(F(),U(Ie,{key:2},[h[5]||(h[5]=M("path",{d:"M9.5 17v-3.5"},null,-1)),h[6]||(h[6]=M("path",{d:"M12.5 17V12"},null,-1)),h[7]||(h[7]=M("path",{d:"M15.5 17v-2"},null,-1))],64)):p.kind==="pdf"?(F(),U(Ie,{key:3},[h[8]||(h[8]=M("path",{d:"M12 11.5v6"},null,-1)),h[9]||(h[9]=M("path",{d:"m9.5 15 2.5 2.5 2.5-2.5"},null,-1))],64)):p.kind==="text"?(F(),U(Ie,{key:4},[h[10]||(h[10]=M("path",{d:"M9 13h6"},null,-1)),h[11]||(h[11]=M("path",{d:"M9 16.5h4"},null,-1))],64)):p.kind==="code"?(F(),U(Ie,{key:5},[h[12]||(h[12]=M("path",{d:"m10 12.5-2 2 2 2"},null,-1)),h[13]||(h[13]=M("path",{d:"m14 12.5 2 2-2 2"},null,-1))],64)):p.kind==="archive"?(F(),U(Ie,{key:6},[h[14]||(h[14]=M("path",{d:"M9 12.5h6v4.5H9z"},null,-1)),h[15]||(h[15]=M("path",{d:"M11 12.5V11h2v1.5"},null,-1))],64)):me("",!0)]))],4),M("span",M6,[M("span",x6,Q(p.name),1),M("span",R6,Q(d.$t(p.labelKey)),1)]),s.removable?(F(),U("button",{key:0,type:"button",class:"file-chip-remove","aria-label":d.$t("chat.removeFile",{name:p.name}),onClick:De(g=>d.$emit("remove",p.path),["stop"])},[...h[17]||(h[17]=[M("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none","aria-hidden":"true"},[M("path",{d:"M2.5 2.5l5 5M7.5 2.5l-5 5",stroke:"currentColor","stroke-width":"1.5","stroke-linecap":"round"})],-1)])],8,I6)):me("",!0)],10,A6))),128))]))}}),AL=qt(L6,[["__scopeId","data-v-0e1473ca"]]),O6={key:0,class:"compact-brief-line",role:"separator"},D6={class:"compact-brief-text"},N6={key:0},$6=["innerHTML"],B6={key:1,class:"image-inline-row"},F6=["onClick"],H6=["src","alt"],U6={key:2,class:"image-inline-row video-inline-row"},W6=["src","alt"],z6={key:3,class:"user-bubble-expand-row"},j6=["title","aria-label","onClick"],V6={key:0,class:"user-bubble-actions"},G6=["title","aria-label","onClick"],K6=["title","aria-label","onClick"],q6={class:"user-bubble-time"},Q6={key:1,class:"assistant-message"},X6={key:0,class:"message-header icon-label"},Y6={key:0,class:"assistant-work-status"},J6={key:1,class:"action-item streaming-content immediate-show assistant-generating-block"},Z6={class:"text-output"},eU={class:"text-content assistant-generating-placeholder",role:"status","aria-live":"polite"},tU=["data-block-id"],sU=["onClick"],nU={class:"status-icon"},iU={class:"status-text"},rU=["onScroll"],oU={key:1,class:"text-output"},aU={key:2,class:"sub-agent-system-summary-line"},lU={class:"append-placeholder-content"},cU={key:0,class:"icon-label append-status"},uU={key:1,class:"icon-label append-status append-error-text"},dU={key:2,class:"append-meta"},hU={key:0},fU={key:1},pU={key:3,class:"append-warning icon-label"},mU={class:"append-placeholder-content"},gU={class:"icon-label append-status"},vU={key:0,class:"append-meta"},yU={key:0},bU={key:1},_U={key:1,class:"append-warning icon-label"},wU=["data-block-id"],SU=["onClick"],kU={class:"status-icon"},CU={class:"status-text"},TU=["onScroll"],AU={key:1,class:"text-output"},EU={key:2,class:"sub-agent-system-summary-line"},MU={class:"append-placeholder-content"},xU={key:0,class:"icon-label append-status"},RU={key:1,class:"icon-label append-status append-error-text"},IU={key:2,class:"append-meta"},PU={key:0},LU={key:1},OU={key:3,class:"append-warning icon-label"},DU={class:"append-placeholder-content"},NU={class:"icon-label append-status"},$U={key:0,class:"append-meta"},BU={key:0},FU={key:1},HU={key:1,class:"append-warning icon-label"},UU={key:2,class:"system-message"},WU=["data-block-id"],zU=["onClick"],jU={class:"status-icon"},VU={class:"status-text"},GU={class:"content-inner"},KU=["aria-label"],qU=["onClick"],QU={class:"quick-nav-preview-user"},XU={class:"quick-nav-preview-ai"},pC=10,mC=240,tp=8,YU=900,JU=36,wx=48.74,gC=34,Sx=116,ZU=ct({__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=Js(),o=be(()=>!!r.loaded||!!r.error),a=be(()=>!!n.historyLoading||!o.value),c=be(()=>rH(n.messages||[]));function l(z){var te;const ie=(te=z==null?void 0:z.metadata)==null?void 0:te.citations;return Array.isArray(ie)?ie:c.value.length?c.value:void 0}function u(z){var ie;return Array.isArray((ie=z==null?void 0:z.metadata)==null?void 0:ie.citations)}const d=be(()=>r.experiments.blockDisplayMode||"stacked"),h=be(()=>r.form.compact_message_display||r.experiments.compactMessageDisplay||"full"),p=be(()=>d.value==="stacked"||d.value==="minimal"),g=be(()=>r.form.use_custom_names&&r.form.self_identify||"Astrion"),v=be(()=>(lt.value,r.form.use_custom_names?r.form.user_name||S("chat.userDefaultName"):S("chat.userDefaultName"))),m=new Map,y=ge({}),_=ge(new Set),b=ge(!1);let k=null,w=new Map,T=0;const A=(z,ie)=>(z==null?void 0:z.id)||`user-bubble-${ie}`,C=(z,ie,te)=>{const de=A(z,ie);if(te instanceof HTMLElement){m.set(de,te),k&&k.observe(te);const Ee=y.value[de];Ee&&Ee.foldHeight===0&&requestAnimationFrame(()=>{te.isConnected&&D()})}else m.delete(de)},E=z=>{const ie=typeof(z==null?void 0:z.content)=="string"?z.content:"";if(!ie)return!1;const de=48*(pC+2),Ee=(ie.match(/\n/g)||[]).length;return ie.length>de||Ee>=pC+2},x=()=>{(Array.isArray(pe.value)?pe.value:[]).forEach((z,ie)=>{if(!z||z.role!=="user")return;const te=A(z,ie);if(y.value[te])return;const de=E(z);y.value[te]={needsFold:de,expanded:!1,foldHeight:0,fullHeight:0}})},D=()=>{m.forEach((z,ie)=>{if(!z.isConnected){m.delete(ie);return}const te=window.getComputedStyle(z),de=parseFloat(te.lineHeight),Ee=Number.isFinite(de)?de:24,fe=Math.round(Ee*pC),Qe=Math.ceil(z.scrollHeight),vt=Qe>fe+1,Pt=y.value[ie];y.value[ie]={needsFold:vt,expanded:(Pt==null?void 0:Pt.expanded)??!1,foldHeight:fe,fullHeight:Qe},z.style.setProperty("--bubble-fold-height",`${fe}px`),z.style.setProperty("--bubble-full-height",`${Qe}px`)})},N=(z,ie)=>{var de;const te=A(z,ie);return!!((de=y.value[te])!=null&&de.needsFold)},O=(z,ie)=>{var de;const te=A(z,ie);return!!((de=y.value[te])!=null&&de.expanded)},G=(z,ie)=>{const te=A(z,ie),de=y.value[te];return!!(de!=null&&de.needsFold)&&!(de!=null&&de.expanded)},Z=(z,ie)=>{const te=A(z,ie),de=y.value[te];!de||!de.needsFold||(y.value[te]={...de,expanded:!de.expanded})},q=z=>{lt.value;const ie=z==null?void 0:z.created_at;if(!ie)return"";const te=new Date(ie),Ee=Math.max(0,new Date().getTime()-te.getTime()),fe=Math.floor(Ee/1e3),Qe=Math.floor(fe/60),vt=Math.floor(Qe/60);if(Math.floor(vt/24)>=1){const Lt=te.getMonth()+1,Bs=te.getDate(),Fs=String(te.getHours()).padStart(2,"0"),fo=String(te.getMinutes()).padStart(2,"0");return S("common.timeDate",{month:Lt,day:Bs,hour:Fs,minute:fo})}return vt>0?S("common.hoursAgo",{n:vt}):Qe>0?S("common.minutesAgo",{n:Qe}):fe>0?S("common.secondsAgo",{n:fe}):S("common.justNow")},V=(z,ie)=>{const te=A(z,ie);return _.value.has(te)},I=async(z,ie)=>{const te=A(z,ie),de=typeof(z==null?void 0:z.content)=="string"?z.content:"";if(!(!de||_.value.has(te)))try{await navigator.clipboard.writeText(de),_.value.add(te);const Ee=w.get(te);Ee&&window.clearTimeout(Ee);const fe=window.setTimeout(()=>{_.value.delete(te),w.delete(te)},5e3);w.set(te,fe)}catch(Ee){console.warn("复制用户消息失败:",Ee)}},$=z=>{},L=()=>{k&&(k.disconnect(),m.forEach(z=>{z.isConnected&&k.observe(z)}))},K=()=>{const z=++T;requestAnimationFrame(()=>{requestAnimationFrame(()=>{z===T&&(b.value=!1)})})},se=/^\u6765\u81ea\s+(.+?)\s+\u7684(.+?)\nid:\s*(\S+)\n\n<(.+?)>\n<(\w+)([^>]*)>\n([\s\S]*?)\n<\/\5>\n<\/\4>$/,oe=/^From\s+(.+?)(?:\s+to\s+.+?)?\s*:\s*(.+?)\nid:\s*(\S+)\n\n<(.+?)>\n<(\w+)([^>]*)>\n([\s\S]*?)\n<\/\5>\n<\/\4>$/;function ve(z){const ie=String(z||""),te=ie.match(se)||ie.match(oe);if(!te)return null;const Ee=(te[6]||"").match(/subtype="([^"]+)"/);return{displayName:te[1].trim(),subtype:Ee?Ee[1]:"",content:te[7]}}function le(z){if(!z||z.role!=="user")return!1;const ie=z.metadata||{};return String(ie.auto_message_type||z.auto_message_type||"").startsWith("multi_agent_")}function ue(z){var de;lt.value;const ie=((de=z==null?void 0:z.metadata)==null?void 0:de.multi_agent_display_name)||(z==null?void 0:z.multi_agent_display_name);if(ie)return ie;const te=ve((z==null?void 0:z.content)||"");return(te==null?void 0:te.displayName)||S("chat.subAgentName")}function P(z,ie){if(!le(z))return!1;const de=he()[ie-1];return!de||!le(de)?!1:ue(z)===ue(de)}function X(z){const ie=ve((z==null?void 0:z.content)||"");return((ie==null?void 0:ie.content)||(z==null?void 0:z.content)||"").trim()}const J=z=>String(z||"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),ne=/\[\$([^\]\n]+)\]\(((?:[^)\n]*[\\/])?\.astrion[\\/]skills[\\/][^)\n]+[\\/]SKILL\.md)\)/g,ce=/\[([^\]\n]+)\]\(file:\/\/([^)\n]+)\)/g,_e=/^(?:\u5b50\u667a\u80fd\u4f53\d+\s*\u4efb\u52a1\u5b8c\u6210|Sub-agent\s*\d+\s*complete)$/,Pe=/^(?:✅\s*)?(?:\u5b50\u667a\u80fd\u4f53|Sub-agent)\s*#?\s*(\d+)\s*(?:\u4efb\u52a1\u6458\u8981|task summary)[::]/,it=/^(?:\[)?(?:\u540e\u53f0\s*run_command\s*\u5b8c\u6210|Background\s*run_command\s*finished)(?:\])?$/,at=new Set(["thinking","text","tool","append","append_payload","system"]);function rt(z){const ie=String(z||""),te=new RegExp(`(?:${ne.source})|(?:${ce.source})`,"g");let de="",Ee=0,fe;for(;fe=te.exec(ie);)de+=J(ie.slice(Ee,fe.index)),fe[1]!==void 0?de+=` <span class="user-skill-link">${J(fe[1]||"")}</span> `:fe[3]!==void 0&&(de+=` <span class="user-file-link">${J(fe[3]||"")}</span> `),Ee=fe.index+fe[0].length;return de+=J(ie.slice(Ee)),de}const Oe=z=>!z||z.role!=="user"?!1:Fd(z)==="hidden",xe=z=>!z||z.role!=="assistant"||(Array.isArray(z.actions)?z.actions:[]).some(Ee=>_d(Ee))||z.awaitingFirstContent?!1:!!!(z.streaming||z.currentStreamingType||z.streamingText||z.streamingThinking),pe=be(()=>{const z=n.messages||[];z.filter(de=>de&&de.role==="system").length>0;const te=z.filter(de=>de&&de.metadata&&de.metadata.system_injected_image||(de==null?void 0:de.role)==="system"||Oe(de)?!1:xe(de)?(jt("ChatArea.filteredMessages:drop-empty-assistant",{actions:Array.isArray(de==null?void 0:de.actions)?de.actions.map(Ee=>Ee==null?void 0:Ee.type):[],awaitingFirstContent:!!(de!=null&&de.awaitingFirstContent)}),!1):!0);return z.length!==te.length&&jt("ChatArea.filteredMessages:dropped",{sourceLength:z.length,resultLength:te.length,dropped:z.length-te.length}),te}),he=()=>Array.isArray(pe.value)?pe.value:[],ye=be(()=>{var de,Ee,fe;const z=new Map,ie=he(),te=!!r.form.edit_summary_live_display;for(let Qe=0;Qe<ie.length;Qe+=1){const vt=ie[Qe];if(!vt||vt.role!=="user"||!$v(vt))continue;const Pt=(de=vt.metadata)==null?void 0:de.edit_summary;if(!Pt||!Array.isArray(Pt.files)||Pt.files.length===0)continue;if(!te){const Bs=(fe=(Ee=vt.metadata)==null?void 0:Ee.work_timer)==null?void 0:fe.status;if(Bs&&Bs!=="completed")continue}let Lt=-1;for(let Bs=Qe+1;Bs<ie.length;Bs+=1){const Fs=ie[Bs];if((Fs==null?void 0:Fs.role)==="user"&&$v(Fs))break;(Fs==null?void 0:Fs.role)==="assistant"&&(Lt=Bs)}Lt>=0&&z.set(Lt,Pt)}return z}),ke=be(()=>he().length-1),Le=ge(Date.now());let st=null;const gt=new Set,Wt=new Set,jt=(...z)=>{},{scrollRef:ht,contentRef:Qt,isAtBottom:It,isNearBottom:ns,escapedFromLock:ot,scrollToBottom:$s,stopScroll:Er}=h3({resize:"instant",initial:"instant"}),In=new WeakMap;let Ko=0;const ao=(z,ie)=>{if(z&&typeof z=="object"){let te=In.get(z);if(!te){const de=z.id;te=de!=null?`msg-${String(de)}`:`mk-${++Ko}`,In.set(z,te)}return te}return`idx-${ie}`},Pn=be(()=>ht.value??void 0),qo=be(()=>{if(!n.streamingMessage)return[];const z=ke.value;return z>=0?[z]:[]});tF("mathRenderedCallback",()=>{wl||ns.value&&Cs&&requestAnimationFrame(()=>{Cs({preserveScrollPosition:!1})})});const Yn=ht,{anchorBlockElement:Oi,stopAll:Mr}=M3(ht,{stopScroll:Er});let Di=null;function gl(){if(Di=null,!n.streamingMessage)return;const z=ht.value;if(z&&!wl&&It.value&&!ot.value){const ie=z.scrollHeight-z.clientHeight;ie-z.scrollTop>1&&(Sa("ChatArea.liveStickLock"),z.scrollTop=ie)}Di=requestAnimationFrame(gl)}function Qo(){Di!==null&&(cancelAnimationFrame(Di),Di=null)}Ke(()=>n.streamingMessage,z=>{z?Di===null&&(Di=requestAnimationFrame(gl)):Qo()},{immediate:!0});const lo=new Map;let fi=null,Ni=0;const wa=new Map;let vl=0,re=0,we=0,Ae=0,bt=0,hs="",Ps=0,is=!1,en=null,ut=null,pn=null,co=null,$i=null,Bc=!1,xr=0,Bi=!1;function Fc(z){const ie=ht.value;if(!ie||!(z instanceof HTMLElement))return!1;let te=z;for(;te&&te!==ie;){if(te.scrollHeight>te.clientHeight+2){const de=getComputedStyle(te).overflowY;if(de==="auto"||de==="scroll")return!0}te=te.parentElement}return!1}function Fi(){var z;if(typeof window>"u")return!1;try{const ie=window.__SCROLL_BOUNCE_TRACE__;if(ie===!1||ie==="0")return!1;if(ie===!0||ie==="1")return!0;const te=(z=window.localStorage)==null?void 0:z.getItem("scrollBounceTrace");return te==="0"||te==="false"?!1:te==="1"||te==="true"}catch{return!1}}function mn(z){const ie=z.scrollTop,te=z.scrollHeight,de=z.clientHeight;return{top:ie,height:te,client:de,remain:te-ie-de,hasShowHtml:!!z.querySelector("show_html, show-html, .chat-inline-html, .chat-inline-card--html")}}function Hi(z,ie={},te=z,de=120){if(!Fi()||Ni>=mC)return;const Ee=Date.now(),fe=wa.get(te)||0;if(!(de>0&&Ee-fe<de)){if(wa.set(te,Ee),Ni+=1,Ni===mC){console.warn("[SCROLL_BOUNCE_TRACE]","log-limit-reached",{max:mC});return}console.log("[SCROLL_BOUNCE_TRACE]",z,ie)}}function Sa(z){bt=Date.now(),hs=z}function yl(){const z=ht.value;z&&en&&z.removeEventListener("scroll",en),z&&ut&&z.removeEventListener("wheel",ut,!0),z&&pn&&z.removeEventListener("touchstart",pn,!0),z&&co&&z.removeEventListener("touchmove",co,!0),z&&$i&&(z.removeEventListener("touchend",$i,!0),z.removeEventListener("touchcancel",$i,!0)),en=null,ut=null,pn=null,co=null,$i=null}function Hc(){const z=ht.value;z&&(en&&z.removeEventListener("scroll",en),ut&&z.removeEventListener("wheel",ut,!0),pn&&z.removeEventListener("touchstart",pn,!0),co&&z.removeEventListener("touchmove",co,!0),$i&&(z.removeEventListener("touchend",$i,!0),z.removeEventListener("touchcancel",$i,!0)),vl=z.scrollTop||0,re=z.scrollHeight||0,xr=0,Bi=!1,pn=ie=>{if(ie.touches.length!==1){xr=0,Bi=!1;return}xr=ie.touches[0].clientY,Bi=!1},co=ie=>{if(Bi||!xr||ie.touches.length!==1)return;const te=ht.value;if(!te)return;const de=ie.touches[0].clientY-xr;if(de<=8)return;const Ee=Date.now();Ee<=Ps||Fc(ie.target)||(Bi=!0,Ae=Ee,Er(),Mr(),qf(),i("user-scroll-intent",{ts:Ee,delta:-de,top:te.scrollTop||0}),Hi("user-scroll-intent:touch-drag",{deltaY:de,top:te.scrollTop||0,...mn(te)},"user-scroll-intent:touch-drag",80))},$i=()=>{xr=0,Bi=!1},z.addEventListener("touchstart",pn,{passive:!0,capture:!0}),z.addEventListener("touchmove",co,{passive:!0,capture:!0}),z.addEventListener("touchend",$i,{passive:!0,capture:!0}),z.addEventListener("touchcancel",$i,{passive:!0,capture:!0}),ut=ie=>{const te=ht.value;if(!te)return;const de=ie.isTrusted===!0,Ee=Number(ie.deltaY||0);if(!(de&&Ee<-1&&Date.now()>Ps))return;const fe=Date.now();Ae=fe,Er(),Mr(),qf(),i("user-scroll-intent",{ts:fe,delta:Ee,top:te.scrollTop||0}),Hi("user-scroll-intent:wheel-up",{deltaY:Ee,top:te.scrollTop||0,...mn(te)},"user-scroll-intent:wheel-up",80)},z.addEventListener("wheel",ut,{passive:!0,capture:!0}),en=ie=>{const te=ie.target;if(!te)return;const de=ie.isTrusted===!0,Ee=te.scrollTop,fe=Ee-vl,Qe=te.scrollHeight||0,vt=Qe-re;vl=Ee,re=Qe,E_(Ee),vt!==0&&Hi("height-change",{heightDelta:vt,scrollHeight:Qe,top:Ee,delta:fe,escapedFromLock:ot.value,isAtBottom:It.value,isNearBottom:ns.value},"height-change",120);const Pt=Math.max(200,te.clientHeight*.35||200);!is&&vt>Pt&&!ot.value&&(Hi("large-growth:trigger",{heightDelta:vt,threshold:Pt,top:Ee,delta:fe,escapedFromLock:ot.value,isAtBottom:It.value,isNearBottom:ns.value},"large-growth:trigger",0),is=!0,Sa("ChatArea.largeGrowth"),Ps=Date.now()+900,$s({animation:"instant",preserveScrollPosition:!1}),Hi("large-growth:instant-scroll",{heightDelta:vt,threshold:Pt,...mn(te)},"large-growth:instant-scroll",120),setTimeout(()=>{is=!1},400));const Lt=Date.now(),Bs=Lt-bt<=140,Fs=Math.abs(vt)>2,fo=fe<-3&&Lt-Ae<=240,Jo=fe<-18&&Lt>Ps&&!Bs;if(de&&Math.abs(fe)>5&&Lt>Ps&&(!Bs||Jo)&&(fe<0&&(Jo||fo)||!Fs)&&(Er(),Mr(),we=Lt,i("user-scroll-intent",{ts:we,delta:fe,top:Ee}),Hi("user-scroll-intent",{delta:fe,top:Ee,ts:we,closeToProgrammaticHint:Bs,likelyLayoutDriven:Fs,manualUpByWheel:fo,strongManualUp:Jo,...mn(te)},"user-scroll-intent",120)),fe<-8){if(Lt-we<=1400){const kl=Lt-bt<=1200;Hi("rebound:detected",{delta:fe,trusted:de,likelySource:kl?hs||"programmatic-unknown":"unknown(internal-stick/browser-anchor)",msSinceUserDown:Lt-we,msSinceProgrammatic:Lt-bt,...mn(te),stickState:{isAtBottom:!!It.value,isNearBottom:!!ns.value,escapedFromLock:!!ot.value}},"rebound:detected",0)}}else Hi("scroll:event",{delta:fe,trusted:de,...mn(te),stickState:{isAtBottom:!!It.value,isNearBottom:!!ns.value,escapedFromLock:!!ot.value}},"scroll:event",180)},z.addEventListener("scroll",en,{passive:!0}),!Bc&&Fi()&&(Bc=!0,console.warn("[SCROLL_BOUNCE_TRACE]","listener-attached",{hasElement:!!z,className:z.className||""})))}function Xo(){const z=ht.value;if(!z)return;const ie=Math.max(0,z.offsetWidth-z.clientWidth);z.style.setProperty("--chat-scrollbar-width",`${ie}px`)}Ke([It,ns,ot],([z,ie,te])=>{i("stick-state-change",{isAtBottom:!!z,isNearBottom:!!ie,escapedFromLock:!!te})},{immediate:!0});function Yo(z){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(z):z.replace(/["\\]/g,"\\$&")}const et=ge(new Set);function ae(z){return n.streamingMessage?wl?!0:!(!ot.value&&!!It.value)||!z?!1:z.classList.contains("processing")||z.classList.contains("running")||!!z.querySelector(".processing, .running, .thinking-animation"):!1}Ke(()=>n.expandedBlocks,(z,ie)=>{const te=ie??et.value,de=new Set([...Array.from(z),...Array.from(te)]),Ee=new Set;for(const Qe of de)z.has(Qe)!==te.has(Qe)&&Ee.add(Qe);if(et.value=new Set(z),Ee.size===0)return;const fe=ht.value;if(fe)for(const Qe of Ee){const vt=fe.querySelector(`[data-block-id="${Yo(Qe)}"]`);ae(vt)||vt&&Oi(vt,Qe,{direction:"auto",duration:260,phase:z.has(Qe)?"expand":"collapse"})}},{flush:"post"});function Me(z){ae(z.element)||Oi(z.element,`more-${z.stackKey}`,{direction:"auto",duration:260,phase:expanded?"expand":"collapse"})}function Ge(z){const{groupId:ie,expanded:te}=z,de=ht.value;if(!de)return;const Ee=de.querySelector(`[data-group-id="${Yo(ie)}"]`);ae(Ee)||Ee&&Oi(Ee,ie,{direction:"auto",duration:300,phase:te?"expand":"collapse"})}const Bt=(z,ie)=>{if(!(ie instanceof HTMLElement))return;const te=600;requestAnimationFrame(()=>{const de=ie.scrollHeight||ie.offsetHeight||0;de>0&&ie.style.setProperty("--collapse-max",`${Math.min(de,te)}px`)})};function Tt(z,ie){ie instanceof HTMLElement?lo.set(z,ie):lo.delete(z)}function Zt(z){return lo.get(z)||null}async function Cs(z={}){const ie=ht.value;return ie&&Hi("programmatic:scrollToBottom:before",{source:"ChatArea.stickScrollToBottom",behavior:z.behavior||"auto",force:!!z.force,preserveScrollPosition:!!z.preserveScrollPosition,...mn(ie)},"programmatic:scrollToBottom:before",80),Sa("ChatArea.stickScrollToBottom"),(z.force||z.behavior==="smooth")&&(Ps=Date.now()+900),await $s({animation:z.behavior==="smooth"?"smooth":"auto",ignoreEscapes:!!z.force,preserveScrollPosition:!!z.preserveScrollPosition,duration:z.force?260:0})}async function pi(z={}){const ie=ht.value;return ie&&Hi("programmatic:conditional:before",{source:"ChatArea.stickConditionalScrollToBottom",force:!!z.force,...mn(ie)},"programmatic:conditional:before",100),Sa("ChatArea.stickConditionalScrollToBottom"),z.force?await Cs({force:!0,preserveScrollPosition:!1}):await Cs({preserveScrollPosition:!1})}function mi(){return{isAtBottom:!!It.value,isNearBottom:!!ns.value,escapedFromLock:!!ot.value}}function fs(z,ie){return typeof n.iconStyle=="function"?n.iconStyle(z,ie):{}}function Es(z){return z?typeof z=="string"?z:typeof(z==null?void 0:z.path)=="string"?z.path:typeof(z==null?void 0:z.source_path)=="string"?z.source_path:"":""}function rs(z){const ie=Es(z);if(!ie)return typeof(z==null?void 0:z.name)=="string"&&z.name?z.name:typeof(z==null?void 0:z.title)=="string"&&z.title?z.title:typeof(z==null?void 0:z.media_id)=="string"&&z.media_id?z.media_id:"";const te=ie.split(/[/\\]/);return te[te.length-1]||ie}function Ln(z){var te;const ie=(te=z==null?void 0:z.metadata)==null?void 0:te.files;return Array.isArray(ie)?ie.filter(de=>typeof de=="string"&&de||de&&typeof de.path=="string"&&de.path).slice(0,9):[]}function bd(z,ie){const te=Ui(z,ie,"image");te&&Is().openImagePreview({url:te,name:rs(ie)})}function cr(z,ie,te){var vt;const de=(z==null?void 0:z.media_refs)||((vt=z==null?void 0:z.metadata)==null?void 0:vt.media_refs)||[];if(!Array.isArray(de)||!de.length)return null;const Ee=typeof(ie==null?void 0:ie.media_id)=="string"?ie.media_id:"";if(Ee){const Pt=de.find(Lt=>(Lt==null?void 0:Lt.media_id)===Ee);if(Pt)return Pt}const fe=Es(ie);if(fe){const Pt=de.find(Lt=>Lt&&Lt.kind===te&&typeof Lt.source_path=="string"&&Lt.source_path===fe);if(Pt)return Pt}return de.find(Pt=>Pt&&Pt.kind===te)||null}function Ui(z,ie,te){const de=cr(z,ie,te),Ee=typeof(de==null?void 0:de.media_id)=="string"?de.media_id:"";if(Ee)return`/api/conversations/media/${encodeURIComponent(Ee)}`;const fe=Es(ie);return fe?`/api/gui/files/download?path=${encodeURIComponent(fe)}`:""}function Rr(z,ie,te){const de=cr(z,ie,"image")||cr(z,ie,"video");if(typeof(de==null?void 0:de.media_id)=="string"&&de.media_id)return`${de.media_id}-${te}`;const Ee=Es(ie);return Ee?`${Ee}-${te}`:`media-${te}`}function Sg(z){const ie=Math.max(0,Math.floor((z||0)/1e3)),te=Math.floor(ie/3600),de=Math.floor(ie%3600/60),Ee=ie%60;return te>0?`${String(te).padStart(2,"0")}:${String(de).padStart(2,"0")}:${String(Ee).padStart(2,"0")}`:`${String(de).padStart(2,"0")}:${String(Ee).padStart(2,"0")}`}function Uc(z){if(lt.value,!z||z.type!=="system")return null;const ie=typeof z.content=="string"?z.content.trim():"",te=(z==null?void 0:z.id)||`no-id-${ie.slice(0,32)}`;if(!ie)return gt.has(`${te}-empty`)||gt.add(`${te}-empty`),null;if(z.variant==="sub_agent_done"&&(_e.test(ie)||it.test(ie)))return gt.has(`${te}-variant-pass`)||gt.add(`${te}-variant-pass`),ie;const de=ie.match(Pe);return de&&/(?:\u5df2\u5b8c\u6210|Completed\.)/.test(ie)?(gt.has(`${te}-regex-pass`)||gt.add(`${te}-regex-pass`),S("chat.subAgentDoneLabel",{n:de[1]})):(gt.has(`${te}-blocked`)||gt.add(`${te}-blocked`),null)}function _d(z){if(!z)return!1;const ie=z.type;if(!at.has(ie)){const te=(z==null?void 0:z.id)||`unknown-${ie||"none"}`;return Wt.has(te)||Wt.add(te),!1}if(z.type==="tool"){const te=(z==null?void 0:z.tool)||{},de=typeof te.name=="string"&&te.name.trim().length>0,Ee=typeof te.message=="string"&&te.message.trim().length>0,fe=te.result!==null&&te.result!==void 0,Qe=te.arguments&&typeof te.arguments=="object"&&Object.keys(te.arguments).length>0;return de||Ee||fe||Qe}return z.type!=="system"?!0:!!Uc(z)}function k_(z=[]){return(z||[]).some(ie=>_d(ie))}function C_(z){if(!z||z.role!=="assistant")return!1;const ie=(z.actions||[]).filter(Ee=>_d(Ee));if(ie.length!==1)return!1;const te=ie[0],de=(te==null?void 0:te.type)==="system"&&!!Uc(te);return de&&jt("ChatArea.isSubAgentNoticeOnlyMessage:hit",{actionId:te==null?void 0:te.id,content:te==null?void 0:te.content}),de}function Fk(z){var Ee;const ie=he(),te=ie[z+1],de=!!te&&C_(te);return de&&jt("ChatArea.isFollowedBySubAgentNotice:hit",{index:z,currentRole:(Ee=ie[z])==null?void 0:Ee.role,nextRole:te==null?void 0:te.role}),de}function Wc(z){var Qe;if(lt.value,z<=0)return"";const ie=T_(z),te=(Qe=ie==null?void 0:ie.metadata)==null?void 0:Qe.work_timer;if(!te||!te.started_at)return"";const de=Date.parse(te.started_at);if(!Number.isFinite(de))return"";if((te.status||"working")==="working")return S("chat.workInProgress",{duration:Sg(Le.value-de)});const fe=typeof te.duration_ms=="number"?te.duration_ms:Math.max(0,(Number.isFinite(Date.parse(te.finished_at||""))?Date.parse(te.finished_at):Le.value)-de);return S("chat.workCompleted",{duration:Sg(fe)})}function Hk(z){return!!T_(z)}function T_(z){if(z<=0)return null;const ie=he(),te=ie[z-1];if(!te||te.role!=="user")return null;for(let de=z-1;de>=0;de-=1){const Ee=ie[de];if(!Ee||Ee.role!=="user")break;if($v(Ee))return Ee}return null}function jf(z){var ie;return String(((ie=z==null?void 0:z.metadata)==null?void 0:ie.message_source)||"user").trim().toLowerCase()}function bl(z){lt.value;const ie=jf(z);return ie==="guidance"?S("chat.userHeaderGuide"):ie==="goal"?S("chat.userHeaderGoal"):ie==="goal_review"?S("chat.userHeaderReview"):ie==="compression"||ie==="compression_handoff"?S("chat.userHeaderCompression"):ie==="notify"||ie==="sub_agent"||ie==="background_command"?S("chat.userHeaderNotify"):v.value}function uo(z){const ie=jf(z);return ie==="guidance"?"navigation":ie==="goal"?"flag":ie==="goal_review"?"circleAlert":ie==="compression"||ie==="compression_handoff"?"layers":ie==="notify"||ie==="sub_agent"||ie==="background_command"?"bell":"user"}function ka(z){return!z||z.role!=="user"||h.value!=="brief"?!1:Fd(z)==="compact"}function zc(z){switch(lt.value,jf(z)){case"goal_review":return S("chat.briefGoalReview");case"sub_agent":return S("chat.briefSubAgent");case"background_command":return S("chat.briefBackgroundCommand");case"compression":case"compression_handoff":return S("chat.briefCompression");case"goal":return S("chat.briefGoal");case"guidance":return S("chat.briefGuidance");case"notify":return S("chat.briefNotify");default:return S("chat.briefSystem")}}Ke(()=>he().map(z=>{var ie;return(z==null?void 0:z.id)??((ie=z==null?void 0:z.content)==null?void 0:ie.slice(0,80))}),()=>{b.value=!0,x(),ft(()=>{requestAnimationFrame(()=>{D(),L(),K()})})},{immediate:!0}),dn(()=>{Hc(),Xo(),typeof ResizeObserver<"u"&&ht.value&&(fi=new ResizeObserver(Xo),fi.observe(ht.value)),typeof ResizeObserver<"u"&&(k=new ResizeObserver(()=>{requestAnimationFrame(D)}),ft(()=>L())),Fi()&&console.warn("[SCROLL_BOUNCE_TRACE]","mounted",{hasScrollRef:!!ht.value}),st=window.setInterval(()=>{Le.value=Date.now()},1e3),Gk()}),Ke(ht,()=>{Hc(),Xo(),fi&&(fi.disconnect(),fi=null),typeof ResizeObserver<"u"&&ht.value&&(fi=new ResizeObserver(Xo),fi.observe(ht.value))}),Rn(()=>{yl(),Mr(),qf(),Qo(),fi&&(fi.disconnect(),fi=null),k&&(k.disconnect(),k=null),m.clear(),w.forEach(z=>window.clearTimeout(z)),w.clear(),st!==null&&(clearInterval(st),st=null),Kk()});const jc=z=>z&&(z.type==="thinking"||z.type==="tool"),kg=z=>!z||z.type!=="text"?!1:!(typeof z.content=="string"?z.content:"").trim(),Vf=(z=[],ie=0)=>{const te=[];let de=[];const Ee=()=>{de.length>=1&&te.push({kind:"stack",actions:de.slice(),key:`stack-${ie}-${te.length}`}),de=[]};return z.forEach((fe,Qe)=>{kg(fe)||(jc(fe)?de.push(fe):(Ee(),te.push({kind:"single",action:fe,actionIndex:Qe,key:fe.id||`single-${ie}-${Qe}`})))}),Ee(),te};function Cg(z){lt.value;const ie=typeof(z==null?void 0:z.generatingLabel)=="string"&&z.generatingLabel.trim()?z.generatingLabel.trim():S("chat.generating");return Array.from(ie)}const ur=ge(null),Tg=ge(null),_l=ge(-1),Gf=new Map,Uk=z=>{var te;if(!z||z.role!=="user")return!1;const ie=String(((te=z==null?void 0:z.metadata)==null?void 0:te.message_source)||"user").trim().toLowerCase();return ie==="user"||ie==="presend"};function wd(z){lt.value;const ie=z==null?void 0:z.content;let te="";return typeof ie=="string"?te=ie:Array.isArray(ie)?te=ie.filter(Ee=>Ee&&Ee.type==="text"&&typeof Ee.text=="string").map(Ee=>Ee.text).join(`
|
||
`):ie!=null&&(te=String(ie)),te.split(`
|
||
`).map(Ee=>Ee.trim()).filter(Ee=>Ee&&!Ee.startsWith("[系统通知|"))[0]||S("chat.emptyInput")}function Ag(z){const ie=Array.isArray(z==null?void 0:z.actions)?z.actions:[];for(let de=ie.length-1;de>=0;de-=1){const Ee=ie[de];if((Ee==null?void 0:Ee.type)==="text"&&typeof(Ee==null?void 0:Ee.content)=="string"&&Ee.content.trim())return Ee.content.trim()}const te=z==null?void 0:z.content;return typeof te=="string"?te.trim():""}const ho=be(()=>{lt.value;const z=he(),ie=[];for(let te=0;te<z.length;te+=1)Uk(z[te])&&ie.push(te);return ie.map((te,de)=>{const Ee=de+1<ie.length?ie[de+1]:z.length;let fe="";for(let Qe=Ee-1;Qe>te;Qe-=1){const vt=z[Qe];if(!vt||vt.role!=="assistant")continue;const Pt=Ag(vt);if(Pt){fe=Pt;break}}return{msgIndex:te,userText:wd(z[te]),aiText:fe||S("chat.noReply")}})}),A_=[34,25,17,12];function Wk(z){const ie=_l.value;if(ie<0)return tp;const te=Math.abs(z-ie),de=A_[te]??tp;if(de===tp)return de;const Ee=zk.value;return Math.max(tp,Math.round(de*Ee))}const Eg=ge(-1);function E_(z){var Pt;const ie=ho.value;if(!ie.length){Eg.value=-1;return}const te=Tg.value;if(!te)return;const de=typeof z=="number"?z:Number(te.scrollOffset)||0,Ee=Number(te.viewportSize)||((Pt=ur.value)==null?void 0:Pt.clientHeight)||0,fe=de+Ee*.25,Qe=te.findItemIndex(fe);let vt=-1;for(let Lt=0;Lt<ie.length&&ie[Lt].msgIndex<=Qe;Lt+=1)vt=Lt;Eg.value=vt<0?0:vt}Ke(ho,()=>{E_()});const Kf=ge(100),Mg=ge(!0),xg=ge(wx/2),Sd=be(()=>Kf.value<JU?"hidden":Mg.value?"pinned":"center"),zk=be(()=>{const z=Kf.value;if(Sd.value==="pinned"){const ie=xg.value-tp/2;return Math.max(0,Math.min(1,(z-ie-6)/gC))}return Sd.value==="center"?Math.max(0,Math.min(1,(z-6)/gC)):1}),jk=be(()=>{const z={"--qn-count":String(ho.value.length)};if(Sd.value==="center")return{...z,left:"0px",width:`${Kf.value}px`};const ie=xg.value-tp/2;return{...z,left:`${ie}px`,width:`${gC}px`}});function M_(){const z=ur.value,ie=Qt.value;if(!z||!ie)return;const te=z.getBoundingClientRect(),de=ie.getBoundingClientRect(),Ee=ht.value,fe=Ee?Math.max(0,Ee.offsetWidth-Ee.clientWidth):0;xg.value=(wx+fe/2)/2,Kf.value=de.left-te.left,Mg.value=de.width>=YU-.5}let Ks=null;function Ir(z,ie){ie?Gf.set(z,ie):Gf.delete(z)}function Vk(z){let ie=-1,te=1/0;Gf.forEach((de,Ee)=>{const fe=de.getBoundingClientRect(),Qe=Math.abs(z.clientY-(fe.top+fe.height/2));Qe<te&&(te=Qe,ie=Ee)}),_l.value=ie}function x_(){_l.value=-1}function Gk(){typeof ResizeObserver>"u"||!ur.value||(Ks=new ResizeObserver(()=>{M_()}),Ks.observe(ur.value),Qt.value&&Ks.observe(Qt.value),M_())}function Kk(){Ks&&(Ks.disconnect(),Ks=null)}let Vc=null,wl=!1;function qf(){Vc!==null&&(cancelAnimationFrame(Vc),Vc=null),wl=!1}function qk(z){var vt;const ie=ht.value,te=Tg.value;if(!ie||!te||typeof te.getItemOffset!="function"){(vt=te==null?void 0:te.scrollToIndex)==null||vt.call(te,z,{align:"start",smooth:!0});return}qf(),wl=!0;const de=ie.scrollTop,Ee=performance.now(),fe=380,Qe=()=>{if(Vc=null,!wl)return;const Pt=Math.max(0,ie.scrollHeight-ie.clientHeight),Lt=Math.max(0,Math.min(Number(te.getItemOffset(z))||0,Pt)),Bs=Math.min(1,(performance.now()-Ee)/fe),Fs=1-Math.pow(1-Bs,3);Sa("ChatArea.quickNavJump"),ie.scrollTop=de+(Lt-de)*Fs,Bs<1?Vc=requestAnimationFrame(Qe):(Sa("ChatArea.quickNavJump"),ie.scrollTop=Lt,wl=!1)};Vc=requestAnimationFrame(Qe)}function R_(z){const ie=ht.value,te=Date.now();Er(),Mr(),i("user-scroll-intent",{ts:te,delta:-1,top:ie&&ie.scrollTop||0}),qk(z.msgIndex)}const kd=ge(""),I_=ge(""),Cd=ge({});return Ke(_l,z=>{if(z<0)return;const ie=ho.value[z];if(!ie)return;kd.value=ie.userText,I_.value=ie.aiText;const te=ur.value,de=Gf.get(z);if(!te||!de)return;const Ee=te.getBoundingClientRect(),fe=de.getBoundingClientRect();let vt=fe.top-Ee.top+fe.height/2-Sx/2;vt=Math.max(8,Math.min(vt,Ee.height-Sx-8));const Pt=fe.right-Ee.left+14;Cd.value={top:`${vt}px`,left:`${Pt}px`}}),e({rootEl:Yn,getThinkingRef:Zt,isUsingStickToBottom:()=>!0,getStickState:mi,stopStickScroll:Er,scrollToBottom:Cs,conditionalStickToBottom:pi}),(z,ie)=>(F(),U("div",{class:"chat-area-shell",ref_key:"shellRef",ref:ur},[M("div",{class:Ce(["messages-area messages-area--stick",{"messages-area--render-pending":a.value}]),ref_key:"scrollRef",ref:ht},[M("div",{class:"messages-flow",ref_key:"contentRef",ref:Qt},[Pn.value?(F(),Ft(Ne(E3),{key:0,ref_key:"virtualizerRef",ref:Tg,data:pe.value||[],"scroll-ref":Pn.value,"buffer-size":400,"keep-mounted":qo.value},{default:Gt(({item:te,index:de})=>{var Ee;return[(F(),U("div",{key:ao(te,de),class:Ce(["message-block",{"message-block--compact-user":Ne(Fd)(te)==="compact","message-block--sub-agent-notice":C_(te),"message-block--before-sub-agent-notice":Fk(de),"message-block--multi-agent":le(te),"message-block--first":de===0,"message-block--last":de===(pe.value||[]).length-1}])},[te.role==="user"?(F(),U("div",{key:0,class:Ce(["user-message",{"user-message--multi-agent":le(te),"user-message--compact":Ne(Fd)(te)==="compact","user-message--brief":ka(te)}])},[ka(te)?(F(),U("div",O6,[M("span",D6,Q(zc(te)),1)])):(F(),U(Ie,{key:1},[M("div",{class:Ce(["message-header icon-label",{"message-header--multi-agent":le(te),"message-header--hidden":le(te)&&P(te,de)}])},[le(te)?(F(),U("span",N6,Q(ue(te)),1)):(F(),U(Ie,{key:1},[M("span",{class:"icon icon-sm",style:qe(fs(uo(te))),"aria-hidden":"true"},null,4),M("span",null,Q(bl(te)),1)],64))],2),M("div",{class:Ce(["message-text user-bubble-text",{"is-collapsed":G(te,de),"is-expandable":N(te,de),"is-history-loading":n.historyLoading||b.value}])},[te.content?(F(),U("div",{key:0,class:Ce(["bubble-text",{"is-expanded":O(te,de)}]),ref:fe=>C(te,de,fe)},[le(te)?(F(),Ft(zg,{key:0,content:X(te),"is-streaming":!1},null,8,["content"])):(F(),U("span",{key:1,innerHTML:rt(te.content)},null,8,$6))],2)):me("",!0),te.images&&te.images.length||Ln(te).length?(F(),U("div",B6,[(F(!0),U(Ie,null,Ze(te.images,(fe,Qe)=>(F(),U("div",{class:"image-thumbnail-wrapper",key:Rr(te,fe,Qe),onClick:De(vt=>bd(te,fe),["stop"])},[M("img",{src:Ui(te,fe,"image"),alt:rs(fe),class:"image-thumbnail"},null,8,H6)],8,F6))),128)),Ln(te).length?(F(),Ft(AL,{key:0,files:Ln(te)},null,8,["files"])):me("",!0)])):me("",!0),te.videos&&te.videos.length?(F(),U("div",U6,[(F(!0),U(Ie,null,Ze(te.videos,(fe,Qe)=>(F(),U("div",{class:"image-thumbnail-wrapper",key:Rr(te,fe,Qe)},[M("img",{src:Ui(te,fe,"video"),alt:rs(fe),class:"image-thumbnail"},null,8,W6)]))),128))])):me("",!0),N(te,de)?(F(),U("div",z6,[M("button",{class:Ce(["user-bubble-action-btn user-bubble-expand-btn",{expanded:O(te,de)}]),title:O(te,de)?z.$t("chat.collapse"):z.$t("chat.expand"),"aria-label":O(te,de)?z.$t("chat.collapse"):z.$t("chat.expand"),onClick:De(fe=>Z(te,de),["stop"])},null,10,j6)])):me("",!0)],2),le(te)?me("",!0):(F(),U("div",V6,[M("button",{class:Ce(["user-bubble-action-btn copy",{copied:V(te,de)}]),title:V(te,de)?z.$t("common.copied"):z.$t("common.copy"),"aria-label":V(te,de)?z.$t("common.copied"):z.$t("common.copy"),onClick:fe=>I(te,de)},null,10,G6),M("button",{class:"user-bubble-action-btn branch",title:z.$t("chat.branch"),"aria-label":z.$t("chat.branch"),onClick:fe=>$(te)},null,8,K6),M("span",q6,Q(q(te)),1)]))],64))],2)):te.role==="assistant"?(F(),U("div",Q6,[Hk(de)&&(k_(te.actions||[])||te.awaitingFirstContent)?(F(),U("div",X6,[M("span",null,Q(g.value),1),Wc(de)?(F(),U("span",Y6,Q(Wc(de)),1)):me("",!0)])):me("",!0),te.awaitingFirstContent?(F(),U("div",J6,[M("div",Z6,[M("div",eU,[(F(!0),U(Ie,null,Ze(Cg(te),(fe,Qe)=>(F(),U("span",{key:Qe,class:"assistant-generating-letter",style:qe({animationDelay:`${Qe*.08}s`})},Q(fe),5))),128))])])])):me("",!0),d.value==="minimal"?(F(),U(Ie,{key:2},[k_(te.actions||[])?(F(),Ft(zH,{key:0,actions:te.actions||[],citations:l(te),"citations-final":u(te),"enable-citations":"","conversation-running":s.streamingMessage,"is-latest-message":de===ke.value,"icon-style":fs,"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":Tt,"handle-thinking-scroll":n.handleThinkingScroll,onGroupToggle:Ge},null,8,["actions","citations","citations-final","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"])):me("",!0)],64)):p.value?(F(!0),U(Ie,{key:3},Ze(Vf(te.actions||[],de),fe=>{var Qe,vt,Pt,Lt,Bs,Fs,fo,Jo,Sl,Ca,kl,po,Rg,P_,W,j,ee,Te,Re,Ve,Ue,Ye,Xe,xt,Ot;return F(),U(Ie,{key:fe.key},[fe.kind==="stack"?(F(),Ft(K5,{key:0,class:"stacked-blocks-wrapper",actions:fe.actions,"expanded-blocks":s.expandedBlocks,"conversation-running":s.streamingMessage,"is-latest-message":de===ke.value,"icon-style":fs,"toggle-block":s.toggleBlock,"register-thinking-ref":Tt,"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:Me},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"])):_d(fe.action)?(F(),U("div",{class:Ce(["action-item",{"streaming-content":(Qe=fe.action)==null?void 0:Qe.streaming,"completed-tool":((vt=fe.action)==null?void 0:vt.type)==="tool"&&!((Pt=fe.action)!=null&&Pt.streaming),"immediate-show":((Lt=fe.action)==null?void 0:Lt.streaming)||((Bs=fe.action)==null?void 0:Bs.type)==="text"||((Fs=fe.action)==null?void 0:Fs.type)==="thinking","thinking-finished":((fo=fe.action)==null?void 0:fo.type)==="thinking"&&!((Jo=fe.action)!=null&&Jo.streaming),"no-entry-animation":!s.streamingMessage||de!==ke.value}]),key:((Sl=fe.action)==null?void 0:Sl.id)||`${de}-${fe.actionIndex}`},[((Ca=fe.action)==null?void 0:Ca.type)==="thinking"?(F(),U("div",{key:0,class:Ce(["collapsible-block thinking-block",{expanded:(kl=s.expandedBlocks)==null?void 0:kl.has(fe.action.blockId||`${de}-thinking-${fe.actionIndex}`)}]),"data-block-id":fe.action.blockId||`${de}-thinking-${fe.actionIndex}`},[M("div",{class:"collapsible-header",onClick:Jt=>s.toggleBlock(fe.action.blockId||`${de}-thinking-${fe.actionIndex}`)},[ie[0]||(ie[0]=M("div",{class:"arrow"},null,-1)),M("div",nU,[M("span",{class:Ce(["thinking-icon",{"thinking-animation":fe.action.streaming}])},[M("span",{class:"icon icon-sm",style:qe(fs("brain")),"aria-hidden":"true"},null,4)],2)]),M("span",iU,Q(fe.action.streaming?z.$t("chat.thinkingRunning"):z.$t("chat.thinking")),1)],8,sU),M("div",{class:"collapsible-content",ref_for:!0,ref:Jt=>Bt(fe.action.blockId||`${de}-thinking-${fe.actionIndex}`,Jt)},[M("div",{class:"content-inner thinking-content",ref_for:!0,ref:Jt=>Tt(fe.action.blockId||`${de}-thinking-${fe.actionIndex}`,Jt),onScroll:Jt=>s.handleThinkingScroll(fe.action.blockId||`${de}-thinking-${fe.actionIndex}`,Jt),style:{"max-height":"240px","overflow-y":"auto"}},Q(fe.action.content),41,rU)],512)],10,tU)):((po=fe.action)==null?void 0:po.type)==="text"?(F(),U("div",oU,[M("div",{class:Ce(["text-content",{"streaming-text":fe.action.streaming}])},[We(zg,{content:fe.action.content||"","is-streaming":fe.action.streaming,citations:l(te),"citations-final":u(te),"enable-citations":""},null,8,["content","is-streaming","citations","citations-final"])],2)])):((Rg=fe.action)==null?void 0:Rg.type)==="system"&&Uc(fe.action)?(F(),U("div",aU,Q(Uc(fe.action)),1)):((P_=fe.action)==null?void 0:P_.type)==="append_payload"?(F(),U("div",{key:3,class:Ce(["append-placeholder",{"append-error":((W=fe.action.append)==null?void 0:W.success)===!1}])},[M("div",lU,[((j=fe.action.append)==null?void 0:j.success)!==!1?(F(),U("div",cU,[M("span",{class:"icon icon-sm",style:qe(fs("pencil")),"aria-hidden":"true"},null,4),M("span",null,Q(z.$t("chat.appendSuccess",{path:((ee=fe.action.append)==null?void 0:ee.path)||z.$t("chat.targetFile")})),1)])):(F(),U("div",uU,[M("span",{class:"icon icon-sm",style:qe(fs("x")),"aria-hidden":"true"},null,4),M("span",null,Q(z.$t("chat.appendFailed",{path:((Te=fe.action.append)==null?void 0:Te.path)||z.$t("chat.targetFile")})),1)])),fe.action.append?(F(),U("div",dU,[fe.action.append.lines!==null&&fe.action.append.lines!==void 0?(F(),U("span",hU,Q(z.$t("chat.linesCount",{n:fe.action.append.lines})),1)):me("",!0),fe.action.append.bytes!==null&&fe.action.append.bytes!==void 0?(F(),U("span",fU,Q(z.$t("chat.bytesCount",{n:fe.action.append.bytes})),1)):me("",!0)])):me("",!0),(Re=fe.action.append)!=null&&Re.forced?(F(),U("div",pU,[M("span",{class:"icon icon-sm",style:qe(fs("triangleAlert")),"aria-hidden":"true"},null,4),M("span",null,Q(z.$t("chat.appendWarning")),1)])):me("",!0)])],2)):((Ve=fe.action)==null?void 0:Ve.type)==="append"?(F(),U("div",{key:4,class:Ce(["append-placeholder",{"append-error":((Ue=fe.action.append)==null?void 0:Ue.success)===!1}])},[M("div",mU,[M("div",gU,[M("span",{class:"icon icon-sm",style:qe(fs("pencil")),"aria-hidden":"true"},null,4),M("span",null,Q(((Ye=fe.action.append)==null?void 0:Ye.summary)||z.$t("chat.appendDone")),1)]),fe.action.append?(F(),U("div",vU,[M("span",null,Q(fe.action.append.path||z.$t("chat.targetFile")),1),fe.action.append.lines?(F(),U("span",yU,Q(z.$t("chat.linesCount",{n:fe.action.append.lines})),1)):me("",!0),fe.action.append.bytes?(F(),U("span",bU,Q(z.$t("chat.bytesCount",{n:fe.action.append.bytes})),1)):me("",!0)])):me("",!0),(Xe=fe.action.append)!=null&&Xe.forced?(F(),U("div",_U,[M("span",{class:"icon icon-sm",style:qe(fs("triangleAlert")),"aria-hidden":"true"},null,4),M("span",null,Q(z.$t("chat.appendWarningFollow")),1)])):me("",!0)])],2)):((xt=fe.action)==null?void 0:xt.type)==="tool"?(F(),Ft(cx,{key:5,action:fe.action,expanded:(Ot=s.expandedBlocks)==null?void 0:Ot.has(fe.action.blockId||`${de}-tool-${fe.actionIndex}`),"icon-style":fs,"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":Bt,"collapse-key":fe.action.blockId||`${de}-tool-${fe.actionIndex}`,"block-id":fe.action.blockId||`${de}-tool-${fe.actionIndex}`,onToggle:Jt=>s.toggleBlock(fe.action.blockId||`${de}-tool-${fe.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"])):me("",!0)],2)):me("",!0)],64)}),128)):(F(!0),U(Ie,{key:4},Ze(te.actions||[],(fe,Qe)=>{var vt,Pt,Lt,Bs,Fs,fo,Jo,Sl,Ca,kl;return F(),U(Ie,{key:fe.id||`${de}-${Qe}`},[_d(fe)?(F(),U("div",{key:0,class:Ce(["action-item",{"streaming-content":fe.streaming,"completed-tool":fe.type==="tool"&&!fe.streaming,"immediate-show":fe.streaming||fe.type==="text"||fe.type==="thinking","thinking-finished":fe.type==="thinking"&&!fe.streaming,"no-entry-animation":!s.streamingMessage||de!==ke.value}])},[fe.type==="thinking"?(F(),U("div",{key:0,class:Ce(["collapsible-block thinking-block",{expanded:(vt=s.expandedBlocks)==null?void 0:vt.has(fe.blockId||`${de}-thinking-${Qe}`)}]),"data-block-id":fe.blockId||`${de}-thinking-${Qe}`},[M("div",{class:"collapsible-header",onClick:po=>s.toggleBlock(fe.blockId||`${de}-thinking-${Qe}`)},[ie[1]||(ie[1]=M("div",{class:"arrow"},null,-1)),M("div",kU,[M("span",{class:Ce(["thinking-icon",{"thinking-animation":fe.streaming}])},[M("span",{class:"icon icon-sm",style:qe(fs("brain")),"aria-hidden":"true"},null,4)],2)]),M("span",CU,Q(fe.streaming?z.$t("chat.thinkingRunning"):z.$t("chat.thinking")),1)],8,SU),M("div",{class:"collapsible-content",ref_for:!0,ref:po=>Bt(fe.blockId||`${de}-thinking-${Qe}`,po)},[M("div",{class:"content-inner thinking-content",ref_for:!0,ref:po=>Tt(fe.blockId||`${de}-thinking-${Qe}`,po),onScroll:po=>s.handleThinkingScroll(fe.blockId||`${de}-thinking-${Qe}`,po),style:{"max-height":"240px","overflow-y":"auto"}},Q(fe.content),41,TU)],512)],10,wU)):fe.type==="text"?(F(),U("div",AU,[M("div",{class:Ce(["text-content",{"streaming-text":fe.streaming}])},[We(zg,{content:fe.content||"","is-streaming":fe.streaming,citations:l(te),"citations-final":u(te),"enable-citations":""},null,8,["content","is-streaming","citations","citations-final"])],2)])):fe.type==="system"&&Uc(fe)?(F(),U("div",EU,Q(Uc(fe)),1)):fe.type==="append_payload"?(F(),U("div",{key:3,class:Ce(["append-placeholder",{"append-error":((Pt=fe.append)==null?void 0:Pt.success)===!1}])},[M("div",MU,[((Lt=fe.append)==null?void 0:Lt.success)!==!1?(F(),U("div",xU,[M("span",{class:"icon icon-sm",style:qe(fs("pencil")),"aria-hidden":"true"},null,4),M("span",null,Q(z.$t("chat.appendSuccess",{path:((Bs=fe.append)==null?void 0:Bs.path)||z.$t("chat.targetFile")})),1)])):(F(),U("div",RU,[M("span",{class:"icon icon-sm",style:qe(fs("x")),"aria-hidden":"true"},null,4),M("span",null,Q(z.$t("chat.appendFailed",{path:((Fs=fe.append)==null?void 0:Fs.path)||z.$t("chat.targetFile")})),1)])),fe.append?(F(),U("div",IU,[fe.append.lines!==null&&fe.append.lines!==void 0?(F(),U("span",PU,Q(z.$t("chat.linesCount",{n:fe.append.lines})),1)):me("",!0),fe.append.bytes!==null&&fe.append.bytes!==void 0?(F(),U("span",LU,Q(z.$t("chat.bytesCount",{n:fe.append.bytes})),1)):me("",!0)])):me("",!0),(fo=fe.append)!=null&&fo.forced?(F(),U("div",OU,[M("span",{class:"icon icon-sm",style:qe(fs("triangleAlert")),"aria-hidden":"true"},null,4),M("span",null,Q(z.$t("chat.appendWarning")),1)])):me("",!0)])],2)):fe.type==="append"?(F(),U("div",{key:4,class:Ce(["append-placeholder",{"append-error":((Jo=fe.append)==null?void 0:Jo.success)===!1}])},[M("div",DU,[M("div",NU,[M("span",{class:"icon icon-sm",style:qe(fs("pencil")),"aria-hidden":"true"},null,4),M("span",null,Q(((Sl=fe.append)==null?void 0:Sl.summary)||z.$t("chat.appendDone")),1)]),fe.append?(F(),U("div",$U,[M("span",null,Q(fe.append.path||z.$t("chat.targetFile")),1),fe.append.lines?(F(),U("span",BU,Q(z.$t("chat.linesCount",{n:fe.append.lines})),1)):me("",!0),fe.append.bytes?(F(),U("span",FU,Q(z.$t("chat.bytesCount",{n:fe.append.bytes})),1)):me("",!0)])):me("",!0),(Ca=fe.append)!=null&&Ca.forced?(F(),U("div",HU,[M("span",{class:"icon icon-sm",style:qe(fs("triangleAlert")),"aria-hidden":"true"},null,4),M("span",null,Q(z.$t("chat.appendWarningFollow")),1)])):me("",!0)])],2)):fe.type==="tool"?(F(),Ft(cx,{key:5,action:fe,expanded:(kl=s.expandedBlocks)==null?void 0:kl.has(fe.blockId||`${de}-tool-${Qe}`),"icon-style":fs,"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":Bt,"collapse-key":fe.blockId||`${de}-tool-${Qe}`,"block-id":fe.blockId||`${de}-tool-${Qe}`,onToggle:po=>s.toggleBlock(fe.blockId||`${de}-tool-${Qe}`)},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"])):me("",!0)],2)):me("",!0)],64)}),128)),ye.value.has(de)?(F(),Ft(_6,{key:5,summary:ye.value.get(de),"icon-style":fs},null,8,["summary"])):me("",!0)])):(F(),U("div",UU,[M("div",{class:Ce(["collapsible-block system-block",{expanded:(Ee=s.expandedBlocks)==null?void 0:Ee.has(`system-${de}`)}]),"data-block-id":`system-${de}`},[M("div",{class:"collapsible-header",onClick:fe=>s.toggleBlock(`system-${de}`)},[ie[2]||(ie[2]=M("div",{class:"arrow"},null,-1)),M("div",jU,[M("span",{class:"tool-icon icon icon-md",style:qe(fs("info")),"aria-hidden":"true"},null,4)]),M("span",VU,Q(z.$t("chat.systemMessage",{role:te.role})),1)],8,zU),M("div",{class:"collapsible-content",ref:fe=>Bt(`system-${de}`,fe)},[M("div",GU,Q(te.content),1)],512)],10,WU)]))],2))]}),_:1},8,["data","scroll-ref","keep-mounted"])):me("",!0)],512),ie[3]||(ie[3]=M("div",{class:"messages-bottom-spacer","aria-hidden":"true"},null,-1))],2),ho.value.length>0&&Sd.value!=="hidden"?(F(),U("nav",{key:0,class:Ce(["chat-quick-nav",{"chat-quick-nav--center":Sd.value==="center"}]),style:qe(jk.value),"aria-label":z.$t("chat.quickNavAria"),onMousemove:Vk,onMouseleave:x_},[(F(!0),U(Ie,null,Ze(ho.value,(te,de)=>(F(),U("div",{key:te.msgIndex,class:Ce(["qn-line",{"is-hot":_l.value===de,"is-current":Eg.value===de}]),style:qe({width:Wk(de)+"px"}),ref_for:!0,ref:Ee=>Ir(de,Ee),onClick:Ee=>R_(te)},null,14,qU))),128))],46,KU)):me("",!0),M("div",{class:Ce(["quick-nav-preview",{"is-visible":_l.value>=0}]),style:qe(Cd.value)},[M("div",QU,Q(kd.value),1),M("div",XU,[We(zg,{content:I_.value,"is-streaming":!1},null,8,["content"])])],6)],512))}}),e8=["aria-label"],t8={class:"ws-switcher__header"},s8={class:"ws-switcher__title"},n8={class:"ws-switcher__count"},i8=["data-ws-id","aria-selected","onClick"],r8={key:0,class:"ws-confirm"},o8={class:"ws-confirm-text"},a8={class:"ws-confirm-actions"},l8=["disabled"],c8=["disabled","onClick"],u8={class:"ws-row-text"},d8=["disabled","onKeydown"],h8={key:1,class:"ws-row-name"},f8={key:2,class:"ws-row-path"},p8={class:"ws-row-meta"},m8={key:0,class:"ws-tag"},g8=["aria-expanded","aria-label","onClick"],v8={key:0,class:"ws-empty"},y8=["disabled"],b8=["placeholder","disabled"],_8=["placeholder","disabled"],w8={key:1,class:"ws-create-error"},S8={class:"ws-create-actions"},k8=["disabled"],C8=["disabled"],T8=["disabled"],A8=["disabled"],E8=["disabled"],M8=["disabled"],vC=300,x8=480,R8=ct({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=be(()=>t.workspaceKind==="project"),r=be(()=>i.value?"sidebar.project":"sidebar.workspace"),o=ge(null),a=ge(null),c=ge(null),l=ge(null),u=ge(null),d=ge(null),h=ge(null),p=ge(null),g=ge(""),v=ge(!1),m=ge(""),y=ge(""),_=ge(!1),b=ge({}),k=()=>{var ue;const L=t.anchorRect;if(!L||typeof window>"u")return;const K=window.innerWidth,se=window.innerHeight,oe=((ue=o.value)==null?void 0:ue.offsetHeight)||360;let ve=L.right+8,le=L.top-6;K<x8?(ve=Math.max(8,(K-vC)/2),le=Math.max(8,(se-oe)/2)):ve+vC>K-8&&(ve=Math.max(8,Math.min(L.left,K-vC-8)),le=L.bottom+6),le+oe>se-8&&(le=Math.max(8,se-oe-8)),b.value={left:`${Math.round(ve)}px`,top:`${Math.round(le)}px`}},w=ge({}),T=()=>{d.value=null},A=async L=>{var ne;if(t.busy)return;if(d.value===L.workspace_id){T();return}h.value=null,p.value=null,d.value=L.workspace_id,await ft();const K=L.workspace_id,se=(ne=a.value)==null?void 0:ne.querySelector(`.ws-row[data-ws-id="${CSS.escape(K)}"]`),oe=se==null?void 0:se.querySelector(".ws-more");if(!oe){T();return}const ve=oe.getBoundingClientRect(),le=document.querySelector(".ws-menu-floating"),ue=(le==null?void 0:le.offsetWidth)||150,P=(le==null?void 0:le.offsetHeight)||150;let X=ve.right-ue,J=ve.bottom+4;X=Math.max(8,Math.min(X,window.innerWidth-ue-8)),J+P>window.innerHeight-8&&(J=ve.top-P-4),w.value={left:`${Math.round(X)}px`,top:`${Math.round(J)}px`}},C=L=>{const K=d.value,se=t.workspaces.find(oe=>oe.workspace_id===K);T(),se&&(L==="set-default"?n("set-default",se.workspace_id):L==="rename"?(h.value=se.workspace_id,g.value=se.label,ft(()=>{var ve;const oe=(ve=u.value)==null?void 0:ve[0];oe==null||oe.focus(),oe==null||oe.select()})):L==="reveal"?n("reveal",se.workspace_id):L==="delete"&&(p.value=se.workspace_id))},E=L=>{if(!t.busy&&!(h.value||p.value)){if(d.value){T();return}L.workspace_id!==t.currentWorkspaceId&&n("switch",L.workspace_id)}},x=L=>{const K=g.value.trim();K&&K!==L.label&&n("rename",{workspace_id:L.workspace_id,label:K}),h.value=null},D=L=>{p.value=null,n("delete",L)};let N=!1;const O=(L,K)=>{if(N)return;N=!0;const se=c.value;if(!se){v.value=L,N=!1,K&&K();return}const oe=se.offsetHeight;se.style.height=`${oe}px`,_.value=!0,window.setTimeout(()=>{v.value=L,ft(()=>{se.style.height="auto";const ve=se.offsetHeight;se.style.height=`${oe}px`,se.offsetHeight,se.style.height=`${ve}px`,_.value=!1,window.setTimeout(()=>{se.style.height="",N=!1,K&&K()},210)})},130)},G=()=>{v.value||t.busy||(T(),m.value="",y.value="",O(!0,()=>{var L;return(L=l.value)==null?void 0:L.focus()}))},Z=()=>{v.value&&O(!1)},q=()=>{n("create",{path:m.value.trim(),label:y.value.trim()})};Ke(()=>t.createSubmitting,(L,K)=>{K&&!L&&v.value&&!t.errorMessage&&Z()});const V=L=>{var se;const K=L.target;if(K&&!((se=K.closest)!=null&&se.call(K,".ws-menu-floating"))&&o.value&&!o.value.contains(K)){const oe=t.anchorRect;if(oe){const ve=L.clientX,le=L.clientY;if(ve>=oe.left&&ve<=oe.right&&le>=oe.top&&le<=oe.bottom)return}n("close")}},I=L=>{if(L.key==="Escape"){if(d.value){T();return}if(h.value||p.value){h.value=null,p.value=null;return}if(v.value){Z();return}n("close")}},$=()=>{T(),k()};return Ke(()=>t.open,async L=>{L?(d.value=null,h.value=null,p.value=null,await ft(),k(),document.addEventListener("click",V,!0),document.addEventListener("keydown",I),window.addEventListener("resize",$)):(v.value&&(v.value=!1),document.removeEventListener("click",V,!0),document.removeEventListener("keydown",I),window.removeEventListener("resize",$))}),Rn(()=>{document.removeEventListener("click",V,!0),document.removeEventListener("keydown",I),window.removeEventListener("resize",$)}),(L,K)=>(F(),Ft(Tf,{to:"body"},[We(gs,{name:"ws-switcher"},{default:Gt(()=>[s.open?(F(),U("div",{key:0,ref_key:"popoverEl",ref:o,class:Ce(["ws-switcher",{"ws-switcher--project":i.value}]),style:qe(b.value),role:"dialog","aria-label":L.$t(r.value),onClick:K[6]||(K[6]=De(()=>{},["stop"]))},[M("div",t8,[M("span",s8,Q(L.$t(r.value)),1),M("span",n8,Q(L.$t("sidebar.workspaceCount",{n:s.workspaces.length})),1)]),M("div",{class:"ws-switcher__list",ref_key:"listEl",ref:a,onScroll:T},[(F(!0),U(Ie,null,Ze(s.workspaces,se=>(F(),U("div",{key:se.workspace_id,class:Ce(["ws-row",{current:se.workspace_id===s.currentWorkspaceId,"menu-open":d.value===se.workspace_id}]),"data-ws-id":se.workspace_id,role:"option","aria-selected":se.workspace_id===s.currentWorkspaceId,onClick:oe=>E(se)},[p.value===se.workspace_id?(F(),U("div",r8,[M("div",o8,Q(L.$t(i.value?"sidebar.deleteProjectConfirm":"sidebar.deleteWorkspaceConfirm",{label:se.label})),1),M("div",a8,[M("button",{type:"button",class:"ws-btn ghost",disabled:s.busy,onClick:K[0]||(K[0]=De(oe=>p.value=null,["stop"]))},Q(L.$t("common.cancel")),9,l8),M("button",{type:"button",class:"ws-btn danger",disabled:s.busy,onClick:De(oe=>D(se),["stop"])},Q(L.$t("common.delete")),9,c8)])])):(F(),U(Ie,{key:1},[K[13]||(K[13]=M("span",{class:"ws-row-icon","aria-hidden":"true"},[M("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"1.8","stroke-linecap":"round","stroke-linejoin":"round"},[M("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)),M("span",u8,[h.value===se.workspace_id?Ov((F(),U("input",{key:0,ref_for:!0,ref_key:"renameInputEl",ref:u,"onUpdate:modelValue":K[1]||(K[1]=oe=>g.value=oe),class:"ws-rename-input",disabled:s.busy,onClick:K[2]||(K[2]=De(()=>{},["stop"])),onKeydown:[Dv(De(oe=>x(se),["prevent"]),["enter"]),K[3]||(K[3]=Dv(De(oe=>h.value=null,["prevent"]),["esc"]))]},null,40,d8)),[[yw,g.value]]):(F(),U("span",h8,Q(se.label),1)),i.value?me("",!0):(F(),U("span",f8,Q(se.path||L.$t("sidebar.unconfiguredPath")),1))]),M("span",p8,[se.workspace_id===s.defaultWorkspaceId?(F(),U("span",m8,Q(L.$t("sidebar.default")),1)):me("",!0),M("button",{type:"button",class:"ws-more","aria-expanded":d.value===se.workspace_id,"aria-label":L.$t("common.moreActions"),onClick:De(oe=>A(se),["stop"])},[...K[12]||(K[12]=[M("svg",{viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true"},[M("circle",{cx:"5",cy:"12",r:"1.6"}),M("circle",{cx:"12",cy:"12",r:"1.6"}),M("circle",{cx:"19",cy:"12",r:"1.6"})],-1)])],8,g8)])],64))],10,i8))),128)),s.workspaces.length?me("",!0):(F(),U("div",v8,Q(i.value?L.$t("sidebar.noProjects"):L.$t("sidebar.noWorkspaces")),1))],544),M("div",{class:"ws-bottom",ref_key:"bottomEl",ref:c},[v.value?(F(),U("form",{key:1,class:Ce(["ws-create-form",{fading:_.value}]),onSubmit:De(q,["prevent"])},[Ov(M("input",{ref_key:"createNameEl",ref:l,"onUpdate:modelValue":K[4]||(K[4]=se=>y.value=se),type:"text",placeholder:i.value?L.$t("sidebar.projectNamePlaceholder"):L.$t("sidebar.workspaceNamePlaceholder"),autocomplete:"off",disabled:s.createSubmitting},null,8,b8),[[yw,y.value]]),i.value?me("",!0):Ov((F(),U("input",{key:0,"onUpdate:modelValue":K[5]||(K[5]=se=>m.value=se),type:"text",placeholder:L.$t("sidebar.pathPlaceholder"),autocomplete:"off",disabled:s.createSubmitting},null,8,_8)),[[yw,m.value]]),s.errorMessage?(F(),U("div",w8,Q(s.errorMessage),1)):me("",!0),M("div",S8,[M("button",{type:"button",class:"ws-btn ghost",disabled:s.createSubmitting,onClick:De(Z,["stop"])},Q(L.$t("common.cancel")),9,k8),M("button",{type:"submit",class:"ws-btn primary",disabled:s.createSubmitting},Q(s.createSubmitting?L.$t("sidebar.creating"):L.$t("sidebar.create")),9,C8)])],34)):(F(),U("div",{key:0,class:Ce(["ws-footer",{fading:_.value}])},[M("button",{type:"button",class:"ws-create-btn",disabled:s.busy,onClick:De(G,["stop"])},[K[14]||(K[14]=M("span",{class:"ws-create-icon","aria-hidden":"true"},[M("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"1.8","stroke-linecap":"round","stroke-linejoin":"round"},[M("path",{d:"M5 12h14"}),M("path",{d:"M12 5v14"})])],-1)),M("span",null,Q(L.$t("sidebar.createNoun",{noun:L.$t(r.value)})),1)],8,y8)],2))],512)],14,e8)):me("",!0)]),_:1}),We(gs,{name:"ws-menu"},{default:Gt(()=>[d.value?(F(),U("div",{key:0,class:"ws-menu-floating",style:qe(w.value),role:"menu",onClick:K[11]||(K[11]=De(()=>{},["stop"]))},[M("button",{type:"button",disabled:d.value===s.defaultWorkspaceId||s.busy,onClick:K[7]||(K[7]=se=>C("set-default"))},Q(L.$t("sidebar.setDefault")),9,T8),M("button",{type:"button",disabled:s.busy,onClick:K[8]||(K[8]=se=>C("rename"))},Q(L.$t("sidebar.rename")),9,A8),M("button",{type:"button",disabled:i.value||s.busy,onClick:K[9]||(K[9]=se=>C("reveal"))},Q(L.$t("sidebar.revealInFolder")),9,E8),K[15]||(K[15]=M("div",{class:"ws-menu-sep"},null,-1)),M("button",{type:"button",class:"danger",disabled:s.busy,onClick:K[10]||(K[10]=se=>C("delete"))},Q(L.$t("common.delete")),9,M8)],4)):me("",!0)]),_:1})]))}}),I8=qt(R8,[["__scopeId","data-v-e7284b1f"]]),P8={class:"conversation-sidebar-inner"},L8={class:"conversation-primary-actions"},O8=["title"],D8={class:"sidebar-nav-label"},N8=["title"],$8={class:"sidebar-nav-label"},B8=["title"],F8={class:"sidebar-nav-label"},H8=["title"],U8={class:"sidebar-nav-label"},W8={class:"conversation-search"},z8={class:"search-input-wrap"},j8={class:"sidebar-nav-icon search-inline-icon","aria-hidden":"true"},V8=["value","placeholder"],G8={key:0,class:"conversation-type-switch"},K8={key:0,class:"running-task-section"},q8={class:"running-task-section-title"},Q8=["onClick"],X8={class:"running-task-workspace"},Y8={class:"running-task-main"},J8={class:"running-task-title"},Z8=["aria-label"],eW=["aria-label"],tW=["onMouseenter"],sW=["onClick"],nW={class:"workspace-group-label"},iW=["aria-label"],rW=["aria-label"],oW=["title","aria-label","onClick"],aW=["title","aria-label","aria-expanded","onClick"],lW=["onClick"],cW=["onClick"],uW=["onClick"],dW={class:"workspace-group-children-inner"},hW={key:0,class:"workspace-no-conversations"},fW=["onClick"],pW={class:"conversation-title"},mW=["aria-label","title"],gW=["aria-label","title"],vW=["title","aria-label","data-action-trigger","aria-expanded","onClick"],yW=["onClick"],bW=["onClick"],_W={key:0,class:"load-more workspace-load-more"},wW=["disabled","onClick"],SW={key:2,class:"workspace-groups search-result-groups"},kW={key:0,class:"no-conversations"},CW={class:"workspace-group-header search-result-group-header"},TW={class:"workspace-group-toggle search-result-group-toggle"},AW={class:"workspace-group-label"},EW={class:"workspace-group-children expanded"},MW={class:"workspace-group-children-inner"},xW={class:"workspace-conversations-list"},RW=["onClick"],IW={class:"conversation-title"},PW=["aria-label","title"],LW=["aria-label","title"],OW=["title","aria-label","data-action-trigger","aria-expanded","onClick"],DW=["onClick"],NW=["onClick"],$W={key:0,class:"loading-conversations"},BW={key:1,class:"no-conversations"},FW=["onClick"],HW={class:"conversation-title"},UW=["aria-label","title"],WW=["aria-label","title"],zW=["title","aria-label","data-action-trigger","aria-expanded","onClick"],jW=["onClick"],VW=["onClick"],GW={key:4,class:"load-more"},KW=["disabled"],qW={key:5,class:"load-more search-more"},QW={key:0,class:"search-progress"},XW={class:"search-spinner","aria-hidden":"true"},YW={class:"search-spinner-orbit"},JW={class:"search-progress-text"},ZW={key:2,class:"search-done"},ez={class:"workspace-rename-card"},tz={class:"workspace-rename-title"},sz=["placeholder","onKeydown"],nz={class:"workspace-rename-actions"},iz=["title"],rz={class:"sidebar-nav-label personal-label"},oz=ct({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=Is(),r=kr(),o=Js(),a=be(()=>r.sidebarConversationType),c=be(()=>a.value==="multi_agent"?"type-slide-left":"type-slide-right"),l=ge(null),u=re=>{r.sidebarConversationType!==re&&(l.value&&(l.value.scrollTop=0),r.setSidebarConversationType(re),n("conversation-type-change",re))},{sidebarCollapsed:d}=xi(i),{searchQuery:h,searchResults:p,searchGroups:g,searchActive:v,searchInProgress:m,searchMoreAvailable:y,conversations:_,conversationInsertAnimations:b,conversationListAnimationMode:k,pendingDeletingConversationIds:w,conversationsLoading:T,hasMoreConversations:A,loadingMoreConversations:C,currentConversationId:E}=xi(r),{visible:x}=xi(o),D=re=>t.iconStyle?t.iconStyle(re):{},N=ge(null),O=ge(!1),G=ge(null),Z=()=>{if(O.value){O.value=!1;return}const re=N.value;if(re){const we=re.getBoundingClientRect(),Ae=re.closest(".conversation-sidebar"),bt=Ae?Ae.getBoundingClientRect().right:we.right;G.value={left:we.left,top:we.top,right:Math.min(we.right,bt),bottom:we.bottom}}O.value=!0},q=ge(null),V=ge({top:0,right:0}),I=ge(!1),$=ge(null),L=ge(null),K=ge(null),se=ge(""),oe=ge(null);Ke(K,async re=>{var we,Ae;re&&(await ft(),(we=oe.value)==null||we.focus(),(Ae=oe.value)==null||Ae.select())});const ve=re=>{if(typeof document>"u")return;const we=document.querySelector(`[data-action-trigger="${re}"]`);if(!we)return;const Ae=we.getBoundingClientRect();V.value={top:Ae.bottom+6,right:(typeof window<"u"?window.innerWidth:0)-Ae.right}},le=re=>{q.value===re?q.value=null:(ve(re),q.value=re)};Ke(q,async re=>{re&&(await ft(),ve(re))});const ue=re=>q.value===re&&!ot(re)&&!$s(re),P=re=>{const we=re;we.style.top=`${we.offsetTop}px`},X=()=>{q.value=null},J=ge(new Set),ne=ge([]),ce=ge(!1),_e=()=>{J.value=new Set(Array.isArray(o.form.sidebar_pinned_workspaces)?o.form.sidebar_pinned_workspaces:[])},Pe=()=>{ne.value=Array.isArray(o.form.sidebar_workspace_order)?[...o.form.sidebar_workspace_order]:[]},it=()=>{if(!ce.value)return;const re=Array.from(J.value),we=o.form.sidebar_pinned_workspaces||[];JSON.stringify(re)!==JSON.stringify(we)&&o.updateField({key:"sidebar_pinned_workspaces",value:re})},at=()=>{if(!ce.value)return;const re=Array.from(ne.value),we=o.form.sidebar_workspace_order||[];JSON.stringify(re)!==JSON.stringify(we)&&o.updateField({key:"sidebar_workspace_order",value:re})},rt=()=>{if(!ce.value)return;const re=String(t.currentWorkspaceId||"");if(!re||J.value.has(re)||ne.value[0]===re)return;const we=ne.value.filter(Ae=>Ae!==re);we.unshift(re),ne.value=we,at()},Oe=re=>{if(!ce.value||!Array.isArray(re))return;const we=re.map(is=>String((is==null?void 0:is.workspace_id)||"")).filter(Boolean),Ae=new Set(ne.value),bt=new Set(we.filter(is=>J.value.has(is))),hs=we.filter(is=>!Ae.has(is)&&!bt.has(is)),Ps=new Set(ne.value.filter(is=>!we.includes(is)));(hs.length||Ps.size)&&(ne.value=ne.value.filter(is=>!Ps.has(is)).concat(hs),at())},xe=()=>{!o.loaded||ce.value||(_e(),Pe(),ce.value=!0,Array.isArray(t.workspaces)&&t.workspaces.length>0&&Oe(t.workspaces),rt())};Ke(()=>o.loaded,re=>{re&&xe()},{immediate:!0}),Ke(()=>o.form.sidebar_pinned_workspaces,()=>{ce.value&&_e()},{deep:!0}),Ke(()=>o.form.sidebar_workspace_order,()=>{ce.value&&(Pe(),Array.isArray(t.workspaces)&&t.workspaces.length>0&&Oe(t.workspaces),rt())},{deep:!0}),Ke(()=>t.workspaces,re=>{Array.isArray(re)&&re.length>0&&Oe(re)},{immediate:!0,deep:!0});const pe=be(()=>t.groupByWorkspace&&t.hostWorkspaceEnabled&&Array.isArray(t.workspaces)&&t.workspaces.length>0);Ke(()=>t.currentWorkspaceId,async()=>{pe.value?(I.value=!0,rt(),await ft(),I.value=!1):rt()},{immediate:!0});const he=be(()=>(Array.isArray(t.workspaces)?[...t.workspaces]:[]).sort((we,Ae)=>{const bt=String((we==null?void 0:we.workspace_id)||""),hs=String((Ae==null?void 0:Ae.workspace_id)||""),Ps=J.value.has(bt)?1:0,is=J.value.has(hs)?1:0;if(Ps!==is)return is-Ps;const en=ne.value.indexOf(bt),ut=ne.value.indexOf(hs);return en!==-1&&ut!==-1?en-ut:en!==-1?-1:ut!==-1?1:String((we==null?void 0:we.label)||bt).localeCompare(String((Ae==null?void 0:Ae.label)||hs))})),ye=be(()=>v.value?p.value:_.value),ke=be(()=>(Array.isArray(g.value)?[...g.value]:[]).sort((we,Ae)=>{const bt=String((we==null?void 0:we.workspace_id)||""),hs=String((Ae==null?void 0:Ae.workspace_id)||""),Ps=J.value.has(bt)?1:0,is=J.value.has(hs)?1:0;if(Ps!==is)return is-Ps;const en=ne.value.indexOf(bt),ut=ne.value.indexOf(hs);return en!==-1&&ut!==-1?en-ut:en!==-1?-1:ut!==-1?1:String((we==null?void 0:we.label)||bt).localeCompare(String((Ae==null?void 0:Ae.label)||hs))})),Le=be(()=>v.value?m.value:T.value),st=be(()=>k.value==="delete"),gt=be(()=>Array.isArray(t.runningTasks)?t.runningTasks.filter(re=>re&&re.task_id&&re.conversation_id&&re.conversation_id!==E.value&&String(re.workspace_id||"")!==String(t.currentWorkspaceId||"")):[]),Wt=new Set(["pending","running","cancel_requested"]),jt=new Set(["succeeded","failed","canceled"]),ht=re=>Wt.has(String((re==null?void 0:re.status)||"")),Qt=re=>jt.has(String((re==null?void 0:re.status)||"")),It=be(()=>new Set((Array.isArray(t.runningTasks)?t.runningTasks:[]).filter(re=>ht(re)).map(re=>String((re==null?void 0:re.conversation_id)||"")).filter(Boolean))),ns=be(()=>new Set((Array.isArray(t.runningTasks)?t.runningTasks:[]).filter(re=>Qt(re)).map(re=>String((re==null?void 0:re.conversation_id)||"")).filter(Boolean))),ot=re=>!!(It.value.has(String(re||""))||t.currentTaskInProgress&&String(re||"")===String(t.currentConversationId||"")),$s=re=>ns.value.has(String(re||"")),Er=re=>(Array.isArray(t.runningTasks)?t.runningTasks:[]).some(we=>ht(we)&&String((we==null?void 0:we.workspace_id)||"")===re),In=re=>r.workspaceGroups.find(we=>we.workspaceId===re),Ko=re=>{const we=In(re);if(!we)return[];const Ae=we.visibleLimit+we.bufferLimit;return we.conversations.slice(0,Ae)},ao=re=>{const we=In(re);return we?we.hasMore||we.conversations.length>we.visibleLimit:!1},Pn=re=>{const we=In(re);return we?we.expanded:!0},qo=re=>{const we=In(re);if(!we){r.ensureWorkspaceGroup(re),r.loadWorkspaceConversations(re);return}r.setWorkspaceGroupExpanded(re,!we.expanded),!we.expanded&&we.conversations.length===0&&!we.loading&&r.loadWorkspaceConversations(re)},Yn=re=>{const we=In(re);we?we.conversations.length===0&&!we.loading&&!we.loadingMore&&r.loadWorkspaceConversations(re):(r.ensureWorkspaceGroup(re),r.loadWorkspaceConversations(re))};Ke([pe,he],([re,we])=>{re&&we.length>0&&we.forEach(Ae=>Yn(String((Ae==null?void 0:Ae.workspace_id)||"")))},{immediate:!0});const Oi=(re,we)=>{L.value=null,n("select-workspace-conversation",{conversationId:re,workspaceId:we})},Mr=re=>{L.value=null,n("create-workspace-conversation",re)},Di=re=>{L.value=L.value===re?null:re},gl=()=>{L.value=null},Qo=re=>{L.value=null;const we=[...ne.value],Ae=we.indexOf(re);if(J.value.has(re)){J.value.delete(re),Ae!==-1&&we.splice(Ae,1);const bt=String(t.currentWorkspaceId||""),hs=we.indexOf(bt),Ps=hs!==-1?hs+1:0;we.splice(Ps,0,re)}else J.value.add(re),Ae!==-1&&we.splice(Ae,1);ne.value=we,it(),at(),n("pin-workspace",re)},lo=re=>{L.value=null,n("reveal-workspace",re)},fi=re=>{L.value=null,K.value=String((re==null?void 0:re.workspace_id)||""),se.value=String((re==null?void 0:re.label)||(re==null?void 0:re.workspace_id)||"")},Ni=()=>{const re=K.value,we=se.value.trim();re&&we&&n("rename-workspace",{workspaceId:re,label:we}),K.value=null,se.value=""},wa=()=>{K.value=null,se.value=""},vl=re=>{r.loadMoreWorkspaceConversations(re)};return dn(()=>{document.addEventListener("click",X),document.addEventListener("click",gl),pe.value&&he.value.forEach(re=>Yn(String((re==null?void 0:re.workspace_id)||"")))}),Rn(()=>{document.removeEventListener("click",X),document.removeEventListener("click",gl)}),(re,we)=>(F(),U("aside",{class:Ce(["conversation-sidebar",{collapsed:Ne(d)}])},[M("div",P8,[M("div",L8,[M("button",{type:"button",class:"sidebar-nav-row conversation-menu-btn",title:Ne(d)?re.$t("sidebar.expandConversations"):re.$t("sidebar.collapseConversations"),onClick:we[0]||(we[0]=Ae=>re.$emit("toggle"))},[we[22]||(we[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>',1)),M("span",D8,Q(re.$t("sidebar.conversationHistory")),1)],8,O8),M("button",{type:"button",class:"sidebar-nav-row",title:re.$t("sidebar.newConversation"),onClick:we[1]||(we[1]=Ae=>re.$emit("create"))},[we[23]||(we[23]=M("span",{class:"sidebar-nav-icon pencil-icon","data-tutorial":"quick-new-conversation","aria-hidden":"true"},[M("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"},[M("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"}),M("path",{d:"m15 5 4 4"})])],-1)),M("span",$8,Q(re.$t("sidebar.newConversation")),1)],8,N8),s.hostWorkspaceEnabled?(F(),U("button",{key:0,type:"button",class:Ce(["sidebar-nav-row workspace-entry-btn",{active:O.value}]),title:s.workspaceKind==="project"?re.$t("sidebar.project"):re.$t("sidebar.workspace"),"data-tutorial":"workspace-toggle",ref_key:"workspaceEntryBtn",ref:N,onClick:Z},[we[24]||(we[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)),M("span",F8,Q(s.workspaceKind==="project"?re.$t("sidebar.project"):re.$t("sidebar.workspace")),1)],10,B8)):me("",!0),M("button",{type:"button",class:"sidebar-nav-row",title:re.$t("sidebar.workflows"),onClick:we[2]||(we[2]=Ae=>re.$emit("open-workflows"))},[we[25]||(we[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>',1)),M("span",U8,Q(re.$t("sidebar.workflows")),1)],8,H8)]),M("div",W8,[M("label",z8,[M("span",j8,[M("span",{class:"icon icon-sm",style:qe(D("search"))},null,4)]),M("input",{class:"search-input",value:Ne(h),placeholder:re.$t("sidebar.searchConversationPlaceholder"),onInput:we[3]||(we[3]=Ae=>re.$emit("search",Ae.target.value)),onKeydown:we[4]||(we[4]=Dv(De(Ae=>re.$emit("search-submit",Ae.target.value),["prevent"]),["enter"]))},null,40,V8)])]),Ne(v)?me("",!0):(F(),U("div",G8,[M("button",{type:"button",class:Ce(["conversation-type-option",{active:a.value==="normal"}]),onClick:we[5]||(we[5]=Ae=>u("normal"))},Q(re.$t("sidebar.normalConversations")),3),M("button",{type:"button",class:Ce(["conversation-type-option",{active:a.value==="multi_agent"}]),onClick:we[6]||(we[6]=Ae=>u("multi_agent"))},Q(re.$t("sidebar.multiAgent")),3)])),M("div",{ref_key:"conversationListEl",ref:l,class:"conversation-list"},[We(gs,{name:c.value},{default:Gt(()=>[(F(),U("div",{key:a.value,class:"conversation-list-pane"},[gt.value.length&&!Ne(v)&&!pe.value?(F(),U("div",K8,[M("div",q8,Q(re.$t("sidebar.runningTasksTitle")),1),(F(!0),U(Ie,null,Ze(gt.value,Ae=>(F(),U("button",{key:Ae.task_id,type:"button",class:Ce(["running-task-item",{active:Ae.conversation_id===Ne(E)}]),onClick:bt=>re.$emit("select-running-task",Ae)},[M("span",X8,Q(Ae.workspace_label||Ae.workspace_id),1),M("span",Y8,[M("span",J8,Q(Ae.conversation_title||Ae.message||re.$t("sidebar.runningConversation")),1),ht(Ae)?(F(),U("span",{key:0,class:"conversation-running-loader running-task-state","aria-label":re.$t("common.running")},null,8,Z8)):(F(),U("span",{key:1,class:"conversation-complete-check running-task-state","aria-label":re.$t("sidebar.completed")},null,8,eW))])],10,Q8))),128))])):me("",!0),pe.value&&!Ne(v)?(F(),U("div",{key:1,class:Ce(["workspace-groups",{"switch-instant":I.value}])},[(F(!0),U(Ie,null,Ze(he.value,Ae=>{var bt,hs,Ps,is,en;return F(),U("div",{key:String(Ae.workspace_id||Ae.label),class:"workspace-group"},[M("div",{class:Ce(["workspace-group-header",{active:String(Ae.workspace_id||"")===s.currentWorkspaceId}]),onMouseenter:ut=>$.value=String(Ae.workspace_id||""),onMouseleave:we[7]||(we[7]=ut=>$.value=null)},[M("button",{type:"button",class:"workspace-group-toggle",onClick:ut=>qo(String(Ae.workspace_id||""))},[M("span",{class:"icon icon-sm workspace-folder-icon",style:qe(D(Pn(String(Ae.workspace_id||""))?"folderOpen":"folderClosed")),"aria-hidden":"true"},null,4),M("span",nW,Q(Ae.label||Ae.workspace_id),1),String(Ae.workspace_id||"")===s.currentWorkspaceId?(F(),U("span",{key:0,class:"workspace-current-dot","aria-label":re.$t("sidebar.currentWorkspace")},null,8,iW)):me("",!0),Er(String(Ae.workspace_id||""))&&!Pn(String(Ae.workspace_id||""))&&$.value!==String(Ae.workspace_id||"")&&L.value!==String(Ae.workspace_id||"")?(F(),U("span",{key:1,class:"workspace-running-loader","aria-label":re.$t("common.running")},null,8,rW)):me("",!0)],8,sW),M("div",{class:Ce(["workspace-group-actions",{visible:$.value===String(Ae.workspace_id||"")||L.value===String(Ae.workspace_id||"")}])},[M("button",{type:"button",class:"workspace-new-btn",title:re.$t("sidebar.newConversation"),"aria-label":re.$t("sidebar.newConversation"),onClick:ut=>Mr(String(Ae.workspace_id||""))},[M("span",{class:"icon icon-sm",style:qe(D("pencil")),"aria-hidden":"true"},null,4)],8,oW),M("button",{type:"button",class:"workspace-more-btn",title:re.$t("common.moreActions"),"aria-label":re.$t("common.moreActions"),"aria-expanded":L.value===String(Ae.workspace_id||""),onClick:De(ut=>Di(String(Ae.workspace_id||"")),["stop"])},[...we[26]||(we[26]=[M("span",{"aria-hidden":"true"},null,-1)])],8,aW),M("div",{class:Ce(["workspace-actions-menu",{open:L.value===String(Ae.workspace_id||"")}])},[M("button",{type:"button",onClick:ut=>Qo(String(Ae.workspace_id||""))},[M("span",null,Q(J.value.has(String(Ae.workspace_id||""))?re.$t("sidebar.unpinWorkspace"):re.$t("sidebar.pinWorkspace")),1)],8,lW),t.versioningHostMode?(F(),U("button",{key:0,type:"button",onClick:ut=>lo(String(Ae.workspace_id||""))},[M("span",null,Q(re.$t("sidebar.revealInFolder")),1)],8,cW)):me("",!0),M("button",{type:"button",onClick:ut=>fi(Ae)},[M("span",null,Q(re.$t("sidebar.rename")),1)],8,uW)],2)],2)],42,tW),M("div",{class:Ce(["workspace-group-children",{expanded:Pn(String(Ae.workspace_id||""))}])},[M("div",dW,[(hs=(bt=In(String(Ae.workspace_id||"")))==null?void 0:bt.conversations)!=null&&hs.length?(F(),U(Ie,{key:1},[M("div",{class:"workspace-conversations-viewport",style:qe({"--workspace-visible-count":((Ps=In(String(Ae.workspace_id||"")))==null?void 0:Ps.visibleLimit)||5})},[We(ay,{name:"conversation-delete",tag:"div",class:Ce(["workspace-conversations-list",`animation-mode-${Ne(k)}`]),onBeforeLeave:P},{default:Gt(()=>[(F(!0),U(Ie,null,Ze(Ko(String(Ae.workspace_id||"")),ut=>(F(),U("div",{key:ut.id,class:Ce(["conversation-item workspace-conversation-item",{active:ut.id===Ne(E),running:ot(ut.id)||$s(ut.id),"insert-from-left":Ne(b)[ut.id]==="create","insert-from-under":Ne(b)[ut.id]==="duplicate","duplicate-source-mask":Ne(b)[ut.id]==="duplicateSource"}]),onClick:pn=>Oi(ut.id,String(Ae.workspace_id||""))},[M("div",pW,Q(ut.title),1),M("div",{class:Ce(["conversation-action-wrap",{"menu-open":q.value===ut.id}]),onClick:we[8]||(we[8]=De(()=>{},["stop"]))},[ot(ut.id)?(F(),U("span",{key:0,class:"conversation-running-loader","aria-label":re.$t("common.running"),title:re.$t("common.running")},null,8,mW)):$s(ut.id)?(F(),U("span",{key:1,class:"conversation-complete-check","aria-label":re.$t("sidebar.completed"),title:re.$t("sidebar.completed")},null,8,gW)):(F(),U("button",{key:2,type:"button",class:"conversation-more-btn",title:re.$t("common.moreActions"),"aria-label":re.$t("common.moreActions"),"data-action-trigger":ut.id,"aria-expanded":q.value===ut.id,onClick:pn=>le(ut.id)},[...we[27]||(we[27]=[M("span",{"aria-hidden":"true"},null,-1)])],8,vW)),(F(),Ft(Tf,{to:"body"},[ue(ut.id)?(F(),U("div",{key:0,class:Ce(["conversation-actions-menu conversation-actions-menu--fixed",{open:q.value===ut.id}]),style:qe({top:V.value.top+"px",right:V.value.right+"px"})},[M("button",{type:"button",onClick:pn=>{q.value=null,re.$emit("duplicate",ut.id)}},[M("span",{class:"icon icon-sm",style:qe(D("copy")),"aria-hidden":"true"},null,4),M("span",null,Q(re.$t("common.copy")),1)],8,yW),M("button",{type:"button",class:"danger",onClick:pn=>{q.value=null,re.$emit("delete",{id:ut.id,workspaceId:String(Ae.workspace_id||"")})}},[M("span",{class:"icon icon-sm",style:qe(D("trash")),"aria-hidden":"true"},null,4),M("span",null,Q(re.$t("common.delete")),1)],8,bW)],6)):me("",!0)]))],2)],10,fW))),128))]),_:2},1032,["class"])],4),ao(String(Ae.workspace_id||""))?(F(),U("div",_W,[M("button",{class:"load-more-btn",type:"button",disabled:(is=In(String(Ae.workspace_id||"")))==null?void 0:is.loadingMore,onClick:ut=>vl(String(Ae.workspace_id||""))},Q((en=In(String(Ae.workspace_id||"")))!=null&&en.loadingMore?re.$t("sidebar.loadingMore"):re.$t("sidebar.loadMore")),9,wW)])):me("",!0)],64)):(F(),U("div",hW,Q(re.$t("sidebar.noConversations")),1))])],2)])}),128))],2)):pe.value&&Ne(v)?(F(),U("div",SW,[!Ne(m)&&!ke.value.length?(F(),U("div",kW,Q(re.$t("sidebar.noMatchingConversations")),1)):me("",!0),(F(!0),U(Ie,null,Ze(ke.value,Ae=>(F(),U("div",{key:String(Ae.workspace_id||""),class:"workspace-group"},[M("div",CW,[M("div",TW,[M("span",{class:"icon icon-sm workspace-folder-icon",style:qe(D("folderClosed")),"aria-hidden":"true"},null,4),M("span",AW,Q(Ae.label||Ae.workspace_id),1)])]),M("div",EW,[M("div",MW,[M("div",xW,[(F(!0),U(Ie,null,Ze(Ae.results,bt=>(F(),U("div",{key:bt.id,class:Ce(["conversation-item workspace-conversation-item",{active:bt.id===Ne(E),running:ot(bt.id)||$s(bt.id)}]),onClick:hs=>Oi(bt.id,String(Ae.workspace_id||""))},[M("div",IW,Q(bt.title),1),M("div",{class:Ce(["conversation-action-wrap",{"menu-open":q.value===bt.id}]),onClick:we[9]||(we[9]=De(()=>{},["stop"]))},[ot(bt.id)?(F(),U("span",{key:0,class:"conversation-running-loader","aria-label":re.$t("common.running"),title:re.$t("common.running")},null,8,PW)):$s(bt.id)?(F(),U("span",{key:1,class:"conversation-complete-check","aria-label":re.$t("sidebar.completed"),title:re.$t("sidebar.completed")},null,8,LW)):(F(),U("button",{key:2,type:"button",class:"conversation-more-btn",title:re.$t("common.moreActions"),"aria-label":re.$t("common.moreActions"),"data-action-trigger":bt.id,"aria-expanded":q.value===bt.id,onClick:hs=>le(bt.id)},[...we[28]||(we[28]=[M("span",{"aria-hidden":"true"},null,-1)])],8,OW)),(F(),Ft(Tf,{to:"body"},[ue(bt.id)?(F(),U("div",{key:0,class:Ce(["conversation-actions-menu conversation-actions-menu--fixed",{open:q.value===bt.id}]),style:qe({top:V.value.top+"px",right:V.value.right+"px"})},[M("button",{type:"button",onClick:hs=>{q.value=null,re.$emit("duplicate",bt.id)}},[M("span",{class:"icon icon-sm",style:qe(D("copy")),"aria-hidden":"true"},null,4),M("span",null,Q(re.$t("common.copy")),1)],8,DW),M("button",{type:"button",class:"danger",onClick:hs=>{q.value=null,re.$emit("delete",{id:bt.id,workspaceId:String(Ae.workspace_id||"")})}},[M("span",{class:"icon icon-sm",style:qe(D("trash")),"aria-hidden":"true"},null,4),M("span",null,Q(re.$t("common.delete")),1)],8,NW)],6)):me("",!0)]))],2)],10,RW))),128))])])])]))),128))])):(F(),U(Ie,{key:3},[Le.value&&!ye.value.length&&!Ne(v)&&!st.value?(F(),U("div",$W,Q(re.$t("sidebar.loading")),1)):!ye.value.length&&!Le.value&&!st.value?(F(),U("div",BW,Q(Ne(v)?re.$t("sidebar.noMatchingConversations"):re.$t("sidebar.noConversationHistory")),1)):(F(),Ft(ay,{key:2,name:"conversation-delete",tag:"div",class:Ce(["conversation-list-items",`animation-mode-${Ne(k)}`])},{default:Gt(()=>[(F(!0),U(Ie,null,Ze(ye.value,Ae=>(F(),U("div",{key:Ae.id,class:Ce(["conversation-item",{active:Ae.id===Ne(E),running:ot(Ae.id)||$s(Ae.id),"insert-from-left":Ne(b)[Ae.id]==="create","insert-from-under":Ne(b)[Ae.id]==="duplicate","duplicate-source-mask":Ne(b)[Ae.id]==="duplicateSource",deleting:Ne(w).includes(Ae.id)}]),onClick:bt=>{q.value=null,re.$emit("select",Ae.id)}},[M("div",HW,Q(Ae.title),1),M("div",{class:Ce(["conversation-action-wrap",{"menu-open":q.value===Ae.id}]),onClick:we[10]||(we[10]=De(()=>{},["stop"]))},[ot(Ae.id)?(F(),U("span",{key:0,class:"conversation-running-loader","aria-label":re.$t("common.running"),title:re.$t("common.running")},null,8,UW)):$s(Ae.id)?(F(),U("span",{key:1,class:"conversation-complete-check","aria-label":re.$t("sidebar.completed"),title:re.$t("sidebar.completed")},null,8,WW)):(F(),U("button",{key:2,type:"button",class:"conversation-more-btn",title:re.$t("common.moreActions"),"aria-label":re.$t("common.moreActions"),"data-action-trigger":Ae.id,"aria-expanded":q.value===Ae.id,onClick:bt=>le(Ae.id)},[...we[29]||(we[29]=[M("span",{"aria-hidden":"true"},null,-1)])],8,zW)),(F(),Ft(Tf,{to:"body"},[!ot(Ae.id)&&!$s(Ae.id)&&q.value===Ae.id?(F(),U("div",{key:0,class:Ce(["conversation-actions-menu conversation-actions-menu--fixed",{open:q.value===Ae.id}]),style:qe({top:V.value.top+"px",right:V.value.right+"px"})},[M("button",{type:"button",onClick:bt=>{q.value=null,re.$emit("duplicate",Ae.id)}},[M("span",{class:"icon icon-sm",style:qe(D("copy")),"aria-hidden":"true"},null,4),M("span",null,Q(re.$t("common.copy")),1)],8,jW),M("button",{type:"button",class:"danger",onClick:bt=>{q.value=null,re.$emit("delete",Ae.id)}},[M("span",{class:"icon icon-sm",style:qe(D("trash")),"aria-hidden":"true"},null,4),M("span",null,Q(re.$t("common.delete")),1)],8,VW)],6)):me("",!0)]))],2)],10,FW))),128))]),_:1},8,["class"]))],64)),!Ne(v)&&!pe.value&&Ne(A)?(F(),U("div",GW,[M("button",{class:"load-more-btn",type:"button",disabled:Ne(C),onClick:we[11]||(we[11]=Ae=>re.$emit("load-more"))},Q(Ne(C)?re.$t("sidebar.loadingMore"):re.$t("sidebar.loadMore")),9,KW)])):Ne(v)?(F(),U("div",qW,[Ne(m)?(F(),U("div",QW,[M("span",XW,[M("span",YW,[M("span",{class:"icon icon-sm search-spinner-icon",style:qe(D("search"))},null,4)])]),M("span",JW,Q(re.$t("sidebar.searching")),1)])):Ne(y)?(F(),U("button",{key:1,class:"load-more-btn",type:"button",onClick:we[12]||(we[12]=Ae=>re.$emit("search-more"))},Q(re.$t("sidebar.searchMore")),1)):ye.value.length?(F(),U("div",ZW,Q(re.$t("sidebar.searchExhausted")),1)):me("",!0)])):me("",!0)]))]),_:1},8,["name"])],512),K.value?(F(),U("div",{key:1,class:"workspace-rename-overlay",onClick:De(wa,["self"])},[M("div",ez,[M("div",tz,Q(re.$t("sidebar.renameTitle",{kind:re.$t(s.workspaceKind==="workspace"?"sidebar.workspace":"sidebar.project")})),1),Ov(M("input",{ref_key:"renameInput",ref:oe,"onUpdate:modelValue":we[13]||(we[13]=Ae=>se.value=Ae),type:"text",class:"workspace-rename-input",placeholder:re.$t("sidebar.renamePlaceholder"),onKeydown:[Dv(De(Ni,["prevent"]),["enter"]),Dv(De(wa,["prevent"]),["esc"])]},null,40,sz),[[yw,se.value]]),M("div",nz,[M("button",{type:"button",class:"workspace-rename-cancel",onClick:wa},Q(re.$t("common.cancel")),1),M("button",{type:"button",class:"workspace-rename-confirm",onClick:Ni},Q(re.$t("common.confirm")),1)])])])):me("",!0),We(I8,{open:O.value,"anchor-rect":G.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:we[14]||(we[14]=Ae=>O.value=!1),onSwitch:we[15]||(we[15]=Ae=>re.$emit("switch-workspace",Ae)),onCreate:we[16]||(we[16]=Ae=>re.$emit("create-workspace",Ae)),onRename:we[17]||(we[17]=Ae=>re.$emit("rename-workspace",Ae)),onDelete:we[18]||(we[18]=Ae=>re.$emit("delete-workspace",Ae)),onSetDefault:we[19]||(we[19]=Ae=>re.$emit("set-default-workspace",Ae)),onReveal:we[20]||(we[20]=Ae=>re.$emit("reveal-workspace",Ae))},null,8,["open","anchor-rect","workspaces","current-workspace-id","default-workspace-id","workspace-kind","busy","create-submitting","error-message"]),M("div",{class:Ce(["conversation-personal-entry",{active:Ne(x)}])},[M("button",{type:"button",class:"sidebar-nav-row personal-page-btn","data-tutorial":"open-personal-space",title:re.$t("sidebar.personalSpace"),onClick:we[21]||(we[21]=Ae=>re.$emit("personal"))},[we[30]||(we[30]=M("span",{class:"sidebar-nav-icon","aria-hidden":"true"},[M("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor"},[M("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)),M("span",rz,Q(re.$t("sidebar.personalSpace")),1)],8,iz)],2)])],2))}}),az={class:"icon-label"},lz={key:0,class:"approval-panel-body"},cz={key:0,class:"no-files"},uz={key:1,class:"approval-list"},dz={class:"approval-card__title"},hz={class:"approval-card__summary"},fz={key:0,class:"approval-edit-preview"},pz={class:"approval-path"},mz={class:"tool-result-diff approval-diff"},gz={key:1,class:"approval-edit-preview"},vz={class:"approval-path"},yz={class:"tool-result-diff approval-diff"},bz={key:2,class:"approval-kv"},_z={class:"approval-value approval-value--path"},wz={key:3,class:"approval-kv"},Sz={class:"approval-value approval-value--path"},kz={key:4,class:"approval-lines approval-lines--cmd"},Cz={key:5,class:"approval-kv"},Tz={key:0},Az={class:"approval-actions"},Ez=["disabled","onClick"],Mz=["disabled","onClick"],xz=["disabled","onClick"],Rz={key:0,class:"auto-approval-block__title"},Iz={class:"auto-approval-block__content"},Pz={key:1,class:"auto-approval-block__final"},Lz={class:"auto-approval-block__reason"},Oz=ct({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=be(()=>(lt.value,t.autoApprovalTitle||S("appTasks.autoApprovalRecordTitle"))),i=be(()=>(lt.value,n.value===S("appTasks.goalReviewTitle"))),r=be(()=>(lt.value,i.value?S("appTasks.goalReviewTitle"):S("shell.toolApprovalTitle",{n:t.approvals.length}))),o=e,a=()=>{o("close")},c=be(()=>typeof window<"u"&&window.innerWidth<=768);dn(()=>{document.querySelector(".tool-approval-panel");const w=document.querySelector(".tool-approval-panel .sidebar-header");w&&window.getComputedStyle(w)});const l=w=>{var T;return(w==null?void 0:w.tool_name)==="edit_file"&&((T=w==null?void 0:w.preview)==null?void 0:T.edit_context)},u=w=>["run_command","terminal_input"].includes(w==null?void 0:w.tool_name),d=w=>(w==null?void 0:w.tool_name)==="write_file",h=w=>(w==null?void 0:w.tool_name)==="rename_file",p=w=>["create_file","create_folder","delete_file"].includes(w==null?void 0:w.tool_name),g=w=>Array.isArray(t.decidingApprovalIds)&&t.decidingApprovalIds.includes(w),v=w=>{var T,A,C,E;return((T=w==null?void 0:w.preview)==null?void 0:T.path)||((A=w==null?void 0:w.preview)==null?void 0:A.file_path)||((C=w==null?void 0:w.arguments)==null?void 0:C.path)||((E=w==null?void 0:w.arguments)==null?void 0:E.file_path)||""},m=w=>{lt.value;const T=String(w||""),C={run_command:"shell.toolRunCommand",terminal_input:"shell.toolTerminalInput",create_file:"shell.toolCreateFile",create_folder:"shell.toolCreateFolder",delete_file:"shell.toolDeleteFile",rename_file:"shell.toolRenameFile",write_file:"shell.toolWriteFile",edit_file:"shell.toolEditFile"}[T];return C?S(C):T||S("shell.pendingApproval")},y=w=>{var A;return String(((A=w==null?void 0:w.preview)==null?void 0:A.content_preview)||"").split(`
|
||
`)},_=w=>{var A,C;return(Array.isArray((C=(A=w==null?void 0:w.preview)==null?void 0:A.edit_context)==null?void 0:C.old)?w.preview.edit_context.old:[]).map(E=>String((E==null?void 0:E.content)??""))},b=w=>{var A,C;return(Array.isArray((C=(A=w==null?void 0:w.preview)==null?void 0:A.edit_context)==null?void 0:C.new)?w.preview.edit_context.new:[]).map(E=>String((E==null?void 0:E.content)??""))},k=w=>{const A=String(w||"").split(`
|
||
`),C=String(A[0]||"").trim(),E=String(A.slice(1).join(`
|
||
`)||"").trim();return{title:C,reason:E,isApproved:C.includes(S("appTasks.approvalApproved"))}};return(w,T)=>(F(),U("aside",{class:Ce(["sidebar right-sidebar tool-approval-panel",{collapsed:s.collapsed,"is-goal-approval-mode":i.value}]),style:qe({width:s.collapsed?"0px":s.width+"px"})},[M("div",{class:Ce(["sidebar-header",{"mobile-header":c.value}])},[M("h3",az,Q(r.value),1),We(ml,{label:w.$t("shell.closeApprovalPanel"),onClick:a},null,8,["label"])],2),s.collapsed?me("",!0):(F(),U("div",lz,[!s.approvals.length&&!i.value?(F(),U("div",cz,Q(w.$t("shell.noPendingApprovals")),1)):(F(),U("div",uz,[(F(!0),U(Ie,null,Ze(s.approvals,A=>{var C,E,x,D,N,O,G,Z;return F(),U("div",{key:A.approval_id,class:"approval-card"},[M("div",dz,Q(A.tool_name),1),M("div",hz,Q(m(A.tool_name)),1),l(A)?(F(),U("div",fz,[M("div",pz,Q(((C=A.preview)==null?void 0:C.file_path)||((E=A.preview)==null?void 0:E.resolved_path)),1),M("div",mz,[(F(!0),U(Ie,null,Ze(_(A),(q,V)=>(F(),U("div",{class:"diff-line diff-remove",key:`o-${A.approval_id}-${V}`}," - "+Q(q),1))),128)),(F(!0),U(Ie,null,Ze(b(A),(q,V)=>(F(),U("div",{class:"diff-line diff-add",key:`n-${A.approval_id}-${V}`}," + "+Q(q),1))),128))])])):d(A)?(F(),U("div",gz,[M("div",vz,Q((x=A.preview)==null?void 0:x.file_path),1),M("div",yz,[(F(!0),U(Ie,null,Ze(y(A),(q,V)=>(F(),U("div",{class:"diff-line diff-add",key:`w-${A.approval_id}-${V}`}," + "+Q(q),1))),128))])])):p(A)?(F(),U("div",bz,[M("div",null,[M("strong",null,Q(w.$t("shell.pathLabel")),1),M("span",_z,Q(v(A)),1)])])):h(A)?(F(),U("div",wz,[M("div",null,[M("strong",null,Q(w.$t("shell.renameLabel")),1),M("span",Sz,Q((D=A.preview)==null?void 0:D.old_path)+" → "+Q((N=A.preview)==null?void 0:N.new_path),1)])])):u(A)?(F(),U("pre",kz,Q(((O=A.preview)==null?void 0:O.code)||((G=A.preview)==null?void 0:G.command)||""),1)):(F(),U("div",Cz,[M("div",null,[M("strong",null,Q(w.$t("shell.toolLabel")),1),cn(Q(A.tool_name),1)]),(Z=A.preview)!=null&&Z.summary?(F(),U("div",Tz,[M("strong",null,Q(w.$t("shell.summaryLabel")),1),cn(Q(A.preview.summary),1)])):me("",!0)])),M("div",Az,[M("button",{type:"button",class:"approval-btn approval-btn--switch",disabled:g(A.approval_id),onClick:q=>w.$emit("switch-unrestricted",A.approval_id)},Q(w.$t("shell.switchToUnrestricted")),9,Ez),M("button",{type:"button",class:"approval-btn approval-btn--approve",disabled:g(A.approval_id),onClick:q=>w.$emit("approve",A.approval_id)},Q(w.$t("shell.run")),9,Mz),M("button",{type:"button",class:"approval-btn approval-btn--reject",disabled:g(A.approval_id),onClick:q=>w.$emit("reject",A.approval_id)},Q(w.$t("shell.reject")),9,xz)])])}),128))])),s.autoApprovalFeedLines.length||s.autoApprovalFinalMessage?(F(),U("div",{key:2,class:Ce(["auto-approval-block",{"auto-approval-block--goal":i.value}])},[i.value?me("",!0):(F(),U("div",Rz,Q(n.value),1)),M("pre",Iz,Q(s.autoApprovalFeedLines.join(`
|
||
`)),1),s.autoApprovalFinalMessage?(F(),U("div",Pz,[k(s.autoApprovalFinalMessage).title?(F(),U("div",{key:0,class:Ce(["auto-approval-block__decision",k(s.autoApprovalFinalMessage).isApproved?"auto-approval-block__decision--approved":"auto-approval-block__decision--rejected"])},Q(k(s.autoApprovalFinalMessage).title),3)):me("",!0),M("div",Lz,Q(k(s.autoApprovalFinalMessage).reason),1)])):me("",!0)],2)):me("",!0)]))],6))}}),Dz=qt(Oz,[["__scopeId","data-v-8dea89c1"]]),Nz={class:"git-changes-panel__header"},$z={class:"git-changes-panel__title"},Bz={class:"git-changes-panel__branch"},Fz={class:"git-changes-panel__upstream"},Hz={class:"git-changes-panel__summary"},Uz={class:"git-changes-panel__add"},Wz={class:"git-changes-panel__del"},zz={class:"git-changes-panel__body"},jz={key:0,class:"git-changes-panel__empty"},Vz={key:1,class:"git-changes-panel__empty git-changes-panel__empty--error"},Gz={key:2,class:"git-changes-panel__empty"},Kz={class:"git-change-file__header"},qz={class:"git-change-file__title"},Qz={class:"git-change-file__open-wrap"},Xz=["disabled","title","onClick"],Yz=["src"],Jz={key:0,class:"git-change-file__open-empty"},Zz=["onClick"],ej=["src"],tj={key:2,class:"git-change-file__open-empty"},sj={class:"git-change-file__path"},nj=["onClick"],ij={class:"git-change-file__stats"},rj={class:"git-changes-panel__add"},oj={class:"git-changes-panel__del"},aj={class:"git-change-file__diff"},lj={class:"git-change-file__diff-inner"},cj=["onClick"],uj={class:"git-change-file__fold-content"},dj={class:"git-change-line__num"},hj={class:"git-change-line__marker"},fj={class:"git-change-line__text"},pj=["onClick"],mj={class:"git-change-file__fold-content"},gj=ct({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=be(()=>{var w;return String(((w=t.diff)==null?void 0:w.branch)||"HEAD")}),r=be(()=>{var w;return lt.value,String(((w=t.diff)==null?void 0:w.upstream)||S("shell.unsetUpstream"))}),o=be(()=>{var w;return Math.max(0,Number(((w=t.diff)==null?void 0:w.additions)||0))}),a=be(()=>{var w;return Math.max(0,Number(((w=t.diff)==null?void 0:w.deletions)||0))}),c=be(()=>{var w;return Array.isArray((w=t.diff)==null?void 0:w.files)?t.diff.files:[]}),l=w=>{var A;const T=(A=t.foldContexts)==null?void 0:A[w];return!!T&&Object.values(T).some(C=>Number(C||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,d=ge(""),h=ge([]),p=ge(""),g=ge(""),v=w=>{const T=(w==null?void 0:w.kind)==="delete"?w.old_line:w==null?void 0:w.new_line,A=Number(T);return Number.isFinite(A)&&A>0?String(A):""},m=w=>w==="add"?"+":w==="delete"?"-":" ",y=(w,T)=>{n("expand-context",{path:w,foldKey:T})},_=w=>{n("reset-context",w)},b=async w=>{var T;if(t.hostMode){if(d.value===w){d.value="";return}d.value="",h.value=[],p.value="",g.value=w;try{const A=await fetch(`/api/project/file-open-apps?path=${encodeURIComponent(w)}`),C=await A.json().catch(()=>({}));if(!A.ok||!(C!=null&&C.success))throw new Error((C==null?void 0:C.error)||S("shell.detectAppsFailed"));h.value=Array.isArray((T=C==null?void 0:C.data)==null?void 0:T.apps)?C.data.apps:[],d.value=w}catch(A){p.value=(A==null?void 0:A.message)||S("shell.detectAppsFailed"),d.value=w}finally{g.value=""}}},k=async(w,T)=>{try{const A=await fetch("/api/project/open-file-with-app",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:w,app_id:T})}),C=await A.json().catch(()=>({}));if(!A.ok||!(C!=null&&C.success))throw new Error((C==null?void 0:C.error)||S("shell.openFileFailed"));d.value=""}catch(A){p.value=A instanceof Error?A.message:S("shell.openFileFailed")}};return(w,T)=>(F(),U("aside",{class:"git-changes-panel",style:qe({width:s.width+"px"})},[M("header",Nz,[M("div",$z,[M("span",Bz,Q(i.value),1),T[2]||(T[2]=M("span",{class:"git-changes-panel__arrow"},"→",-1)),M("span",Fz,Q(r.value),1)]),M("div",Hz,[M("span",Uz,"+"+Q(o.value),1),M("span",Wz,"-"+Q(a.value),1),We(ml,{label:w.$t("shell.closeGitPanel"),onClick:T[0]||(T[0]=A=>w.$emit("close"))},null,8,["label"])])]),M("div",zz,[s.loading&&!s.diff?(F(),U("div",jz,Q(w.$t("shell.loadingGitChanges")),1)):s.error&&!c.value.length?(F(),U("div",Vz,Q(s.error),1)):c.value.length?(F(!0),U(Ie,{key:3},Ze(c.value,A=>(F(),U("section",{key:A.path,class:"git-change-file"},[M("div",Kz,[M("span",qz,[M("span",Qz,[M("button",{type:"button",class:Ce(["git-change-file__open-btn",{open:d.value===A.path||g.value===A.path}]),disabled:!s.hostMode,title:s.hostMode?w.$t("shell.openFileWithApp"):w.$t("shell.dockerModeUnavailable"),onClick:De(C=>b(A.path),["stop","prevent"])},[M("img",{class:"git-change-file__open-icon",src:Ne(u),alt:"","aria-hidden":"true"},null,8,Yz),T[4]||(T[4]=M("span",{class:"git-change-file__open-caret","aria-hidden":"true"},null,-1))],10,Xz),d.value===A.path?(F(),U("div",{key:0,class:"git-change-file__open-menu",onClick:T[1]||(T[1]=De(()=>{},["stop"]))},[p.value?(F(),U("div",Jz,Q(p.value),1)):(F(!0),U(Ie,{key:1},Ze(h.value,C=>(F(),U("button",{key:C.id,type:"button",class:"git-change-file__open-option",onClick:De(E=>k(A.path,C.id),["stop","prevent"])},[M("img",{class:"git-change-file__open-option-icon",src:C.icon_url||Ne(u),alt:"","aria-hidden":"true"},null,8,ej),M("span",null,Q(C.label),1)],8,Zz))),128)),!g.value&&!p.value&&!h.value.length?(F(),U("div",tj,Q(w.$t("shell.noAppsDetected")),1)):me("",!0)])):me("",!0)]),M("span",sj,Q(A.path),1),l(A.path)?(F(),U("button",{key:0,type:"button",class:"git-change-file__reset",onClick:De(C=>_(A.path),["stop","prevent"])},Q(w.$t("shell.restore")),9,nj)):me("",!0)]),M("span",ij,[M("span",rj,"+"+Q(A.additions||0),1),M("span",oj,"-"+Q(A.deletions||0),1)])]),M("div",aj,[M("div",lj,[(F(!0),U(Ie,null,Ze(A.hunks,(C,E)=>(F(),U(Ie,{key:`${A.path}-${E}`},[C.before_hidden>0?(F(),U("button",{key:0,type:"button",class:"git-change-file__fold",onClick:De(x=>y(A.path,C.before_fold_key),["stop","prevent"])},[M("span",uj,[T[5]||(T[5]=M("span",{class:"git-change-file__fold-icon git-change-file__fold-icon--up","aria-hidden":"true"},null,-1)),M("span",null,Q(w.$t("shell.hiddenLines",{n:C.before_hidden})),1)])],8,cj)):me("",!0),(F(!0),U(Ie,null,Ze(C.lines,(x,D)=>(F(),U("div",{key:`${A.path}-${E}-${D}`,class:Ce(["git-change-line",{"git-change-line--add":x.kind==="add","git-change-line--delete":x.kind==="delete"}])},[M("span",dj,Q(v(x)),1),M("span",hj,Q(m(x.kind)),1),M("span",fj,Q(x.text),1)],2))),128))],64))),128)),A.after_hidden>0?(F(),U("button",{key:0,type:"button",class:"git-change-file__fold",onClick:De(C=>y(A.path,A.after_fold_key||"after"),["stop","prevent"])},[M("span",mj,[T[6]||(T[6]=M("span",{class:"git-change-file__fold-icon git-change-file__fold-icon--down","aria-hidden":"true"},null,-1)),M("span",null,Q(w.$t("shell.hiddenLines",{n:A.after_hidden})),1)])],8,pj)):me("",!0)])])]))),128)):(F(),U("div",Gz,[T[3]||(T[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>',1)),M("span",null,Q(w.$t("shell.noUncommittedChanges")),1)]))])],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(b,k,w,T){var A,C=arguments.length,E=C<3?k:T===null?T=Object.getOwnPropertyDescriptor(k,w):T;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")E=Reflect.decorate(b,k,w,T);else for(var x=b.length-1;x>=0;x--)(A=b[x])&&(E=(C<3?A(E):C>3?A(k,w,E):A(k,w))||E);return C>3&&E&&Object.defineProperty(k,w,E),E},u=this&&this.__param||function(b,k){return function(w,T){k(w,T,b)}};Object.defineProperty(a,"__esModule",{value:!0}),a.AccessibilityManager=void 0;const d=c(9042),h=c(6114),p=c(9924),g=c(844),v=c(5596),m=c(4725),y=c(3656);let _=a.AccessibilityManager=class extends g.Disposable{constructor(b,k){super(),this._terminal=b,this._renderService=k,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 w=0;w<this._terminal.rows;w++)this._rowElements[w]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[w]);if(this._topBoundaryFocusListener=w=>this._handleBoundaryFocus(w,0),this._bottomBoundaryFocusListener=w=>this._handleBoundaryFocus(w,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(w=>this._handleResize(w.rows))),this.register(this._terminal.onRender(w=>this._refreshRows(w.start,w.end))),this.register(this._terminal.onScroll(()=>this._refreshRows())),this.register(this._terminal.onA11yChar(w=>this._handleChar(w))),this.register(this._terminal.onLineFeed(()=>this._handleChar(`
|
||
`))),this.register(this._terminal.onA11yTab(w=>this._handleTab(w))),this.register(this._terminal.onKey(w=>this._handleKey(w.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,g.toDisposable)(()=>{this._accessibilityContainer.remove(),this._rowElements.length=0}))}_handleTab(b){for(let k=0;k<b;k++)this._handleChar(" ")}_handleChar(b){this._liveRegionLineCount<21&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==b&&(this._charsToAnnounce+=b):this._charsToAnnounce+=b,b===`
|
||
`&&(this._liveRegionLineCount++,this._liveRegionLineCount===21&&(this._liveRegion.textContent+=d.tooMuchOutput)),h.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,h.isMac&&this._liveRegion.remove()}_handleKey(b){this._clearLiveRegion(),new RegExp("\\p{Control}","u").test(b)||this._charsToConsume.push(b)}_refreshRows(b,k){this._liveRegionDebouncer.refresh(b,k,this._terminal.rows)}_renderRows(b,k){const w=this._terminal.buffer,T=w.lines.length.toString();for(let A=b;A<=k;A++){const C=w.translateBufferLineToString(w.ydisp+A,!0),E=(w.ydisp+A+1).toString(),x=this._rowElements[A];x&&(C.length===0?x.innerText=" ":x.textContent=C,x.setAttribute("aria-posinset",E),x.setAttribute("aria-setsize",T))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(b,k){const w=b.target,T=this._rowElements[k===0?1:this._rowElements.length-2];if(w.getAttribute("aria-posinset")===(k===0?"1":`${this._terminal.buffer.lines.length}`)||b.relatedTarget!==T)return;let A,C;if(k===0?(A=w,C=this._rowElements.pop(),this._rowContainer.removeChild(C)):(A=this._rowElements.shift(),C=w,this._rowContainer.removeChild(A)),A.removeEventListener("focus",this._topBoundaryFocusListener),C.removeEventListener("focus",this._bottomBoundaryFocusListener),k===0){const E=this._createAccessibilityTreeNode();this._rowElements.unshift(E),this._rowContainer.insertAdjacentElement("afterbegin",E)}else{const E=this._createAccessibilityTreeNode();this._rowElements.push(E),this._rowContainer.appendChild(E)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(k===0?-1:1),this._rowElements[k===0?1:this._rowElements.length-2].focus(),b.preventDefault(),b.stopImmediatePropagation()}_handleResize(b){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let k=this._rowContainer.children.length;k<this._terminal.rows;k++)this._rowElements[k]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[k]);for(;this._rowElements.length>b;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){const b=document.createElement("div");return b.setAttribute("role","listitem"),b.tabIndex=-1,this._refreshRowDimensions(b),b}_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 b=0;b<this._terminal.rows;b++)this._refreshRowDimensions(this._rowElements[b])}}_refreshRowDimensions(b){b.style.height=`${this._renderService.dimensions.css.cell.height}px`}};a.AccessibilityManager=_=l([u(1,m.IRenderService)],_)},3614:(o,a)=>{function c(h){return h.replace(/\r?\n/g,"\r")}function l(h,p){return p?"\x1B[200~"+h+"\x1B[201~":h}function u(h,p,g,v){h=l(h=c(h),g.decPrivateModes.bracketedPasteMode&&v.rawOptions.ignoreBracketedPasteMode!==!0),g.triggerDataEvent(h,!0),p.value=""}function d(h,p,g){const v=g.getBoundingClientRect(),m=h.clientX-v.left-10,y=h.clientY-v.top-10;p.style.width="20px",p.style.height="20px",p.style.left=`${m}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(h,p){h.clipboardData&&h.clipboardData.setData("text/plain",p.selectionText),h.preventDefault()},a.handlePasteEvent=function(h,p,g,v){h.stopPropagation(),h.clipboardData&&u(h.clipboardData.getData("text/plain"),p,g,v)},a.paste=u,a.moveTextAreaUnderMouseCursor=d,a.rightClickHandler=function(h,p,g,v,m){d(h,p,g),m&&v.rightClickSelect(h),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,d,h){this._css.set(u,d,h)}getCss(u,d){return this._css.get(u,d)}setColor(u,d,h){this._color.set(u,d,h)}getColor(u,d){return this._color.get(u,d)}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,d){c.addEventListener(l,u,d);let h=!1;return{dispose:()=>{h||(h=!0,c.removeEventListener(l,u,d))}}}},6465:function(o,a,c){var l=this&&this.__decorate||function(m,y,_,b){var k,w=arguments.length,T=w<3?y:b===null?b=Object.getOwnPropertyDescriptor(y,_):b;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")T=Reflect.decorate(m,y,_,b);else for(var A=m.length-1;A>=0;A--)(k=m[A])&&(T=(w<3?k(T):w>3?k(y,_,T):k(y,_))||T);return w>3&&T&&Object.defineProperty(y,_,T),T},u=this&&this.__param||function(m,y){return function(_,b){y(_,b,m)}};Object.defineProperty(a,"__esModule",{value:!0}),a.Linkifier2=void 0;const d=c(3656),h=c(8460),p=c(844),g=c(2585);let v=a.Linkifier2=class extends p.Disposable{get currentLink(){return this._currentLink}constructor(m){super(),this._bufferService=m,this._linkProviders=[],this._linkCacheDisposables=[],this._isMouseOut=!0,this._wasResized=!1,this._activeLine=-1,this._onShowLinkUnderline=this.register(new h.EventEmitter),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this.register(new h.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(m){return this._linkProviders.push(m),{dispose:()=>{const y=this._linkProviders.indexOf(m);y!==-1&&this._linkProviders.splice(y,1)}}}attachToDom(m,y,_){this._element=m,this._mouseService=y,this._renderService=_,this.register((0,d.addDisposableDomListener)(this._element,"mouseleave",()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this.register((0,d.addDisposableDomListener)(this._element,"mousemove",this._handleMouseMove.bind(this))),this.register((0,d.addDisposableDomListener)(this._element,"mousedown",this._handleMouseDown.bind(this))),this.register((0,d.addDisposableDomListener)(this._element,"mouseup",this._handleMouseUp.bind(this)))}_handleMouseMove(m){if(this._lastMouseEvent=m,!this._element||!this._mouseService)return;const y=this._positionFromMouseEvent(m,this._element,this._mouseService);if(!y)return;this._isMouseOut=!1;const _=m.composedPath();for(let b=0;b<_.length;b++){const k=_[b];if(k.classList.contains("xterm"))break;if(k.classList.contains("xterm-hover"))return}this._lastBufferCell&&y.x===this._lastBufferCell.x&&y.y===this._lastBufferCell.y||(this._handleHover(y),this._lastBufferCell=y)}_handleHover(m){if(this._activeLine!==m.y||this._wasResized)return this._clearCurrentLink(),this._askForLink(m,!1),void(this._wasResized=!1);this._currentLink&&this._linkAtPosition(this._currentLink.link,m)||(this._clearCurrentLink(),this._askForLink(m,!0))}_askForLink(m,y){var _,b;this._activeProviderReplies&&y||((_=this._activeProviderReplies)===null||_===void 0||_.forEach(w=>{w==null||w.forEach(T=>{T.link.dispose&&T.link.dispose()})}),this._activeProviderReplies=new Map,this._activeLine=m.y);let k=!1;for(const[w,T]of this._linkProviders.entries())y?!((b=this._activeProviderReplies)===null||b===void 0)&&b.get(w)&&(k=this._checkLinkProviderResult(w,m,k)):T.provideLinks(m.y,A=>{var C,E;if(this._isMouseOut)return;const x=A==null?void 0:A.map(D=>({link:D}));(C=this._activeProviderReplies)===null||C===void 0||C.set(w,x),k=this._checkLinkProviderResult(w,m,k),((E=this._activeProviderReplies)===null||E===void 0?void 0:E.size)===this._linkProviders.length&&this._removeIntersectingLinks(m.y,this._activeProviderReplies)})}_removeIntersectingLinks(m,y){const _=new Set;for(let b=0;b<y.size;b++){const k=y.get(b);if(k)for(let w=0;w<k.length;w++){const T=k[w],A=T.link.range.start.y<m?0:T.link.range.start.x,C=T.link.range.end.y>m?this._bufferService.cols:T.link.range.end.x;for(let E=A;E<=C;E++){if(_.has(E)){k.splice(w--,1);break}_.add(E)}}}}_checkLinkProviderResult(m,y,_){var b;if(!this._activeProviderReplies)return _;const k=this._activeProviderReplies.get(m);let w=!1;for(let T=0;T<m;T++)this._activeProviderReplies.has(T)&&!this._activeProviderReplies.get(T)||(w=!0);if(!w&&k){const T=k.find(A=>this._linkAtPosition(A.link,y));T&&(_=!0,this._handleNewLink(T))}if(this._activeProviderReplies.size===this._linkProviders.length&&!_)for(let T=0;T<this._activeProviderReplies.size;T++){const A=(b=this._activeProviderReplies.get(T))===null||b===void 0?void 0:b.find(C=>this._linkAtPosition(C.link,y));if(A){_=!0,this._handleNewLink(A);break}}return _}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(m){if(!this._element||!this._mouseService||!this._currentLink)return;const y=this._positionFromMouseEvent(m,this._element,this._mouseService);y&&this._mouseDownLink===this._currentLink&&this._linkAtPosition(this._currentLink.link,y)&&this._currentLink.link.activate(m,this._currentLink.link.text)}_clearCurrentLink(m,y){this._element&&this._currentLink&&this._lastMouseEvent&&(!m||!y||this._currentLink.link.range.start.y>=m&&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(m){if(!this._element||!this._lastMouseEvent||!this._mouseService)return;const y=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);y&&this._linkAtPosition(m.link,y)&&(this._currentLink=m,this._currentLink.state={decorations:{underline:m.link.decorations===void 0||m.link.decorations.underline,pointerCursor:m.link.decorations===void 0||m.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,m.link,this._lastMouseEvent),m.link.decorations={},Object.defineProperties(m.link.decorations,{pointerCursor:{get:()=>{var _,b;return(b=(_=this._currentLink)===null||_===void 0?void 0:_.state)===null||b===void 0?void 0:b.decorations.pointerCursor},set:_=>{var b,k;!((b=this._currentLink)===null||b===void 0)&&b.state&&this._currentLink.state.decorations.pointerCursor!==_&&(this._currentLink.state.decorations.pointerCursor=_,this._currentLink.state.isHovered&&((k=this._element)===null||k===void 0||k.classList.toggle("xterm-cursor-pointer",_)))}},underline:{get:()=>{var _,b;return(b=(_=this._currentLink)===null||_===void 0?void 0:_.state)===null||b===void 0?void 0:b.decorations.underline},set:_=>{var b,k,w;!((b=this._currentLink)===null||b===void 0)&&b.state&&((w=(k=this._currentLink)===null||k===void 0?void 0:k.state)===null||w===void 0?void 0:w.decorations.underline)!==_&&(this._currentLink.state.decorations.underline=_,this._currentLink.state.isHovered&&this._fireUnderlineEvent(m.link,_))}}}),this._renderService&&this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange(_=>{if(!this._currentLink)return;const b=_.start===0?0:_.start+1+this._bufferService.buffer.ydisp,k=this._bufferService.buffer.ydisp+1+_.end;if(this._currentLink.link.range.start.y>=b&&this._currentLink.link.range.end.y<=k&&(this._clearCurrentLink(b,k),this._lastMouseEvent&&this._element)){const w=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);w&&this._askForLink(w,!1)}})))}_linkHover(m,y,_){var b;!((b=this._currentLink)===null||b===void 0)&&b.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(y,!0),this._currentLink.state.decorations.pointerCursor&&m.classList.add("xterm-cursor-pointer")),y.hover&&y.hover(_,y.text)}_fireUnderlineEvent(m,y){const _=m.range,b=this._bufferService.buffer.ydisp,k=this._createLinkUnderlineEvent(_.start.x-1,_.start.y-b-1,_.end.x,_.end.y-b-1,void 0);(y?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(k)}_linkLeave(m,y,_){var b;!((b=this._currentLink)===null||b===void 0)&&b.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(y,!1),this._currentLink.state.decorations.pointerCursor&&m.classList.remove("xterm-cursor-pointer")),y.leave&&y.leave(_,y.text)}_linkAtPosition(m,y){const _=m.range.start.y*this._bufferService.cols+m.range.start.x,b=m.range.end.y*this._bufferService.cols+m.range.end.x,k=y.y*this._bufferService.cols+y.x;return _<=k&&k<=b}_positionFromMouseEvent(m,y,_){const b=_.getCoords(m,y,this._bufferService.cols,this._bufferService.rows);if(b)return{x:b[0],y:b[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(m,y,_,b,k){return{x1:m,y1:y,x2:_,y2:b,cols:this._bufferService.cols,fg:k}}};a.Linkifier2=v=l([u(0,g.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,m,y,_){var b,k=arguments.length,w=k<3?m:_===null?_=Object.getOwnPropertyDescriptor(m,y):_;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")w=Reflect.decorate(v,m,y,_);else for(var T=v.length-1;T>=0;T--)(b=v[T])&&(w=(k<3?b(w):k>3?b(m,y,w):b(m,y))||w);return k>3&&w&&Object.defineProperty(m,y,w),w},u=this&&this.__param||function(v,m){return function(y,_){m(y,_,v)}};Object.defineProperty(a,"__esModule",{value:!0}),a.OscLinkProvider=void 0;const d=c(511),h=c(2585);let p=a.OscLinkProvider=class{constructor(v,m,y){this._bufferService=v,this._optionsService=m,this._oscLinkService=y}provideLinks(v,m){var y;const _=this._bufferService.buffer.lines.get(v-1);if(!_)return void m(void 0);const b=[],k=this._optionsService.rawOptions.linkHandler,w=new d.CellData,T=_.getTrimmedLength();let A=-1,C=-1,E=!1;for(let x=0;x<T;x++)if(C!==-1||_.hasContent(x)){if(_.loadCell(x,w),w.hasExtendedAttrs()&&w.extended.urlId){if(C===-1){C=x,A=w.extended.urlId;continue}E=w.extended.urlId!==A}else C!==-1&&(E=!0);if(E||C!==-1&&x===T-1){const D=(y=this._oscLinkService.getLinkData(A))===null||y===void 0?void 0:y.uri;if(D){const N={start:{x:C+1,y:v},end:{x:x+(E||x!==T-1?0:1),y:v}};let O=!1;if(!(k!=null&&k.allowNonHttpProtocols))try{const G=new URL(D);["http:","https:"].includes(G.protocol)||(O=!0)}catch{O=!0}O||b.push({text:D,range:N,activate:(G,Z)=>k?k.activate(G,Z,N):g(0,Z),hover:(G,Z)=>{var q;return(q=k==null?void 0:k.hover)===null||q===void 0?void 0:q.call(k,G,Z,N)},leave:(G,Z)=>{var q;return(q=k==null?void 0:k.leave)===null||q===void 0?void 0:q.call(k,G,Z,N)}})}E=!1,w.hasExtendedAttrs()&&w.extended.urlId?(C=x,A=w.extended.urlId):(C=-1,A=-1)}}m(b)}};function g(v,m){if(confirm(`Do you want to navigate to ${m}?
|
||
|
||
WARNING: This link could potentially be dangerous`)){const y=window.open();if(y){try{y.opener=null}catch{}y.location.href=m}else console.warn("Opening link blocked as opener could not be cleared")}}a.OscLinkProvider=p=l([u(0,h.IBufferService),u(1,h.IOptionsService),u(2,h.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(h){super(),this._parentWindow=h,this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this.register((0,l.toDisposable)(()=>{this.clearListener()}))}setListener(h){this._listener&&this.clearListener(),this._listener=h,this._outerListener=()=>{this._listener&&(this._listener(this._parentWindow.devicePixelRatio,this._currentDevicePixelRatio),this._updateDpr())},this._updateDpr()}_updateDpr(){var h;this._outerListener&&((h=this._resolutionMediaMatchList)===null||h===void 0||h.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),d=c(6465),h=c(9042),p=c(3730),g=c(1680),v=c(3107),m=c(5744),y=c(2950),_=c(1296),b=c(428),k=c(4269),w=c(5114),T=c(8934),A=c(3230),C=c(9312),E=c(4725),x=c(6731),D=c(8055),N=c(8969),O=c(8460),G=c(844),Z=c(6114),q=c(8437),V=c(2584),I=c(7399),$=c(5941),L=c(9074),K=c(2585),se=c(5435),oe=c(4567),ve=typeof window<"u"?window.document:null;class le extends N.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(P={}){super(P),this.browser=Z,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this.register(new G.MutableDisposable),this._onCursorMove=this.register(new O.EventEmitter),this.onCursorMove=this._onCursorMove.event,this._onKey=this.register(new O.EventEmitter),this.onKey=this._onKey.event,this._onRender=this.register(new O.EventEmitter),this.onRender=this._onRender.event,this._onSelectionChange=this.register(new O.EventEmitter),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this.register(new O.EventEmitter),this.onTitleChange=this._onTitleChange.event,this._onBell=this.register(new O.EventEmitter),this.onBell=this._onBell.event,this._onFocus=this.register(new O.EventEmitter),this._onBlur=this.register(new O.EventEmitter),this._onA11yCharEmitter=this.register(new O.EventEmitter),this._onA11yTabEmitter=this.register(new O.EventEmitter),this._onWillOpen=this.register(new O.EventEmitter),this._setup(),this.linkifier2=this.register(this._instantiationService.createInstance(d.Linkifier2)),this.linkifier2.registerLinkProvider(this._instantiationService.createInstance(p.OscLinkProvider)),this._decorationService=this._instantiationService.createInstance(L.DecorationService),this._instantiationService.setService(K.IDecorationService,this._decorationService),this.register(this._inputHandler.onRequestBell(()=>this._onBell.fire())),this.register(this._inputHandler.onRequestRefreshRows((X,J)=>this.refresh(X,J))),this.register(this._inputHandler.onRequestSendFocus(()=>this._reportFocus())),this.register(this._inputHandler.onRequestReset(()=>this.reset())),this.register(this._inputHandler.onRequestWindowsOptionsReport(X=>this._reportWindowsOptions(X))),this.register(this._inputHandler.onColor(X=>this._handleColorEvent(X))),this.register((0,O.forwardEvent)(this._inputHandler.onCursorMove,this._onCursorMove)),this.register((0,O.forwardEvent)(this._inputHandler.onTitleChange,this._onTitleChange)),this.register((0,O.forwardEvent)(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this.register((0,O.forwardEvent)(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this.register(this._bufferService.onResize(X=>this._afterResize(X.cols,X.rows))),this.register((0,G.toDisposable)(()=>{var X,J;this._customKeyEventHandler=void 0,(J=(X=this.element)===null||X===void 0?void 0:X.parentNode)===null||J===void 0||J.removeChild(this.element)}))}_handleColorEvent(P){if(this._themeService)for(const X of P){let J,ne="";switch(X.index){case 256:J="foreground",ne="10";break;case 257:J="background",ne="11";break;case 258:J="cursor",ne="12";break;default:J="ansi",ne="4;"+X.index}switch(X.type){case 0:const ce=D.color.toColorRGB(J==="ansi"?this._themeService.colors.ansi[X.index]:this._themeService.colors[J]);this.coreService.triggerDataEvent(`${V.C0.ESC}]${ne};${(0,$.toRgbString)(ce)}${V.C1_ESCAPED.ST}`);break;case 1:if(J==="ansi")this._themeService.modifyColors(_e=>_e.ansi[X.index]=D.rgba.toColor(...X.color));else{const _e=J;this._themeService.modifyColors(Pe=>Pe[_e]=D.rgba.toColor(...X.color))}break;case 2:this._themeService.restoreColor(X.index)}}}_setup(){super._setup(),this._customKeyEventHandler=void 0}get buffer(){return this.buffers.active}focus(){this.textarea&&this.textarea.focus({preventScroll:!0})}_handleScreenReaderModeOptionChange(P){P?!this._accessibilityManager.value&&this._renderService&&(this._accessibilityManager.value=this._instantiationService.createInstance(oe.AccessibilityManager,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(P){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(V.C0.ESC+"[I"),this.updateCursorStyle(P),this.element.classList.add("focus"),this._showCursor(),this._onFocus.fire()}blur(){var P;return(P=this.textarea)===null||P===void 0?void 0:P.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 P=this.buffer.ybase+this.buffer.y,X=this.buffer.lines.get(P);if(!X)return;const J=Math.min(this.buffer.x,this.cols-1),ne=this._renderService.dimensions.css.cell.height,ce=X.getWidth(J),_e=this._renderService.dimensions.css.cell.width*ce,Pe=this.buffer.y*this._renderService.dimensions.css.cell.height,it=J*this._renderService.dimensions.css.cell.width;this.textarea.style.left=it+"px",this.textarea.style.top=Pe+"px",this.textarea.style.width=_e+"px",this.textarea.style.height=ne+"px",this.textarea.style.lineHeight=ne+"px",this.textarea.style.zIndex="-5"}_initGlobal(){this._bindKeys(),this.register((0,u.addDisposableDomListener)(this.element,"copy",X=>{this.hasSelection()&&(0,l.copyHandler)(X,this._selectionService)}));const P=X=>(0,l.handlePasteEvent)(X,this.textarea,this.coreService,this.optionsService);this.register((0,u.addDisposableDomListener)(this.textarea,"paste",P)),this.register((0,u.addDisposableDomListener)(this.element,"paste",P)),Z.isFirefox?this.register((0,u.addDisposableDomListener)(this.element,"mousedown",X=>{X.button===2&&(0,l.rightClickHandler)(X,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this.register((0,u.addDisposableDomListener)(this.element,"contextmenu",X=>{(0,l.rightClickHandler)(X,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),Z.isLinux&&this.register((0,u.addDisposableDomListener)(this.element,"auxclick",X=>{X.button===1&&(0,l.moveTextAreaUnderMouseCursor)(X,this.textarea,this.screenElement)}))}_bindKeys(){this.register((0,u.addDisposableDomListener)(this.textarea,"keyup",P=>this._keyUp(P),!0)),this.register((0,u.addDisposableDomListener)(this.textarea,"keydown",P=>this._keyDown(P),!0)),this.register((0,u.addDisposableDomListener)(this.textarea,"keypress",P=>this._keyPress(P),!0)),this.register((0,u.addDisposableDomListener)(this.textarea,"compositionstart",()=>this._compositionHelper.compositionstart())),this.register((0,u.addDisposableDomListener)(this.textarea,"compositionupdate",P=>this._compositionHelper.compositionupdate(P))),this.register((0,u.addDisposableDomListener)(this.textarea,"compositionend",()=>this._compositionHelper.compositionend())),this.register((0,u.addDisposableDomListener)(this.textarea,"input",P=>this._inputEvent(P),!0)),this.register(this.onRender(()=>this._compositionHelper.updateCompositionElements()))}open(P){var X;if(!P)throw new Error("Terminal requires a parent element.");P.isConnected||this._logService.debug("Terminal.open was called on an element that was not attached to the DOM"),this._document=P.ownerDocument,this.element=this._document.createElement("div"),this.element.dir="ltr",this.element.classList.add("terminal"),this.element.classList.add("xterm"),P.appendChild(this.element);const J=ve.createDocumentFragment();this._viewportElement=ve.createElement("div"),this._viewportElement.classList.add("xterm-viewport"),J.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),J.appendChild(this.screenElement),this.textarea=ve.createElement("textarea"),this.textarea.classList.add("xterm-helper-textarea"),this.textarea.setAttribute("aria-label",h.promptLabel),Z.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(w.CoreBrowserService,this.textarea,(X=this._document.defaultView)!==null&&X!==void 0?X:window),this._instantiationService.setService(E.ICoreBrowserService,this._coreBrowserService),this.register((0,u.addDisposableDomListener)(this.textarea,"focus",ne=>this._handleTextAreaFocus(ne))),this.register((0,u.addDisposableDomListener)(this.textarea,"blur",()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(b.CharSizeService,this._document,this._helperContainer),this._instantiationService.setService(E.ICharSizeService,this._charSizeService),this._themeService=this._instantiationService.createInstance(x.ThemeService),this._instantiationService.setService(E.IThemeService,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(k.CharacterJoinerService),this._instantiationService.setService(E.ICharacterJoinerService,this._characterJoinerService),this._renderService=this.register(this._instantiationService.createInstance(A.RenderService,this.rows,this.screenElement)),this._instantiationService.setService(E.IRenderService,this._renderService),this.register(this._renderService.onRenderedViewportChange(ne=>this._onRender.fire(ne))),this.onResize(ne=>this._renderService.resize(ne.cols,ne.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(J);try{this._onWillOpen.fire(this.element)}catch{}this._renderService.hasRenderer()||this._renderService.setRenderer(this._createRenderer()),this._mouseService=this._instantiationService.createInstance(T.MouseService),this._instantiationService.setService(E.IMouseService,this._mouseService),this.viewport=this._instantiationService.createInstance(g.Viewport,this._viewportElement,this._viewportScrollArea),this.viewport.onRequestScrollLines(ne=>this.scrollLines(ne.amount,ne.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(C.SelectionService,this.element,this.screenElement,this.linkifier2)),this._instantiationService.setService(E.ISelectionService,this._selectionService),this.register(this._selectionService.onRequestScrollLines(ne=>this.scrollLines(ne.amount,ne.suppressScrollEvent))),this.register(this._selectionService.onSelectionChange(()=>this._onSelectionChange.fire())),this.register(this._selectionService.onRequestRedraw(ne=>this._renderService.handleSelectionChanged(ne.start,ne.end,ne.columnSelectMode))),this.register(this._selectionService.onLinuxMouseSelection(ne=>{this.textarea.value=ne,this.textarea.focus(),this.textarea.select()})),this.register(this._onScroll.event(ne=>{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",ne=>this._selectionService.handleMouseDown(ne))),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(oe.AccessibilityManager,this)),this.register(this.optionsService.onSpecificOptionChange("screenReaderMode",ne=>this._handleScreenReaderModeOptionChange(ne))),this.options.overviewRulerWidth&&(this._overviewRulerRenderer=this.register(this._instantiationService.createInstance(m.OverviewRulerRenderer,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange("overviewRulerWidth",ne=>{!this._overviewRulerRenderer&&ne&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this.register(this._instantiationService.createInstance(m.OverviewRulerRenderer,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(_.DomRenderer,this.element,this.screenElement,this._viewportElement,this.linkifier2)}bindMouse(){const P=this,X=this.element;function J(_e){const Pe=P._mouseService.getMouseReportCoords(_e,P.screenElement);if(!Pe)return!1;let it,at;switch(_e.overrideType||_e.type){case"mousemove":at=32,_e.buttons===void 0?(it=3,_e.button!==void 0&&(it=_e.button<3?_e.button:3)):it=1&_e.buttons?0:4&_e.buttons?1:2&_e.buttons?2:3;break;case"mouseup":at=0,it=_e.button<3?_e.button:3;break;case"mousedown":at=1,it=_e.button<3?_e.button:3;break;case"wheel":if(P.viewport.getLinesScrolled(_e)===0)return!1;at=_e.deltaY<0?0:1,it=4;break;default:return!1}return!(at===void 0||it===void 0||it>4)&&P.coreMouseService.triggerMouseEvent({col:Pe.col,row:Pe.row,x:Pe.x,y:Pe.y,button:it,action:at,ctrl:_e.ctrlKey,alt:_e.altKey,shift:_e.shiftKey})}const ne={mouseup:null,wheel:null,mousedrag:null,mousemove:null},ce={mouseup:_e=>(J(_e),_e.buttons||(this._document.removeEventListener("mouseup",ne.mouseup),ne.mousedrag&&this._document.removeEventListener("mousemove",ne.mousedrag)),this.cancel(_e)),wheel:_e=>(J(_e),this.cancel(_e,!0)),mousedrag:_e=>{_e.buttons&&J(_e)},mousemove:_e=>{_e.buttons||J(_e)}};this.register(this.coreMouseService.onProtocolChange(_e=>{_e?(this.optionsService.rawOptions.logLevel==="debug"&&this._logService.debug("Binding to mouse events:",this.coreMouseService.explainEvents(_e)),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&_e?ne.mousemove||(X.addEventListener("mousemove",ce.mousemove),ne.mousemove=ce.mousemove):(X.removeEventListener("mousemove",ne.mousemove),ne.mousemove=null),16&_e?ne.wheel||(X.addEventListener("wheel",ce.wheel,{passive:!1}),ne.wheel=ce.wheel):(X.removeEventListener("wheel",ne.wheel),ne.wheel=null),2&_e?ne.mouseup||(X.addEventListener("mouseup",ce.mouseup),ne.mouseup=ce.mouseup):(this._document.removeEventListener("mouseup",ne.mouseup),X.removeEventListener("mouseup",ne.mouseup),ne.mouseup=null),4&_e?ne.mousedrag||(ne.mousedrag=ce.mousedrag):(this._document.removeEventListener("mousemove",ne.mousedrag),ne.mousedrag=null)})),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this.register((0,u.addDisposableDomListener)(X,"mousedown",_e=>{if(_e.preventDefault(),this.focus(),this.coreMouseService.areMouseEventsActive&&!this._selectionService.shouldForceSelection(_e))return J(_e),ne.mouseup&&this._document.addEventListener("mouseup",ne.mouseup),ne.mousedrag&&this._document.addEventListener("mousemove",ne.mousedrag),this.cancel(_e)})),this.register((0,u.addDisposableDomListener)(X,"wheel",_e=>{if(!ne.wheel){if(!this.buffer.hasScrollback){const Pe=this.viewport.getLinesScrolled(_e);if(Pe===0)return;const it=V.C0.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?"O":"[")+(_e.deltaY<0?"A":"B");let at="";for(let rt=0;rt<Math.abs(Pe);rt++)at+=it;return this.coreService.triggerDataEvent(at,!0),this.cancel(_e,!0)}return this.viewport.handleWheel(_e)?this.cancel(_e):void 0}},{passive:!1})),this.register((0,u.addDisposableDomListener)(X,"touchstart",_e=>{if(!this.coreMouseService.areMouseEventsActive)return this.viewport.handleTouchStart(_e),this.cancel(_e)},{passive:!0})),this.register((0,u.addDisposableDomListener)(X,"touchmove",_e=>{if(!this.coreMouseService.areMouseEventsActive)return this.viewport.handleTouchMove(_e)?void 0:this.cancel(_e)},{passive:!1}))}refresh(P,X){var J;(J=this._renderService)===null||J===void 0||J.refreshRows(P,X)}updateCursorStyle(P){var X;!((X=this._selectionService)===null||X===void 0)&&X.shouldColumnSelect(P)?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(P,X,J=0){var ne;J===1?(super.scrollLines(P,X,J),this.refresh(0,this.rows-1)):(ne=this.viewport)===null||ne===void 0||ne.scrollLines(P)}paste(P){(0,l.paste)(P,this.textarea,this.coreService,this.optionsService)}attachCustomKeyEventHandler(P){this._customKeyEventHandler=P}registerLinkProvider(P){return this.linkifier2.registerLinkProvider(P)}registerCharacterJoiner(P){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");const X=this._characterJoinerService.register(P);return this.refresh(0,this.rows-1),X}deregisterCharacterJoiner(P){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");this._characterJoinerService.deregister(P)&&this.refresh(0,this.rows-1)}get markers(){return this.buffer.markers}registerMarker(P){return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+P)}registerDecoration(P){return this._decorationService.registerDecoration(P)}hasSelection(){return!!this._selectionService&&this._selectionService.hasSelection}select(P,X,J){this._selectionService.setSelection(P,X,J)}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 P;(P=this._selectionService)===null||P===void 0||P.clearSelection()}selectAll(){var P;(P=this._selectionService)===null||P===void 0||P.selectAll()}selectLines(P,X){var J;(J=this._selectionService)===null||J===void 0||J.selectLines(P,X)}_keyDown(P){if(this._keyDownHandled=!1,this._keyDownSeen=!0,this._customKeyEventHandler&&this._customKeyEventHandler(P)===!1)return!1;const X=this.browser.isMac&&this.options.macOptionIsMeta&&P.altKey;if(!X&&!this._compositionHelper.keydown(P))return this.options.scrollOnUserInput&&this.buffer.ybase!==this.buffer.ydisp&&this.scrollToBottom(),!1;X||P.key!=="Dead"&&P.key!=="AltGraph"||(this._unprocessedDeadKey=!0);const J=(0,I.evaluateKeyboardEvent)(P,this.coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(P),J.type===3||J.type===2){const ne=this.rows-1;return this.scrollLines(J.type===2?-ne:ne),this.cancel(P,!0)}return J.type===1&&this.selectAll(),!!this._isThirdLevelShift(this.browser,P)||(J.cancel&&this.cancel(P,!0),!J.key||!!(P.key&&!P.ctrlKey&&!P.altKey&&!P.metaKey&&P.key.length===1&&P.key.charCodeAt(0)>=65&&P.key.charCodeAt(0)<=90)||(this._unprocessedDeadKey?(this._unprocessedDeadKey=!1,!0):(J.key!==V.C0.ETX&&J.key!==V.C0.CR||(this.textarea.value=""),this._onKey.fire({key:J.key,domEvent:P}),this._showCursor(),this.coreService.triggerDataEvent(J.key,!0),!this.optionsService.rawOptions.screenReaderMode||P.altKey||P.ctrlKey?this.cancel(P,!0):void(this._keyDownHandled=!0))))}_isThirdLevelShift(P,X){const J=P.isMac&&!this.options.macOptionIsMeta&&X.altKey&&!X.ctrlKey&&!X.metaKey||P.isWindows&&X.altKey&&X.ctrlKey&&!X.metaKey||P.isWindows&&X.getModifierState("AltGraph");return X.type==="keypress"?J:J&&(!X.keyCode||X.keyCode>47)}_keyUp(P){this._keyDownSeen=!1,this._customKeyEventHandler&&this._customKeyEventHandler(P)===!1||(function(X){return X.keyCode===16||X.keyCode===17||X.keyCode===18}(P)||this.focus(),this.updateCursorStyle(P),this._keyPressHandled=!1)}_keyPress(P){let X;if(this._keyPressHandled=!1,this._keyDownHandled||this._customKeyEventHandler&&this._customKeyEventHandler(P)===!1)return!1;if(this.cancel(P),P.charCode)X=P.charCode;else if(P.which===null||P.which===void 0)X=P.keyCode;else{if(P.which===0||P.charCode===0)return!1;X=P.which}return!(!X||(P.altKey||P.ctrlKey||P.metaKey)&&!this._isThirdLevelShift(this.browser,P)||(X=String.fromCharCode(X),this._onKey.fire({key:X,domEvent:P}),this._showCursor(),this.coreService.triggerDataEvent(X,!0),this._keyPressHandled=!0,this._unprocessedDeadKey=!1,0))}_inputEvent(P){if(P.data&&P.inputType==="insertText"&&(!P.composed||!this._keyDownSeen)&&!this.optionsService.rawOptions.screenReaderMode){if(this._keyPressHandled)return!1;this._unprocessedDeadKey=!1;const X=P.data;return this.coreService.triggerDataEvent(X,!0),this.cancel(P),!0}return!1}resize(P,X){P!==this.cols||X!==this.rows?super.resize(P,X):this._charSizeService&&!this._charSizeService.hasValidSize&&this._charSizeService.measure()}_afterResize(P,X){var J,ne;(J=this._charSizeService)===null||J===void 0||J.measure(),(ne=this.viewport)===null||ne===void 0||ne.syncScrollArea(!0)}clear(){var P;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 X=1;X<this.rows;X++)this.buffer.lines.push(this.buffer.getBlankLine(q.DEFAULT_ATTR_DATA));this._onScroll.fire({position:this.buffer.ydisp,source:0}),(P=this.viewport)===null||P===void 0||P.reset(),this.refresh(0,this.rows-1)}}reset(){var P,X;this.options.rows=this.rows,this.options.cols=this.cols;const J=this._customKeyEventHandler;this._setup(),super.reset(),(P=this._selectionService)===null||P===void 0||P.reset(),this._decorationService.reset(),(X=this.viewport)===null||X===void 0||X.reset(),this._customKeyEventHandler=J,this.refresh(0,this.rows-1)}clearTextureAtlas(){var P;(P=this._renderService)===null||P===void 0||P.clearTextureAtlas()}_reportFocus(){var P;!((P=this.element)===null||P===void 0)&&P.classList.contains("focus")?this.coreService.triggerDataEvent(V.C0.ESC+"[I"):this.coreService.triggerDataEvent(V.C0.ESC+"[O")}_reportWindowsOptions(P){if(this._renderService)switch(P){case se.WindowsOptionsReportType.GET_WIN_SIZE_PIXELS:const X=this._renderService.dimensions.css.canvas.width.toFixed(0),J=this._renderService.dimensions.css.canvas.height.toFixed(0);this.coreService.triggerDataEvent(`${V.C0.ESC}[4;${J};${X}t`);break;case se.WindowsOptionsReportType.GET_CELL_SIZE_PIXELS:const ne=this._renderService.dimensions.css.cell.width.toFixed(0),ce=this._renderService.dimensions.css.cell.height.toFixed(0);this.coreService.triggerDataEvent(`${V.C0.ESC}[6;${ce};${ne}t`)}}cancel(P,X){if(this.options.cancelEvents||X)return P.preventDefault(),P.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 d=Date.now();if(d-this._lastRefreshMs>=this._debounceThresholdMS)this._lastRefreshMs=d,this._innerRefresh();else if(!this._additionalRefreshRequested){const h=d-this._lastRefreshMs,p=this._debounceThresholdMS-h;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,k){var w,T=arguments.length,A=T<3?_:k===null?k=Object.getOwnPropertyDescriptor(_,b):k;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")A=Reflect.decorate(y,_,b,k);else for(var C=y.length-1;C>=0;C--)(w=y[C])&&(A=(T<3?w(A):T>3?w(_,b,A):w(_,b))||A);return T>3&&A&&Object.defineProperty(_,b,A),A},u=this&&this.__param||function(y,_){return function(b,k){_(b,k,y)}};Object.defineProperty(a,"__esModule",{value:!0}),a.Viewport=void 0;const d=c(3656),h=c(4725),p=c(8460),g=c(844),v=c(2585);let m=a.Viewport=class extends g.Disposable{constructor(y,_,b,k,w,T,A,C){super(),this._viewportElement=y,this._scrollArea=_,this._bufferService=b,this._optionsService=k,this._charSizeService=w,this._renderService=T,this._coreBrowserService=A,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,d.addDisposableDomListener)(this._viewportElement,"scroll",this._handleScroll.bind(this))),this._activeBuffer=this._bufferService.buffer,this.register(this._bufferService.buffers.onBufferActivate(E=>this._activeBuffer=E.activeBuffer)),this._renderDimensions=this._renderService.dimensions,this.register(this._renderService.onDimensionsChange(E=>this._renderDimensions=E)),this._handleThemeChange(C.colors),this.register(C.onChangeColors(E=>this._handleThemeChange(E))),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 _=Math.round(this._currentRowHeight*this._lastRecordedBufferLength)+(this._lastRecordedViewportHeight-this._renderService.dimensions.css.canvas.height);this._lastRecordedBufferHeight!==_&&(this._lastRecordedBufferHeight=_,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 _=Math.round(this._lastScrollTop/this._currentRowHeight)-this._bufferService.buffer.ydisp;this._onRequestScrollLines.fire({amount:_,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,_){const b=this._viewportElement.scrollTop+this._lastRecordedViewportHeight;return!(_<0&&this._viewportElement.scrollTop!==0||_>0&&b<this._lastRecordedBufferHeight)||(y.cancelable&&y.preventDefault(),!1)}handleWheel(y){const _=this._getPixelsScrolled(y);return _!==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+_:this._smoothScrollState.target+=_,this._smoothScrollState.target=Math.max(Math.min(this._smoothScrollState.target,this._viewportElement.scrollHeight),0),this._smoothScroll()):this._clearSmoothScrollState()):this._viewportElement.scrollTop+=_,this._bubbleScroll(y,_))}scrollLines(y){if(y!==0)if(this._optionsService.rawOptions.smoothScrollDuration){const _=y*this._currentRowHeight;this._smoothScrollState.startTime=Date.now(),this._smoothScrollPercent()<1?(this._smoothScrollState.origin=this._viewportElement.scrollTop,this._smoothScrollState.target=this._smoothScrollState.origin+_,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 _=this._applyScrollModifier(y.deltaY,y);return y.deltaMode===WheelEvent.DOM_DELTA_LINE?_*=this._currentRowHeight:y.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(_*=this._currentRowHeight*this._bufferService.rows),_}getBufferElements(y,_){var b;let k,w="";const T=[],A=_??this._bufferService.buffer.lines.length,C=this._bufferService.buffer.lines;for(let E=y;E<A;E++){const x=C.get(E);if(!x)continue;const D=(b=C.get(E+1))===null||b===void 0?void 0:b.isWrapped;if(w+=x.translateToString(!D),!D||E===C.length-1){const N=document.createElement("div");N.textContent=w,T.push(N),w.length>0&&(k=N),w=""}}return{bufferElements:T,cursorElement:k}}getLinesScrolled(y){if(y.deltaY===0||y.shiftKey)return 0;let _=this._applyScrollModifier(y.deltaY,y);return y.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(_/=this._currentRowHeight+0,this._wheelPartialScroll+=_,_=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):y.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(_*=this._bufferService.rows),_}_applyScrollModifier(y,_){const b=this._optionsService.rawOptions.fastScrollModifier;return b==="alt"&&_.altKey||b==="ctrl"&&_.ctrlKey||b==="shift"&&_.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 _=this._lastTouchY-y.touches[0].pageY;return this._lastTouchY=y.touches[0].pageY,_!==0&&(this._viewportElement.scrollTop+=_,this._bubbleScroll(y,_))}};a.Viewport=m=l([u(2,v.IBufferService),u(3,v.IOptionsService),u(4,h.ICharSizeService),u(5,h.IRenderService),u(6,h.ICoreBrowserService),u(7,h.IThemeService)],m)},3107:function(o,a,c){var l=this&&this.__decorate||function(m,y,_,b){var k,w=arguments.length,T=w<3?y:b===null?b=Object.getOwnPropertyDescriptor(y,_):b;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")T=Reflect.decorate(m,y,_,b);else for(var A=m.length-1;A>=0;A--)(k=m[A])&&(T=(w<3?k(T):w>3?k(y,_,T):k(y,_))||T);return w>3&&T&&Object.defineProperty(y,_,T),T},u=this&&this.__param||function(m,y){return function(_,b){y(_,b,m)}};Object.defineProperty(a,"__esModule",{value:!0}),a.BufferDecorationRenderer=void 0;const d=c(3656),h=c(4725),p=c(844),g=c(2585);let v=a.BufferDecorationRenderer=class extends p.Disposable{constructor(m,y,_,b){super(),this._screenElement=m,this._bufferService=y,this._decorationService=_,this._renderService=b,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,d.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(k=>this._removeDecoration(k))),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 m of this._decorationService.decorations)this._renderDecoration(m);this._dimensionsChanged=!1}_renderDecoration(m){this._refreshStyle(m),this._dimensionsChanged&&this._refreshXPosition(m)}_createElement(m){var y,_;const b=document.createElement("div");b.classList.add("xterm-decoration"),b.classList.toggle("xterm-decoration-top-layer",((y=m==null?void 0:m.options)===null||y===void 0?void 0:y.layer)==="top"),b.style.width=`${Math.round((m.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,b.style.height=(m.options.height||1)*this._renderService.dimensions.css.cell.height+"px",b.style.top=(m.marker.line-this._bufferService.buffers.active.ydisp)*this._renderService.dimensions.css.cell.height+"px",b.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`;const k=(_=m.options.x)!==null&&_!==void 0?_:0;return k&&k>this._bufferService.cols&&(b.style.display="none"),this._refreshXPosition(m,b),b}_refreshStyle(m){const y=m.marker.line-this._bufferService.buffers.active.ydisp;if(y<0||y>=this._bufferService.rows)m.element&&(m.element.style.display="none",m.onRenderEmitter.fire(m.element));else{let _=this._decorationElements.get(m);_||(_=this._createElement(m),m.element=_,this._decorationElements.set(m,_),this._container.appendChild(_),m.onDispose(()=>{this._decorationElements.delete(m),_.remove()})),_.style.top=y*this._renderService.dimensions.css.cell.height+"px",_.style.display=this._altBufferIsActive?"none":"block",m.onRenderEmitter.fire(_)}}_refreshXPosition(m,y=m.element){var _;if(!y)return;const b=(_=m.options.x)!==null&&_!==void 0?_:0;(m.options.anchor||"left")==="right"?y.style.right=b?b*this._renderService.dimensions.css.cell.width+"px":"":y.style.left=b?b*this._renderService.dimensions.css.cell.width+"px":""}_removeDecoration(m){var y;(y=this._decorationElements.get(m))===null||y===void 0||y.remove(),this._decorationElements.delete(m),m.dispose()}};a.BufferDecorationRenderer=v=l([u(1,g.IBufferService),u(2,g.IDecorationService),u(3,h.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(k,w,T,A){var C,E=arguments.length,x=E<3?w:A===null?A=Object.getOwnPropertyDescriptor(w,T):A;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")x=Reflect.decorate(k,w,T,A);else for(var D=k.length-1;D>=0;D--)(C=k[D])&&(x=(E<3?C(x):E>3?C(w,T,x):C(w,T))||x);return E>3&&x&&Object.defineProperty(w,T,x),x},u=this&&this.__param||function(k,w){return function(T,A){w(T,A,k)}};Object.defineProperty(a,"__esModule",{value:!0}),a.OverviewRulerRenderer=void 0;const d=c(5871),h=c(3656),p=c(4725),g=c(844),v=c(2585),m={full:0,left:0,center:0,right:0},y={full:0,left:0,center:0,right:0},_={full:0,left:0,center:0,right:0};let b=a.OverviewRulerRenderer=class extends g.Disposable{get _width(){return this._optionsService.options.overviewRulerWidth||0}constructor(k,w,T,A,C,E,x){var D;super(),this._viewportElement=k,this._screenElement=w,this._bufferService=T,this._decorationService=A,this._renderService=C,this._optionsService=E,this._coreBrowseService=x,this._colorZoneStore=new d.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(),(D=this._viewportElement.parentElement)===null||D===void 0||D.insertBefore(this._canvas,this._viewportElement);const N=this._canvas.getContext("2d");if(!N)throw new Error("Ctx cannot be null");this._ctx=N,this._registerDecorationListeners(),this._registerBufferChangeListeners(),this._registerDimensionChangeListeners(),this.register((0,g.toDisposable)(()=>{var O;(O=this._canvas)===null||O===void 0||O.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,h.addDisposableDomListener)(this._coreBrowseService.window,"resize",()=>this._queueRefresh(!0))),this._queueRefresh(!0)}_refreshDrawConstants(){const k=Math.floor(this._canvas.width/3),w=Math.ceil(this._canvas.width/3);y.full=this._canvas.width,y.left=k,y.center=w,y.right=k,this._refreshDrawHeightConstants(),_.full=0,_.left=0,_.center=y.left,_.right=y.left+y.center}_refreshDrawHeightConstants(){m.full=Math.round(2*this._coreBrowseService.dpr);const k=this._canvas.height/this._bufferService.buffer.lines.length,w=Math.round(Math.max(Math.min(k,12),6)*this._coreBrowseService.dpr);m.left=w,m.center=w,m.right=w}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*m.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*m.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*m.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*m.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 w of this._decorationService.decorations)this._colorZoneStore.addDecoration(w);this._ctx.lineWidth=1;const k=this._colorZoneStore.zones;for(const w of k)w.position!=="full"&&this._renderColorZone(w);for(const w of k)w.position==="full"&&this._renderColorZone(w);this._shouldUpdateDimensions=!1,this._shouldUpdateAnchor=!1}_renderColorZone(k){this._ctx.fillStyle=k.color,this._ctx.fillRect(_[k.position||"full"],Math.round((this._canvas.height-1)*(k.startBufferLine/this._bufferService.buffers.active.lines.length)-m[k.position||"full"]/2),y[k.position||"full"],Math.round((this._canvas.height-1)*((k.endBufferLine-k.startBufferLine)/this._bufferService.buffers.active.lines.length)+m[k.position||"full"]))}_queueRefresh(k,w){this._shouldUpdateDimensions=k||this._shouldUpdateDimensions,this._shouldUpdateAnchor=w||this._shouldUpdateAnchor,this._animationFrame===void 0&&(this._animationFrame=this._coreBrowseService.window.requestAnimationFrame(()=>{this._refreshDecorations(),this._animationFrame=void 0}))}};a.OverviewRulerRenderer=b=l([u(2,v.IBufferService),u(3,v.IDecorationService),u(4,p.IRenderService),u(5,v.IOptionsService),u(6,p.ICoreBrowserService)],b)},2950:function(o,a,c){var l=this&&this.__decorate||function(v,m,y,_){var b,k=arguments.length,w=k<3?m:_===null?_=Object.getOwnPropertyDescriptor(m,y):_;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")w=Reflect.decorate(v,m,y,_);else for(var T=v.length-1;T>=0;T--)(b=v[T])&&(w=(k<3?b(w):k>3?b(m,y,w):b(m,y))||w);return k>3&&w&&Object.defineProperty(m,y,w),w},u=this&&this.__param||function(v,m){return function(y,_){m(y,_,v)}};Object.defineProperty(a,"__esModule",{value:!0}),a.CompositionHelper=void 0;const d=c(4725),h=c(2585),p=c(2584);let g=a.CompositionHelper=class{get isComposing(){return this._isComposing}constructor(v,m,y,_,b,k){this._textarea=v,this._compositionView=m,this._bufferService=y,this._optionsService=_,this._coreService=b,this._renderService=k,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 m={start:this._compositionPosition.start,end:this._compositionPosition.end};this._isSendingComposition=!0,setTimeout(()=>{if(this._isSendingComposition){let y;this._isSendingComposition=!1,m.start+=this._dataAlreadySent.length,y=this._isComposing?this._textarea.value.substring(m.start,m.end):this._textarea.value.substring(m.start),y.length>0&&this._coreService.triggerDataEvent(y,!0)}},0)}else{this._isSendingComposition=!1;const m=this._textarea.value.substring(this._compositionPosition.start,this._compositionPosition.end);this._coreService.triggerDataEvent(m,!0)}}_handleAnyTextareaChanges(){const v=this._textarea.value;setTimeout(()=>{if(!this._isComposing){const m=this._textarea.value,y=m.replace(v,"");this._dataAlreadySent=y,m.length>v.length?this._coreService.triggerDataEvent(y,!0):m.length<v.length?this._coreService.triggerDataEvent(`${p.C0.DEL}`,!0):m.length===v.length&&m!==v&&this._coreService.triggerDataEvent(m,!0)}},0)}updateCompositionElements(v){if(this._isComposing){if(this._bufferService.buffer.isCursorInViewport){const m=Math.min(this._bufferService.buffer.x,this._bufferService.cols-1),y=this._renderService.dimensions.css.cell.height,_=this._bufferService.buffer.y*this._renderService.dimensions.css.cell.height,b=m*this._renderService.dimensions.css.cell.width;this._compositionView.style.left=b+"px",this._compositionView.style.top=_+"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 k=this._compositionView.getBoundingClientRect();this._textarea.style.left=b+"px",this._textarea.style.top=_+"px",this._textarea.style.width=Math.max(k.width,1)+"px",this._textarea.style.height=Math.max(k.height,1)+"px",this._textarea.style.lineHeight=k.height+"px"}v||setTimeout(()=>this.updateCompositionElements(!0),0)}}};a.CompositionHelper=g=l([u(2,h.IBufferService),u(3,h.IOptionsService),u(4,h.ICoreService),u(5,d.IRenderService)],g)},9806:(o,a)=>{function c(l,u,d){const h=d.getBoundingClientRect(),p=l.getComputedStyle(d),g=parseInt(p.getPropertyValue("padding-left")),v=parseInt(p.getPropertyValue("padding-top"));return[u.clientX-h.left-g,u.clientY-h.top-v]}Object.defineProperty(a,"__esModule",{value:!0}),a.getCoords=a.getCoordsRelativeToElement=void 0,a.getCoordsRelativeToElement=c,a.getCoords=function(l,u,d,h,p,g,v,m,y){if(!g)return;const _=c(l,u,d);return _?(_[0]=Math.ceil((_[0]+(y?v/2:0))/v),_[1]=Math.ceil(_[1]/m),_[0]=Math.min(Math.max(_[0],1),h+(y?1:0)),_[1]=Math.min(Math.max(_[1],1),p),_):void 0}},9504:(o,a,c)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.moveToCellSequence=void 0;const l=c(2584);function u(m,y,_,b){const k=m-d(m,_),w=y-d(y,_),T=Math.abs(k-w)-function(A,C,E){let x=0;const D=A-d(A,E),N=C-d(C,E);for(let O=0;O<Math.abs(D-N);O++){const G=h(A,C)==="A"?-1:1,Z=E.buffer.lines.get(D+G*O);Z!=null&&Z.isWrapped&&x++}return x}(m,y,_);return v(T,g(h(m,y),b))}function d(m,y){let _=0,b=y.buffer.lines.get(m),k=b==null?void 0:b.isWrapped;for(;k&&m>=0&&m<y.rows;)_++,b=y.buffer.lines.get(--m),k=b==null?void 0:b.isWrapped;return _}function h(m,y){return m>y?"A":"B"}function p(m,y,_,b,k,w){let T=m,A=y,C="";for(;T!==_||A!==b;)T+=k?1:-1,k&&T>w.cols-1?(C+=w.buffer.translateBufferLineToString(A,!1,m,T),T=0,m=0,A++):!k&&T<0&&(C+=w.buffer.translateBufferLineToString(A,!1,0,m+1),T=w.cols-1,m=T,A--);return C+w.buffer.translateBufferLineToString(A,!1,m,T)}function g(m,y){const _=y?"O":"[";return l.C0.ESC+_+m}function v(m,y){m=Math.floor(m);let _="";for(let b=0;b<m;b++)_+=y;return _}a.moveToCellSequence=function(m,y,_,b){const k=_.buffer.x,w=_.buffer.y;if(!_.buffer.hasScrollback)return function(C,E,x,D,N,O){return u(E,D,N,O).length===0?"":v(p(C,E,C,E-d(E,N),!1,N).length,g("D",O))}(k,w,0,y,_,b)+u(w,y,_,b)+function(C,E,x,D,N,O){let G;G=u(E,D,N,O).length>0?D-d(D,N):E;const Z=D,q=function(V,I,$,L,K,se){let oe;return oe=u($,L,K,se).length>0?L-d(L,K):I,V<$&&oe<=L||V>=$&&oe<L?"C":"D"}(C,E,x,D,N,O);return v(p(C,G,x,Z,q==="C",N).length,g(q,O))}(k,w,m,y,_,b);let T;if(w===y)return T=k>m?"D":"C",v(Math.abs(k-m),g(T,b));T=w>y?"D":"C";const A=Math.abs(w-y);return v(function(C,E){return E.cols-C}(w>y?m:k,_)+(A-1)*_.cols+1+((w>y?k:m)-1),g(T,b))}},1296:function(o,a,c){var l=this&&this.__decorate||function(N,O,G,Z){var q,V=arguments.length,I=V<3?O:Z===null?Z=Object.getOwnPropertyDescriptor(O,G):Z;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")I=Reflect.decorate(N,O,G,Z);else for(var $=N.length-1;$>=0;$--)(q=N[$])&&(I=(V<3?q(I):V>3?q(O,G,I):q(O,G))||I);return V>3&&I&&Object.defineProperty(O,G,I),I},u=this&&this.__param||function(N,O){return function(G,Z){O(G,Z,N)}};Object.defineProperty(a,"__esModule",{value:!0}),a.DomRenderer=void 0;const d=c(3787),h=c(2550),p=c(2223),g=c(6171),v=c(4725),m=c(8055),y=c(8460),_=c(844),b=c(2585),k="xterm-dom-renderer-owner-",w="xterm-rows",T="xterm-fg-",A="xterm-bg-",C="xterm-focus",E="xterm-selection";let x=1,D=a.DomRenderer=class extends _.Disposable{constructor(N,O,G,Z,q,V,I,$,L,K){super(),this._element=N,this._screenElement=O,this._viewportElement=G,this._linkifier2=Z,this._charSizeService=V,this._optionsService=I,this._bufferService=$,this._coreBrowserService=L,this._themeService=K,this._terminalClass=x++,this._rowElements=[],this.onRequestRedraw=this.register(new y.EventEmitter).event,this._rowContainer=document.createElement("div"),this._rowContainer.classList.add(w),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(E),this._selectionContainer.setAttribute("aria-hidden","true"),this.dimensions=(0,g.createRenderDimensions)(),this._updateDimensions(),this.register(this._optionsService.onOptionChange(()=>this._handleOptionsChanged())),this.register(this._themeService.onChangeColors(se=>this._injectCss(se))),this._injectCss(this._themeService.colors),this._rowFactory=q.createInstance(d.DomRendererRowFactory,document),this._element.classList.add(k+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this.register(this._linkifier2.onShowLinkUnderline(se=>this._handleLinkHover(se))),this.register(this._linkifier2.onHideLinkUnderline(se=>this._handleLinkLeave(se))),this.register((0,_.toDisposable)(()=>{this._element.classList.remove(k+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()})),this._widthCache=new h.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 N=this._coreBrowserService.dpr;this.dimensions.device.char.width=this._charSizeService.width*N,this.dimensions.device.char.height=Math.ceil(this._charSizeService.height*N),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/N),this.dimensions.css.canvas.height=Math.round(this.dimensions.device.canvas.height/N),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 G of this._rowElements)G.style.width=`${this.dimensions.css.canvas.width}px`,G.style.height=`${this.dimensions.css.cell.height}px`,G.style.lineHeight=`${this.dimensions.css.cell.height}px`,G.style.overflow="hidden";this._dimensionsStyleElement||(this._dimensionsStyleElement=document.createElement("style"),this._screenElement.appendChild(this._dimensionsStyleElement));const O=`${this._terminalSelector} .${w} span { display: inline-block; height: 100%; vertical-align: top;}`;this._dimensionsStyleElement.textContent=O,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(N){this._themeStyleElement||(this._themeStyleElement=document.createElement("style"),this._screenElement.appendChild(this._themeStyleElement));let O=`${this._terminalSelector} .${w} { color: ${N.foreground.css}; font-family: ${this._optionsService.rawOptions.fontFamily}; font-size: ${this._optionsService.rawOptions.fontSize}px; font-kerning: none; white-space: pre}`;O+=`${this._terminalSelector} .${w} .xterm-dim { color: ${m.color.multiplyOpacity(N.foreground,.5).css};}`,O+=`${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;}`,O+="@keyframes blink_box_shadow_"+this._terminalClass+" { 50% { border-bottom-style: hidden; }}",O+="@keyframes blink_block_"+this._terminalClass+` { 0% { background-color: ${N.cursor.css}; color: ${N.cursorAccent.css}; } 50% { background-color: inherit; color: ${N.cursor.css}; }}`,O+=`${this._terminalSelector} .${w}.${C} .xterm-cursor.xterm-cursor-blink:not(.xterm-cursor-block) { animation: blink_box_shadow_`+this._terminalClass+` 1s step-end infinite;}${this._terminalSelector} .${w}.${C} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: blink_block_`+this._terminalClass+` 1s step-end infinite;}${this._terminalSelector} .${w} .xterm-cursor.xterm-cursor-block { background-color: ${N.cursor.css}; color: ${N.cursorAccent.css};}${this._terminalSelector} .${w} .xterm-cursor.xterm-cursor-outline { outline: 1px solid ${N.cursor.css}; outline-offset: -1px;}${this._terminalSelector} .${w} .xterm-cursor.xterm-cursor-bar { box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${N.cursor.css} inset;}${this._terminalSelector} .${w} .xterm-cursor.xterm-cursor-underline { border-bottom: 1px ${N.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`,O+=`${this._terminalSelector} .${E} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${E} div { position: absolute; background-color: ${N.selectionBackgroundOpaque.css};}${this._terminalSelector} .${E} div { position: absolute; background-color: ${N.selectionInactiveBackgroundOpaque.css};}`;for(const[G,Z]of N.ansi.entries())O+=`${this._terminalSelector} .${T}${G} { color: ${Z.css}; }${this._terminalSelector} .${T}${G}.xterm-dim { color: ${m.color.multiplyOpacity(Z,.5).css}; }${this._terminalSelector} .${A}${G} { background-color: ${Z.css}; }`;O+=`${this._terminalSelector} .${T}${p.INVERTED_DEFAULT_COLOR} { color: ${m.color.opaque(N.background).css}; }${this._terminalSelector} .${T}${p.INVERTED_DEFAULT_COLOR}.xterm-dim { color: ${m.color.multiplyOpacity(m.color.opaque(N.background),.5).css}; }${this._terminalSelector} .${A}${p.INVERTED_DEFAULT_COLOR} { background-color: ${N.foreground.css}; }`,this._themeStyleElement.textContent=O}_setDefaultSpacing(){const N=this.dimensions.css.cell.width-this._widthCache.get("W",!1,!1);this._rowContainer.style.letterSpacing=`${N}px`,this._rowFactory.defaultSpacing=N}handleDevicePixelRatioChange(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}_refreshRowElements(N,O){for(let G=this._rowElements.length;G<=O;G++){const Z=document.createElement("div");this._rowContainer.appendChild(Z),this._rowElements.push(Z)}for(;this._rowElements.length>O;)this._rowContainer.removeChild(this._rowElements.pop())}handleResize(N,O){this._refreshRowElements(N,O),this._updateDimensions()}handleCharSizeChanged(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}handleBlur(){this._rowContainer.classList.remove(C)}handleFocus(){this._rowContainer.classList.add(C),this.renderRows(this._bufferService.buffer.y,this._bufferService.buffer.y)}handleSelectionChanged(N,O,G){if(this._selectionContainer.replaceChildren(),this._rowFactory.handleSelectionChanged(N,O,G),this.renderRows(0,this._bufferService.rows-1),!N||!O)return;const Z=N[1]-this._bufferService.buffer.ydisp,q=O[1]-this._bufferService.buffer.ydisp,V=Math.max(Z,0),I=Math.min(q,this._bufferService.rows-1);if(V>=this._bufferService.rows||I<0)return;const $=document.createDocumentFragment();if(G){const L=N[0]>O[0];$.appendChild(this._createSelectionElement(V,L?O[0]:N[0],L?N[0]:O[0],I-V+1))}else{const L=Z===V?N[0]:0,K=V===q?O[0]:this._bufferService.cols;$.appendChild(this._createSelectionElement(V,L,K));const se=I-V-1;if($.appendChild(this._createSelectionElement(V+1,0,this._bufferService.cols,se)),V!==I){const oe=q===I?O[0]:this._bufferService.cols;$.appendChild(this._createSelectionElement(I,0,oe))}}this._selectionContainer.appendChild($)}_createSelectionElement(N,O,G,Z=1){const q=document.createElement("div");return q.style.height=Z*this.dimensions.css.cell.height+"px",q.style.top=N*this.dimensions.css.cell.height+"px",q.style.left=O*this.dimensions.css.cell.width+"px",q.style.width=this.dimensions.css.cell.width*(G-O)+"px",q}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 N of this._rowElements)N.replaceChildren()}renderRows(N,O){const G=this._bufferService.buffer,Z=G.ybase+G.y,q=Math.min(G.x,this._bufferService.cols-1),V=this._optionsService.rawOptions.cursorBlink,I=this._optionsService.rawOptions.cursorStyle,$=this._optionsService.rawOptions.cursorInactiveStyle;for(let L=N;L<=O;L++){const K=L+G.ydisp,se=this._rowElements[L],oe=G.lines.get(K);if(!se||!oe)break;se.replaceChildren(...this._rowFactory.createRow(oe,K,K===Z,I,$,q,V,this.dimensions.css.cell.width,this._widthCache,-1,-1))}}get _terminalSelector(){return`.${k}${this._terminalClass}`}_handleLinkHover(N){this._setCellUnderline(N.x1,N.x2,N.y1,N.y2,N.cols,!0)}_handleLinkLeave(N){this._setCellUnderline(N.x1,N.x2,N.y1,N.y2,N.cols,!1)}_setCellUnderline(N,O,G,Z,q,V){G<0&&(N=0),Z<0&&(O=0);const I=this._bufferService.rows-1;G=Math.max(Math.min(G,I),0),Z=Math.max(Math.min(Z,I),0),q=Math.min(q,this._bufferService.cols);const $=this._bufferService.buffer,L=$.ybase+$.y,K=Math.min($.x,q-1),se=this._optionsService.rawOptions.cursorBlink,oe=this._optionsService.rawOptions.cursorStyle,ve=this._optionsService.rawOptions.cursorInactiveStyle;for(let le=G;le<=Z;++le){const ue=le+$.ydisp,P=this._rowElements[le],X=$.lines.get(ue);if(!P||!X)break;P.replaceChildren(...this._rowFactory.createRow(X,ue,ue===L,oe,ve,K,se,this.dimensions.css.cell.width,this._widthCache,V?le===G?N:0:-1,V?(le===Z?O:q)-1:-1))}}};a.DomRenderer=D=l([u(4,b.IInstantiationService),u(5,v.ICharSizeService),u(6,b.IOptionsService),u(7,b.IBufferService),u(8,v.ICoreBrowserService),u(9,v.IThemeService)],D)},3787:function(o,a,c){var l=this&&this.__decorate||function(T,A,C,E){var x,D=arguments.length,N=D<3?A:E===null?E=Object.getOwnPropertyDescriptor(A,C):E;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")N=Reflect.decorate(T,A,C,E);else for(var O=T.length-1;O>=0;O--)(x=T[O])&&(N=(D<3?x(N):D>3?x(A,C,N):x(A,C))||N);return D>3&&N&&Object.defineProperty(A,C,N),N},u=this&&this.__param||function(T,A){return function(C,E){A(C,E,T)}};Object.defineProperty(a,"__esModule",{value:!0}),a.DomRendererRowFactory=void 0;const d=c(2223),h=c(643),p=c(511),g=c(2585),v=c(8055),m=c(4725),y=c(4269),_=c(6171),b=c(3734);let k=a.DomRendererRowFactory=class{constructor(T,A,C,E,x,D,N){this._document=T,this._characterJoinerService=A,this._optionsService=C,this._coreBrowserService=E,this._coreService=x,this._decorationService=D,this._themeService=N,this._workCell=new p.CellData,this._columnSelectMode=!1,this.defaultSpacing=0}handleSelectionChanged(T,A,C){this._selectionStart=T,this._selectionEnd=A,this._columnSelectMode=C}createRow(T,A,C,E,x,D,N,O,G,Z,q){const V=[],I=this._characterJoinerService.getJoinedCharacters(A),$=this._themeService.colors;let L,K=T.getNoBgTrimmedLength();C&&K<D+1&&(K=D+1);let se=0,oe="",ve=0,le=0,ue=0,P=!1,X=0,J=!1,ne=0;const ce=[],_e=Z!==-1&&q!==-1;for(let Pe=0;Pe<K;Pe++){T.loadCell(Pe,this._workCell);let it=this._workCell.getWidth();if(it===0)continue;let at=!1,rt=Pe,Oe=this._workCell;if(I.length>0&&Pe===I[0][0]){at=!0;const ot=I.shift();Oe=new y.JoinedCellData(this._workCell,T.translateToString(!0,ot[0],ot[1]),ot[1]-ot[0]),rt=ot[1]-1,it=Oe.getWidth()}const xe=this._isCellInSelection(Pe,A),pe=C&&Pe===D,he=_e&&Pe>=Z&&Pe<=q;let ye=!1;this._decorationService.forEachDecorationAtCell(Pe,A,void 0,ot=>{ye=!0});let ke=Oe.getChars()||h.WHITESPACE_CELL_CHAR;if(ke===" "&&(Oe.isUnderline()||Oe.isOverline())&&(ke=" "),ne=it*O-G.get(ke,Oe.isBold(),Oe.isItalic()),L){if(se&&(xe&&J||!xe&&!J&&Oe.bg===ve)&&(xe&&J&&$.selectionForeground||Oe.fg===le)&&Oe.extended.ext===ue&&he===P&&ne===X&&!pe&&!at&&!ye){oe+=ke,se++;continue}se&&(L.textContent=oe),L=this._document.createElement("span"),se=0,oe=""}else L=this._document.createElement("span");if(ve=Oe.bg,le=Oe.fg,ue=Oe.extended.ext,P=he,X=ne,J=xe,at&&D>=Pe&&D<=rt&&(D=Pe),!this._coreService.isCursorHidden&&pe){if(ce.push("xterm-cursor"),this._coreBrowserService.isFocused)N&&ce.push("xterm-cursor-blink"),ce.push(E==="bar"?"xterm-cursor-bar":E==="underline"?"xterm-cursor-underline":"xterm-cursor-block");else if(x)switch(x){case"outline":ce.push("xterm-cursor-outline");break;case"block":ce.push("xterm-cursor-block");break;case"bar":ce.push("xterm-cursor-bar");break;case"underline":ce.push("xterm-cursor-underline")}}if(Oe.isBold()&&ce.push("xterm-bold"),Oe.isItalic()&&ce.push("xterm-italic"),Oe.isDim()&&ce.push("xterm-dim"),oe=Oe.isInvisible()?h.WHITESPACE_CELL_CHAR:Oe.getChars()||h.WHITESPACE_CELL_CHAR,Oe.isUnderline()&&(ce.push(`xterm-underline-${Oe.extended.underlineStyle}`),oe===" "&&(oe=" "),!Oe.isUnderlineColorDefault()))if(Oe.isUnderlineColorRGB())L.style.textDecorationColor=`rgb(${b.AttributeData.toColorRGB(Oe.getUnderlineColor()).join(",")})`;else{let ot=Oe.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&Oe.isBold()&&ot<8&&(ot+=8),L.style.textDecorationColor=$.ansi[ot].css}Oe.isOverline()&&(ce.push("xterm-overline"),oe===" "&&(oe=" ")),Oe.isStrikethrough()&&ce.push("xterm-strikethrough"),he&&(L.style.textDecoration="underline");let Le=Oe.getFgColor(),st=Oe.getFgColorMode(),gt=Oe.getBgColor(),Wt=Oe.getBgColorMode();const jt=!!Oe.isInverse();if(jt){const ot=Le;Le=gt,gt=ot;const $s=st;st=Wt,Wt=$s}let ht,Qt,It,ns=!1;switch(this._decorationService.forEachDecorationAtCell(Pe,A,void 0,ot=>{ot.options.layer!=="top"&&ns||(ot.backgroundColorRGB&&(Wt=50331648,gt=ot.backgroundColorRGB.rgba>>8&16777215,ht=ot.backgroundColorRGB),ot.foregroundColorRGB&&(st=50331648,Le=ot.foregroundColorRGB.rgba>>8&16777215,Qt=ot.foregroundColorRGB),ns=ot.options.layer==="top")}),!ns&&xe&&(ht=this._coreBrowserService.isFocused?$.selectionBackgroundOpaque:$.selectionInactiveBackgroundOpaque,gt=ht.rgba>>8&16777215,Wt=50331648,ns=!0,$.selectionForeground&&(st=50331648,Le=$.selectionForeground.rgba>>8&16777215,Qt=$.selectionForeground)),ns&&ce.push("xterm-decoration-top"),Wt){case 16777216:case 33554432:It=$.ansi[gt],ce.push(`xterm-bg-${gt}`);break;case 50331648:It=v.rgba.toColor(gt>>16,gt>>8&255,255>),this._addStyle(L,`background-color:#${w((gt>>>0).toString(16),"0",6)}`);break;default:jt?(It=$.foreground,ce.push(`xterm-bg-${d.INVERTED_DEFAULT_COLOR}`)):It=$.background}switch(ht||Oe.isDim()&&(ht=v.color.multiplyOpacity(It,.5)),st){case 16777216:case 33554432:Oe.isBold()&&Le<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&(Le+=8),this._applyMinimumContrast(L,It,$.ansi[Le],Oe,ht,void 0)||ce.push(`xterm-fg-${Le}`);break;case 50331648:const ot=v.rgba.toColor(Le>>16&255,Le>>8&255,255&Le);this._applyMinimumContrast(L,It,ot,Oe,ht,Qt)||this._addStyle(L,`color:#${w(Le.toString(16),"0",6)}`);break;default:this._applyMinimumContrast(L,It,$.foreground,Oe,ht,void 0)||jt&&ce.push(`xterm-fg-${d.INVERTED_DEFAULT_COLOR}`)}ce.length&&(L.className=ce.join(" "),ce.length=0),pe||at||ye?L.textContent=oe:se++,ne!==this.defaultSpacing&&(L.style.letterSpacing=`${ne}px`),V.push(L),Pe=rt}return L&&se&&(L.textContent=oe),V}_applyMinimumContrast(T,A,C,E,x,D){if(this._optionsService.rawOptions.minimumContrastRatio===1||(0,_.excludeFromContrastRatioDemands)(E.getCode()))return!1;const N=this._getContrastCache(E);let O;if(x||D||(O=N.getColor(A.rgba,C.rgba)),O===void 0){const G=this._optionsService.rawOptions.minimumContrastRatio/(E.isDim()?2:1);O=v.color.ensureContrastRatio(x||A,D||C,G),N.setColor((x||A).rgba,(D||C).rgba,O??null)}return!!O&&(this._addStyle(T,`color:${O.css}`),!0)}_getContrastCache(T){return T.isDim()?this._themeService.colors.halfContrastCache:this._themeService.colors.contrastCache}_addStyle(T,A){T.setAttribute("style",`${T.getAttribute("style")||""}${A};`)}_isCellInSelection(T,A){const C=this._selectionStart,E=this._selectionEnd;return!(!C||!E)&&(this._columnSelectMode?C[0]<=E[0]?T>=C[0]&&A>=C[1]&&T<E[0]&&A<=E[1]:T<C[0]&&A>=C[1]&&T>=E[0]&&A<=E[1]:A>C[1]&&A<E[1]||C[1]===E[1]&&A===C[1]&&T>=C[0]&&T<E[0]||C[1]<E[1]&&A===E[1]&&T<E[0]||C[1]<E[1]&&A===C[1]&&T>=C[0])}};function w(T,A,C){for(;T.length<C;)T=A+T;return T}a.DomRendererRowFactory=k=l([u(1,m.ICharacterJoinerService),u(2,g.IOptionsService),u(3,m.ICoreBrowserService),u(4,g.ICoreService),u(5,g.IDecorationService),u(6,m.IThemeService)],k)},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 d=c.createElement("span");d.style.fontStyle="italic";const h=c.createElement("span");h.style.fontWeight="bold",h.style.fontStyle="italic",this._measureElements=[l,u,d,h],this._container.appendChild(l),this._container.appendChild(u),this._container.appendChild(d),this._container.appendChild(h),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,d){c===this._font&&l===this._fontSize&&u===this._weight&&d===this._weightBold||(this._font=c,this._fontSize=l,this._weight=u,this._weightBold=d,this._container.style.fontFamily=this._font,this._container.style.fontSize=`${this._fontSize}px`,this._measureElements[0].style.fontWeight=`${u}`,this._measureElements[1].style.fontWeight=`${d}`,this._measureElements[2].style.fontWeight=`${u}`,this._measureElements[3].style.fontWeight=`${d}`,this.clear())}get(c,l,u){let d=0;if(!l&&!u&&c.length===1&&(d=c.charCodeAt(0))<256)return this._flat[d]!==-9999?this._flat[d]:this._flat[d]=this._measure(c,0);let h=c;l&&(h+="B"),u&&(h+="I");let p=this._holey.get(h);if(p===void 0){let g=0;l&&(g|=1),u&&(g|=2),p=this._measure(c,g),this._holey.set(h,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(m,y,_,b){var k,w=arguments.length,T=w<3?y:b===null?b=Object.getOwnPropertyDescriptor(y,_):b;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")T=Reflect.decorate(m,y,_,b);else for(var A=m.length-1;A>=0;A--)(k=m[A])&&(T=(w<3?k(T):w>3?k(y,_,T):k(y,_))||T);return w>3&&T&&Object.defineProperty(y,_,T),T},u=this&&this.__param||function(m,y){return function(_,b){y(_,b,m)}};Object.defineProperty(a,"__esModule",{value:!0}),a.CharSizeService=void 0;const d=c(2585),h=c(8460),p=c(844);let g=a.CharSizeService=class extends p.Disposable{get hasValidSize(){return this.width>0&&this.height>0}constructor(m,y,_){super(),this._optionsService=_,this.width=0,this.height=0,this._onCharSizeChange=this.register(new h.EventEmitter),this.onCharSizeChange=this._onCharSizeChange.event,this._measureStrategy=new v(m,y,this._optionsService),this.register(this._optionsService.onMultipleOptionChange(["fontFamily","fontSize"],()=>this.measure()))}measure(){const m=this._measureStrategy.measure();m.width===this.width&&m.height===this.height||(this.width=m.width,this.height=m.height,this._onCharSizeChange.fire())}};a.CharSizeService=g=l([u(2,d.IOptionsService)],g);class v{constructor(y,_,b){this._document=y,this._parentElement=_,this._optionsService=b,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,k){var w,T=arguments.length,A=T<3?_:k===null?k=Object.getOwnPropertyDescriptor(_,b):k;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")A=Reflect.decorate(y,_,b,k);else for(var C=y.length-1;C>=0;C--)(w=y[C])&&(A=(T<3?w(A):T>3?w(_,b,A):w(_,b))||A);return T>3&&A&&Object.defineProperty(_,b,A),A},u=this&&this.__param||function(y,_){return function(b,k){_(b,k,y)}};Object.defineProperty(a,"__esModule",{value:!0}),a.CharacterJoinerService=a.JoinedCellData=void 0;const d=c(3734),h=c(643),p=c(511),g=c(2585);class v extends d.AttributeData{constructor(_,b,k){super(),this.content=0,this.combinedData="",this.fg=_.fg,this.bg=_.bg,this.combinedData=b,this._width=k}isCombined(){return 2097152}getWidth(){return this._width}getChars(){return this.combinedData}getCode(){return 2097151}setFromCharData(_){throw new Error("not implemented")}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}}a.JoinedCellData=v;let m=a.CharacterJoinerService=class ML{constructor(_){this._bufferService=_,this._characterJoiners=[],this._nextCharacterJoinerId=0,this._workCell=new p.CellData}register(_){const b={id:this._nextCharacterJoinerId++,handler:_};return this._characterJoiners.push(b),b.id}deregister(_){for(let b=0;b<this._characterJoiners.length;b++)if(this._characterJoiners[b].id===_)return this._characterJoiners.splice(b,1),!0;return!1}getJoinedCharacters(_){if(this._characterJoiners.length===0)return[];const b=this._bufferService.buffer.lines.get(_);if(!b||b.length===0)return[];const k=[],w=b.translateToString(!0);let T=0,A=0,C=0,E=b.getFg(0),x=b.getBg(0);for(let D=0;D<b.getTrimmedLength();D++)if(b.loadCell(D,this._workCell),this._workCell.getWidth()!==0){if(this._workCell.fg!==E||this._workCell.bg!==x){if(D-T>1){const N=this._getJoinedRanges(w,C,A,b,T);for(let O=0;O<N.length;O++)k.push(N[O])}T=D,C=A,E=this._workCell.fg,x=this._workCell.bg}A+=this._workCell.getChars().length||h.WHITESPACE_CELL_CHAR.length}if(this._bufferService.cols-T>1){const D=this._getJoinedRanges(w,C,A,b,T);for(let N=0;N<D.length;N++)k.push(D[N])}return k}_getJoinedRanges(_,b,k,w,T){const A=_.substring(b,k);let C=[];try{C=this._characterJoiners[0].handler(A)}catch(E){console.error(E)}for(let E=1;E<this._characterJoiners.length;E++)try{const x=this._characterJoiners[E].handler(A);for(let D=0;D<x.length;D++)ML._mergeRanges(C,x[D])}catch(x){console.error(x)}return this._stringRangesToCellRanges(C,w,T),C}_stringRangesToCellRanges(_,b,k){let w=0,T=!1,A=0,C=_[w];if(C){for(let E=k;E<this._bufferService.cols;E++){const x=b.getWidth(E),D=b.getString(E).length||h.WHITESPACE_CELL_CHAR.length;if(x!==0){if(!T&&C[0]<=A&&(C[0]=E,T=!0),C[1]<=A){if(C[1]=E,C=_[++w],!C)break;C[0]<=A?(C[0]=E,T=!0):T=!1}A+=D}}C&&(C[1]=this._bufferService.cols)}}static _mergeRanges(_,b){let k=!1;for(let w=0;w<_.length;w++){const T=_[w];if(k){if(b[1]<=T[0])return _[w-1][1]=b[1],_;if(b[1]<=T[1])return _[w-1][1]=Math.max(b[1],T[1]),_.splice(w,1),_;_.splice(w,1),w--}else{if(b[1]<=T[0])return _.splice(w,0,b),_;if(b[1]<=T[1])return T[0]=Math.min(b[0],T[0]),_;b[0]<T[1]&&(T[0]=Math.min(b[0],T[0]),k=!0)}}return k?_[_.length-1][1]=b[1]:_.push(b),_}};a.CharacterJoinerService=m=l([u(0,g.IBufferService)],m)},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(g,v,m,y){var _,b=arguments.length,k=b<3?v:y===null?y=Object.getOwnPropertyDescriptor(v,m):y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")k=Reflect.decorate(g,v,m,y);else for(var w=g.length-1;w>=0;w--)(_=g[w])&&(k=(b<3?_(k):b>3?_(v,m,k):_(v,m))||k);return b>3&&k&&Object.defineProperty(v,m,k),k},u=this&&this.__param||function(g,v){return function(m,y){v(m,y,g)}};Object.defineProperty(a,"__esModule",{value:!0}),a.MouseService=void 0;const d=c(4725),h=c(9806);let p=a.MouseService=class{constructor(g,v){this._renderService=g,this._charSizeService=v}getCoords(g,v,m,y,_){return(0,h.getCoords)(window,g,v,m,y,this._charSizeService.hasValidSize,this._renderService.dimensions.css.cell.width,this._renderService.dimensions.css.cell.height,_)}getMouseReportCoords(g,v){const m=(0,h.getCoordsRelativeToElement)(window,g,v);if(this._charSizeService.hasValidSize)return m[0]=Math.min(Math.max(m[0],0),this._renderService.dimensions.css.canvas.width-1),m[1]=Math.min(Math.max(m[1],0),this._renderService.dimensions.css.canvas.height-1),{col:Math.floor(m[0]/this._renderService.dimensions.css.cell.width),row:Math.floor(m[1]/this._renderService.dimensions.css.cell.height),x:Math.floor(m[0]),y:Math.floor(m[1])}}};a.MouseService=p=l([u(0,d.IRenderService),u(1,d.ICharSizeService)],p)},3230:function(o,a,c){var l=this&&this.__decorate||function(k,w,T,A){var C,E=arguments.length,x=E<3?w:A===null?A=Object.getOwnPropertyDescriptor(w,T):A;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")x=Reflect.decorate(k,w,T,A);else for(var D=k.length-1;D>=0;D--)(C=k[D])&&(x=(E<3?C(x):E>3?C(w,T,x):C(w,T))||x);return E>3&&x&&Object.defineProperty(w,T,x),x},u=this&&this.__param||function(k,w){return function(T,A){w(T,A,k)}};Object.defineProperty(a,"__esModule",{value:!0}),a.RenderService=void 0;const d=c(3656),h=c(6193),p=c(5596),g=c(4725),v=c(8460),m=c(844),y=c(7226),_=c(2585);let b=a.RenderService=class extends m.Disposable{get dimensions(){return this._renderer.value.dimensions}constructor(k,w,T,A,C,E,x,D){if(super(),this._rowCount=k,this._charSizeService=A,this._renderer=this.register(new m.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 h.RenderDebouncer(x.window,(N,O)=>this._renderRows(N,O)),this.register(this._renderDebouncer),this._screenDprMonitor=new p.ScreenDprMonitor(x.window),this._screenDprMonitor.setListener(()=>this.handleDevicePixelRatioChange()),this.register(this._screenDprMonitor),this.register(E.onResize(()=>this._fullRefresh())),this.register(E.buffers.onBufferActivate(()=>{var N;return(N=this._renderer.value)===null||N===void 0?void 0:N.clear()})),this.register(T.onOptionChange(()=>this._handleOptionsChanged())),this.register(this._charSizeService.onCharSizeChange(()=>this.handleCharSizeChanged())),this.register(C.onDecorationRegistered(()=>this._fullRefresh())),this.register(C.onDecorationRemoved(()=>this._fullRefresh())),this.register(T.onMultipleOptionChange(["customGlyphs","drawBoldTextInBrightColors","letterSpacing","lineHeight","fontFamily","fontSize","fontWeight","fontWeightBold","minimumContrastRatio"],()=>{this.clear(),this.handleResize(E.cols,E.rows),this._fullRefresh()})),this.register(T.onMultipleOptionChange(["cursorBlink","cursorStyle"],()=>this.refreshRows(E.buffer.y,E.buffer.y,!0))),this.register((0,d.addDisposableDomListener)(x.window,"resize",()=>this.handleDevicePixelRatioChange())),this.register(D.onChangeColors(()=>this._fullRefresh())),"IntersectionObserver"in x.window){const N=new x.window.IntersectionObserver(O=>this._handleIntersectionChange(O[O.length-1]),{threshold:0});N.observe(w),this.register({dispose:()=>N.disconnect()})}}_handleIntersectionChange(k){this._isPaused=k.isIntersecting===void 0?k.intersectionRatio===0:!k.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(k,w,T=!1){this._isPaused?this._needsFullRefresh=!0:(T||(this._isNextRenderRedrawOnly=!1),this._renderDebouncer.refresh(k,w,this._rowCount))}_renderRows(k,w){this._renderer.value&&(k=Math.min(k,this._rowCount-1),w=Math.min(w,this._rowCount-1),this._renderer.value.renderRows(k,w),this._needsSelectionRefresh&&(this._renderer.value.handleSelectionChanged(this._selectionState.start,this._selectionState.end,this._selectionState.columnSelectMode),this._needsSelectionRefresh=!1),this._isNextRenderRedrawOnly||this._onRenderedViewportChange.fire({start:k,end:w}),this._onRender.fire({start:k,end:w}),this._isNextRenderRedrawOnly=!0)}resize(k,w){this._rowCount=w,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(k){this._renderer.value=k,this._renderer.value.onRequestRedraw(w=>this.refreshRows(w.start,w.end,!0)),this._needsSelectionRefresh=!0,this._fullRefresh()}addRefreshCallback(k){return this._renderDebouncer.addRefreshCallback(k)}_fullRefresh(){this._isPaused?this._needsFullRefresh=!0:this.refreshRows(0,this._rowCount-1)}clearTextureAtlas(){var k,w;this._renderer.value&&((w=(k=this._renderer.value).clearTextureAtlas)===null||w===void 0||w.call(k),this._fullRefresh())}handleDevicePixelRatioChange(){this._charSizeService.measure(),this._renderer.value&&(this._renderer.value.handleDevicePixelRatioChange(),this.refreshRows(0,this._rowCount-1))}handleResize(k,w){this._renderer.value&&(this._isPaused?this._pausedResizeTask.set(()=>this._renderer.value.handleResize(k,w)):this._renderer.value.handleResize(k,w),this._fullRefresh())}handleCharSizeChanged(){var k;(k=this._renderer.value)===null||k===void 0||k.handleCharSizeChanged()}handleBlur(){var k;(k=this._renderer.value)===null||k===void 0||k.handleBlur()}handleFocus(){var k;(k=this._renderer.value)===null||k===void 0||k.handleFocus()}handleSelectionChanged(k,w,T){var A;this._selectionState.start=k,this._selectionState.end=w,this._selectionState.columnSelectMode=T,(A=this._renderer.value)===null||A===void 0||A.handleSelectionChanged(k,w,T)}handleCursorMove(){var k;(k=this._renderer.value)===null||k===void 0||k.handleCursorMove()}clear(){var k;(k=this._renderer.value)===null||k===void 0||k.clear()}};a.RenderService=b=l([u(2,_.IOptionsService),u(3,g.ICharSizeService),u(4,_.IDecorationService),u(5,_.IBufferService),u(6,g.ICoreBrowserService),u(7,g.IThemeService)],b)},9312:function(o,a,c){var l=this&&this.__decorate||function(C,E,x,D){var N,O=arguments.length,G=O<3?E:D===null?D=Object.getOwnPropertyDescriptor(E,x):D;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")G=Reflect.decorate(C,E,x,D);else for(var Z=C.length-1;Z>=0;Z--)(N=C[Z])&&(G=(O<3?N(G):O>3?N(E,x,G):N(E,x))||G);return O>3&&G&&Object.defineProperty(E,x,G),G},u=this&&this.__param||function(C,E){return function(x,D){E(x,D,C)}};Object.defineProperty(a,"__esModule",{value:!0}),a.SelectionService=void 0;const d=c(9806),h=c(9504),p=c(456),g=c(4725),v=c(8460),m=c(844),y=c(6114),_=c(4841),b=c(511),k=c(2585),w=" ",T=new RegExp(w,"g");let A=a.SelectionService=class extends m.Disposable{constructor(C,E,x,D,N,O,G,Z,q){super(),this._element=C,this._screenElement=E,this._linkifier=x,this._bufferService=D,this._coreService=N,this._mouseService=O,this._optionsService=G,this._renderService=Z,this._coreBrowserService=q,this._dragScrollAmount=0,this._enabled=!0,this._workCell=new b.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,m.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 C=this._model.finalSelectionStart,E=this._model.finalSelectionEnd;return!(!C||!E||C[0]===E[0]&&C[1]===E[1])}get selectionText(){const C=this._model.finalSelectionStart,E=this._model.finalSelectionEnd;if(!C||!E)return"";const x=this._bufferService.buffer,D=[];if(this._activeSelectionMode===3){if(C[0]===E[0])return"";const N=C[0]<E[0]?C[0]:E[0],O=C[0]<E[0]?E[0]:C[0];for(let G=C[1];G<=E[1];G++){const Z=x.translateBufferLineToString(G,!0,N,O);D.push(Z)}}else{const N=C[1]===E[1]?E[0]:void 0;D.push(x.translateBufferLineToString(C[1],!0,C[0],N));for(let O=C[1]+1;O<=E[1]-1;O++){const G=x.lines.get(O),Z=x.translateBufferLineToString(O,!0);G!=null&&G.isWrapped?D[D.length-1]+=Z:D.push(Z)}if(C[1]!==E[1]){const O=x.lines.get(E[1]),G=x.translateBufferLineToString(E[1],!0,0,E[0]);O&&O.isWrapped?D[D.length-1]+=G:D.push(G)}}return D.map(N=>N.replace(T," ")).join(y.isWindows?`\r
|
||
`:`
|
||
`)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(C){this._refreshAnimationFrame||(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh())),y.isLinux&&C&&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(C){const E=this._getMouseBufferCoords(C),x=this._model.finalSelectionStart,D=this._model.finalSelectionEnd;return!!(x&&D&&E)&&this._areCoordsInSelection(E,x,D)}isCellInSelection(C,E){const x=this._model.finalSelectionStart,D=this._model.finalSelectionEnd;return!(!x||!D)&&this._areCoordsInSelection([C,E],x,D)}_areCoordsInSelection(C,E,x){return C[1]>E[1]&&C[1]<x[1]||E[1]===x[1]&&C[1]===E[1]&&C[0]>=E[0]&&C[0]<x[0]||E[1]<x[1]&&C[1]===x[1]&&C[0]<x[0]||E[1]<x[1]&&C[1]===E[1]&&C[0]>=E[0]}_selectWordAtCursor(C,E){var x,D;const N=(D=(x=this._linkifier.currentLink)===null||x===void 0?void 0:x.link)===null||D===void 0?void 0:D.range;if(N)return this._model.selectionStart=[N.start.x-1,N.start.y-1],this._model.selectionStartLength=(0,_.getRangeLength)(N,this._bufferService.cols),this._model.selectionEnd=void 0,!0;const O=this._getMouseBufferCoords(C);return!!O&&(this._selectWordAt(O,E),this._model.selectionEnd=void 0,!0)}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(C,E){this._model.clearSelection(),C=Math.max(C,0),E=Math.min(E,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,C],this._model.selectionEnd=[this._bufferService.cols,E],this.refresh(),this._onSelectionChange.fire()}_handleTrim(C){this._model.handleTrim(C)&&this.refresh()}_getMouseBufferCoords(C){const E=this._mouseService.getCoords(C,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(E)return E[0]--,E[1]--,E[1]+=this._bufferService.buffer.ydisp,E}_getMouseEventScrollAmount(C){let E=(0,d.getCoordsRelativeToElement)(this._coreBrowserService.window,C,this._screenElement)[1];const x=this._renderService.dimensions.css.canvas.height;return E>=0&&E<=x?0:(E>x&&(E-=x),E=Math.min(Math.max(E,-50),50),E/=50,E/Math.abs(E)+Math.round(14*E))}shouldForceSelection(C){return y.isMac?C.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:C.shiftKey}handleMouseDown(C){if(this._mouseDownTimeStamp=C.timeStamp,(C.button!==2||!this.hasSelection)&&C.button===0){if(!this._enabled){if(!this.shouldForceSelection(C))return;C.stopPropagation()}C.preventDefault(),this._dragScrollAmount=0,this._enabled&&C.shiftKey?this._handleIncrementalClick(C):C.detail===1?this._handleSingleClick(C):C.detail===2?this._handleDoubleClick(C):C.detail===3&&this._handleTripleClick(C),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(C){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(C))}_handleSingleClick(C){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(C)?3:0,this._model.selectionStart=this._getMouseBufferCoords(C),!this._model.selectionStart)return;this._model.selectionEnd=void 0;const E=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);E&&E.length!==this._model.selectionStart[0]&&E.hasWidth(this._model.selectionStart[0])===0&&this._model.selectionStart[0]++}_handleDoubleClick(C){this._selectWordAtCursor(C,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(C){const E=this._getMouseBufferCoords(C);E&&(this._activeSelectionMode=2,this._selectLineAt(E[1]))}shouldColumnSelect(C){return C.altKey&&!(y.isMac&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(C){if(C.stopImmediatePropagation(),!this._model.selectionStart)return;const E=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(C),!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(C),this._activeSelectionMode!==3&&(this._dragScrollAmount>0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));const x=this._bufferService.buffer;if(this._model.selectionEnd[1]<x.lines.length){const D=x.lines.get(this._model.selectionEnd[1]);D&&D.hasWidth(this._model.selectionEnd[0])===0&&this._model.selectionEnd[0]++}E&&E[0]===this._model.selectionEnd[0]&&E[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 C=this._bufferService.buffer;this._dragScrollAmount>0?(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=this._bufferService.cols),this._model.selectionEnd[1]=Math.min(C.ydisp+this._bufferService.rows,C.lines.length-1)):(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=0),this._model.selectionEnd[1]=C.ydisp),this.refresh()}}_handleMouseUp(C){const E=C.timeStamp-this._mouseDownTimeStamp;if(this._removeMouseDownListeners(),this.selectionText.length<=1&&E<500&&C.altKey&&this._optionsService.rawOptions.altClickMovesCursor){if(this._bufferService.buffer.ybase===this._bufferService.buffer.ydisp){const x=this._mouseService.getCoords(C,this._element,this._bufferService.cols,this._bufferService.rows,!1);if(x&&x[0]!==void 0&&x[1]!==void 0){const D=(0,h.moveToCellSequence)(x[0]-1,x[1]-1,this._bufferService,this._coreService.decPrivateModes.applicationCursorKeys);this._coreService.triggerDataEvent(D,!0)}}}else this._fireEventIfSelectionChanged()}_fireEventIfSelectionChanged(){const C=this._model.finalSelectionStart,E=this._model.finalSelectionEnd,x=!(!C||!E||C[0]===E[0]&&C[1]===E[1]);x?C&&E&&(this._oldSelectionStart&&this._oldSelectionEnd&&C[0]===this._oldSelectionStart[0]&&C[1]===this._oldSelectionStart[1]&&E[0]===this._oldSelectionEnd[0]&&E[1]===this._oldSelectionEnd[1]||this._fireOnSelectionChange(C,E,x)):this._oldHasSelection&&this._fireOnSelectionChange(C,E,x)}_fireOnSelectionChange(C,E,x){this._oldSelectionStart=C,this._oldSelectionEnd=E,this._oldHasSelection=x,this._onSelectionChange.fire()}_handleBufferActivate(C){this.clearSelection(),this._trimListener.dispose(),this._trimListener=C.activeBuffer.lines.onTrim(E=>this._handleTrim(E))}_convertViewportColToCharacterIndex(C,E){let x=E;for(let D=0;E>=D;D++){const N=C.loadCell(D,this._workCell).getChars().length;this._workCell.getWidth()===0?x--:N>1&&E!==D&&(x+=N-1)}return x}setSelection(C,E,x){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[C,E],this._model.selectionStartLength=x,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(C){this._isClickInSelection(C)||(this._selectWordAtCursor(C,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(C,E,x=!0,D=!0){if(C[0]>=this._bufferService.cols)return;const N=this._bufferService.buffer,O=N.lines.get(C[1]);if(!O)return;const G=N.translateBufferLineToString(C[1],!1);let Z=this._convertViewportColToCharacterIndex(O,C[0]),q=Z;const V=C[0]-Z;let I=0,$=0,L=0,K=0;if(G.charAt(Z)===" "){for(;Z>0&&G.charAt(Z-1)===" ";)Z--;for(;q<G.length&&G.charAt(q+1)===" ";)q++}else{let ve=C[0],le=C[0];O.getWidth(ve)===0&&(I++,ve--),O.getWidth(le)===2&&($++,le++);const ue=O.getString(le).length;for(ue>1&&(K+=ue-1,q+=ue-1);ve>0&&Z>0&&!this._isCharWordSeparator(O.loadCell(ve-1,this._workCell));){O.loadCell(ve-1,this._workCell);const P=this._workCell.getChars().length;this._workCell.getWidth()===0?(I++,ve--):P>1&&(L+=P-1,Z-=P-1),Z--,ve--}for(;le<O.length&&q+1<G.length&&!this._isCharWordSeparator(O.loadCell(le+1,this._workCell));){O.loadCell(le+1,this._workCell);const P=this._workCell.getChars().length;this._workCell.getWidth()===2?($++,le++):P>1&&(K+=P-1,q+=P-1),q++,le++}}q++;let se=Z+V-I+L,oe=Math.min(this._bufferService.cols,q-Z+I+$-L-K);if(E||G.slice(Z,q).trim()!==""){if(x&&se===0&&O.getCodePoint(0)!==32){const ve=N.lines.get(C[1]-1);if(ve&&O.isWrapped&&ve.getCodePoint(this._bufferService.cols-1)!==32){const le=this._getWordAt([this._bufferService.cols-1,C[1]-1],!1,!0,!1);if(le){const ue=this._bufferService.cols-le.start;se-=ue,oe+=ue}}}if(D&&se+oe===this._bufferService.cols&&O.getCodePoint(this._bufferService.cols-1)!==32){const ve=N.lines.get(C[1]+1);if(ve!=null&&ve.isWrapped&&ve.getCodePoint(0)!==32){const le=this._getWordAt([0,C[1]+1],!1,!1,!0);le&&(oe+=le.length)}}return{start:se,length:oe}}}_selectWordAt(C,E){const x=this._getWordAt(C,E);if(x){for(;x.start<0;)x.start+=this._bufferService.cols,C[1]--;this._model.selectionStart=[x.start,C[1]],this._model.selectionStartLength=x.length}}_selectToWordAt(C){const E=this._getWordAt(C,!0);if(E){let x=C[1];for(;E.start<0;)E.start+=this._bufferService.cols,x--;if(!this._model.areSelectionValuesReversed())for(;E.start+E.length>this._bufferService.cols;)E.length-=this._bufferService.cols,x++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?E.start:E.start+E.length,x]}}_isCharWordSeparator(C){return C.getWidth()!==0&&this._optionsService.rawOptions.wordSeparator.indexOf(C.getChars())>=0}_selectLineAt(C){const E=this._bufferService.buffer.getWrappedRangeForLine(C),x={start:{x:0,y:E.first},end:{x:this._bufferService.cols-1,y:E.last}};this._model.selectionStart=[0,E.first],this._model.selectionEnd=void 0,this._model.selectionStartLength=(0,_.getRangeLength)(x,this._bufferService.cols)}};a.SelectionService=A=l([u(3,k.IBufferService),u(4,k.ICoreService),u(5,g.IMouseService),u(6,k.IOptionsService),u(7,g.IRenderService),u(8,g.ICoreBrowserService)],A)},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(A,C,E,x){var D,N=arguments.length,O=N<3?C:x===null?x=Object.getOwnPropertyDescriptor(C,E):x;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")O=Reflect.decorate(A,C,E,x);else for(var G=A.length-1;G>=0;G--)(D=A[G])&&(O=(N<3?D(O):N>3?D(C,E,O):D(C,E))||O);return N>3&&O&&Object.defineProperty(C,E,O),O},u=this&&this.__param||function(A,C){return function(E,x){C(E,x,A)}};Object.defineProperty(a,"__esModule",{value:!0}),a.ThemeService=a.DEFAULT_ANSI_COLORS=void 0;const d=c(7239),h=c(8055),p=c(8460),g=c(844),v=c(2585),m=h.css.toColor("#ffffff"),y=h.css.toColor("#000000"),_=h.css.toColor("#ffffff"),b=h.css.toColor("#000000"),k={css:"rgba(255, 255, 255, 0.3)",rgba:4294967117};a.DEFAULT_ANSI_COLORS=Object.freeze((()=>{const A=[h.css.toColor("#2e3436"),h.css.toColor("#cc0000"),h.css.toColor("#4e9a06"),h.css.toColor("#c4a000"),h.css.toColor("#3465a4"),h.css.toColor("#75507b"),h.css.toColor("#06989a"),h.css.toColor("#d3d7cf"),h.css.toColor("#555753"),h.css.toColor("#ef2929"),h.css.toColor("#8ae234"),h.css.toColor("#fce94f"),h.css.toColor("#729fcf"),h.css.toColor("#ad7fa8"),h.css.toColor("#34e2e2"),h.css.toColor("#eeeeec")],C=[0,95,135,175,215,255];for(let E=0;E<216;E++){const x=C[E/36%6|0],D=C[E/6%6|0],N=C[E%6];A.push({css:h.channels.toCss(x,D,N),rgba:h.channels.toRgba(x,D,N)})}for(let E=0;E<24;E++){const x=8+10*E;A.push({css:h.channels.toCss(x,x,x),rgba:h.channels.toRgba(x,x,x)})}return A})());let w=a.ThemeService=class extends g.Disposable{get colors(){return this._colors}constructor(A){super(),this._optionsService=A,this._contrastCache=new d.ColorContrastCache,this._halfContrastCache=new d.ColorContrastCache,this._onChangeColors=this.register(new p.EventEmitter),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:m,background:y,cursor:_,cursorAccent:b,selectionForeground:void 0,selectionBackgroundTransparent:k,selectionBackgroundOpaque:h.color.blend(y,k),selectionInactiveBackgroundTransparent:k,selectionInactiveBackgroundOpaque:h.color.blend(y,k),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(A={}){const C=this._colors;if(C.foreground=T(A.foreground,m),C.background=T(A.background,y),C.cursor=T(A.cursor,_),C.cursorAccent=T(A.cursorAccent,b),C.selectionBackgroundTransparent=T(A.selectionBackground,k),C.selectionBackgroundOpaque=h.color.blend(C.background,C.selectionBackgroundTransparent),C.selectionInactiveBackgroundTransparent=T(A.selectionInactiveBackground,C.selectionBackgroundTransparent),C.selectionInactiveBackgroundOpaque=h.color.blend(C.background,C.selectionInactiveBackgroundTransparent),C.selectionForeground=A.selectionForeground?T(A.selectionForeground,h.NULL_COLOR):void 0,C.selectionForeground===h.NULL_COLOR&&(C.selectionForeground=void 0),h.color.isOpaque(C.selectionBackgroundTransparent)&&(C.selectionBackgroundTransparent=h.color.opacity(C.selectionBackgroundTransparent,.3)),h.color.isOpaque(C.selectionInactiveBackgroundTransparent)&&(C.selectionInactiveBackgroundTransparent=h.color.opacity(C.selectionInactiveBackgroundTransparent,.3)),C.ansi=a.DEFAULT_ANSI_COLORS.slice(),C.ansi[0]=T(A.black,a.DEFAULT_ANSI_COLORS[0]),C.ansi[1]=T(A.red,a.DEFAULT_ANSI_COLORS[1]),C.ansi[2]=T(A.green,a.DEFAULT_ANSI_COLORS[2]),C.ansi[3]=T(A.yellow,a.DEFAULT_ANSI_COLORS[3]),C.ansi[4]=T(A.blue,a.DEFAULT_ANSI_COLORS[4]),C.ansi[5]=T(A.magenta,a.DEFAULT_ANSI_COLORS[5]),C.ansi[6]=T(A.cyan,a.DEFAULT_ANSI_COLORS[6]),C.ansi[7]=T(A.white,a.DEFAULT_ANSI_COLORS[7]),C.ansi[8]=T(A.brightBlack,a.DEFAULT_ANSI_COLORS[8]),C.ansi[9]=T(A.brightRed,a.DEFAULT_ANSI_COLORS[9]),C.ansi[10]=T(A.brightGreen,a.DEFAULT_ANSI_COLORS[10]),C.ansi[11]=T(A.brightYellow,a.DEFAULT_ANSI_COLORS[11]),C.ansi[12]=T(A.brightBlue,a.DEFAULT_ANSI_COLORS[12]),C.ansi[13]=T(A.brightMagenta,a.DEFAULT_ANSI_COLORS[13]),C.ansi[14]=T(A.brightCyan,a.DEFAULT_ANSI_COLORS[14]),C.ansi[15]=T(A.brightWhite,a.DEFAULT_ANSI_COLORS[15]),A.extendedAnsi){const E=Math.min(C.ansi.length-16,A.extendedAnsi.length);for(let x=0;x<E;x++)C.ansi[x+16]=T(A.extendedAnsi[x],a.DEFAULT_ANSI_COLORS[x+16])}this._contrastCache.clear(),this._halfContrastCache.clear(),this._updateRestoreColors(),this._onChangeColors.fire(this.colors)}restoreColor(A){this._restoreColor(A),this._onChangeColors.fire(this.colors)}_restoreColor(A){if(A!==void 0)switch(A){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[A]=this._restoreColors.ansi[A]}else for(let C=0;C<this._restoreColors.ansi.length;++C)this._colors.ansi[C]=this._restoreColors.ansi[C]}modifyColors(A){A(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 T(A,C){if(A!==void 0)try{return h.css.toColor(A)}catch{}return C}a.ThemeService=w=l([u(0,v.IOptionsService)],w)},6349:(o,a,c)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.CircularList=void 0;const l=c(8460),u=c(844);class d 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 g=new Array(p);for(let v=0;v<Math.min(p,this.length);v++)g[v]=this._array[this._getCyclicIndex(v)];this._array=g,this._maxLength=p,this._startIndex=0}get length(){return this._length}set length(p){if(p>this._length)for(let g=this._length;g<p;g++)this._array[g]=void 0;this._length=p}get(p){return this._array[this._getCyclicIndex(p)]}set(p,g){this._array[this._getCyclicIndex(p)]=g}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,g,...v){if(g){for(let m=p;m<this._length-g;m++)this._array[this._getCyclicIndex(m)]=this._array[this._getCyclicIndex(m+g)];this._length-=g,this.onDeleteEmitter.fire({index:p,amount:g})}for(let m=this._length-1;m>=p;m--)this._array[this._getCyclicIndex(m+v.length)]=this._array[this._getCyclicIndex(m)];for(let m=0;m<v.length;m++)this._array[this._getCyclicIndex(p+m)]=v[m];if(v.length&&this.onInsertEmitter.fire({index:p,amount:v.length}),this._length+v.length>this._maxLength){const m=this._length+v.length-this._maxLength;this._startIndex+=m,this._length=this._maxLength,this.onTrimEmitter.fire(m)}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,g,v){if(!(g<=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=g-1;y>=0;y--)this.set(p+y+v,this.get(p+y));const m=p+g+v-this._length;if(m>0)for(this._length+=m;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let m=0;m<g;m++)this.set(p+m+v,this.get(p+m))}}_getCyclicIndex(p){return(this._startIndex+p)%this._maxLength}}a.CircularList=d},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 d=Array.isArray(l)?[]:{};for(const h in l)d[h]=u<=1?l[h]:l[h]&&c(l[h],u-1);return d}},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,d=0,h=0,p=0;var g,v,m,y,_;function b(w){const T=w.toString(16);return T.length<2?"0"+T:T}function k(w,T){return w<T?(T+.05)/(w+.05):(w+.05)/(T+.05)}a.NULL_COLOR={css:"#00000000",rgba:0},function(w){w.toCss=function(T,A,C,E){return E!==void 0?`#${b(T)}${b(A)}${b(C)}${b(E)}`:`#${b(T)}${b(A)}${b(C)}`},w.toRgba=function(T,A,C,E=255){return(T<<24|A<<16|C<<8|E)>>>0}}(g||(a.channels=g={})),function(w){function T(A,C){return p=Math.round(255*C),[u,d,h]=_.toChannels(A.rgba),{css:g.toCss(u,d,h,p),rgba:g.toRgba(u,d,h,p)}}w.blend=function(A,C){if(p=(255&C.rgba)/255,p===1)return{css:C.css,rgba:C.rgba};const E=C.rgba>>24&255,x=C.rgba>>16&255,D=C.rgba>>8&255,N=A.rgba>>24&255,O=A.rgba>>16&255,G=A.rgba>>8&255;return u=N+Math.round((E-N)*p),d=O+Math.round((x-O)*p),h=G+Math.round((D-G)*p),{css:g.toCss(u,d,h),rgba:g.toRgba(u,d,h)}},w.isOpaque=function(A){return(255&A.rgba)==255},w.ensureContrastRatio=function(A,C,E){const x=_.ensureContrastRatio(A.rgba,C.rgba,E);if(x)return _.toColor(x>>24&255,x>>16&255,x>>8&255)},w.opaque=function(A){const C=(255|A.rgba)>>>0;return[u,d,h]=_.toChannels(C),{css:g.toCss(u,d,h),rgba:C}},w.opacity=T,w.multiplyOpacity=function(A,C){return p=255&A.rgba,T(A,p*C/255)},w.toColorRGB=function(A){return[A.rgba>>24&255,A.rgba>>16&255,A.rgba>>8&255]}}(v||(a.color=v={})),function(w){let T,A;if(!l.isNode){const C=document.createElement("canvas");C.width=1,C.height=1;const E=C.getContext("2d",{willReadFrequently:!0});E&&(T=E,T.globalCompositeOperation="copy",A=T.createLinearGradient(0,0,1,1))}w.toColor=function(C){if(C.match(/#[\da-f]{3,8}/i))switch(C.length){case 4:return u=parseInt(C.slice(1,2).repeat(2),16),d=parseInt(C.slice(2,3).repeat(2),16),h=parseInt(C.slice(3,4).repeat(2),16),_.toColor(u,d,h);case 5:return u=parseInt(C.slice(1,2).repeat(2),16),d=parseInt(C.slice(2,3).repeat(2),16),h=parseInt(C.slice(3,4).repeat(2),16),p=parseInt(C.slice(4,5).repeat(2),16),_.toColor(u,d,h,p);case 7:return{css:C,rgba:(parseInt(C.slice(1),16)<<8|255)>>>0};case 9:return{css:C,rgba:parseInt(C.slice(1),16)>>>0}}const E=C.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(E)return u=parseInt(E[1]),d=parseInt(E[2]),h=parseInt(E[3]),p=Math.round(255*(E[5]===void 0?1:parseFloat(E[5]))),_.toColor(u,d,h,p);if(!T||!A)throw new Error("css.toColor: Unsupported css format");if(T.fillStyle=A,T.fillStyle=C,typeof T.fillStyle!="string")throw new Error("css.toColor: Unsupported css format");if(T.fillRect(0,0,1,1),[u,d,h,p]=T.getImageData(0,0,1,1).data,p!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:g.toRgba(u,d,h,p),css:C}}}(m||(a.css=m={})),function(w){function T(A,C,E){const x=A/255,D=C/255,N=E/255;return .2126*(x<=.03928?x/12.92:Math.pow((x+.055)/1.055,2.4))+.7152*(D<=.03928?D/12.92:Math.pow((D+.055)/1.055,2.4))+.0722*(N<=.03928?N/12.92:Math.pow((N+.055)/1.055,2.4))}w.relativeLuminance=function(A){return T(A>>16&255,A>>8&255,255&A)},w.relativeLuminance2=T}(y||(a.rgb=y={})),function(w){function T(C,E,x){const D=C>>24&255,N=C>>16&255,O=C>>8&255;let G=E>>24&255,Z=E>>16&255,q=E>>8&255,V=k(y.relativeLuminance2(G,Z,q),y.relativeLuminance2(D,N,O));for(;V<x&&(G>0||Z>0||q>0);)G-=Math.max(0,Math.ceil(.1*G)),Z-=Math.max(0,Math.ceil(.1*Z)),q-=Math.max(0,Math.ceil(.1*q)),V=k(y.relativeLuminance2(G,Z,q),y.relativeLuminance2(D,N,O));return(G<<24|Z<<16|q<<8|255)>>>0}function A(C,E,x){const D=C>>24&255,N=C>>16&255,O=C>>8&255;let G=E>>24&255,Z=E>>16&255,q=E>>8&255,V=k(y.relativeLuminance2(G,Z,q),y.relativeLuminance2(D,N,O));for(;V<x&&(G<255||Z<255||q<255);)G=Math.min(255,G+Math.ceil(.1*(255-G))),Z=Math.min(255,Z+Math.ceil(.1*(255-Z))),q=Math.min(255,q+Math.ceil(.1*(255-q))),V=k(y.relativeLuminance2(G,Z,q),y.relativeLuminance2(D,N,O));return(G<<24|Z<<16|q<<8|255)>>>0}w.ensureContrastRatio=function(C,E,x){const D=y.relativeLuminance(C>>8),N=y.relativeLuminance(E>>8);if(k(D,N)<x){if(N<D){const Z=T(C,E,x),q=k(D,y.relativeLuminance(Z>>8));if(q<x){const V=A(C,E,x);return q>k(D,y.relativeLuminance(V>>8))?Z:V}return Z}const O=A(C,E,x),G=k(D,y.relativeLuminance(O>>8));if(G<x){const Z=T(C,E,x);return G>k(D,y.relativeLuminance(Z>>8))?O:Z}return O}},w.reduceLuminance=T,w.increaseLuminance=A,w.toChannels=function(C){return[C>>24&255,C>>16&255,C>>8&255,255&C]},w.toColor=function(C,E,x,D){return{css:g.toCss(C,E,x,D),rgba:g.toRgba(C,E,x,D)}}}(_||(a.rgba=_={})),a.toPaddedHex=b,a.contrastRatio=k},8969:(o,a,c)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.CoreTerminal=void 0;const l=c(844),u=c(2585),d=c(4348),h=c(7866),p=c(744),g=c(7302),v=c(6975),m=c(8460),y=c(1753),_=c(1480),b=c(7994),k=c(9282),w=c(5435),T=c(5981),A=c(2660);let C=!1;class E extends l.Disposable{get onScroll(){return this._onScrollApi||(this._onScrollApi=this.register(new m.EventEmitter),this._onScroll.event(D=>{var N;(N=this._onScrollApi)===null||N===void 0||N.fire(D.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(D){for(const N in D)this.optionsService.options[N]=D[N]}constructor(D){super(),this._windowsWrappingHeuristics=this.register(new l.MutableDisposable),this._onBinary=this.register(new m.EventEmitter),this.onBinary=this._onBinary.event,this._onData=this.register(new m.EventEmitter),this.onData=this._onData.event,this._onLineFeed=this.register(new m.EventEmitter),this.onLineFeed=this._onLineFeed.event,this._onResize=this.register(new m.EventEmitter),this.onResize=this._onResize.event,this._onWriteParsed=this.register(new m.EventEmitter),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this.register(new m.EventEmitter),this._instantiationService=new d.InstantiationService,this.optionsService=this.register(new g.OptionsService(D)),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(h.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(_.UnicodeService)),this._instantiationService.setService(u.IUnicodeService,this.unicodeService),this._charsetService=this._instantiationService.createInstance(b.CharsetService),this._instantiationService.setService(u.ICharsetService,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(A.OscLinkService),this._instantiationService.setService(u.IOscLinkService,this._oscLinkService),this._inputHandler=this.register(new w.InputHandler(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this.register((0,m.forwardEvent)(this._inputHandler.onLineFeed,this._onLineFeed)),this.register(this._inputHandler),this.register((0,m.forwardEvent)(this._bufferService.onResize,this._onResize)),this.register((0,m.forwardEvent)(this.coreService.onData,this._onData)),this.register((0,m.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(N=>{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(N=>{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 T.WriteBuffer((N,O)=>this._inputHandler.parse(N,O))),this.register((0,m.forwardEvent)(this._writeBuffer.onWriteParsed,this._onWriteParsed))}write(D,N){this._writeBuffer.write(D,N)}writeSync(D,N){this._logService.logLevel<=u.LogLevelEnum.WARN&&!C&&(this._logService.warn("writeSync is unreliable and will be removed soon."),C=!0),this._writeBuffer.writeSync(D,N)}resize(D,N){isNaN(D)||isNaN(N)||(D=Math.max(D,p.MINIMUM_COLS),N=Math.max(N,p.MINIMUM_ROWS),this._bufferService.resize(D,N))}scroll(D,N=!1){this._bufferService.scroll(D,N)}scrollLines(D,N,O){this._bufferService.scrollLines(D,N,O)}scrollPages(D){this.scrollLines(D*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(D){const N=D-this._bufferService.buffer.ydisp;N!==0&&this.scrollLines(N)}registerEscHandler(D,N){return this._inputHandler.registerEscHandler(D,N)}registerDcsHandler(D,N){return this._inputHandler.registerDcsHandler(D,N)}registerCsiHandler(D,N){return this._inputHandler.registerCsiHandler(D,N)}registerOscHandler(D,N){return this._inputHandler.registerOscHandler(D,N)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let D=!1;const N=this.optionsService.rawOptions.windowsPty;N&&N.buildNumber!==void 0&&N.buildNumber!==void 0?D=N.backend==="conpty"&&N.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(D=!0),D?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){const D=[];D.push(this.onLineFeed(k.updateWindowsModeWrappedState.bind(null,this._bufferService))),D.push(this.registerCsiHandler({final:"H"},()=>((0,k.updateWindowsModeWrappedState)(this._bufferService),!1))),this._windowsWrappingHeuristics.value=(0,l.toDisposable)(()=>{for(const N of D)N.dispose()})}}}a.CoreTerminal=E},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 d=0;d<this._listeners.length;d++)u.push(this._listeners[d]);for(let d=0;d<u.length;d++)u[d].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,I,$,L){var K,se=arguments.length,oe=se<3?I:L===null?L=Object.getOwnPropertyDescriptor(I,$):L;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")oe=Reflect.decorate(V,I,$,L);else for(var ve=V.length-1;ve>=0;ve--)(K=V[ve])&&(oe=(se<3?K(oe):se>3?K(I,$,oe):K(I,$))||oe);return se>3&&oe&&Object.defineProperty(I,$,oe),oe},u=this&&this.__param||function(V,I){return function($,L){I($,L,V)}};Object.defineProperty(a,"__esModule",{value:!0}),a.InputHandler=a.WindowsOptionsReportType=void 0;const d=c(2584),h=c(7116),p=c(2015),g=c(844),v=c(482),m=c(8437),y=c(8460),_=c(643),b=c(511),k=c(3734),w=c(2585),T=c(6242),A=c(6351),C=c(5941),E={"(":0,")":1,"*":2,"+":3,"-":1,".":2},x=131072;function D(V,I){if(V>24)return I.setWinLines||!1;switch(V){case 1:return!!I.restoreWin;case 2:return!!I.minimizeWin;case 3:return!!I.setWinPosition;case 4:return!!I.setWinSizePixels;case 5:return!!I.raiseWin;case 6:return!!I.lowerWin;case 7:return!!I.refreshWin;case 8:return!!I.setWinSizeChars;case 9:return!!I.maximizeWin;case 10:return!!I.fullscreenWin;case 11:return!!I.getWinState;case 13:return!!I.getWinPosition;case 14:return!!I.getWinSizePixels;case 15:return!!I.getScreenSizePixels;case 16:return!!I.getCellSizePixels;case 18:return!!I.getWinSizeChars;case 19:return!!I.getScreenSizeChars;case 20:return!!I.getIconTitle;case 21:return!!I.getWinTitle;case 22:return!!I.pushTitle;case 23:return!!I.popTitle;case 24:return!!I.setWinLines}return!1}var N;(function(V){V[V.GET_WIN_SIZE_PIXELS=0]="GET_WIN_SIZE_PIXELS",V[V.GET_CELL_SIZE_PIXELS=1]="GET_CELL_SIZE_PIXELS"})(N||(a.WindowsOptionsReportType=N={}));let O=0;class G extends g.Disposable{getAttrData(){return this._curAttrData}constructor(I,$,L,K,se,oe,ve,le,ue=new p.EscapeSequenceParser){super(),this._bufferService=I,this._charsetService=$,this._coreService=L,this._logService=K,this._optionsService=se,this._oscLinkService=oe,this._coreMouseService=ve,this._unicodeService=le,this._parser=ue,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new v.StringToUtf32,this._utf8Decoder=new v.Utf8ToUtf32,this._workCell=new b.CellData,this._windowTitle="",this._iconName="",this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=m.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=m.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 Z(this._bufferService),this._activeBuffer=this._bufferService.buffer,this.register(this._bufferService.buffers.onBufferActivate(P=>this._activeBuffer=P.activeBuffer)),this._parser.setCsiHandlerFallback((P,X)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(P),params:X.toArray()})}),this._parser.setEscHandlerFallback(P=>{this._logService.debug("Unknown ESC code: ",{identifier:this._parser.identToString(P)})}),this._parser.setExecuteHandlerFallback(P=>{this._logService.debug("Unknown EXECUTE code: ",{code:P})}),this._parser.setOscHandlerFallback((P,X,J)=>{this._logService.debug("Unknown OSC code: ",{identifier:P,action:X,data:J})}),this._parser.setDcsHandlerFallback((P,X,J)=>{X==="HOOK"&&(J=J.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(P),action:X,payload:J})}),this._parser.setPrintHandler((P,X,J)=>this.print(P,X,J)),this._parser.registerCsiHandler({final:"@"},P=>this.insertChars(P)),this._parser.registerCsiHandler({intermediates:" ",final:"@"},P=>this.scrollLeft(P)),this._parser.registerCsiHandler({final:"A"},P=>this.cursorUp(P)),this._parser.registerCsiHandler({intermediates:" ",final:"A"},P=>this.scrollRight(P)),this._parser.registerCsiHandler({final:"B"},P=>this.cursorDown(P)),this._parser.registerCsiHandler({final:"C"},P=>this.cursorForward(P)),this._parser.registerCsiHandler({final:"D"},P=>this.cursorBackward(P)),this._parser.registerCsiHandler({final:"E"},P=>this.cursorNextLine(P)),this._parser.registerCsiHandler({final:"F"},P=>this.cursorPrecedingLine(P)),this._parser.registerCsiHandler({final:"G"},P=>this.cursorCharAbsolute(P)),this._parser.registerCsiHandler({final:"H"},P=>this.cursorPosition(P)),this._parser.registerCsiHandler({final:"I"},P=>this.cursorForwardTab(P)),this._parser.registerCsiHandler({final:"J"},P=>this.eraseInDisplay(P,!1)),this._parser.registerCsiHandler({prefix:"?",final:"J"},P=>this.eraseInDisplay(P,!0)),this._parser.registerCsiHandler({final:"K"},P=>this.eraseInLine(P,!1)),this._parser.registerCsiHandler({prefix:"?",final:"K"},P=>this.eraseInLine(P,!0)),this._parser.registerCsiHandler({final:"L"},P=>this.insertLines(P)),this._parser.registerCsiHandler({final:"M"},P=>this.deleteLines(P)),this._parser.registerCsiHandler({final:"P"},P=>this.deleteChars(P)),this._parser.registerCsiHandler({final:"S"},P=>this.scrollUp(P)),this._parser.registerCsiHandler({final:"T"},P=>this.scrollDown(P)),this._parser.registerCsiHandler({final:"X"},P=>this.eraseChars(P)),this._parser.registerCsiHandler({final:"Z"},P=>this.cursorBackwardTab(P)),this._parser.registerCsiHandler({final:"`"},P=>this.charPosAbsolute(P)),this._parser.registerCsiHandler({final:"a"},P=>this.hPositionRelative(P)),this._parser.registerCsiHandler({final:"b"},P=>this.repeatPrecedingCharacter(P)),this._parser.registerCsiHandler({final:"c"},P=>this.sendDeviceAttributesPrimary(P)),this._parser.registerCsiHandler({prefix:">",final:"c"},P=>this.sendDeviceAttributesSecondary(P)),this._parser.registerCsiHandler({final:"d"},P=>this.linePosAbsolute(P)),this._parser.registerCsiHandler({final:"e"},P=>this.vPositionRelative(P)),this._parser.registerCsiHandler({final:"f"},P=>this.hVPosition(P)),this._parser.registerCsiHandler({final:"g"},P=>this.tabClear(P)),this._parser.registerCsiHandler({final:"h"},P=>this.setMode(P)),this._parser.registerCsiHandler({prefix:"?",final:"h"},P=>this.setModePrivate(P)),this._parser.registerCsiHandler({final:"l"},P=>this.resetMode(P)),this._parser.registerCsiHandler({prefix:"?",final:"l"},P=>this.resetModePrivate(P)),this._parser.registerCsiHandler({final:"m"},P=>this.charAttributes(P)),this._parser.registerCsiHandler({final:"n"},P=>this.deviceStatus(P)),this._parser.registerCsiHandler({prefix:"?",final:"n"},P=>this.deviceStatusPrivate(P)),this._parser.registerCsiHandler({intermediates:"!",final:"p"},P=>this.softReset(P)),this._parser.registerCsiHandler({intermediates:" ",final:"q"},P=>this.setCursorStyle(P)),this._parser.registerCsiHandler({final:"r"},P=>this.setScrollRegion(P)),this._parser.registerCsiHandler({final:"s"},P=>this.saveCursor(P)),this._parser.registerCsiHandler({final:"t"},P=>this.windowOptions(P)),this._parser.registerCsiHandler({final:"u"},P=>this.restoreCursor(P)),this._parser.registerCsiHandler({intermediates:"'",final:"}"},P=>this.insertColumns(P)),this._parser.registerCsiHandler({intermediates:"'",final:"~"},P=>this.deleteColumns(P)),this._parser.registerCsiHandler({intermediates:'"',final:"q"},P=>this.selectProtected(P)),this._parser.registerCsiHandler({intermediates:"$",final:"p"},P=>this.requestMode(P,!0)),this._parser.registerCsiHandler({prefix:"?",intermediates:"$",final:"p"},P=>this.requestMode(P,!1)),this._parser.setExecuteHandler(d.C0.BEL,()=>this.bell()),this._parser.setExecuteHandler(d.C0.LF,()=>this.lineFeed()),this._parser.setExecuteHandler(d.C0.VT,()=>this.lineFeed()),this._parser.setExecuteHandler(d.C0.FF,()=>this.lineFeed()),this._parser.setExecuteHandler(d.C0.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler(d.C0.BS,()=>this.backspace()),this._parser.setExecuteHandler(d.C0.HT,()=>this.tab()),this._parser.setExecuteHandler(d.C0.SO,()=>this.shiftOut()),this._parser.setExecuteHandler(d.C0.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(d.C1.IND,()=>this.index()),this._parser.setExecuteHandler(d.C1.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(d.C1.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new T.OscHandler(P=>(this.setTitle(P),this.setIconName(P),!0))),this._parser.registerOscHandler(1,new T.OscHandler(P=>this.setIconName(P))),this._parser.registerOscHandler(2,new T.OscHandler(P=>this.setTitle(P))),this._parser.registerOscHandler(4,new T.OscHandler(P=>this.setOrReportIndexedColor(P))),this._parser.registerOscHandler(8,new T.OscHandler(P=>this.setHyperlink(P))),this._parser.registerOscHandler(10,new T.OscHandler(P=>this.setOrReportFgColor(P))),this._parser.registerOscHandler(11,new T.OscHandler(P=>this.setOrReportBgColor(P))),this._parser.registerOscHandler(12,new T.OscHandler(P=>this.setOrReportCursorColor(P))),this._parser.registerOscHandler(104,new T.OscHandler(P=>this.restoreIndexedColor(P))),this._parser.registerOscHandler(110,new T.OscHandler(P=>this.restoreFgColor(P))),this._parser.registerOscHandler(111,new T.OscHandler(P=>this.restoreBgColor(P))),this._parser.registerOscHandler(112,new T.OscHandler(P=>this.restoreCursorColor(P))),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 P in h.CHARSETS)this._parser.registerEscHandler({intermediates:"(",final:P},()=>this.selectCharset("("+P)),this._parser.registerEscHandler({intermediates:")",final:P},()=>this.selectCharset(")"+P)),this._parser.registerEscHandler({intermediates:"*",final:P},()=>this.selectCharset("*"+P)),this._parser.registerEscHandler({intermediates:"+",final:P},()=>this.selectCharset("+"+P)),this._parser.registerEscHandler({intermediates:"-",final:P},()=>this.selectCharset("-"+P)),this._parser.registerEscHandler({intermediates:".",final:P},()=>this.selectCharset("."+P)),this._parser.registerEscHandler({intermediates:"/",final:P},()=>this.selectCharset("/"+P));this._parser.registerEscHandler({intermediates:"#",final:"8"},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler(P=>(this._logService.error("Parsing error: ",P),P)),this._parser.registerDcsHandler({intermediates:"$",final:"q"},new A.DcsHandler((P,X)=>this.requestStatusString(P,X)))}_preserveStack(I,$,L,K){this._parseStack.paused=!0,this._parseStack.cursorStartX=I,this._parseStack.cursorStartY=$,this._parseStack.decodedLength=L,this._parseStack.position=K}_logSlowResolvingAsync(I){this._logService.logLevel<=w.LogLevelEnum.WARN&&Promise.race([I,new Promise(($,L)=>setTimeout(()=>L("#SLOW_TIMEOUT"),5e3))]).catch($=>{if($!=="#SLOW_TIMEOUT")throw $;console.warn("async parser handler taking longer than 5000 ms")})}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(I,$){let L,K=this._activeBuffer.x,se=this._activeBuffer.y,oe=0;const ve=this._parseStack.paused;if(ve){if(L=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,$))return this._logSlowResolvingAsync(L),L;K=this._parseStack.cursorStartX,se=this._parseStack.cursorStartY,this._parseStack.paused=!1,I.length>x&&(oe=this._parseStack.position+x)}if(this._logService.logLevel<=w.LogLevelEnum.DEBUG&&this._logService.debug("parsing data"+(typeof I=="string"?` "${I}"`:` "${Array.prototype.map.call(I,le=>String.fromCharCode(le)).join("")}"`),typeof I=="string"?I.split("").map(le=>le.charCodeAt(0)):I),this._parseBuffer.length<I.length&&this._parseBuffer.length<x&&(this._parseBuffer=new Uint32Array(Math.min(I.length,x))),ve||this._dirtyRowTracker.clearRange(),I.length>x)for(let le=oe;le<I.length;le+=x){const ue=le+x<I.length?le+x:I.length,P=typeof I=="string"?this._stringDecoder.decode(I.substring(le,ue),this._parseBuffer):this._utf8Decoder.decode(I.subarray(le,ue),this._parseBuffer);if(L=this._parser.parse(this._parseBuffer,P))return this._preserveStack(K,se,P,le),this._logSlowResolvingAsync(L),L}else if(!ve){const le=typeof I=="string"?this._stringDecoder.decode(I,this._parseBuffer):this._utf8Decoder.decode(I,this._parseBuffer);if(L=this._parser.parse(this._parseBuffer,le))return this._preserveStack(K,se,le,0),this._logSlowResolvingAsync(L),L}this._activeBuffer.x===K&&this._activeBuffer.y===se||this._onCursorMove.fire(),this._onRequestRefreshRows.fire(this._dirtyRowTracker.start,this._dirtyRowTracker.end)}print(I,$,L){let K,se;const oe=this._charsetService.charset,ve=this._optionsService.rawOptions.screenReaderMode,le=this._bufferService.cols,ue=this._coreService.decPrivateModes.wraparound,P=this._coreService.modes.insertMode,X=this._curAttrData;let J=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._activeBuffer.x&&L-$>0&&J.getWidth(this._activeBuffer.x-1)===2&&J.setCellFromCodePoint(this._activeBuffer.x-1,0,1,X.fg,X.bg,X.extended);for(let ne=$;ne<L;++ne){if(K=I[ne],se=this._unicodeService.wcwidth(K),K<127&&oe){const ce=oe[String.fromCharCode(K)];ce&&(K=ce.charCodeAt(0))}if(ve&&this._onA11yChar.fire((0,v.stringFromCodePoint)(K)),this._getCurrentLinkId()&&this._oscLinkService.addLineToLink(this._getCurrentLinkId(),this._activeBuffer.ybase+this._activeBuffer.y),se||!this._activeBuffer.x){if(this._activeBuffer.x+se-1>=le){if(ue){for(;this._activeBuffer.x<le;)J.setCellFromCodePoint(this._activeBuffer.x++,0,1,X.fg,X.bg,X.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),J=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y)}else if(this._activeBuffer.x=le-1,se===2)continue}if(P&&(J.insertCells(this._activeBuffer.x,se,this._activeBuffer.getNullCell(X),X),J.getWidth(le-1)===2&&J.setCellFromCodePoint(le-1,_.NULL_CELL_CODE,_.NULL_CELL_WIDTH,X.fg,X.bg,X.extended)),J.setCellFromCodePoint(this._activeBuffer.x++,K,se,X.fg,X.bg,X.extended),se>0)for(;--se;)J.setCellFromCodePoint(this._activeBuffer.x++,0,0,X.fg,X.bg,X.extended)}else J.getWidth(this._activeBuffer.x-1)?J.addCodepointToCell(this._activeBuffer.x-1,K):J.addCodepointToCell(this._activeBuffer.x-2,K)}L-$>0&&(J.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&&L-$>0&&J.getWidth(this._activeBuffer.x)===0&&!J.hasContent(this._activeBuffer.x)&&J.setCellFromCodePoint(this._activeBuffer.x,0,1,X.fg,X.bg,X.extended),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(I,$){return I.final!=="t"||I.prefix||I.intermediates?this._parser.registerCsiHandler(I,$):this._parser.registerCsiHandler(I,L=>!D(L.params[0],this._optionsService.rawOptions.windowOptions)||$(L))}registerDcsHandler(I,$){return this._parser.registerDcsHandler(I,new A.DcsHandler($))}registerEscHandler(I,$){return this._parser.registerEscHandler(I,$)}registerOscHandler(I,$){return this._parser.registerOscHandler(I,new T.OscHandler($))}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 I;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&&(!((I=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y))===null||I===void 0)&&I.isWrapped)){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;const $=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);$.hasWidth(this._activeBuffer.x)&&!$.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;const I=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-I),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(I=this._bufferService.cols-1){this._activeBuffer.x=Math.min(I,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(I,$){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=I,this._activeBuffer.y=this._activeBuffer.scrollTop+$):(this._activeBuffer.x=I,this._activeBuffer.y=$),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(I,$){this._restrictCursor(),this._setCursor(this._activeBuffer.x+I,this._activeBuffer.y+$)}cursorUp(I){const $=this._activeBuffer.y-this._activeBuffer.scrollTop;return $>=0?this._moveCursor(0,-Math.min($,I.params[0]||1)):this._moveCursor(0,-(I.params[0]||1)),!0}cursorDown(I){const $=this._activeBuffer.scrollBottom-this._activeBuffer.y;return $>=0?this._moveCursor(0,Math.min($,I.params[0]||1)):this._moveCursor(0,I.params[0]||1),!0}cursorForward(I){return this._moveCursor(I.params[0]||1,0),!0}cursorBackward(I){return this._moveCursor(-(I.params[0]||1),0),!0}cursorNextLine(I){return this.cursorDown(I),this._activeBuffer.x=0,!0}cursorPrecedingLine(I){return this.cursorUp(I),this._activeBuffer.x=0,!0}cursorCharAbsolute(I){return this._setCursor((I.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(I){return this._setCursor(I.length>=2?(I.params[1]||1)-1:0,(I.params[0]||1)-1),!0}charPosAbsolute(I){return this._setCursor((I.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(I){return this._moveCursor(I.params[0]||1,0),!0}linePosAbsolute(I){return this._setCursor(this._activeBuffer.x,(I.params[0]||1)-1),!0}vPositionRelative(I){return this._moveCursor(0,I.params[0]||1),!0}hVPosition(I){return this.cursorPosition(I),!0}tabClear(I){const $=I.params[0];return $===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:$===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(I){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let $=I.params[0]||1;for(;$--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(I){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let $=I.params[0]||1;for(;$--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(I){const $=I.params[0];return $===1&&(this._curAttrData.bg|=536870912),$!==2&&$!==0||(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(I,$,L,K=!1,se=!1){const oe=this._activeBuffer.lines.get(this._activeBuffer.ybase+I);oe.replaceCells($,L,this._activeBuffer.getNullCell(this._eraseAttrData()),this._eraseAttrData(),se),K&&(oe.isWrapped=!1)}_resetBufferLine(I,$=!1){const L=this._activeBuffer.lines.get(this._activeBuffer.ybase+I);L&&(L.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),$),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+I),L.isWrapped=!1)}eraseInDisplay(I,$=!1){let L;switch(this._restrictCursor(this._bufferService.cols),I.params[0]){case 0:for(L=this._activeBuffer.y,this._dirtyRowTracker.markDirty(L),this._eraseInBufferLine(L++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,$);L<this._bufferService.rows;L++)this._resetBufferLine(L,$);this._dirtyRowTracker.markDirty(L);break;case 1:for(L=this._activeBuffer.y,this._dirtyRowTracker.markDirty(L),this._eraseInBufferLine(L,0,this._activeBuffer.x+1,!0,$),this._activeBuffer.x+1>=this._bufferService.cols&&(this._activeBuffer.lines.get(L+1).isWrapped=!1);L--;)this._resetBufferLine(L,$);this._dirtyRowTracker.markDirty(0);break;case 2:for(L=this._bufferService.rows,this._dirtyRowTracker.markDirty(L-1);L--;)this._resetBufferLine(L,$);this._dirtyRowTracker.markDirty(0);break;case 3:const K=this._activeBuffer.lines.length-this._bufferService.rows;K>0&&(this._activeBuffer.lines.trimStart(K),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-K,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-K,0),this._onScroll.fire(0))}return!0}eraseInLine(I,$=!1){switch(this._restrictCursor(this._bufferService.cols),I.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,$);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,$);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,$)}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(I){this._restrictCursor();let $=I.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;const L=this._activeBuffer.ybase+this._activeBuffer.y,K=this._bufferService.rows-1-this._activeBuffer.scrollBottom,se=this._bufferService.rows-1+this._activeBuffer.ybase-K+1;for(;$--;)this._activeBuffer.lines.splice(se-1,1),this._activeBuffer.lines.splice(L,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}deleteLines(I){this._restrictCursor();let $=I.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;const L=this._activeBuffer.ybase+this._activeBuffer.y;let K;for(K=this._bufferService.rows-1-this._activeBuffer.scrollBottom,K=this._bufferService.rows-1+this._activeBuffer.ybase-K;$--;)this._activeBuffer.lines.splice(L,1),this._activeBuffer.lines.splice(K,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}insertChars(I){this._restrictCursor();const $=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return $&&($.insertCells(this._activeBuffer.x,I.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData()),this._eraseAttrData()),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}deleteChars(I){this._restrictCursor();const $=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return $&&($.deleteCells(this._activeBuffer.x,I.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData()),this._eraseAttrData()),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}scrollUp(I){let $=I.params[0]||1;for(;$--;)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(I){let $=I.params[0]||1;for(;$--;)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(m.DEFAULT_ATTR_DATA));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollLeft(I){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;const $=I.params[0]||1;for(let L=this._activeBuffer.scrollTop;L<=this._activeBuffer.scrollBottom;++L){const K=this._activeBuffer.lines.get(this._activeBuffer.ybase+L);K.deleteCells(0,$,this._activeBuffer.getNullCell(this._eraseAttrData()),this._eraseAttrData()),K.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollRight(I){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;const $=I.params[0]||1;for(let L=this._activeBuffer.scrollTop;L<=this._activeBuffer.scrollBottom;++L){const K=this._activeBuffer.lines.get(this._activeBuffer.ybase+L);K.insertCells(0,$,this._activeBuffer.getNullCell(this._eraseAttrData()),this._eraseAttrData()),K.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}insertColumns(I){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;const $=I.params[0]||1;for(let L=this._activeBuffer.scrollTop;L<=this._activeBuffer.scrollBottom;++L){const K=this._activeBuffer.lines.get(this._activeBuffer.ybase+L);K.insertCells(this._activeBuffer.x,$,this._activeBuffer.getNullCell(this._eraseAttrData()),this._eraseAttrData()),K.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}deleteColumns(I){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;const $=I.params[0]||1;for(let L=this._activeBuffer.scrollTop;L<=this._activeBuffer.scrollBottom;++L){const K=this._activeBuffer.lines.get(this._activeBuffer.ybase+L);K.deleteCells(this._activeBuffer.x,$,this._activeBuffer.getNullCell(this._eraseAttrData()),this._eraseAttrData()),K.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}eraseChars(I){this._restrictCursor();const $=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return $&&($.replaceCells(this._activeBuffer.x,this._activeBuffer.x+(I.params[0]||1),this._activeBuffer.getNullCell(this._eraseAttrData()),this._eraseAttrData()),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}repeatPrecedingCharacter(I){if(!this._parser.precedingCodepoint)return!0;const $=I.params[0]||1,L=new Uint32Array($);for(let K=0;K<$;++K)L[K]=this._parser.precedingCodepoint;return this.print(L,0,L.length),!0}sendDeviceAttributesPrimary(I){return I.params[0]>0||(this._is("xterm")||this._is("rxvt-unicode")||this._is("screen")?this._coreService.triggerDataEvent(d.C0.ESC+"[?1;2c"):this._is("linux")&&this._coreService.triggerDataEvent(d.C0.ESC+"[?6c")),!0}sendDeviceAttributesSecondary(I){return I.params[0]>0||(this._is("xterm")?this._coreService.triggerDataEvent(d.C0.ESC+"[>0;276;0c"):this._is("rxvt-unicode")?this._coreService.triggerDataEvent(d.C0.ESC+"[>85;95;0c"):this._is("linux")?this._coreService.triggerDataEvent(I.params[0]+"c"):this._is("screen")&&this._coreService.triggerDataEvent(d.C0.ESC+"[>83;40003;0c")),!0}_is(I){return(this._optionsService.rawOptions.termName+"").indexOf(I)===0}setMode(I){for(let $=0;$<I.length;$++)switch(I.params[$]){case 4:this._coreService.modes.insertMode=!0;break;case 20:this._optionsService.options.convertEol=!0}return!0}setModePrivate(I){for(let $=0;$<I.length;$++)switch(I.params[$]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!0;break;case 2:this._charsetService.setgCharset(0,h.DEFAULT_CHARSET),this._charsetService.setgCharset(1,h.DEFAULT_CHARSET),this._charsetService.setgCharset(2,h.DEFAULT_CHARSET),this._charsetService.setgCharset(3,h.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(I){for(let $=0;$<I.length;$++)switch(I.params[$]){case 4:this._coreService.modes.insertMode=!1;break;case 20:this._optionsService.options.convertEol=!1}return!0}resetModePrivate(I){for(let $=0;$<I.length;$++)switch(I.params[$]){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(),I.params[$]===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(I,$){const L=this._coreService.decPrivateModes,{activeProtocol:K,activeEncoding:se}=this._coreMouseService,oe=this._coreService,{buffers:ve,cols:le}=this._bufferService,{active:ue,alt:P}=ve,X=this._optionsService.rawOptions,J=Pe=>Pe?1:2,ne=I.params[0];return ce=ne,_e=$?ne===2?4:ne===4?J(oe.modes.insertMode):ne===12?3:ne===20?J(X.convertEol):0:ne===1?J(L.applicationCursorKeys):ne===3?X.windowOptions.setWinLines?le===80?2:le===132?1:0:0:ne===6?J(L.origin):ne===7?J(L.wraparound):ne===8?3:ne===9?J(K==="X10"):ne===12?J(X.cursorBlink):ne===25?J(!oe.isCursorHidden):ne===45?J(L.reverseWraparound):ne===66?J(L.applicationKeypad):ne===67?4:ne===1e3?J(K==="VT200"):ne===1002?J(K==="DRAG"):ne===1003?J(K==="ANY"):ne===1004?J(L.sendFocus):ne===1005?4:ne===1006?J(se==="SGR"):ne===1015?4:ne===1016?J(se==="SGR_PIXELS"):ne===1048?1:ne===47||ne===1047||ne===1049?J(ue===P):ne===2004?J(L.bracketedPasteMode):0,oe.triggerDataEvent(`${d.C0.ESC}[${$?"":"?"}${ce};${_e}$y`),!0;var ce,_e}_updateAttrColor(I,$,L,K,se){return $===2?(I|=50331648,I&=-16777216,I|=k.AttributeData.fromColorRGB([L,K,se])):$===5&&(I&=-50331904,I|=33554432|255&L),I}_extractColor(I,$,L){const K=[0,0,-1,0,0,0];let se=0,oe=0;do{if(K[oe+se]=I.params[$+oe],I.hasSubParams($+oe)){const ve=I.getSubParams($+oe);let le=0;do K[1]===5&&(se=1),K[oe+le+1+se]=ve[le];while(++le<ve.length&&le+oe+1+se<K.length);break}if(K[1]===5&&oe+se>=2||K[1]===2&&oe+se>=5)break;K[1]&&(se=1)}while(++oe+$<I.length&&oe+se<K.length);for(let ve=2;ve<K.length;++ve)K[ve]===-1&&(K[ve]=0);switch(K[0]){case 38:L.fg=this._updateAttrColor(L.fg,K[1],K[3],K[4],K[5]);break;case 48:L.bg=this._updateAttrColor(L.bg,K[1],K[3],K[4],K[5]);break;case 58:L.extended=L.extended.clone(),L.extended.underlineColor=this._updateAttrColor(L.extended.underlineColor,K[1],K[3],K[4],K[5])}return oe}_processUnderline(I,$){$.extended=$.extended.clone(),(!~I||I>5)&&(I=1),$.extended.underlineStyle=I,$.fg|=268435456,I===0&&($.fg&=-268435457),$.updateExtended()}_processSGR0(I){I.fg=m.DEFAULT_ATTR_DATA.fg,I.bg=m.DEFAULT_ATTR_DATA.bg,I.extended=I.extended.clone(),I.extended.underlineStyle=0,I.extended.underlineColor&=-67108864,I.updateExtended()}charAttributes(I){if(I.length===1&&I.params[0]===0)return this._processSGR0(this._curAttrData),!0;const $=I.length;let L;const K=this._curAttrData;for(let se=0;se<$;se++)L=I.params[se],L>=30&&L<=37?(K.fg&=-50331904,K.fg|=16777216|L-30):L>=40&&L<=47?(K.bg&=-50331904,K.bg|=16777216|L-40):L>=90&&L<=97?(K.fg&=-50331904,K.fg|=16777224|L-90):L>=100&&L<=107?(K.bg&=-50331904,K.bg|=16777224|L-100):L===0?this._processSGR0(K):L===1?K.fg|=134217728:L===3?K.bg|=67108864:L===4?(K.fg|=268435456,this._processUnderline(I.hasSubParams(se)?I.getSubParams(se)[0]:1,K)):L===5?K.fg|=536870912:L===7?K.fg|=67108864:L===8?K.fg|=1073741824:L===9?K.fg|=2147483648:L===2?K.bg|=134217728:L===21?this._processUnderline(2,K):L===22?(K.fg&=-134217729,K.bg&=-134217729):L===23?K.bg&=-67108865:L===24?(K.fg&=-268435457,this._processUnderline(0,K)):L===25?K.fg&=-536870913:L===27?K.fg&=-67108865:L===28?K.fg&=-1073741825:L===29?K.fg&=2147483647:L===39?(K.fg&=-67108864,K.fg|=16777215&m.DEFAULT_ATTR_DATA.fg):L===49?(K.bg&=-67108864,K.bg|=16777215&m.DEFAULT_ATTR_DATA.bg):L===38||L===48||L===58?se+=this._extractColor(I,se,K):L===53?K.bg|=1073741824:L===55?K.bg&=-1073741825:L===59?(K.extended=K.extended.clone(),K.extended.underlineColor=-1,K.updateExtended()):L===100?(K.fg&=-67108864,K.fg|=16777215&m.DEFAULT_ATTR_DATA.fg,K.bg&=-67108864,K.bg|=16777215&m.DEFAULT_ATTR_DATA.bg):this._logService.debug("Unknown SGR attribute: %d.",L);return!0}deviceStatus(I){switch(I.params[0]){case 5:this._coreService.triggerDataEvent(`${d.C0.ESC}[0n`);break;case 6:const $=this._activeBuffer.y+1,L=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${d.C0.ESC}[${$};${L}R`)}return!0}deviceStatusPrivate(I){if(I.params[0]===6){const $=this._activeBuffer.y+1,L=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${d.C0.ESC}[?${$};${L}R`)}return!0}softReset(I){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=m.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(I){const $=I.params[0]||1;switch($){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 L=$%2==1;return this._optionsService.options.cursorBlink=L,!0}setScrollRegion(I){const $=I.params[0]||1;let L;return(I.length<2||(L=I.params[1])>this._bufferService.rows||L===0)&&(L=this._bufferService.rows),L>$&&(this._activeBuffer.scrollTop=$-1,this._activeBuffer.scrollBottom=L-1,this._setCursor(0,0)),!0}windowOptions(I){if(!D(I.params[0],this._optionsService.rawOptions.windowOptions))return!0;const $=I.length>1?I.params[1]:0;switch(I.params[0]){case 14:$!==2&&this._onRequestWindowsOptionsReport.fire(N.GET_WIN_SIZE_PIXELS);break;case 16:this._onRequestWindowsOptionsReport.fire(N.GET_CELL_SIZE_PIXELS);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${d.C0.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:$!==0&&$!==2||(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>10&&this._windowTitleStack.shift()),$!==0&&$!==1||(this._iconNameStack.push(this._iconName),this._iconNameStack.length>10&&this._iconNameStack.shift());break;case 23:$!==0&&$!==2||this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),$!==0&&$!==1||this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop())}return!0}saveCursor(I){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(I){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(I){return this._windowTitle=I,this._onTitleChange.fire(I),!0}setIconName(I){return this._iconName=I,!0}setOrReportIndexedColor(I){const $=[],L=I.split(";");for(;L.length>1;){const K=L.shift(),se=L.shift();if(/^\d+$/.exec(K)){const oe=parseInt(K);if(q(oe))if(se==="?")$.push({type:0,index:oe});else{const ve=(0,C.parseColor)(se);ve&&$.push({type:1,index:oe,color:ve})}}}return $.length&&this._onColor.fire($),!0}setHyperlink(I){const $=I.split(";");return!($.length<2)&&($[1]?this._createHyperlink($[0],$[1]):!$[0]&&this._finishHyperlink())}_createHyperlink(I,$){this._getCurrentLinkId()&&this._finishHyperlink();const L=I.split(":");let K;const se=L.findIndex(oe=>oe.startsWith("id="));return se!==-1&&(K=L[se].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:K,uri:$}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(I,$){const L=I.split(";");for(let K=0;K<L.length&&!($>=this._specialColors.length);++K,++$)if(L[K]==="?")this._onColor.fire([{type:0,index:this._specialColors[$]}]);else{const se=(0,C.parseColor)(L[K]);se&&this._onColor.fire([{type:1,index:this._specialColors[$],color:se}])}return!0}setOrReportFgColor(I){return this._setOrReportSpecialColor(I,0)}setOrReportBgColor(I){return this._setOrReportSpecialColor(I,1)}setOrReportCursorColor(I){return this._setOrReportSpecialColor(I,2)}restoreIndexedColor(I){if(!I)return this._onColor.fire([{type:2}]),!0;const $=[],L=I.split(";");for(let K=0;K<L.length;++K)if(/^\d+$/.exec(L[K])){const se=parseInt(L[K]);q(se)&&$.push({type:2,index:se})}return $.length&&this._onColor.fire($),!0}restoreFgColor(I){return this._onColor.fire([{type:2,index:256}]),!0}restoreBgColor(I){return this._onColor.fire([{type:2,index:257}]),!0}restoreCursorColor(I){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,h.DEFAULT_CHARSET),!0}selectCharset(I){return I.length!==2?(this.selectDefaultCharset(),!0):(I[0]==="/"||this._charsetService.setgCharset(E[I[0]],h.CHARSETS[I[1]]||h.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 I=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,I,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=m.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=m.DEFAULT_ATTR_DATA.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=67108863&this._curAttrData.bg,this._eraseAttrDataInternal}setgLevel(I){return this._charsetService.setgLevel(I),!0}screenAlignmentPattern(){const I=new b.CellData;I.content=4194373,I.fg=this._curAttrData.fg,I.bg=this._curAttrData.bg,this._setCursor(0,0);for(let $=0;$<this._bufferService.rows;++$){const L=this._activeBuffer.ybase+this._activeBuffer.y+$,K=this._activeBuffer.lines.get(L);K&&(K.fill(I),K.isWrapped=!1)}return this._dirtyRowTracker.markAllDirty(),this._setCursor(0,0),!0}requestStatusString(I,$){const L=this._bufferService.buffer,K=this._optionsService.rawOptions;return(se=>(this._coreService.triggerDataEvent(`${d.C0.ESC}${se}${d.C0.ESC}\\`),!0))(I==='"q'?`P1$r${this._curAttrData.isProtected()?1:0}"q`:I==='"p'?'P1$r61;1"p':I==="r"?`P1$r${L.scrollTop+1};${L.scrollBottom+1}r`:I==="m"?"P1$r0m":I===" q"?`P1$r${{block:2,underline:4,bar:6}[K.cursorStyle]-(K.cursorBlink?1:0)} q`:"P0$r")}markRangeDirty(I,$){this._dirtyRowTracker.markRangeDirty(I,$)}}a.InputHandler=G;let Z=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,I){V>I&&(O=V,V=I,I=O),V<this.start&&(this.start=V),I>this.end&&(this.end=I)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};function q(V){return 0<=V&&V<256}Z=l([u(0,w.IBufferService)],Z)},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,d,h){this._data[u]||(this._data[u]={}),this._data[u][d]=h}get(u,d){return this._data[u]?this._data[u][d]:void 0}clear(){this._data={}}}a.TwoKeyMap=c,a.FourKeyMap=class{constructor(){this._data=new c}set(l,u,d,h,p){this._data.get(l,u)||this._data.set(l,u,new c),this._data.get(l,u).set(d,h,p)}get(l,u,d,h){var p;return(p=this._data.get(l,u))===null||p===void 0?void 0:p.get(d,h)}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,d=this._array.length-1;for(;d>=u;){let h=u+d>>1;const p=this._getKey(this._array[h]);if(p>l)d=h-1;else{if(!(p<l)){for(;h>0&&this._getKey(this._array[h-1])===l;)h--;return h}u=h+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 g=0,v=0,m=p.timeRemaining(),y=0;for(;this._i<this._tasks.length;){if(g=Date.now(),this._tasks[this._i]()||this._i++,g=Math.max(1,Date.now()-g),v=Math.max(g,v),y=p.timeRemaining(),1.5*v>y)return m-g<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(m-g))}ms`),void this._start();m=y}this.clear()}}class d extends u{_requestCallback(p){return setTimeout(()=>p(this._createDeadline(16)))}_cancelCallback(p){clearTimeout(p)}_createDeadline(p){const g=Date.now()+p;return{timeRemaining:()=>Math.max(0,g-Date.now())}}}a.PriorityTaskQueue=d,a.IdleTaskQueue=!l.isNode&&"requestIdleCallback"in window?class extends u{_requestCallback(h){return requestIdleCallback(h)}_cancelCallback(h){cancelIdleCallback(h)}}:d,a.DebouncedIdleTask=class{constructor(){this._queue=new a.IdleTaskQueue}set(h){this._queue.clear(),this._queue.enqueue(h)}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 d=u.buffer.lines.get(u.buffer.ybase+u.buffer.y-1),h=d==null?void 0:d.get(u.cols-1),p=u.buffer.lines.get(u.buffer.ybase+u.buffer.y);p&&h&&(p.isWrapped=h[l.CHAR_DATA_CODE_INDEX]!==l.NULL_CELL_CODE&&h[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(d){return[d>>>16&255,d>>>8&255,255&d]}static fromColorRGB(d){return(255&d[0])<<16|(255&d[1])<<8|255&d[2]}clone(){const d=new c;return d.fg=this.fg,d.bg=this.bg,d.extended=this.extended.clone(),d}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(d){this._ext=d}get underlineStyle(){return this._urlId?5:(469762048&this._ext)>>26}set underlineStyle(d){this._ext&=-469762049,this._ext|=d<<26&469762048}get underlineColor(){return 67108863&this._ext}set underlineColor(d){this._ext&=-67108864,this._ext|=67108863&d}get urlId(){return this._urlId}set urlId(d){this._urlId=d}constructor(d=0,h=0){this._ext=0,this._urlId=0,this._ext=d,this._urlId=h}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),d=c(3734),h=c(8437),p=c(4634),g=c(511),v=c(643),m=c(4863),y=c(7116);a.MAX_BUFFER_SIZE=4294967295,a.Buffer=class{constructor(_,b,k){this._hasScrollback=_,this._optionsService=b,this._bufferService=k,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=h.DEFAULT_ATTR_DATA.clone(),this.savedCharset=y.DEFAULT_CHARSET,this.markers=[],this._nullCell=g.CellData.fromCharData([0,v.NULL_CELL_CHAR,v.NULL_CELL_WIDTH,v.NULL_CELL_CODE]),this._whitespaceCell=g.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(_){return _?(this._nullCell.fg=_.fg,this._nullCell.bg=_.bg,this._nullCell.extended=_.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new d.ExtendedAttrs),this._nullCell}getWhitespaceCell(_){return _?(this._whitespaceCell.fg=_.fg,this._whitespaceCell.bg=_.bg,this._whitespaceCell.extended=_.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new d.ExtendedAttrs),this._whitespaceCell}getBlankLine(_,b){return new h.BufferLine(this._bufferService.cols,this.getNullCell(_),b)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){const _=this.ybase+this.y-this.ydisp;return _>=0&&_<this._rows}_getCorrectBufferLength(_){if(!this._hasScrollback)return _;const b=_+this._optionsService.rawOptions.scrollback;return b>a.MAX_BUFFER_SIZE?a.MAX_BUFFER_SIZE:b}fillViewportRows(_){if(this.lines.length===0){_===void 0&&(_=h.DEFAULT_ATTR_DATA);let b=this._rows;for(;b--;)this.lines.push(this.getBlankLine(_))}}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 k=this.getNullCell(h.DEFAULT_ATTR_DATA);let w=0;const T=this._getCorrectBufferLength(b);if(T>this.lines.maxLength&&(this.lines.maxLength=T),this.lines.length>0){if(this._cols<_)for(let C=0;C<this.lines.length;C++)w+=+this.lines.get(C).resize(_,k);let A=0;if(this._rows<b)for(let C=this._rows;C<b;C++)this.lines.length<b+this.ybase&&(this._optionsService.rawOptions.windowsMode||this._optionsService.rawOptions.windowsPty.backend!==void 0||this._optionsService.rawOptions.windowsPty.buildNumber!==void 0?this.lines.push(new h.BufferLine(_,k)):this.ybase>0&&this.lines.length<=this.ybase+this.y+A+1?(this.ybase--,A++,this.ydisp>0&&this.ydisp--):this.lines.push(new h.BufferLine(_,k)));else for(let C=this._rows;C>b;C--)this.lines.length>b+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(T<this.lines.maxLength){const C=this.lines.length-T;C>0&&(this.lines.trimStart(C),this.ybase=Math.max(this.ybase-C,0),this.ydisp=Math.max(this.ydisp-C,0),this.savedY=Math.max(this.savedY-C,0)),this.lines.maxLength=T}this.x=Math.min(this.x,_-1),this.y=Math.min(this.y,b-1),A&&(this.y+=A),this.savedX=Math.min(this.savedX,_-1),this.scrollTop=0}if(this.scrollBottom=b-1,this._isReflowEnabled&&(this._reflow(_,b),this._cols>_))for(let A=0;A<this.lines.length;A++)w+=+this.lines.get(A).resize(_,k);this._cols=_,this._rows=b,this._memoryCleanupQueue.clear(),w>.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue(()=>this._batchedMemoryCleanup()))}_batchedMemoryCleanup(){let _=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,_=!1);let b=0;for(;this._memoryCleanupPosition<this.lines.length;)if(b+=this.lines.get(this._memoryCleanupPosition++).cleanupMemory(),b>100)return!0;return _}get _isReflowEnabled(){const _=this._optionsService.rawOptions.windowsPty;return _&&_.buildNumber?this._hasScrollback&&_.backend==="conpty"&&_.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(_,b){this._cols!==_&&(_>this._cols?this._reflowLarger(_,b):this._reflowSmaller(_,b))}_reflowLarger(_,b){const k=(0,p.reflowLargerGetLinesToRemove)(this.lines,this._cols,_,this.ybase+this.y,this.getNullCell(h.DEFAULT_ATTR_DATA));if(k.length>0){const w=(0,p.reflowLargerCreateNewLayout)(this.lines,k);(0,p.reflowLargerApplyNewLayout)(this.lines,w.layout),this._reflowLargerAdjustViewport(_,b,w.countRemoved)}}_reflowLargerAdjustViewport(_,b,k){const w=this.getNullCell(h.DEFAULT_ATTR_DATA);let T=k;for(;T-- >0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length<b&&this.lines.push(new h.BufferLine(_,w))):(this.ydisp===this.ybase&&this.ydisp--,this.ybase--);this.savedY=Math.max(this.savedY-k,0)}_reflowSmaller(_,b){const k=this.getNullCell(h.DEFAULT_ATTR_DATA),w=[];let T=0;for(let A=this.lines.length-1;A>=0;A--){let C=this.lines.get(A);if(!C||!C.isWrapped&&C.getTrimmedLength()<=_)continue;const E=[C];for(;C.isWrapped&&A>0;)C=this.lines.get(--A),E.unshift(C);const x=this.ybase+this.y;if(x>=A&&x<A+E.length)continue;const D=E[E.length-1].getTrimmedLength(),N=(0,p.reflowSmallerGetNewLineLengths)(E,this._cols,_),O=N.length-E.length;let G;G=this.ybase===0&&this.y!==this.lines.length-1?Math.max(0,this.y-this.lines.maxLength+O):Math.max(0,this.lines.length-this.lines.maxLength+O);const Z=[];for(let K=0;K<O;K++){const se=this.getBlankLine(h.DEFAULT_ATTR_DATA,!0);Z.push(se)}Z.length>0&&(w.push({start:A+E.length+T,newLines:Z}),T+=Z.length),E.push(...Z);let q=N.length-1,V=N[q];V===0&&(q--,V=N[q]);let I=E.length-O-1,$=D;for(;I>=0;){const K=Math.min($,V);if(E[q]===void 0)break;if(E[q].copyCellsFrom(E[I],$-K,V-K,K,!0),V-=K,V===0&&(q--,V=N[q]),$-=K,$===0){I--;const se=Math.max(I,0);$=(0,p.getWrappedLineTrimmedLength)(E,se,this._cols)}}for(let K=0;K<E.length;K++)N[K]<_&&E[K].setCell(N[K],k);let L=O-G;for(;L-- >0;)this.ybase===0?this.y<b-1?(this.y++,this.lines.pop()):(this.ybase++,this.ydisp++):this.ybase<Math.min(this.lines.maxLength,this.lines.length+T)-b&&(this.ybase===this.ydisp&&this.ydisp++,this.ybase++);this.savedY=Math.min(this.savedY+O,this.ybase+b-1)}if(w.length>0){const A=[],C=[];for(let q=0;q<this.lines.length;q++)C.push(this.lines.get(q));const E=this.lines.length;let x=E-1,D=0,N=w[D];this.lines.length=Math.min(this.lines.maxLength,this.lines.length+T);let O=0;for(let q=Math.min(this.lines.maxLength-1,E+T-1);q>=0;q--)if(N&&N.start>x+O){for(let V=N.newLines.length-1;V>=0;V--)this.lines.set(q--,N.newLines[V]);q++,A.push({index:x+1,amount:N.newLines.length}),O+=N.newLines.length,N=w[++D]}else this.lines.set(q,C[x--]);let G=0;for(let q=A.length-1;q>=0;q--)A[q].index+=G,this.lines.onInsertEmitter.fire(A[q]),G+=A[q].amount;const Z=Math.max(0,E+T-this.lines.maxLength);Z>0&&this.lines.onTrimEmitter.fire(Z)}}translateBufferLineToString(_,b,k=0,w){const T=this.lines.get(_);return T?T.translateToString(b,k,w):""}getWrappedRangeForLine(_){let b=_,k=_;for(;b>0&&this.lines.get(b).isWrapped;)b--;for(;k+1<this.lines.length&&this.lines.get(k+1).isWrapped;)k++;return{first:b,last:k}}setupTabStops(_){for(_!=null?this.tabs[_]||(_=this.prevStop(_)):(this.tabs={},_=0);_<this._cols;_+=this._optionsService.rawOptions.tabStopWidth)this.tabs[_]=!0}prevStop(_){for(_==null&&(_=this.x);!this.tabs[--_]&&_>0;);return _>=this._cols?this._cols-1:_<0?0:_}nextStop(_){for(_==null&&(_=this.x);!this.tabs[++_]&&_<this._cols;);return _>=this._cols?this._cols-1:_<0?0:_}clearMarkers(_){this._isClearing=!0;for(let b=0;b<this.markers.length;b++)this.markers[b].line===_&&(this.markers[b].dispose(),this.markers.splice(b--,1));this._isClearing=!1}clearAllMarkers(){this._isClearing=!0;for(let _=0;_<this.markers.length;_++)this.markers[_].dispose(),this.markers.splice(_--,1);this._isClearing=!1}addMarker(_){const b=new m.Marker(_);return this.markers.push(b),b.register(this.lines.onTrim(k=>{b.line-=k,b.line<0&&b.dispose()})),b.register(this.lines.onInsert(k=>{b.line>=k.index&&(b.line+=k.amount)})),b.register(this.lines.onDelete(k=>{b.line>=k.index&&b.line<k.index+k.amount&&b.dispose(),b.line>k.index&&(b.line-=k.amount)})),b.register(b.onDispose(()=>this._removeMarker(b))),b}_removeMarker(_){this._isClearing||this.markers.splice(this.markers.indexOf(_),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),d=c(643),h=c(482);a.DEFAULT_ATTR_DATA=Object.freeze(new l.AttributeData);let p=0;class g{constructor(m,y,_=!1){this.isWrapped=_,this._combined={},this._extendedAttrs={},this._data=new Uint32Array(3*m);const b=y||u.CellData.fromCharData([0,d.NULL_CELL_CHAR,d.NULL_CELL_WIDTH,d.NULL_CELL_CODE]);for(let k=0;k<m;++k)this.setCell(k,b);this.length=m}get(m){const y=this._data[3*m+0],_=2097151&y;return[this._data[3*m+1],2097152&y?this._combined[m]:_?(0,h.stringFromCodePoint)(_):"",y>>22,2097152&y?this._combined[m].charCodeAt(this._combined[m].length-1):_]}set(m,y){this._data[3*m+1]=y[d.CHAR_DATA_ATTR_INDEX],y[d.CHAR_DATA_CHAR_INDEX].length>1?(this._combined[m]=y[1],this._data[3*m+0]=2097152|m|y[d.CHAR_DATA_WIDTH_INDEX]<<22):this._data[3*m+0]=y[d.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|y[d.CHAR_DATA_WIDTH_INDEX]<<22}getWidth(m){return this._data[3*m+0]>>22}hasWidth(m){return 12582912&this._data[3*m+0]}getFg(m){return this._data[3*m+1]}getBg(m){return this._data[3*m+2]}hasContent(m){return 4194303&this._data[3*m+0]}getCodePoint(m){const y=this._data[3*m+0];return 2097152&y?this._combined[m].charCodeAt(this._combined[m].length-1):2097151&y}isCombined(m){return 2097152&this._data[3*m+0]}getString(m){const y=this._data[3*m+0];return 2097152&y?this._combined[m]:2097151&y?(0,h.stringFromCodePoint)(2097151&y):""}isProtected(m){return 536870912&this._data[3*m+2]}loadCell(m,y){return p=3*m,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[m]),268435456&y.bg&&(y.extended=this._extendedAttrs[m]),y}setCell(m,y){2097152&y.content&&(this._combined[m]=y.combinedData),268435456&y.bg&&(this._extendedAttrs[m]=y.extended),this._data[3*m+0]=y.content,this._data[3*m+1]=y.fg,this._data[3*m+2]=y.bg}setCellFromCodePoint(m,y,_,b,k,w){268435456&k&&(this._extendedAttrs[m]=w),this._data[3*m+0]=y|_<<22,this._data[3*m+1]=b,this._data[3*m+2]=k}addCodepointToCell(m,y){let _=this._data[3*m+0];2097152&_?this._combined[m]+=(0,h.stringFromCodePoint)(y):(2097151&_?(this._combined[m]=(0,h.stringFromCodePoint)(2097151&_)+(0,h.stringFromCodePoint)(y),_&=-2097152,_|=2097152):_=y|4194304,this._data[3*m+0]=_)}insertCells(m,y,_,b){if((m%=this.length)&&this.getWidth(m-1)===2&&this.setCellFromCodePoint(m-1,0,1,(b==null?void 0:b.fg)||0,(b==null?void 0:b.bg)||0,(b==null?void 0:b.extended)||new l.ExtendedAttrs),y<this.length-m){const k=new u.CellData;for(let w=this.length-m-y-1;w>=0;--w)this.setCell(m+y+w,this.loadCell(m+w,k));for(let w=0;w<y;++w)this.setCell(m+w,_)}else for(let k=m;k<this.length;++k)this.setCell(k,_);this.getWidth(this.length-1)===2&&this.setCellFromCodePoint(this.length-1,0,1,(b==null?void 0:b.fg)||0,(b==null?void 0:b.bg)||0,(b==null?void 0:b.extended)||new l.ExtendedAttrs)}deleteCells(m,y,_,b){if(m%=this.length,y<this.length-m){const k=new u.CellData;for(let w=0;w<this.length-m-y;++w)this.setCell(m+w,this.loadCell(m+y+w,k));for(let w=this.length-y;w<this.length;++w)this.setCell(w,_)}else for(let k=m;k<this.length;++k)this.setCell(k,_);m&&this.getWidth(m-1)===2&&this.setCellFromCodePoint(m-1,0,1,(b==null?void 0:b.fg)||0,(b==null?void 0:b.bg)||0,(b==null?void 0:b.extended)||new l.ExtendedAttrs),this.getWidth(m)!==0||this.hasContent(m)||this.setCellFromCodePoint(m,0,1,(b==null?void 0:b.fg)||0,(b==null?void 0:b.bg)||0,(b==null?void 0:b.extended)||new l.ExtendedAttrs)}replaceCells(m,y,_,b,k=!1){if(k)for(m&&this.getWidth(m-1)===2&&!this.isProtected(m-1)&&this.setCellFromCodePoint(m-1,0,1,(b==null?void 0:b.fg)||0,(b==null?void 0:b.bg)||0,(b==null?void 0:b.extended)||new l.ExtendedAttrs),y<this.length&&this.getWidth(y-1)===2&&!this.isProtected(y)&&this.setCellFromCodePoint(y,0,1,(b==null?void 0:b.fg)||0,(b==null?void 0:b.bg)||0,(b==null?void 0:b.extended)||new l.ExtendedAttrs);m<y&&m<this.length;)this.isProtected(m)||this.setCell(m,_),m++;else for(m&&this.getWidth(m-1)===2&&this.setCellFromCodePoint(m-1,0,1,(b==null?void 0:b.fg)||0,(b==null?void 0:b.bg)||0,(b==null?void 0:b.extended)||new l.ExtendedAttrs),y<this.length&&this.getWidth(y-1)===2&&this.setCellFromCodePoint(y,0,1,(b==null?void 0:b.fg)||0,(b==null?void 0:b.bg)||0,(b==null?void 0:b.extended)||new l.ExtendedAttrs);m<y&&m<this.length;)this.setCell(m++,_)}resize(m,y){if(m===this.length)return 4*this._data.length*2<this._data.buffer.byteLength;const _=3*m;if(m>this.length){if(this._data.buffer.byteLength>=4*_)this._data=new Uint32Array(this._data.buffer,0,_);else{const b=new Uint32Array(_);b.set(this._data),this._data=b}for(let b=this.length;b<m;++b)this.setCell(b,y)}else{this._data=this._data.subarray(0,_);const b=Object.keys(this._combined);for(let w=0;w<b.length;w++){const T=parseInt(b[w],10);T>=m&&delete this._combined[T]}const k=Object.keys(this._extendedAttrs);for(let w=0;w<k.length;w++){const T=parseInt(k[w],10);T>=m&&delete this._extendedAttrs[T]}}return this.length=m,4*_*2<this._data.buffer.byteLength}cleanupMemory(){if(4*this._data.length*2<this._data.buffer.byteLength){const m=new Uint32Array(this._data.length);return m.set(this._data),this._data=m,1}return 0}fill(m,y=!1){if(y)for(let _=0;_<this.length;++_)this.isProtected(_)||this.setCell(_,m);else{this._combined={},this._extendedAttrs={};for(let _=0;_<this.length;++_)this.setCell(_,m)}}copyFrom(m){this.length!==m.length?this._data=new Uint32Array(m._data):this._data.set(m._data),this.length=m.length,this._combined={};for(const y in m._combined)this._combined[y]=m._combined[y];this._extendedAttrs={};for(const y in m._extendedAttrs)this._extendedAttrs[y]=m._extendedAttrs[y];this.isWrapped=m.isWrapped}clone(){const m=new g(0);m._data=new Uint32Array(this._data),m.length=this.length;for(const y in this._combined)m._combined[y]=this._combined[y];for(const y in this._extendedAttrs)m._extendedAttrs[y]=this._extendedAttrs[y];return m.isWrapped=this.isWrapped,m}getTrimmedLength(){for(let m=this.length-1;m>=0;--m)if(4194303&this._data[3*m+0])return m+(this._data[3*m+0]>>22);return 0}getNoBgTrimmedLength(){for(let m=this.length-1;m>=0;--m)if(4194303&this._data[3*m+0]||50331648&this._data[3*m+2])return m+(this._data[3*m+0]>>22);return 0}copyCellsFrom(m,y,_,b,k){const w=m._data;if(k)for(let A=b-1;A>=0;A--){for(let C=0;C<3;C++)this._data[3*(_+A)+C]=w[3*(y+A)+C];268435456&w[3*(y+A)+2]&&(this._extendedAttrs[_+A]=m._extendedAttrs[y+A])}else for(let A=0;A<b;A++){for(let C=0;C<3;C++)this._data[3*(_+A)+C]=w[3*(y+A)+C];268435456&w[3*(y+A)+2]&&(this._extendedAttrs[_+A]=m._extendedAttrs[y+A])}const T=Object.keys(m._combined);for(let A=0;A<T.length;A++){const C=parseInt(T[A],10);C>=y&&(this._combined[C-y+_]=m._combined[C])}}translateToString(m=!1,y=0,_=this.length){m&&(_=Math.min(_,this.getTrimmedLength()));let b="";for(;y<_;){const k=this._data[3*y+0],w=2097151&k;b+=2097152&k?this._combined[y]:w?(0,h.stringFromCodePoint)(w):d.WHITESPACE_CELL_CHAR,y+=k>>22||1}return b}}a.BufferLine=g},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,d){if(u===l.length-1)return l[u].getTrimmedLength();const h=!l[u].hasContent(d-1)&&l[u].getWidth(d-1)===1,p=l[u+1].getWidth(0)===2;return h&&p?d-1:d}Object.defineProperty(a,"__esModule",{value:!0}),a.getWrappedLineTrimmedLength=a.reflowSmallerGetNewLineLengths=a.reflowLargerApplyNewLayout=a.reflowLargerCreateNewLayout=a.reflowLargerGetLinesToRemove=void 0,a.reflowLargerGetLinesToRemove=function(l,u,d,h,p){const g=[];for(let v=0;v<l.length-1;v++){let m=v,y=l.get(++m);if(!y.isWrapped)continue;const _=[l.get(v)];for(;m<l.length&&y.isWrapped;)_.push(y),y=l.get(++m);if(h>=v&&h<m){v+=_.length-1;continue}let b=0,k=c(_,b,u),w=1,T=0;for(;w<_.length;){const C=c(_,w,u),E=C-T,x=d-k,D=Math.min(E,x);_[b].copyCellsFrom(_[w],T,k,D,!1),k+=D,k===d&&(b++,k=0),T+=D,T===C&&(w++,T=0),k===0&&b!==0&&_[b-1].getWidth(d-1)===2&&(_[b].copyCellsFrom(_[b-1],d-1,k++,1,!1),_[b-1].setCell(d-1,p))}_[b].replaceCells(k,d,p);let A=0;for(let C=_.length-1;C>0&&(C>b||_[C].getTrimmedLength()===0);C--)A++;A>0&&(g.push(v+_.length-A),g.push(A)),v+=_.length-1}return g},a.reflowLargerCreateNewLayout=function(l,u){const d=[];let h=0,p=u[h],g=0;for(let v=0;v<l.length;v++)if(p===v){const m=u[++h];l.onDeleteEmitter.fire({index:v-g,amount:m}),v+=m-1,g+=m,p=u[++h]}else d.push(v);return{layout:d,countRemoved:g}},a.reflowLargerApplyNewLayout=function(l,u){const d=[];for(let h=0;h<u.length;h++)d.push(l.get(u[h]));for(let h=0;h<d.length;h++)l.set(h,d[h]);l.length=u.length},a.reflowSmallerGetNewLineLengths=function(l,u,d){const h=[],p=l.map((y,_)=>c(l,_,u)).reduce((y,_)=>y+_);let g=0,v=0,m=0;for(;m<p;){if(p-m<d){h.push(p-m);break}g+=d;const y=c(l,v,u);g>y&&(g-=y,v++);const _=l[v].getWidth(g-1)===2;_&&g--;const b=_?d-1:d;h.push(b),m+=b}return h},a.getWrappedLineTrimmedLength=c},5295:(o,a,c)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.BufferSet=void 0;const l=c(8460),u=c(844),d=c(9092);class h extends u.Disposable{constructor(g,v){super(),this._optionsService=g,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 d.Buffer(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new d.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(g){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(g),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(g,v){this._normal.resize(g,v),this._alt.resize(g,v),this.setupTabStops(g)}setupTabStops(g){this._normal.setupTabStops(g),this._alt.setupTabStops(g)}}a.BufferSet=h},511:(o,a,c)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.CellData=void 0;const l=c(482),u=c(643),d=c(3734);class h extends d.AttributeData{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new d.ExtendedAttrs,this.combinedData=""}static fromCharData(g){const v=new h;return v.setFromCharData(g),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(g){this.fg=g[u.CHAR_DATA_ATTR_INDEX],this.bg=0;let v=!1;if(g[u.CHAR_DATA_CHAR_INDEX].length>2)v=!0;else if(g[u.CHAR_DATA_CHAR_INDEX].length===2){const m=g[u.CHAR_DATA_CHAR_INDEX].charCodeAt(0);if(55296<=m&&m<=56319){const y=g[u.CHAR_DATA_CHAR_INDEX].charCodeAt(1);56320<=y&&y<=57343?this.content=1024*(m-55296)+y-56320+65536|g[u.CHAR_DATA_WIDTH_INDEX]<<22:v=!0}else v=!0}else this.content=g[u.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|g[u.CHAR_DATA_WIDTH_INDEX]<<22;v&&(this.combinedData=g[u.CHAR_DATA_CHAR_INDEX],this.content=2097152|g[u.CHAR_DATA_WIDTH_INDEX]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}}a.CellData=h},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 d{get id(){return this._id}constructor(p){this.line=p,this.isDisposed=!1,this._disposables=[],this._id=d._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=d,d._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(d){d.NUL="\0",d.SOH="",d.STX="",d.ETX="",d.EOT="",d.ENQ="",d.ACK="",d.BEL="\x07",d.BS="\b",d.HT=" ",d.LF=`
|
||
`,d.VT="\v",d.FF="\f",d.CR="\r",d.SO="",d.SI="",d.DLE="",d.DC1="",d.DC2="",d.DC3="",d.DC4="",d.NAK="",d.SYN="",d.ETB="",d.CAN="",d.EM="",d.SUB="",d.ESC="\x1B",d.FS="",d.GS="",d.RS="",d.US="",d.SP=" ",d.DEL=""}(c||(a.C0=c={})),function(d){d.PAD="",d.HOP="",d.BPH="",d.NBH="",d.IND="",d.NEL="
",d.SSA="",d.ESA="",d.HTS="",d.HTJ="",d.VTS="",d.PLD="",d.PLU="",d.RI="",d.SS2="",d.SS3="",d.DCS="",d.PU1="",d.PU2="",d.STS="",d.CCH="",d.MW="",d.SPA="",d.EPA="",d.SOS="",d.SGCI="",d.SCI="",d.CSI="",d.ST="",d.OSC="",d.PM="",d.APC=""}(l||(a.C1=l={})),function(d){d.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(d,h,p,g){const v={type:0,cancel:!1,key:void 0},m=(d.shiftKey?1:0)|(d.altKey?2:0)|(d.ctrlKey?4:0)|(d.metaKey?8:0);switch(d.keyCode){case 0:d.key==="UIKeyInputUpArrow"?v.key=h?l.C0.ESC+"OA":l.C0.ESC+"[A":d.key==="UIKeyInputLeftArrow"?v.key=h?l.C0.ESC+"OD":l.C0.ESC+"[D":d.key==="UIKeyInputRightArrow"?v.key=h?l.C0.ESC+"OC":l.C0.ESC+"[C":d.key==="UIKeyInputDownArrow"&&(v.key=h?l.C0.ESC+"OB":l.C0.ESC+"[B");break;case 8:if(d.altKey){v.key=l.C0.ESC+l.C0.DEL;break}v.key=l.C0.DEL;break;case 9:if(d.shiftKey){v.key=l.C0.ESC+"[Z";break}v.key=l.C0.HT,v.cancel=!0;break;case 13:v.key=d.altKey?l.C0.ESC+l.C0.CR:l.C0.CR,v.cancel=!0;break;case 27:v.key=l.C0.ESC,d.altKey&&(v.key=l.C0.ESC+l.C0.ESC),v.cancel=!0;break;case 37:if(d.metaKey)break;m?(v.key=l.C0.ESC+"[1;"+(m+1)+"D",v.key===l.C0.ESC+"[1;3D"&&(v.key=l.C0.ESC+(p?"b":"[1;5D"))):v.key=h?l.C0.ESC+"OD":l.C0.ESC+"[D";break;case 39:if(d.metaKey)break;m?(v.key=l.C0.ESC+"[1;"+(m+1)+"C",v.key===l.C0.ESC+"[1;3C"&&(v.key=l.C0.ESC+(p?"f":"[1;5C"))):v.key=h?l.C0.ESC+"OC":l.C0.ESC+"[C";break;case 38:if(d.metaKey)break;m?(v.key=l.C0.ESC+"[1;"+(m+1)+"A",p||v.key!==l.C0.ESC+"[1;3A"||(v.key=l.C0.ESC+"[1;5A")):v.key=h?l.C0.ESC+"OA":l.C0.ESC+"[A";break;case 40:if(d.metaKey)break;m?(v.key=l.C0.ESC+"[1;"+(m+1)+"B",p||v.key!==l.C0.ESC+"[1;3B"||(v.key=l.C0.ESC+"[1;5B")):v.key=h?l.C0.ESC+"OB":l.C0.ESC+"[B";break;case 45:d.shiftKey||d.ctrlKey||(v.key=l.C0.ESC+"[2~");break;case 46:v.key=m?l.C0.ESC+"[3;"+(m+1)+"~":l.C0.ESC+"[3~";break;case 36:v.key=m?l.C0.ESC+"[1;"+(m+1)+"H":h?l.C0.ESC+"OH":l.C0.ESC+"[H";break;case 35:v.key=m?l.C0.ESC+"[1;"+(m+1)+"F":h?l.C0.ESC+"OF":l.C0.ESC+"[F";break;case 33:d.shiftKey?v.type=2:d.ctrlKey?v.key=l.C0.ESC+"[5;"+(m+1)+"~":v.key=l.C0.ESC+"[5~";break;case 34:d.shiftKey?v.type=3:d.ctrlKey?v.key=l.C0.ESC+"[6;"+(m+1)+"~":v.key=l.C0.ESC+"[6~";break;case 112:v.key=m?l.C0.ESC+"[1;"+(m+1)+"P":l.C0.ESC+"OP";break;case 113:v.key=m?l.C0.ESC+"[1;"+(m+1)+"Q":l.C0.ESC+"OQ";break;case 114:v.key=m?l.C0.ESC+"[1;"+(m+1)+"R":l.C0.ESC+"OR";break;case 115:v.key=m?l.C0.ESC+"[1;"+(m+1)+"S":l.C0.ESC+"OS";break;case 116:v.key=m?l.C0.ESC+"[15;"+(m+1)+"~":l.C0.ESC+"[15~";break;case 117:v.key=m?l.C0.ESC+"[17;"+(m+1)+"~":l.C0.ESC+"[17~";break;case 118:v.key=m?l.C0.ESC+"[18;"+(m+1)+"~":l.C0.ESC+"[18~";break;case 119:v.key=m?l.C0.ESC+"[19;"+(m+1)+"~":l.C0.ESC+"[19~";break;case 120:v.key=m?l.C0.ESC+"[20;"+(m+1)+"~":l.C0.ESC+"[20~";break;case 121:v.key=m?l.C0.ESC+"[21;"+(m+1)+"~":l.C0.ESC+"[21~";break;case 122:v.key=m?l.C0.ESC+"[23;"+(m+1)+"~":l.C0.ESC+"[23~";break;case 123:v.key=m?l.C0.ESC+"[24;"+(m+1)+"~":l.C0.ESC+"[24~";break;default:if(!d.ctrlKey||d.shiftKey||d.altKey||d.metaKey)if(p&&!g||!d.altKey||d.metaKey)!p||d.altKey||d.ctrlKey||d.shiftKey||!d.metaKey?d.key&&!d.ctrlKey&&!d.altKey&&!d.metaKey&&d.keyCode>=48&&d.key.length===1?v.key=d.key:d.key&&d.ctrlKey&&(d.key==="_"&&(v.key=l.C0.US),d.key==="@"&&(v.key=l.C0.NUL)):d.keyCode===65&&(v.type=1);else{const y=u[d.keyCode],_=y==null?void 0:y[d.shiftKey?1:0];if(_)v.key=l.C0.ESC+_;else if(d.keyCode>=65&&d.keyCode<=90){const b=d.ctrlKey?d.keyCode-64:d.keyCode+32;let k=String.fromCharCode(b);d.shiftKey&&(k=k.toUpperCase()),v.key=l.C0.ESC+k}else if(d.keyCode===32)v.key=l.C0.ESC+(d.ctrlKey?l.C0.NUL:" ");else if(d.key==="Dead"&&d.code.startsWith("Key")){let b=d.code.slice(3,4);d.shiftKey||(b=b.toLowerCase()),v.key=l.C0.ESC+b,v.cancel=!0}}else d.keyCode>=65&&d.keyCode<=90?v.key=String.fromCharCode(d.keyCode-64):d.keyCode===32?v.key=l.C0.NUL:d.keyCode>=51&&d.keyCode<=55?v.key=String.fromCharCode(d.keyCode-51+27):d.keyCode===56?v.key=l.C0.DEL:d.keyCode===219?v.key=l.C0.ESC:d.keyCode===220?v.key=l.C0.FS:d.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 d="";for(let h=l;h<u;++h){let p=c[h];p>65535?(p-=65536,d+=String.fromCharCode(55296+(p>>10))+String.fromCharCode(p%1024+56320)):d+=String.fromCharCode(p)}return d},a.StringToUtf32=class{constructor(){this._interim=0}clear(){this._interim=0}decode(c,l){const u=c.length;if(!u)return 0;let d=0,h=0;if(this._interim){const p=c.charCodeAt(h++);56320<=p&&p<=57343?l[d++]=1024*(this._interim-55296)+p-56320+65536:(l[d++]=this._interim,l[d++]=p),this._interim=0}for(let p=h;p<u;++p){const g=c.charCodeAt(p);if(55296<=g&&g<=56319){if(++p>=u)return this._interim=g,d;const v=c.charCodeAt(p);56320<=v&&v<=57343?l[d++]=1024*(g-55296)+v-56320+65536:(l[d++]=g,l[d++]=v)}else g!==65279&&(l[d++]=g)}return d}},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 d,h,p,g,v=0,m=0,y=0;if(this.interim[0]){let k=!1,w=this.interim[0];w&=(224&w)==192?31:(240&w)==224?15:7;let T,A=0;for(;(T=63&this.interim[++A])&&A<4;)w<<=6,w|=T;const C=(224&this.interim[0])==192?2:(240&this.interim[0])==224?3:4,E=C-A;for(;y<E;){if(y>=u)return 0;if(T=c[y++],(192&T)!=128){y--,k=!0;break}this.interim[A++]=T,w<<=6,w|=63&T}k||(C===2?w<128?y--:l[v++]=w:C===3?w<2048||w>=55296&&w<=57343||w===65279||(l[v++]=w):w<65536||w>1114111||(l[v++]=w)),this.interim.fill(0)}const _=u-4;let b=y;for(;b<u;){for(;!(!(b<_)||128&(d=c[b])||128&(h=c[b+1])||128&(p=c[b+2])||128&(g=c[b+3]));)l[v++]=d,l[v++]=h,l[v++]=p,l[v++]=g,b+=4;if(d=c[b++],d<128)l[v++]=d;else if((224&d)==192){if(b>=u)return this.interim[0]=d,v;if(h=c[b++],(192&h)!=128){b--;continue}if(m=(31&d)<<6|63&h,m<128){b--;continue}l[v++]=m}else if((240&d)==224){if(b>=u)return this.interim[0]=d,v;if(h=c[b++],(192&h)!=128){b--;continue}if(b>=u)return this.interim[0]=d,this.interim[1]=h,v;if(p=c[b++],(192&p)!=128){b--;continue}if(m=(15&d)<<12|(63&h)<<6|63&p,m<2048||m>=55296&&m<=57343||m===65279)continue;l[v++]=m}else if((248&d)==240){if(b>=u)return this.interim[0]=d,v;if(h=c[b++],(192&h)!=128){b--;continue}if(b>=u)return this.interim[0]=d,this.interim[1]=h,v;if(p=c[b++],(192&p)!=128){b--;continue}if(b>=u)return this.interim[0]=d,this.interim[1]=h,this.interim[2]=p,v;if(g=c[b++],(192&g)!=128){b--;continue}if(m=(7&d)<<18|(63&h)<<12|(63&p)<<6|63&g,m<65536||m>1114111)continue;l[v++]=m}}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 d=0;d<c.length;++d)u.fill(0,c[d][0],c[d][1]+1)}}wcwidth(d){return d<32?0:d<127?1:d<65536?u[d]:function(h,p){let g,v=0,m=p.length-1;if(h<p[0][0]||h>p[m][1])return!1;for(;m>=v;)if(g=v+m>>1,h>p[g][1])v=g+1;else{if(!(h<p[g][0]))return!0;m=g-1}return!1}(d,l)?0:d>=131072&&d<=196605||d>=196608&&d<=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 d 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,g){if(g!==void 0&&this._syncCalls>g)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 m=this._callbacks.shift();m&&m()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(p,g){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(g),void this._innerWrite();setTimeout(()=>this._innerWrite())}this._pendingData+=p.length,this._writeBuffer.push(p),this._callbacks.push(g)}_innerWrite(p=0,g=!0){const v=p||Date.now();for(;this._writeBuffer.length>this._bufferOffset;){const m=this._writeBuffer[this._bufferOffset],y=this._action(m,g);if(y){const b=k=>Date.now()-v>=12?setTimeout(()=>this._innerWrite(0,k)):this._innerWrite(v,k);return void y.catch(k=>(queueMicrotask(()=>{throw k}),Promise.resolve(!1))).then(b)}const _=this._callbacks[this._bufferOffset];if(_&&_(),this._bufferOffset++,this._pendingData-=m.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=d},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(d,h){const p=d.toString(16),g=p.length<2?"0"+p:p;switch(h){case 4:return p[0];case 8:return g;case 12:return(g+g).slice(0,3);default:return g+g}}a.parseColor=function(d){if(!d)return;let h=d.toLowerCase();if(h.indexOf("rgb:")===0){h=h.slice(4);const p=c.exec(h);if(p){const g=p[1]?15:p[4]?255:p[7]?4095:65535;return[Math.round(parseInt(p[1]||p[4]||p[7]||p[10],16)/g*255),Math.round(parseInt(p[2]||p[5]||p[8]||p[11],16)/g*255),Math.round(parseInt(p[3]||p[6]||p[9]||p[12],16)/g*255)]}}else if(h.indexOf("#")===0&&(h=h.slice(1),l.exec(h)&&[3,6,9,12].includes(h.length))){const p=h.length/3,g=[0,0,0];for(let v=0;v<3;++v){const m=parseInt(h.slice(p*v,p*v+p),16);g[v]=p===1?m<<4:p===2?m:p===3?m>>4:m>>8}return g}},a.toRgbString=function(d,h=16){const[p,g,v]=d;return`rgb:${u(p,h)}/${u(g,h)}/${u(v,h)}`}},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),d=c(5770),h=[];a.DcsParser=class{constructor(){this._handlers=Object.create(null),this._active=h,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=h}registerHandler(g,v){this._handlers[g]===void 0&&(this._handlers[g]=[]);const m=this._handlers[g];return m.push(v),{dispose:()=>{const y=m.indexOf(v);y!==-1&&m.splice(y,1)}}}clearHandler(g){this._handlers[g]&&delete this._handlers[g]}setHandlerFallback(g){this._handlerFb=g}reset(){if(this._active.length)for(let g=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;g>=0;--g)this._active[g].unhook(!1);this._stack.paused=!1,this._active=h,this._ident=0}hook(g,v){if(this.reset(),this._ident=g,this._active=this._handlers[g]||h,this._active.length)for(let m=this._active.length-1;m>=0;m--)this._active[m].hook(v);else this._handlerFb(this._ident,"HOOK",v)}put(g,v,m){if(this._active.length)for(let y=this._active.length-1;y>=0;y--)this._active[y].put(g,v,m);else this._handlerFb(this._ident,"PUT",(0,l.utf32ToString)(g,v,m))}unhook(g,v=!0){if(this._active.length){let m=!1,y=this._active.length-1,_=!1;if(this._stack.paused&&(y=this._stack.loopPosition-1,m=v,_=this._stack.fallThrough,this._stack.paused=!1),!_&&m===!1){for(;y>=0&&(m=this._active[y].unhook(g),m!==!0);y--)if(m instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=y,this._stack.fallThrough=!1,m;y--}for(;y>=0;y--)if(m=this._active[y].unhook(!1),m instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=y,this._stack.fallThrough=!0,m}else this._handlerFb(this._ident,"UNHOOK",g);this._active=h,this._ident=0}};const p=new u.Params;p.addParam(0),a.DcsHandler=class{constructor(g){this._handler=g,this._data="",this._params=p,this._hitLimit=!1}hook(g){this._params=g.length>1||g.params[0]?g.clone():p,this._data="",this._hitLimit=!1}put(g,v,m){this._hitLimit||(this._data+=(0,l.utf32ToString)(g,v,m),this._data.length>d.PAYLOAD_LIMIT&&(this._data="",this._hitLimit=!0))}unhook(g){let v=!1;if(this._hitLimit)v=!1;else if(g&&(v=this._handler(this._data,this._params),v instanceof Promise))return v.then(m=>(this._params=p,this._data="",this._hitLimit=!1,m));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),d=c(6242),h=c(6351);class p{constructor(y){this.table=new Uint8Array(y)}setDefault(y,_){this.table.fill(y<<4|_)}add(y,_,b,k){this.table[_<<8|y]=b<<4|k}addMany(y,_,b,k){for(let w=0;w<y.length;w++)this.table[_<<8|y[w]]=b<<4|k}}a.TransitionTable=p;const g=160;a.VT500_TRANSITION_TABLE=function(){const m=new p(4095),y=Array.apply(null,Array(256)).map((A,C)=>C),_=(A,C)=>y.slice(A,C),b=_(32,127),k=_(0,24);k.push(25),k.push.apply(k,_(28,32));const w=_(0,14);let T;for(T in m.setDefault(1,0),m.addMany(b,0,2,0),w)m.addMany([24,26,153,154],T,3,0),m.addMany(_(128,144),T,3,0),m.addMany(_(144,152),T,3,0),m.add(156,T,0,0),m.add(27,T,11,1),m.add(157,T,4,8),m.addMany([152,158,159],T,0,7),m.add(155,T,11,3),m.add(144,T,11,9);return m.addMany(k,0,3,0),m.addMany(k,1,3,1),m.add(127,1,0,1),m.addMany(k,8,0,8),m.addMany(k,3,3,3),m.add(127,3,0,3),m.addMany(k,4,3,4),m.add(127,4,0,4),m.addMany(k,6,3,6),m.addMany(k,5,3,5),m.add(127,5,0,5),m.addMany(k,2,3,2),m.add(127,2,0,2),m.add(93,1,4,8),m.addMany(b,8,5,8),m.add(127,8,5,8),m.addMany([156,27,24,26,7],8,6,0),m.addMany(_(28,32),8,0,8),m.addMany([88,94,95],1,0,7),m.addMany(b,7,0,7),m.addMany(k,7,0,7),m.add(156,7,0,0),m.add(127,7,0,7),m.add(91,1,11,3),m.addMany(_(64,127),3,7,0),m.addMany(_(48,60),3,8,4),m.addMany([60,61,62,63],3,9,4),m.addMany(_(48,60),4,8,4),m.addMany(_(64,127),4,7,0),m.addMany([60,61,62,63],4,0,6),m.addMany(_(32,64),6,0,6),m.add(127,6,0,6),m.addMany(_(64,127),6,0,0),m.addMany(_(32,48),3,9,5),m.addMany(_(32,48),5,9,5),m.addMany(_(48,64),5,0,6),m.addMany(_(64,127),5,7,0),m.addMany(_(32,48),4,9,5),m.addMany(_(32,48),1,9,2),m.addMany(_(32,48),2,9,2),m.addMany(_(48,127),2,10,0),m.addMany(_(48,80),1,10,0),m.addMany(_(81,88),1,10,0),m.addMany([89,90,92],1,10,0),m.addMany(_(96,127),1,10,0),m.add(80,1,11,9),m.addMany(k,9,0,9),m.add(127,9,0,9),m.addMany(_(28,32),9,0,9),m.addMany(_(32,48),9,9,12),m.addMany(_(48,60),9,8,10),m.addMany([60,61,62,63],9,9,10),m.addMany(k,11,0,11),m.addMany(_(32,128),11,0,11),m.addMany(_(28,32),11,0,11),m.addMany(k,10,0,10),m.add(127,10,0,10),m.addMany(_(28,32),10,0,10),m.addMany(_(48,60),10,8,10),m.addMany([60,61,62,63],10,0,11),m.addMany(_(32,48),10,9,12),m.addMany(k,12,0,12),m.add(127,12,0,12),m.addMany(_(28,32),12,0,12),m.addMany(_(32,48),12,9,12),m.addMany(_(48,64),12,0,11),m.addMany(_(64,127),12,12,13),m.addMany(_(64,127),10,12,13),m.addMany(_(64,127),9,12,13),m.addMany(k,13,13,13),m.addMany(b,13,13,13),m.add(127,13,0,13),m.addMany([27,156,24,26],13,14,0),m.add(g,0,2,0),m.add(g,8,5,8),m.add(g,6,0,6),m.add(g,11,0,11),m.add(g,13,13,13),m}();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,k)=>{},this._executeHandlerFb=_=>{},this._csiHandlerFb=(_,b)=>{},this._escHandlerFb=_=>{},this._errorHandlerFb=_=>_,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 d.OscParser),this._dcsParser=this.register(new h.DcsParser),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:"\\"},()=>!0)}_identifier(y,_=[64,126]){let b=0;if(y.prefix){if(y.prefix.length>1)throw new Error("only one byte as prefix supported");if(b=y.prefix.charCodeAt(0),b&&60>b||b>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 w=0;w<y.intermediates.length;++w){const T=y.intermediates.charCodeAt(w);if(32>T||T>47)throw new Error("intermediate must be in range 0x20 .. 0x2f");b<<=8,b|=T}}if(y.final.length!==1)throw new Error("final must be a single byte");const k=y.final.charCodeAt(0);if(_[0]>k||k>_[1])throw new Error(`final must be in range ${_[0]} .. ${_[1]}`);return b<<=8,b|=k,b}identToString(y){const _=[];for(;y;)_.push(String.fromCharCode(255&y)),y>>=8;return _.reverse().join("")}setPrintHandler(y){this._printHandler=y}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(y,_){const b=this._identifier(y,[48,126]);this._escHandlers[b]===void 0&&(this._escHandlers[b]=[]);const k=this._escHandlers[b];return k.push(_),{dispose:()=>{const w=k.indexOf(_);w!==-1&&k.splice(w,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,_){this._executeHandlers[y.charCodeAt(0)]=_}clearExecuteHandler(y){this._executeHandlers[y.charCodeAt(0)]&&delete this._executeHandlers[y.charCodeAt(0)]}setExecuteHandlerFallback(y){this._executeHandlerFb=y}registerCsiHandler(y,_){const b=this._identifier(y);this._csiHandlers[b]===void 0&&(this._csiHandlers[b]=[]);const k=this._csiHandlers[b];return k.push(_),{dispose:()=>{const w=k.indexOf(_);w!==-1&&k.splice(w,1)}}}clearCsiHandler(y){this._csiHandlers[this._identifier(y)]&&delete this._csiHandlers[this._identifier(y)]}setCsiHandlerFallback(y){this._csiHandlerFb=y}registerDcsHandler(y,_){return this._dcsParser.registerHandler(this._identifier(y),_)}clearDcsHandler(y){this._dcsParser.clearHandler(this._identifier(y))}setDcsHandlerFallback(y){this._dcsParser.setHandlerFallback(y)}registerOscHandler(y,_){return this._oscParser.registerHandler(y,_)}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,k,w){this._parseStack.state=y,this._parseStack.handlers=_,this._parseStack.handlerPos=b,this._parseStack.transition=k,this._parseStack.chunkPos=w}parse(y,_,b){let k,w=0,T=0,A=0;if(this._parseStack.state)if(this._parseStack.state===2)this._parseStack.state=0,A=this._parseStack.chunkPos+1;else{if(b===void 0||this._parseStack.state===1)throw this._parseStack.state=1,new Error("improper continuation due to previous async handler, giving up parsing");const C=this._parseStack.handlers;let E=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(b===!1&&E>-1){for(;E>=0&&(k=C[E](this._params),k!==!0);E--)if(k instanceof Promise)return this._parseStack.handlerPos=E,k}this._parseStack.handlers=[];break;case 4:if(b===!1&&E>-1){for(;E>=0&&(k=C[E](),k!==!0);E--)if(k instanceof Promise)return this._parseStack.handlerPos=E,k}this._parseStack.handlers=[];break;case 6:if(w=y[this._parseStack.chunkPos],k=this._dcsParser.unhook(w!==24&&w!==26,b),k)return k;w===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(w=y[this._parseStack.chunkPos],k=this._oscParser.end(w!==24&&w!==26,b),k)return k;w===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0}this._parseStack.state=0,A=this._parseStack.chunkPos+1,this.precedingCodepoint=0,this.currentState=15&this._parseStack.transition}for(let C=A;C<_;++C){switch(w=y[C],T=this._transitions.table[this.currentState<<8|(w<160?w:g)],T>>4){case 2:for(let O=C+1;;++O){if(O>=_||(w=y[O])<32||w>126&&w<g){this._printHandler(y,C,O),C=O-1;break}if(++O>=_||(w=y[O])<32||w>126&&w<g){this._printHandler(y,C,O),C=O-1;break}if(++O>=_||(w=y[O])<32||w>126&&w<g){this._printHandler(y,C,O),C=O-1;break}if(++O>=_||(w=y[O])<32||w>126&&w<g){this._printHandler(y,C,O),C=O-1;break}}break;case 3:this._executeHandlers[w]?this._executeHandlers[w]():this._executeHandlerFb(w),this.precedingCodepoint=0;break;case 0:break;case 1:if(this._errorHandler({position:C,code:w,currentState:this.currentState,collect:this._collect,params:this._params,abort:!1}).abort)return;break;case 7:const E=this._csiHandlers[this._collect<<8|w];let x=E?E.length-1:-1;for(;x>=0&&(k=E[x](this._params),k!==!0);x--)if(k instanceof Promise)return this._preserveStack(3,E,x,T,C),k;x<0&&this._csiHandlerFb(this._collect<<8|w,this._params),this.precedingCodepoint=0;break;case 8:do switch(w){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(w-48)}while(++C<_&&(w=y[C])>47&&w<60);C--;break;case 9:this._collect<<=8,this._collect|=w;break;case 10:const D=this._escHandlers[this._collect<<8|w];let N=D?D.length-1:-1;for(;N>=0&&(k=D[N](),k!==!0);N--)if(k instanceof Promise)return this._preserveStack(4,D,N,T,C),k;N<0&&this._escHandlerFb(this._collect<<8|w),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|w,this._params);break;case 13:for(let O=C+1;;++O)if(O>=_||(w=y[O])===24||w===26||w===27||w>127&&w<g){this._dcsParser.put(y,C,O),C=O-1;break}break;case 14:if(k=this._dcsParser.unhook(w!==24&&w!==26),k)return this._preserveStack(6,[],0,T,C),k;w===27&&(T|=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 O=C+1;;O++)if(O>=_||(w=y[O])<32||w>127&&w<g){this._oscParser.put(y,C,O),C=O-1;break}break;case 6:if(k=this._oscParser.end(w!==24&&w!==26),k)return this._preserveStack(5,[],0,T,C),k;w===27&&(T|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingCodepoint=0}this.currentState=15&T}}}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),d=[];a.OscParser=class{constructor(){this._state=0,this._active=d,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(h,p){this._handlers[h]===void 0&&(this._handlers[h]=[]);const g=this._handlers[h];return g.push(p),{dispose:()=>{const v=g.indexOf(p);v!==-1&&g.splice(v,1)}}}clearHandler(h){this._handlers[h]&&delete this._handlers[h]}setHandlerFallback(h){this._handlerFb=h}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=d}reset(){if(this._state===2)for(let h=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;h>=0;--h)this._active[h].end(!1);this._stack.paused=!1,this._active=d,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||d,this._active.length)for(let h=this._active.length-1;h>=0;h--)this._active[h].start();else this._handlerFb(this._id,"START")}_put(h,p,g){if(this._active.length)for(let v=this._active.length-1;v>=0;v--)this._active[v].put(h,p,g);else this._handlerFb(this._id,"PUT",(0,u.utf32ToString)(h,p,g))}start(){this.reset(),this._state=1}put(h,p,g){if(this._state!==3){if(this._state===1)for(;p<g;){const v=h[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&&g-p>0&&this._put(h,p,g)}}end(h,p=!0){if(this._state!==0){if(this._state!==3)if(this._state===1&&this._start(),this._active.length){let g=!1,v=this._active.length-1,m=!1;if(this._stack.paused&&(v=this._stack.loopPosition-1,g=p,m=this._stack.fallThrough,this._stack.paused=!1),!m&&g===!1){for(;v>=0&&(g=this._active[v].end(h),g!==!0);v--)if(g instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=v,this._stack.fallThrough=!1,g;v--}for(;v>=0;v--)if(g=this._active[v].end(!1),g instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=v,this._stack.fallThrough=!0,g}else this._handlerFb(this._id,"END",h);this._active=d,this._id=-1,this._state=0}}},a.OscHandler=class{constructor(h){this._handler=h,this._data="",this._hitLimit=!1}start(){this._data="",this._hitLimit=!1}put(h,p,g){this._hitLimit||(this._data+=(0,u.utf32ToString)(h,p,g),this._data.length>l.PAYLOAD_LIMIT&&(this._data="",this._hitLimit=!0))}end(h){let p=!1;if(this._hitLimit)p=!1;else if(h&&(p=this._handler(this._data),p instanceof Promise))return p.then(g=>(this._data="",this._hitLimit=!1,g));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(d){const h=new l;if(!d.length)return h;for(let p=Array.isArray(d[0])?1:0;p<d.length;++p){const g=d[p];if(Array.isArray(g))for(let v=0;v<g.length;++v)h.addSubParam(g[v]);else h.addParam(g)}return h}constructor(d=32,h=32){if(this.maxLength=d,this.maxSubParamsLength=h,h>256)throw new Error("maxSubParamsLength must not be greater than 256");this.params=new Int32Array(d),this.length=0,this._subParams=new Int32Array(h),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(d),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}clone(){const d=new l(this.maxLength,this.maxSubParamsLength);return d.params.set(this.params),d.length=this.length,d._subParams.set(this._subParams),d._subParamsLength=this._subParamsLength,d._subParamsIdx.set(this._subParamsIdx),d._rejectDigits=this._rejectDigits,d._rejectSubDigits=this._rejectSubDigits,d._digitIsSub=this._digitIsSub,d}toArray(){const d=[];for(let h=0;h<this.length;++h){d.push(this.params[h]);const p=this._subParamsIdx[h]>>8,g=255&this._subParamsIdx[h];g-p>0&&d.push(Array.prototype.slice.call(this._subParams,p,g))}return d}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(d){if(this._digitIsSub=!1,this.length>=this.maxLength)this._rejectDigits=!0;else{if(d<-1)throw new Error("values lesser than -1 are not allowed");this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=d>c?c:d}}addSubParam(d){if(this._digitIsSub=!0,this.length)if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength)this._rejectSubDigits=!0;else{if(d<-1)throw new Error("values lesser than -1 are not allowed");this._subParams[this._subParamsLength++]=d>c?c:d,this._subParamsIdx[this.length-1]++}}hasSubParams(d){return(255&this._subParamsIdx[d])-(this._subParamsIdx[d]>>8)>0}getSubParams(d){const h=this._subParamsIdx[d]>>8,p=255&this._subParamsIdx[d];return p-h>0?this._subParams.subarray(h,p):null}getSubParamsAll(){const d={};for(let h=0;h<this.length;++h){const p=this._subParamsIdx[h]>>8,g=255&this._subParamsIdx[h];g-p>0&&(d[h]=this._subParams.slice(p,g))}return d}addDigit(d){let h;if(this._rejectDigits||!(h=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;const p=this._digitIsSub?this._subParams:this.params,g=p[h-1];p[h-1]=~g?Math.min(10*g+d,c):d}}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(d,h){this._buffer=d,this.type=h}init(d){return this._buffer=d,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(d){const h=this._buffer.lines.get(d);if(h)return new l.BufferLineApiView(h)}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,d){if(!(u<0||u>=this._line.length))return d?(this._line.loadCell(u,d),d):this._line.loadCell(u,new l.CellData)}translateToString(u,d,h){return this._line.translateToString(u,d,h)}}},8285:(o,a,c)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.BufferNamespaceApi=void 0;const l=c(8771),u=c(8460),d=c(844);class h extends d.Disposable{constructor(g){super(),this._core=g,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=h},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,d)=>l(u,d.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(m,y,_,b){var k,w=arguments.length,T=w<3?y:b===null?b=Object.getOwnPropertyDescriptor(y,_):b;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")T=Reflect.decorate(m,y,_,b);else for(var A=m.length-1;A>=0;A--)(k=m[A])&&(T=(w<3?k(T):w>3?k(y,_,T):k(y,_))||T);return w>3&&T&&Object.defineProperty(y,_,T),T},u=this&&this.__param||function(m,y){return function(_,b){y(_,b,m)}};Object.defineProperty(a,"__esModule",{value:!0}),a.BufferService=a.MINIMUM_ROWS=a.MINIMUM_COLS=void 0;const d=c(8460),h=c(844),p=c(5295),g=c(2585);a.MINIMUM_COLS=2,a.MINIMUM_ROWS=1;let v=a.BufferService=class extends h.Disposable{get buffer(){return this.buffers.active}constructor(m){super(),this.isUserScrolling=!1,this._onResize=this.register(new d.EventEmitter),this.onResize=this._onResize.event,this._onScroll=this.register(new d.EventEmitter),this.onScroll=this._onScroll.event,this.cols=Math.max(m.rawOptions.cols||0,a.MINIMUM_COLS),this.rows=Math.max(m.rawOptions.rows||0,a.MINIMUM_ROWS),this.buffers=this.register(new p.BufferSet(m,this))}resize(m,y){this.cols=m,this.rows=y,this.buffers.resize(m,y),this._onResize.fire({cols:m,rows:y})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(m,y=!1){const _=this.buffer;let b;b=this._cachedBlankLine,b&&b.length===this.cols&&b.getFg(0)===m.fg&&b.getBg(0)===m.bg||(b=_.getBlankLine(m,y),this._cachedBlankLine=b),b.isWrapped=y;const k=_.ybase+_.scrollTop,w=_.ybase+_.scrollBottom;if(_.scrollTop===0){const T=_.lines.isFull;w===_.lines.length-1?T?_.lines.recycle().copyFrom(b):_.lines.push(b.clone()):_.lines.splice(w+1,0,b.clone()),T?this.isUserScrolling&&(_.ydisp=Math.max(_.ydisp-1,0)):(_.ybase++,this.isUserScrolling||_.ydisp++)}else{const T=w-k+1;_.lines.shiftElements(k+1,T-1,-1),_.lines.set(w,b.clone())}this.isUserScrolling||(_.ydisp=_.ybase),this._onScroll.fire(_.ydisp)}scrollLines(m,y,_){const b=this.buffer;if(m<0){if(b.ydisp===0)return;this.isUserScrolling=!0}else m+b.ydisp>=b.ybase&&(this.isUserScrolling=!1);const k=b.ydisp;b.ydisp=Math.max(Math.min(b.ydisp+m,b.ybase),0),k!==b.ydisp&&(y||this._onScroll.fire(b.ydisp))}};a.BufferService=v=l([u(0,g.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(b,k,w,T){var A,C=arguments.length,E=C<3?k:T===null?T=Object.getOwnPropertyDescriptor(k,w):T;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")E=Reflect.decorate(b,k,w,T);else for(var x=b.length-1;x>=0;x--)(A=b[x])&&(E=(C<3?A(E):C>3?A(k,w,E):A(k,w))||E);return C>3&&E&&Object.defineProperty(k,w,E),E},u=this&&this.__param||function(b,k){return function(w,T){k(w,T,b)}};Object.defineProperty(a,"__esModule",{value:!0}),a.CoreMouseService=void 0;const d=c(2585),h=c(8460),p=c(844),g={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:b=>b.button!==4&&b.action===1&&(b.ctrl=!1,b.alt=!1,b.shift=!1,!0)},VT200:{events:19,restrict:b=>b.action!==32},DRAG:{events:23,restrict:b=>b.action!==32||b.button!==3},ANY:{events:31,restrict:b=>!0}};function v(b,k){let w=(b.ctrl?16:0)|(b.shift?4:0)|(b.alt?8:0);return b.button===4?(w|=64,w|=b.action):(w|=3&b.button,4&b.button&&(w|=64),8&b.button&&(w|=128),b.action===32?w|=32:b.action!==0||k||(w|=3)),w}const m=String.fromCharCode,y={DEFAULT:b=>{const k=[v(b,!1)+32,b.col+32,b.row+32];return k[0]>255||k[1]>255||k[2]>255?"":`\x1B[M${m(k[0])}${m(k[1])}${m(k[2])}`},SGR:b=>{const k=b.action===0&&b.button!==4?"m":"M";return`\x1B[<${v(b,!0)};${b.col};${b.row}${k}`},SGR_PIXELS:b=>{const k=b.action===0&&b.button!==4?"m":"M";return`\x1B[<${v(b,!0)};${b.x};${b.y}${k}`}};let _=a.CoreMouseService=class extends p.Disposable{constructor(b,k){super(),this._bufferService=b,this._coreService=k,this._protocols={},this._encodings={},this._activeProtocol="",this._activeEncoding="",this._lastEvent=null,this._onProtocolChange=this.register(new h.EventEmitter),this.onProtocolChange=this._onProtocolChange.event;for(const w of Object.keys(g))this.addProtocol(w,g[w]);for(const w of Object.keys(y))this.addEncoding(w,y[w]);this.reset()}addProtocol(b,k){this._protocols[b]=k}addEncoding(b,k){this._encodings[b]=k}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return this._protocols[this._activeProtocol].events!==0}set activeProtocol(b){if(!this._protocols[b])throw new Error(`unknown protocol "${b}"`);this._activeProtocol=b,this._onProtocolChange.fire(this._protocols[b].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(b){if(!this._encodings[b])throw new Error(`unknown encoding "${b}"`);this._activeEncoding=b}reset(){this.activeProtocol="NONE",this.activeEncoding="DEFAULT",this._lastEvent=null}triggerMouseEvent(b){if(b.col<0||b.col>=this._bufferService.cols||b.row<0||b.row>=this._bufferService.rows||b.button===4&&b.action===32||b.button===3&&b.action!==32||b.button!==4&&(b.action===2||b.action===3)||(b.col++,b.row++,b.action===32&&this._lastEvent&&this._equalEvents(this._lastEvent,b,this._activeEncoding==="SGR_PIXELS"))||!this._protocols[this._activeProtocol].restrict(b))return!1;const k=this._encodings[this._activeEncoding](b);return k&&(this._activeEncoding==="DEFAULT"?this._coreService.triggerBinaryEvent(k):this._coreService.triggerDataEvent(k,!0)),this._lastEvent=b,!0}explainEvents(b){return{down:!!(1&b),up:!!(2&b),drag:!!(4&b),move:!!(8&b),wheel:!!(16&b)}}_equalEvents(b,k,w){if(w){if(b.x!==k.x||b.y!==k.y)return!1}else if(b.col!==k.col||b.row!==k.row)return!1;return b.button===k.button&&b.action===k.action&&b.ctrl===k.ctrl&&b.alt===k.alt&&b.shift===k.shift}};a.CoreMouseService=_=l([u(0,d.IBufferService),u(1,d.ICoreService)],_)},6975:function(o,a,c){var l=this&&this.__decorate||function(_,b,k,w){var T,A=arguments.length,C=A<3?b:w===null?w=Object.getOwnPropertyDescriptor(b,k):w;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")C=Reflect.decorate(_,b,k,w);else for(var E=_.length-1;E>=0;E--)(T=_[E])&&(C=(A<3?T(C):A>3?T(b,k,C):T(b,k))||C);return A>3&&C&&Object.defineProperty(b,k,C),C},u=this&&this.__param||function(_,b){return function(k,w){b(k,w,_)}};Object.defineProperty(a,"__esModule",{value:!0}),a.CoreService=void 0;const d=c(1439),h=c(8460),p=c(844),g=c(2585),v=Object.freeze({insertMode:!1}),m=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,k){super(),this._bufferService=_,this._logService=b,this._optionsService=k,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this.register(new h.EventEmitter),this.onData=this._onData.event,this._onUserInput=this.register(new h.EventEmitter),this.onUserInput=this._onUserInput.event,this._onBinary=this.register(new h.EventEmitter),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this.register(new h.EventEmitter),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=(0,d.clone)(v),this.decPrivateModes=(0,d.clone)(m)}reset(){this.modes=(0,d.clone)(v),this.decPrivateModes=(0,d.clone)(m)}triggerDataEvent(_,b=!1){if(this._optionsService.rawOptions.disableStdin)return;const k=this._bufferService.buffer;b&&this._optionsService.rawOptions.scrollOnUserInput&&k.ybase!==k.ydisp&&this._onRequestScrollToBottom.fire(),b&&this._onUserInput.fire(),this._logService.debug(`sending data "${_}"`,()=>_.split("").map(w=>w.charCodeAt(0))),this._onData.fire(_)}triggerBinaryEvent(_){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${_}"`,()=>_.split("").map(b=>b.charCodeAt(0))),this._onBinary.fire(_))}};a.CoreService=y=l([u(0,g.IBufferService),u(1,g.ILogService),u(2,g.IOptionsService)],y)},9074:(o,a,c)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.DecorationService=void 0;const l=c(8055),u=c(8460),d=c(844),h=c(6106);let p=0,g=0;class v extends d.Disposable{get decorations(){return this._decorations.values()}constructor(){super(),this._decorations=new h.SortedList(_=>_==null?void 0:_.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,d.toDisposable)(()=>this.reset()))}registerDecoration(_){if(_.marker.isDisposed)return;const b=new m(_);if(b){const k=b.marker.onDispose(()=>b.dispose());b.onDispose(()=>{b&&(this._decorations.delete(b)&&this._onDecorationRemoved.fire(b),k.dispose())}),this._decorations.insert(b),this._onDecorationRegistered.fire(b)}return b}reset(){for(const _ of this._decorations.values())_.dispose();this._decorations.clear()}*getDecorationsAtCell(_,b,k){var w,T,A;let C=0,E=0;for(const x of this._decorations.getKeyIterator(b))C=(w=x.options.x)!==null&&w!==void 0?w:0,E=C+((T=x.options.width)!==null&&T!==void 0?T:1),_>=C&&_<E&&(!k||((A=x.options.layer)!==null&&A!==void 0?A:"bottom")===k)&&(yield x)}forEachDecorationAtCell(_,b,k,w){this._decorations.forEachByKey(b,T=>{var A,C,E;p=(A=T.options.x)!==null&&A!==void 0?A:0,g=p+((C=T.options.width)!==null&&C!==void 0?C:1),_>=p&&_<g&&(!k||((E=T.options.layer)!==null&&E!==void 0?E:"bottom")===k)&&w(T)})}}a.DecorationService=v;class m extends d.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(_){super(),this.options=_,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=_.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 d{constructor(...p){this._entries=new Map;for(const[g,v]of p)this.set(g,v)}set(p,g){const v=this._entries.get(p);return this._entries.set(p,g),v}forEach(p){for(const[g,v]of this._entries.entries())p(g,v)}has(p){return this._entries.has(p)}get(p){return this._entries.get(p)}}a.ServiceCollection=d,a.InstantiationService=class{constructor(){this._services=new d,this._services.set(l.IInstantiationService,this)}setService(h,p){this._services.set(h,p)}getService(h){return this._services.get(h)}createInstance(h,...p){const g=(0,u.getServiceDependencies)(h).sort((y,_)=>y.index-_.index),v=[];for(const y of g){const _=this._services.get(y.id);if(!_)throw new Error(`[createInstance] ${h.name} depends on UNKNOWN service ${y.id}.`);v.push(_)}const m=g.length>0?g[0].index:p.length;if(p.length!==m)throw new Error(`[createInstance] First service dependency of ${h.name} at position ${m+1} conflicts with ${p.length} static arguments`);return new h(...p,...v)}}},7866:function(o,a,c){var l=this&&this.__decorate||function(m,y,_,b){var k,w=arguments.length,T=w<3?y:b===null?b=Object.getOwnPropertyDescriptor(y,_):b;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")T=Reflect.decorate(m,y,_,b);else for(var A=m.length-1;A>=0;A--)(k=m[A])&&(T=(w<3?k(T):w>3?k(y,_,T):k(y,_))||T);return w>3&&T&&Object.defineProperty(y,_,T),T},u=this&&this.__param||function(m,y){return function(_,b){y(_,b,m)}};Object.defineProperty(a,"__esModule",{value:!0}),a.traceCall=a.setTraceLogger=a.LogService=void 0;const d=c(844),h=c(2585),p={trace:h.LogLevelEnum.TRACE,debug:h.LogLevelEnum.DEBUG,info:h.LogLevelEnum.INFO,warn:h.LogLevelEnum.WARN,error:h.LogLevelEnum.ERROR,off:h.LogLevelEnum.OFF};let g,v=a.LogService=class extends d.Disposable{get logLevel(){return this._logLevel}constructor(m){super(),this._optionsService=m,this._logLevel=h.LogLevelEnum.OFF,this._updateLogLevel(),this.register(this._optionsService.onSpecificOptionChange("logLevel",()=>this._updateLogLevel())),g=this}_updateLogLevel(){this._logLevel=p[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(m){for(let y=0;y<m.length;y++)typeof m[y]=="function"&&(m[y]=m[y]())}_log(m,y,_){this._evalLazyOptionalParams(_),m.call(console,(this._optionsService.options.logger?"":"xterm.js: ")+y,..._)}trace(m,...y){var _,b;this._logLevel<=h.LogLevelEnum.TRACE&&this._log((b=(_=this._optionsService.options.logger)===null||_===void 0?void 0:_.trace.bind(this._optionsService.options.logger))!==null&&b!==void 0?b:console.log,m,y)}debug(m,...y){var _,b;this._logLevel<=h.LogLevelEnum.DEBUG&&this._log((b=(_=this._optionsService.options.logger)===null||_===void 0?void 0:_.debug.bind(this._optionsService.options.logger))!==null&&b!==void 0?b:console.log,m,y)}info(m,...y){var _,b;this._logLevel<=h.LogLevelEnum.INFO&&this._log((b=(_=this._optionsService.options.logger)===null||_===void 0?void 0:_.info.bind(this._optionsService.options.logger))!==null&&b!==void 0?b:console.info,m,y)}warn(m,...y){var _,b;this._logLevel<=h.LogLevelEnum.WARN&&this._log((b=(_=this._optionsService.options.logger)===null||_===void 0?void 0:_.warn.bind(this._optionsService.options.logger))!==null&&b!==void 0?b:console.warn,m,y)}error(m,...y){var _,b;this._logLevel<=h.LogLevelEnum.ERROR&&this._log((b=(_=this._optionsService.options.logger)===null||_===void 0?void 0:_.error.bind(this._optionsService.options.logger))!==null&&b!==void 0?b:console.error,m,y)}};a.LogService=v=l([u(0,h.IOptionsService)],v),a.setTraceLogger=function(m){g=m},a.traceCall=function(m,y,_){if(typeof _.value!="function")throw new Error("not supported");const b=_.value;_.value=function(...k){if(g.logLevel!==h.LogLevelEnum.TRACE)return b.apply(this,k);g.trace(`GlyphRenderer#${b.name}(${k.map(T=>JSON.stringify(T)).join(", ")})`);const w=b.apply(this,k);return g.trace(`GlyphRenderer#${b.name} return`,w),w}}},7302:(o,a,c)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.OptionsService=a.DEFAULT_OPTIONS=void 0;const l=c(8460),u=c(844),d=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:d.isMac,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:" ()[]{}',\"`",altClickMovesCursor:!0,convertEol:!1,termName:"xterm",cancelEvents:!1,overviewRulerWidth:0};const h=["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 m=Object.assign({},a.DEFAULT_OPTIONS);for(const y in v)if(y in m)try{const _=v[y];m[y]=this._sanitizeAndValidateOption(y,_)}catch(_){console.error(_)}this.rawOptions=m,this.options=Object.assign({},m),this._setupOptions()}onSpecificOptionChange(v,m){return this.onOptionChange(y=>{y===v&&m(this.rawOptions[v])})}onMultipleOptionChange(v,m){return this.onOptionChange(y=>{v.indexOf(y)!==-1&&m()})}_setupOptions(){const v=y=>{if(!(y in a.DEFAULT_OPTIONS))throw new Error(`No option with key "${y}"`);return this.rawOptions[y]},m=(y,_)=>{if(!(y in a.DEFAULT_OPTIONS))throw new Error(`No option with key "${y}"`);_=this._sanitizeAndValidateOption(y,_),this.rawOptions[y]!==_&&(this.rawOptions[y]=_,this._onOptionChange.fire(y))};for(const y in this.rawOptions){const _={get:v.bind(this,y),set:m.bind(this,y)};Object.defineProperty(this.options,y,_)}}_sanitizeAndValidateOption(v,m){switch(v){case"cursorStyle":if(m||(m=a.DEFAULT_OPTIONS[v]),!function(y){return y==="block"||y==="underline"||y==="bar"}(m))throw new Error(`"${m}" is not a valid value for ${v}`);break;case"wordSeparator":m||(m=a.DEFAULT_OPTIONS[v]);break;case"fontWeight":case"fontWeightBold":if(typeof m=="number"&&1<=m&&m<=1e3)break;m=h.includes(m)?m:a.DEFAULT_OPTIONS[v];break;case"cursorWidth":m=Math.floor(m);case"lineHeight":case"tabStopWidth":if(m<1)throw new Error(`${v} cannot be less than 1, value: ${m}`);break;case"minimumContrastRatio":m=Math.max(1,Math.min(21,Math.round(10*m)/10));break;case"scrollback":if((m=Math.min(m,4294967295))<0)throw new Error(`${v} cannot be less than 0, value: ${m}`);break;case"fastScrollSensitivity":case"scrollSensitivity":if(m<=0)throw new Error(`${v} cannot be less than or equal to 0, value: ${m}`);break;case"rows":case"cols":if(!m&&m!==0)throw new Error(`${v} must be numeric, value: ${m}`);break;case"windowsPty":m=m??{}}return m}}a.OptionsService=p},2660:function(o,a,c){var l=this&&this.__decorate||function(p,g,v,m){var y,_=arguments.length,b=_<3?g:m===null?m=Object.getOwnPropertyDescriptor(g,v):m;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")b=Reflect.decorate(p,g,v,m);else for(var k=p.length-1;k>=0;k--)(y=p[k])&&(b=(_<3?y(b):_>3?y(g,v,b):y(g,v))||b);return _>3&&b&&Object.defineProperty(g,v,b),b},u=this&&this.__param||function(p,g){return function(v,m){g(v,m,p)}};Object.defineProperty(a,"__esModule",{value:!0}),a.OscLinkService=void 0;const d=c(2585);let h=a.OscLinkService=class{constructor(p){this._bufferService=p,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(p){const g=this._bufferService.buffer;if(p.id===void 0){const k=g.addMarker(g.ybase+g.y),w={data:p,id:this._nextId++,lines:[k]};return k.onDispose(()=>this._removeMarkerFromLink(w,k)),this._dataByLinkId.set(w.id,w),w.id}const v=p,m=this._getEntryIdKey(v),y=this._entriesWithId.get(m);if(y)return this.addLineToLink(y.id,g.ybase+g.y),y.id;const _=g.addMarker(g.ybase+g.y),b={id:this._nextId++,key:this._getEntryIdKey(v),data:v,lines:[_]};return _.onDispose(()=>this._removeMarkerFromLink(b,_)),this._entriesWithId.set(b.key,b),this._dataByLinkId.set(b.id,b),b.id}addLineToLink(p,g){const v=this._dataByLinkId.get(p);if(v&&v.lines.every(m=>m.line!==g)){const m=this._bufferService.buffer.addMarker(g);v.lines.push(m),m.onDispose(()=>this._removeMarkerFromLink(v,m))}}getLinkData(p){var g;return(g=this._dataByLinkId.get(p))===null||g===void 0?void 0:g.data}_getEntryIdKey(p){return`${p.id};;${p.uri}`}_removeMarkerFromLink(p,g){const v=p.lines.indexOf(g);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=h=l([u(0,d.IBufferService)],h)},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 d=function(h,p,g){if(arguments.length!==3)throw new Error("@IServiceName-decorator can only be used to decorate a parameter");(function(v,m,y){m[c]===m?m[l].push({id:v,index:y}):(m[l]=[{id:v,index:y}],m[c]=m)})(d,h,g)};return d.toString=()=>u,a.serviceRegistry.set(u,d),d}},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(d){d[d.TRACE=0]="TRACE",d[d.DEBUG=1]="DEBUG",d[d.INFO=2]="INFO",d[d.WARN=3]="WARN",d[d.ERROR=4]="ERROR",d[d.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 d=new u.UnicodeV6;this.register(d),this._active=d.version,this._activeProvider=d}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(d){if(!this._providers[d])throw new Error(`unknown Unicode version "${d}"`);this._active=d,this._activeProvider=this._providers[d],this._onChange.fire(d)}register(d){this._providers[d.version]=d}wcwidth(d){return this._activeProvider.wcwidth(d)}getStringCellWidth(d){let h=0;const p=d.length;for(let g=0;g<p;++g){let v=d.charCodeAt(g);if(55296<=v&&v<=56319){if(++g>=p)return h+this.wcwidth(v);const m=d.charCodeAt(g);56320<=m&&m<=57343?v=1024*(v-55296)+m-56320+65536:h+=this.wcwidth(m)}h+=this.wcwidth(v)}return h}}}},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),d=i(8285),h=i(7975),p=i(7090),g=["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 _=k=>this._core.options[k],b=(k,w)=>{this._checkReadonlyOptions(k),this._core.options[k]=w};for(const k in this._core.options){const w={get:_.bind(this,k),set:b.bind(this,k)};Object.defineProperty(this._publicOptions,k,w)}}_checkReadonlyOptions(y){if(g.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 h.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 d.BufferNamespaceApi(this._core))),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){const y=this._core.coreService.decPrivateModes;let _="none";switch(this._core.coreMouseService.activeProtocol){case"X10":_="x10";break;case"VT200":_="vt200";break;case"DRAG":_="drag";break;case"ANY":_="any"}return{applicationCursorKeysMode:y.applicationCursorKeys,applicationKeypadMode:y.applicationKeypad,bracketedPasteMode:y.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:_,originMode:y.origin,reverseWraparoundMode:y.reverseWraparound,sendFocusMode:y.sendFocus,wraparoundMode:y.wraparound}}get options(){return this._publicOptions}set options(y){for(const _ in y)this._publicOptions[_]=y[_]}blur(){this._core.blur()}focus(){this._core.focus()}resize(y,_){this._verifyIntegers(y,_),this._core.resize(y,_)}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,k;return this._checkProposedApi(),this._verifyPositiveIntegers((_=y.x)!==null&&_!==void 0?_:0,(b=y.width)!==null&&b!==void 0?b:0,(k=y.height)!==null&&k!==void 0?k: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,_){this._verifyIntegers(y,_),this._core.selectLines(y,_)}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,_){this._core.write(y,_)}writeln(y,_){this._core.write(y),this._core.write(`\r
|
||
`,_)}paste(y){this._core.paste(y)}refresh(y,_){this._verifyIntegers(y,_),this._core.refresh(y,_)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(y){this._addonManager.loadAddon(this,y)}static get strings(){return a}_verifyIntegers(...y){for(const _ of y)if(_===1/0||isNaN(_)||_%1!=0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...y){for(const _ of y)if(_&&(_===1/0||isNaN(_)||_%1!=0||_<0))throw new Error("This API only accepts positive integers")}}o.Terminal=v})(),r})())})(EL);var vj=EL.exports;const cl=Object.create(null);cl.open="0";cl.close="1";cl.ping="2";cl.pong="3";cl.message="4";cl.upgrade="5";cl.noop="6";const Sw=Object.create(null);Object.keys(cl).forEach(s=>{Sw[cl[s]]=s});const HT={type:"error",data:"parser error"},xL=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",RL=typeof ArrayBuffer=="function",IL=s=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(s):s&&s.buffer instanceof ArrayBuffer,IE=({type:s,data:e},t,n)=>xL&&e instanceof Blob?t?n(e):kx(e,n):RL&&(e instanceof ArrayBuffer||IL(e))?t?n(e):kx(new Blob([e]),n):n(cl[s]+(e||"")),kx=(s,e)=>{const t=new FileReader;return t.onload=function(){const n=t.result.split(",")[1];e("b"+(n||""))},t.readAsDataURL(s)};function Cx(s){return s instanceof Uint8Array?s:s instanceof ArrayBuffer?new Uint8Array(s):new Uint8Array(s.buffer,s.byteOffset,s.byteLength)}let yC;function yj(s,e){if(xL&&s.data instanceof Blob)return s.data.arrayBuffer().then(Cx).then(e);if(RL&&(s.data instanceof ArrayBuffer||IL(s.data)))return e(Cx(s.data));IE(s,!1,t=>{yC||(yC=new TextEncoder),e(yC.encode(t))})}const Tx="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",jg=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let s=0;s<Tx.length;s++)jg[Tx.charCodeAt(s)]=s;const bj=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=jg[s.charCodeAt(n)],o=jg[s.charCodeAt(n+1)],a=jg[s.charCodeAt(n+2)],c=jg[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},_j=typeof ArrayBuffer=="function",PE=(s,e)=>{if(typeof s!="string")return{type:"message",data:PL(s,e)};const t=s.charAt(0);return t==="b"?{type:"message",data:wj(s.substring(1),e)}:Sw[t]?s.length>1?{type:Sw[t],data:s.substring(1)}:{type:Sw[t]}:HT},wj=(s,e)=>{if(_j){const t=bj(s);return PL(t,e)}else return{base64:!0,data:s}},PL=(s,e)=>{switch(e){case"blob":return s instanceof Blob?s:new Blob([s]);case"arraybuffer":default:return s instanceof ArrayBuffer?s:s.buffer}},LL="",Sj=(s,e)=>{const t=s.length,n=new Array(t);let i=0;s.forEach((r,o)=>{IE(r,!1,a=>{n[o]=a,++i===t&&e(n.join(LL))})})},kj=(s,e)=>{const t=s.split(LL),n=[];for(let i=0;i<t.length;i++){const r=PE(t[i],e);if(n.push(r),r.type==="error")break}return n};function Cj(){return new TransformStream({transform(s,e){yj(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 bC;function H_(s){return s.reduce((e,t)=>e+t.length,0)}function U_(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 Tj(s,e){bC||(bC=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(H_(t)<1)break;const c=U_(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(H_(t)<2)break;const c=U_(t,2);i=new DataView(c.buffer,c.byteOffset,c.length).getUint16(0),n=3}else if(n===2){if(H_(t)<8)break;const c=U_(t,8),l=new DataView(c.buffer,c.byteOffset,c.length),u=l.getUint32(0);if(u>Math.pow(2,21)-1){a.enqueue(HT);break}i=u*Math.pow(2,32)+l.getUint32(4),n=3}else{if(H_(t)<i)break;const c=U_(t,i);a.enqueue(PE(r?c:bC.decode(c),e)),n=0}if(i===0||i>s){a.enqueue(HT);break}}}})}const OL=4;function An(s){if(s)return Aj(s)}function Aj(s){for(var e in An.prototype)s[e]=An.prototype[e];return s}An.prototype.on=An.prototype.addEventListener=function(s,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+s]=this._callbacks["$"+s]||[]).push(e),this};An.prototype.once=function(s,e){function t(){this.off(s,t),e.apply(this,arguments)}return t.fn=e,this.on(s,t),this};An.prototype.off=An.prototype.removeListener=An.prototype.removeAllListeners=An.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};An.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};An.prototype.emitReserved=An.prototype.emit;An.prototype.listeners=function(s){return this._callbacks=this._callbacks||{},this._callbacks["$"+s]||[]};An.prototype.hasListeners=function(s){return!!this.listeners(s).length};const ck=typeof Promise=="function"&&typeof Promise.resolve=="function"?e=>Promise.resolve().then(e):(e,t)=>t(e,0),No=typeof self<"u"?self:typeof window<"u"?window:Function("return this")(),Ej="arraybuffer";function DL(s,...e){return e.reduce((t,n)=>(s.hasOwnProperty(n)&&(t[n]=s[n]),t),{})}const Mj=No.setTimeout,xj=No.clearTimeout;function uk(s,e){e.useNativeTimers?(s.setTimeoutFn=Mj.bind(No),s.clearTimeoutFn=xj.bind(No)):(s.setTimeoutFn=No.setTimeout.bind(No),s.clearTimeoutFn=No.clearTimeout.bind(No))}const Rj=1.33;function Ij(s){return typeof s=="string"?Pj(s):Math.ceil((s.byteLength||s.size)*Rj)}function Pj(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 NL(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}function Lj(s){let e="";for(let t in s)s.hasOwnProperty(t)&&(e.length&&(e+="&"),e+=encodeURIComponent(t)+"="+encodeURIComponent(s[t]));return e}function Oj(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 Dj extends Error{constructor(e,t,n){super(e),this.description=t,this.context=n,this.type="TransportError"}}class LE extends An{constructor(e){super(),this.writable=!1,uk(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 Dj(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=PE(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=Lj(e);return t.length?"?"+t:""}}class Nj extends LE{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)};kj(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,Sj(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]=NL()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}}let $L=!1;try{$L=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}const $j=$L;function Bj(){}class Fj extends Nj{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 ll extends An{constructor(e,t,n){super(),this.createRequest=e,uk(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=DL(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=ll.requestsCount++,ll.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=Bj,e)try{this._xhr.abort()}catch{}typeof document<"u"&&delete ll.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()}}ll.requestsCount=0;ll.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",Ax);else if(typeof addEventListener=="function"){const s="onpagehide"in No?"pagehide":"unload";addEventListener(s,Ax,!1)}}function Ax(){for(let s in ll.requests)ll.requests.hasOwnProperty(s)&&ll.requests[s].abort()}const Hj=function(){const s=BL({xdomain:!1});return s&&s.responseType!==null}();class Uj extends Fj{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=Hj&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new ll(BL,this.uri(),e)}}function BL(s){const e=s.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||$j))return new XMLHttpRequest}catch{}if(!e)try{return new No[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}const FL=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class Wj extends LE{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,n=FL?{}:DL(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;IE(n,this.supportsBinary,r=>{try{this.doWrite(n,r)}catch{}i&&ck(()=>{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]=NL()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}const _C=No.WebSocket||No.MozWebSocket;let zj=class extends Wj{createSocket(e,t,n){return FL?new _C(e,t,n):t?new _C(e,t):new _C(e)}doWrite(e,t){this.ws.send(t)}};class jj extends LE{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=Tj(Number.MAX_SAFE_INTEGER,this.socket.binaryType),n=e.readable.pipeThrough(t).getReader(),i=Cj();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&&ck(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}}const Vj={websocket:zj,webtransport:jj,polling:Uj},Gj=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Kj=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function UT(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=Gj.exec(s||""),r={},o=14;for(;o--;)r[Kj[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=qj(r,r.path),r.queryKey=Qj(r,r.query),r}function qj(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 Qj(s,e){const t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(n,i,r){i&&(t[i]=r)}),t}const WT=typeof addEventListener=="function"&&typeof removeEventListener=="function",kw=[];WT&&addEventListener("offline",()=>{kw.forEach(s=>s())},!1);class ad extends An{constructor(e,t){if(super(),this.binaryType=Ej,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=UT(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=UT(t.host).host);uk(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=Oj(this.opts.query)),WT&&(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"})},kw.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=OL,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&&ad.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",ad.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+=Ij(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,ck(()=>{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(ad.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(),WT&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const n=kw.indexOf(this._offlineEventListener);n!==-1&&kw.splice(n,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}ad.protocol=OL;class Xj extends ad{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;ad.priorWebsocketSuccess=!1;const i=()=>{n||(t.send([{type:"ping",data:"probe"}]),t.once("packet",d=>{if(!n)if(d.type==="pong"&&d.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;ad.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 h=new Error("probe error");h.transport=t.name,this.emitReserved("upgradeError",h)}}))};function r(){n||(n=!0,u(),t.close(),t=null)}const o=d=>{const h=new Error("probe error: "+d);h.transport=t.name,r(),this.emitReserved("upgradeError",h)};function a(){o("transport closed")}function c(){o("socket closed")}function l(d){t&&d.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 Yj=class extends Xj{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=>Vj[i]).filter(i=>!!i)),super(e,n)}};function Jj(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=UT(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 Zj=typeof ArrayBuffer=="function",e9=s=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(s):s.buffer instanceof ArrayBuffer,HL=Object.prototype.toString,t9=typeof Blob=="function"||typeof Blob<"u"&&HL.call(Blob)==="[object BlobConstructor]",s9=typeof File=="function"||typeof File<"u"&&HL.call(File)==="[object FileConstructor]";function OE(s){return Zj&&(s instanceof ArrayBuffer||e9(s))||t9&&s instanceof Blob||s9&&s instanceof File}function Cw(s,e){if(!s||typeof s!="object")return!1;if(Array.isArray(s)){for(let t=0,n=s.length;t<n;t++)if(Cw(s[t]))return!0;return!1}if(OE(s))return!0;if(s.toJSON&&typeof s.toJSON=="function"&&arguments.length===1)return Cw(s.toJSON(),!0);for(const t in s)if(Object.prototype.hasOwnProperty.call(s,t)&&Cw(s[t]))return!0;return!1}function n9(s){const e=[],t=s.data,n=s;return n.data=zT(t,e),n.attachments=e.length,{packet:n,buffers:e}}function zT(s,e){if(!s)return s;if(OE(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]=zT(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]=zT(s[n],e));return t}return s}function i9(s,e){return s.data=jT(s.data,e),delete s.attachments,s}function jT(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]=jT(s[t],e);else if(typeof s=="object")for(const t in s)Object.prototype.hasOwnProperty.call(s,t)&&(s[t]=jT(s[t],e));return s}const r9=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var Kt;(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"})(Kt||(Kt={}));class o9{constructor(e){this.replacer=e}encode(e){return(e.type===Kt.EVENT||e.type===Kt.ACK)&&Cw(e)?this.encodeAsBinary({type:e.type===Kt.EVENT?Kt.BINARY_EVENT:Kt.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=""+e.type;return(e.type===Kt.BINARY_EVENT||e.type===Kt.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=n9(e),n=this.encodeAsString(t.packet),i=t.buffers;return i.unshift(n),i}}class DE extends An{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===Kt.BINARY_EVENT;n||t.type===Kt.BINARY_ACK?(t.type=n?Kt.EVENT:Kt.ACK,this.reconstructor=new a9(t),t.attachments===0&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else if(OE(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(Kt[n.type]===void 0)throw new Error("unknown packet type "+n.type);if(n.type===Kt.BINARY_EVENT||n.type===Kt.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(!l9(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(DE.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 Kt.CONNECT:return Ex(t);case Kt.DISCONNECT:return t===void 0;case Kt.CONNECT_ERROR:return typeof t=="string"||Ex(t);case Kt.EVENT:case Kt.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]=="number"||typeof t[0]=="string"&&r9.indexOf(t[0])===-1);case Kt.ACK:case Kt.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class a9{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=i9(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const l9=Number.isInteger||function(s){return typeof s=="number"&&isFinite(s)&&Math.floor(s)===s};function Ex(s){return Object.prototype.toString.call(s)==="[object Object]"}const c9=Object.freeze(Object.defineProperty({__proto__:null,Decoder:DE,Encoder:o9,get PacketType(){return Kt}},Symbol.toStringTag,{value:"Module"}));function va(s,e,t){return s.on(e,t),function(){s.off(e,t)}}const u9=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class UL extends An{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=[va(e,"open",this.onopen.bind(this)),va(e,"packet",this.onpacket.bind(this)),va(e,"error",this.onerror.bind(this)),va(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(u9.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:Kt.EVENT,data:t};if(o.options={},o.options.compress=this.flags.compress!==!1,typeof t[t.length-1]=="function"){const u=this.ids++,d=t.pop();this._registerAckCallback(u,d),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:Kt.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 Kt.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 Kt.EVENT:case Kt.BINARY_EVENT:this.onevent(e);break;case Kt.ACK:case Kt.BINARY_ACK:this.onack(e);break;case Kt.DISCONNECT:this.ondisconnect();break;case Kt.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:Kt.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:Kt.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 bg(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}bg.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};bg.prototype.reset=function(){this.attempts=0};bg.prototype.setMin=function(s){this.ms=s};bg.prototype.setMax=function(s){this.max=s};bg.prototype.setJitter=function(s){this.jitter=s};class VT extends An{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,uk(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 bg({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||c9;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 Yj(this.uri,this.opts);const t=this.engine,n=this;this._readyState="opening",this.skipReconnect=!1;const i=va(t,"open",function(){n.onopen(),e&&e()}),r=a=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",a),e?e(a):this.maybeReconnectOnOpen()},o=va(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(va(e,"ping",this.onping.bind(this)),va(e,"data",this.ondata.bind(this)),va(e,"error",this.onerror.bind(this)),va(e,"close",this.onclose.bind(this)),va(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){ck(()=>{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 UL(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 Lg={};function Tw(s,e){typeof s=="object"&&(e=s,s=void 0),e=e||{};const t=Jj(s,e.path||"/socket.io"),n=t.source,i=t.id,r=t.path,o=Lg[i]&&r in Lg[i].nsps,a=e.forceNew||e["force new connection"]||e.multiplex===!1||o;let c;return a?c=new VT(n,e):(Lg[i]||(Lg[i]=new VT(n,e)),c=Lg[i]),t.query&&!e.query&&(e.query=t.queryKey),c.socket(t.path,e)}Object.assign(Tw,{Manager:VT,Socket:UL,io:Tw,connect:Tw});const d9={class:"terminal-panel__header"},h9={class:"terminal-panel__tabs"},f9={key:0,class:"terminal-panel__empty-tab"},p9=["title","onClick"],m9={class:"terminal-panel__tab-name"},g9={key:0,class:"terminal-panel__idle"},v9=ct({name:"TerminalPanel",__name:"TerminalPanel",props:{width:{},workspaceId:{},conversationId:{}},emits:["close"],setup(s,{emit:e}){const t=s,n=ge({}),i=ge(""),r=ge({}),o=ge({});let a=null;const c=ge(null);let l=null,u=null,d=null;const h=ge({}),p=ge({}),g=be(()=>Object.keys(n.value));function v(E){const x=E==null?void 0:E.conversation_id;return!x||!t.conversationId?!1:x===t.conversationId}function m(){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 _(){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 b(){if(!l)return;const E=m()==="dark";l.options.theme=E?_():y()}function k(){if(!c.value)return;const x=m()==="dark"?_():y();l=new vj.Terminal({cursorBlink:!0,fontSize:13,fontFamily:'"JetBrains Mono", "SF Mono", "Fira Code", "Consolas", monospace',theme:x,scrollback:1e4,convertEol:!0,allowTransparency:!1,disableStdin:!0}),l.open(c.value),d=new ResizeObserver(()=>{if(!l||!c.value)return;const D=c.value.getBoundingClientRect();if(D.width<40||D.height<40)return;const N=l._core._renderService.dimensions.css.cell.width||7.8,O=l._core._renderService.dimensions.css.cell.height||17,G=Math.max(2,Math.floor((D.width-16)/N)),Z=Math.max(1,Math.floor((D.height-16)/O));(G!==l.cols||Z!==l.rows)&&l.resize(G,Z)}),d.observe(c.value),u=new MutationObserver(()=>b()),u.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]})}function w(){d==null||d.disconnect(),d=null,u==null||u.disconnect(),u=null,l==null||l.dispose(),l=null}function T(){if(!l||!i.value)return;const E=r.value[i.value]||"";l.clear(),E&&l.write(E,()=>{l==null||l.scrollToBottom()})}function A(E){if(E&&(i.value=E,!o.value[E])){h.value={...h.value,[E]:!1};const x={...p.value};delete x[E],p.value=x,a!=null&&a.connected&&a.emit("get_terminal_output",{session:E,lines:0,conversation_id:t.conversationId})}}Ke(i,E=>{l&&T()}),Ke(g,E=>{E.length>0&&l&&!i.value&&A(E[0])}),Ke(()=>t.workspaceId,(E,x)=>{E&&x&&E!==x&&(a&&(a.disconnect(),a=null),n.value={},i.value="",r.value={},o.value={},h.value={},p.value={},l&&l.clear(),C())}),Ke(()=>t.conversationId,(E,x)=>{E!==x&&(n.value={},i.value="",r.value={},o.value={},h.value={},p.value={},l&&l.clear(),a!=null&&a.connected&&a.emit("terminal_subscribe",{all:!0,conversation_id:E}))});async function C(){a=Tw("/",{transports:["websocket","polling"],autoConnect:!1});const E=async()=>{const N=window;if(typeof N.requestSocketToken!="function")return console.warn("[TerminalPanel] requestSocketToken 不可用"),!1;try{const O=await N.requestSocketToken();return a.auth={socket_token:O},!0}catch(O){return console.error("[TerminalPanel] 获取 token 失败:",O),!1}};if(a.io.on("reconnect_attempt",()=>E()),!await E()){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",N=>{if(N!=null&&N.terminals){const O={};for(const G of N.terminals)O[G.name]={working_dir:G.working_dir,shell:"bash"};n.value=O,N.terminals.length>0&&!i.value&&A(N.terminals[0].name)}}),a.on("terminal_started",N=>{v(N)&&(n.value={...n.value,[N.session]:{working_dir:N.working_dir,shell:"bash"}},i.value||A(N.session))}),a.on("terminal_list_update",N=>{if(v(N)&&N!=null&&N.terminals){const O={};for(const G of N.terminals)O[G.name]={working_dir:G.working_dir,shell:"bash"};n.value=O,N.active&&!i.value&&A(N.active)}}),a.on("terminal_output",N=>{if(!v(N))return;const O=N.session;if(!O)return;const G=N.data||"",Z=p.value[O]||0,q=typeof N.timestamp=="number"?N.timestamp:0;Z>0&&q>0&&q<=Z||(r.value[O]=(r.value[O]||"")+G,O===i.value&&l&&h.value[O]&&l.write(G),i.value||A(O))}),a.on("terminal_input",N=>{v(N)&&!i.value&&N.session&&A(N.session)}),a.on("terminal_closed",N=>{if(!v(N))return;const O={...n.value};delete O[N.session],n.value=O;const G=Object.keys(O);i.value===N.session&&(i.value=G.length>0?G[0]:"")}),a.on("terminal_reset",N=>{if(!v(N))return;const O=N.session||i.value;if(O){r.value={...r.value,[O]:""},o.value={...o.value,[O]:!0};const G={...p.value};delete G[O],p.value=G,O===i.value&&T()}}),a.on("terminal_switched",N=>{v(N)&&N.current&&A(N.current)});const D=N=>{const O=N.session||N.active;if(!O)return;const G=N.output||N.data||"";let Z="";typeof G=="string"?Z=G:Array.isArray(G)&&(Z=G.join(`
|
||
`)),Z&&(r.value[O]=Z),o.value={...o.value,[O]:!0},h.value={...h.value,[O]:!0};const q=typeof N.last_event_time=="number"?N.last_event_time:0;p.value={...p.value,[O]:q},O===i.value&&T()};a.on("terminal_output_history",D),a.on("terminal_history",D),a.connect()}return dn(()=>{ft(()=>{k(),C()})}),Rn(()=>{w(),a&&(a.disconnect(),a=null)}),(E,x)=>(F(),U("aside",{class:"terminal-panel",style:qe({width:s.width+"px"})},[M("header",d9,[M("div",h9,[g.value.length?me("",!0):(F(),U("div",f9,[M("span",null,Q(E.$t("shell.waitingTerminalSession")),1)])),(F(!0),U(Ie,null,Ze(g.value,D=>{var N;return F(),U("button",{key:D,type:"button",class:Ce(["terminal-panel__tab",{active:D===i.value}]),title:((N=n.value[D])==null?void 0:N.working_dir)||D,onClick:O=>A(D)},[M("span",m9,Q(D),1)],10,p9)}),128))]),We(ml,{label:E.$t("shell.closeTerminalPanel"),onClick:x[0]||(x[0]=D=>E.$emit("close"))},null,8,["label"])]),M("div",{class:"terminal-panel__body",ref_key:"terminalContainer",ref:c},[g.value.length?me("",!0):(F(),U("div",g9,[x[1]||(x[1]=M("svg",{class:"terminal-panel__idle-svg",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true"},[M("rect",{x:"2",y:"3",width:"20",height:"16",rx:"2",stroke:"currentColor","stroke-width":"1.5"}),M("path",{d:"M6 7h12M6 10h8",stroke:"currentColor","stroke-width":"1.5","stroke-linecap":"round"})],-1)),M("span",null,Q(E.$t("shell.noOpenTerminals")),1)]))],512)],4))}}),y9=qt(v9,[["__scopeId","data-v-fa145c42"]]),b9={class:"token-display-panel"},_9={class:"token-panel-content"},w9={class:"usage-dashboard"},S9={class:"usage-cell usage-cell--left usage-cell--token panel-card"},k9={class:"usage-title"},C9={class:"stat-grid stat-grid--triple"},T9={class:"stat-block"},A9={class:"stat-label"},E9={class:"stat-value stat-value--accent"},M9={class:"stat-block"},x9={class:"stat-label"},R9={class:"stat-value stat-value--success"},I9={class:"stat-block"},P9={class:"stat-label"},L9={class:"stat-value stat-value--warning"},O9={class:"stat-block"},D9={class:"stat-label"},N9={class:"stat-value"},$9={class:"stat-block"},B9={class:"stat-label"},F9={class:"stat-value"},H9={class:"usage-cell usage-cell--right usage-cell--performance panel-card"},U9={class:"usage-title"},W9={key:0,class:"stat-grid stat-grid--double"},z9={class:"stat-block"},j9={class:"stat-value"},V9={class:"stat-block"},G9={class:"stat-label"},K9={class:"stat-value stat-value--mono"},q9={key:0,class:"stat-foot"},Q9={key:1,class:"usage-placeholder"},X9={key:1,class:"usage-placeholder"},Y9={class:"usage-cell usage-cell--left usage-cell--quota panel-card"},J9={class:"usage-title"},Z9={class:"stat-grid stat-grid--triple"},e7={class:"stat-label"},t7={class:"stat-value"},s7={key:0,class:"stat-foot"},n7={class:"usage-cell usage-cell--right usage-cell--resource panel-card"},i7={class:"usage-title"},r7={class:"stat-grid stat-grid--double"},o7={class:"stat-block"},a7={class:"stat-label"},l7={class:"stat-value stat-value--mono"},c7={class:"stat-block"},u7={class:"stat-label"},d7={class:"stat-value stat-value--mono"},h7={key:0,class:"stat-foot"},f7=ct({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=be(()=>[{key:"fast",label:"sidebar.quotaTierFast",value:n.usageQuota.fast},{key:"thinking",label:"sidebar.quotaTierThinking",value:n.usageQuota.thinking},{key:"search",label:"sidebar.quotaTierSearch",value:n.usageQuota.search}]),r=be(()=>{const l=n.currentConversationTokens.cumulative_input_tokens||0,u=n.currentConversationTokens.cache_exempt_input_tokens||0,d=l-u;return d<=0?"--":`${((n.currentConversationTokens.cumulative_cached_input_tokens||0)/d*100).toFixed(1)}%`}),o=be(()=>{const l=n.containerStatus;return!l||!l.stats?!1:typeof l.stats.cpu_percent<"u"?!0:!!(l.stats.memory&&typeof l.stats.memory.used_bytes<"u")}),a=be(()=>{const l=n.containerStatus;if(!l)return{};if(l.mode!=="docker")return{"status-pill--host":!0};const u=l.state&&l.state.running===!1;return{"status-pill--running":!u,"status-pill--stopped":u}}),c=be(()=>{lt.value;const l=n.containerStatus;return l?l.mode!=="docker"?"Host":l.state&&l.state.running===!1?S("sidebar.stopped"):S("sidebar.containerRunning"):S("sidebar.unknown")});return(l,u)=>s.visible?(F(),U("div",{key:0,class:Ce(["token-drawer",{collapsed:s.collapsed}]),"data-tutorial":"token-drawer"},[M("div",b9,[We(ml,{class:"token-close-btn","data-tutorial":"token-close",label:l.$t("sidebar.collapseUsage"),onClick:u[0]||(u[0]=d=>t("toggle"))},null,8,["label"]),M("div",_9,[M("div",w9,[M("div",S9,[M("div",k9,Q(l.$t("sidebar.tokenStats")),1),M("div",C9,[M("div",T9,[M("div",A9,Q(l.$t("sidebar.currentContext")),1),M("div",E9,Q(s.formatTokenCount(s.currentContextTokens||0)),1)]),M("div",M9,[M("div",x9,Q(l.$t("sidebar.cumulativeInput")),1),M("div",R9,Q(s.formatTokenCount(s.currentConversationTokens.cumulative_input_tokens||0)),1)]),M("div",I9,[M("div",P9,Q(l.$t("sidebar.cumulativeOutput")),1),M("div",L9,Q(s.formatTokenCount(s.currentConversationTokens.cumulative_output_tokens||0)),1)]),M("div",O9,[M("div",D9,Q(l.$t("sidebar.cumulativeCachedInput")),1),M("div",N9,Q(s.formatTokenCount(s.currentConversationTokens.cumulative_cached_input_tokens||0)),1)]),M("div",$9,[M("div",B9,Q(l.$t("sidebar.cacheHitRate")),1),M("div",F9,Q(r.value),1)])])]),M("div",H9,[M("div",U9,[M("span",null,Q(l.$t("sidebar.performanceStats")),1),s.containerStatus?(F(),U("span",{key:0,class:Ce(["status-pill",a.value])},Q(c.value),3)):me("",!0)]),s.containerStatus&&s.containerStatus.mode==="docker"?(F(),U(Ie,{key:0},[o.value?(F(),U("div",W9,[M("div",z9,[u[1]||(u[1]=M("div",{class:"stat-label"},"CPU",-1)),M("div",j9,Q(s.formatPercentage(s.containerStatus.stats.cpu_percent)),1)]),M("div",V9,[M("div",G9,Q(l.$t("sidebar.memory")),1),M("div",K9,[cn(Q(s.formatBytes(s.containerStatus.stats.memory.used_bytes))+" ",1),s.containerStatus.stats.memory.limit_bytes?(F(),U(Ie,{key:0},[cn(" / "+Q(s.formatBytes(s.containerStatus.stats.memory.limit_bytes)),1)],64)):me("",!0)]),s.containerStatus.stats.memory.percent?(F(),U("div",q9,Q(s.formatPercentage(s.containerStatus.stats.memory.percent)),1)):me("",!0)])])):(F(),U("div",Q9,Q(l.$t("sidebar.containerMetricsPending")),1))],64)):(F(),U("div",X9,Q(l.$t("sidebar.hostModeNoContainer")),1))]),M("div",Y9,[M("div",J9,Q(l.$t("sidebar.quotaStats")),1),M("div",Z9,[(F(!0),U(Ie,null,Ze(i.value,d=>(F(),U("div",{class:"stat-block",key:d.key},[M("div",e7,Q(l.$t(d.label)),1),M("div",t7,Q(s.formatQuotaValue(d.value)),1),(d.value.count||0)>0?(F(),U("div",s7,Q(l.$t("sidebar.resetAt",{time:s.formatResetTime(d.value.reset_at)})),1)):me("",!0)]))),128))])]),M("div",n7,[M("div",i7,Q(l.$t("sidebar.resourceStats")),1),M("div",r7,[M("div",o7,[M("div",a7,Q(l.$t("sidebar.network")),1),M("div",l7," ↓"+Q(s.formatRate(s.containerNetRate.down_bps))+" ↑"+Q(s.formatRate(s.containerNetRate.up_bps)),1)]),M("div",c7,[M("div",u7,Q(l.$t("sidebar.storage")),1),M("div",d7,[cn(Q(s.formatBytes(s.projectStorage.used_bytes))+" ",1),s.projectStorage.limit_bytes?(F(),U(Ie,{key:0},[cn("/ "+Q(s.formatBytes(s.projectStorage.limit_bytes)),1)],64)):me("",!0)]),typeof s.projectStorage.usage_percent=="number"?(F(),U("div",h7,Q(s.projectStorage.usage_percent.toFixed(1))+"% ",1)):me("",!0)])])])])])])],2)):me("",!0)}}),p7={class:"quick-menu-list"},m7=["disabled"],g7=["disabled"],v7=["disabled"],y7=["disabled"],b7=["disabled"],_7=["disabled"],w7={class:"entry-arrow"},S7=["disabled"],k7={key:0,class:"quick-submenu tool-submenu"},C7={key:0,class:"submenu-status"},T7={key:1,class:"submenu-empty"},A7={key:2,class:"submenu-list tool-submenu-list"},E7=["onClick","disabled"],M7={class:"submenu-label icon-label"},x7={class:"entry-arrow"},R7={key:0,class:"quick-submenu settings-submenu"},I7={class:"submenu-list"},P7=["disabled"],L7=["disabled"],O7=["disabled"],D7=["disabled"],N7=ct({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=be(()=>{var a;const o=(a=e.modelOptions)==null?void 0:a.find(c=>c.key===e.currentModelKey);return!!(o!=null&&o.supportsImage)}),i=be(()=>{var a;const o=(a=e.modelOptions)==null?void 0:a.find(c=>c.key===e.currentModelKey);return!!(o!=null&&o.supportsVideo)}),r=be(()=>{var o;return String(((o=e.goalProgress)==null?void 0:o.status)||"").toLowerCase()==="done"});return(o,a)=>(F(),Ft(gs,{name:"quick-menu"},{default:Gt(()=>[s.open?(F(),U("div",{key:0,class:"quick-menu",onClick:a[12]||(a[12]=De(()=>{},["stop"]))},[M("div",p7,[M("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},Q(s.uploading?o.$t("quickdock.uploading"):o.$t("quickdock.uploadFile")),9,m7),M("button",{type:"button",class:"menu-entry","data-tutorial":"quick-review",onClick:a[1]||(a[1]=De(c=>o.$emit("open-review"),["stop"])),disabled:!s.isConnected||s.streamingMessage},Q(o.$t("quickdock.conversationReview")),9,g7),n.value?(F(),U("button",{key:0,type:"button",class:"menu-entry","data-tutorial":"quick-send-image",onClick:a[2]||(a[2]=De(c=>o.$emit("pick-images"),["stop"])),disabled:!s.isConnected||s.streamingMessage},Q(o.$t("quickdock.sendImage")),9,v7)):me("",!0),i.value?(F(),U("button",{key:1,type:"button",class:"menu-entry","data-tutorial":"quick-send-video",onClick:a[3]||(a[3]=De(c=>o.$emit("pick-video"),["stop"])),disabled:!s.isConnected||s.streamingMessage},Q(o.$t("quickdock.sendVideo")),9,y7)):me("",!0),M("button",{type:"button",class:"menu-entry has-submenu","data-tutorial":"quick-tool-menu",onClick:a[4]||(a[4]=De(c=>o.$emit("toggle-tool-menu"),["stop"])),disabled:!s.isConnected},[cn(Q(o.$t("quickdock.disableTools"))+" ",1),a[13]||(a[13]=M("span",{class:"entry-arrow"},"›",-1))],8,b7),M("button",{type:"button",class:Ce(["menu-entry",{"goal-entry-active":s.goalModeArmed||s.goalRunning||r.value}]),onClick:a[5]||(a[5]=De(c=>o.$emit("toggle-goal-mode"),["stop"])),disabled:!s.isConnected},[cn(Q(o.$t("quickdock.goalMode"))+" ",1),M("span",w7,[s.goalRunning?(F(),U(Ie,{key:0},[cn(Q(o.$t("common.running")),1)],64)):r.value?(F(),U(Ie,{key:1},[cn(Q(o.$t("quickdock.goalDone")),1)],64)):(F(),U(Ie,{key:2},[cn(Q(s.goalModeArmed?o.$t("quickdock.goalArmed"):""),1)],64))])],10,_7),M("button",{type:"button",class:"menu-entry has-submenu","data-tutorial":"quick-settings-menu",onClick:a[6]||(a[6]=De(c=>o.$emit("toggle-settings"),["stop"])),disabled:!s.isConnected},[cn(Q(o.$t("quickdock.settingsMenu"))+" ",1),a[14]||(a[14]=M("span",{class:"entry-arrow"},"›",-1))],8,S7)]),We(gs,{name:"submenu-slide"},{default:Gt(()=>[s.toolMenuOpen?(F(),U("div",k7,[s.toolSettingsLoading?(F(),U("div",C7,Q(o.$t("quickdock.toolSettingsSyncing")),1)):s.toolSettings.length?(F(),U("div",A7,[(F(!0),U(Ie,null,Ze(s.toolSettings,c=>(F(),U("button",{key:c.id,type:"button",class:Ce(["menu-entry submenu-entry",{disabled:!c.enabled||c.locked}]),onClick:De(l=>o.$emit("update-tool-category",c.id,!c.enabled),["stop"]),disabled:s.streamingMessage||!s.isConnected||s.toolSettingsLoading},[M("span",M7,[M("span",{class:"icon icon-sm",style:qe(t(s.toolCategoryIcon(c.id))),"aria-hidden":"true"},null,4),M("span",null,Q(c.label),1)]),M("span",x7,[c.locked?(F(),U(Ie,{key:0},[cn(Q(o.$t("quickdock.lockedByAdmin")),1)],64)):(F(),U(Ie,{key:1},[cn(Q(c.enabled?o.$t("quickdock.toolDisable"):o.$t("quickdock.toolEnable")),1)],64))])],10,E7))),128))])):(F(),U("div",T7,Q(o.$t("quickdock.noControllableTools")),1))])):me("",!0)]),_:1}),We(gs,{name:"submenu-slide"},{default:Gt(()=>[s.settingsOpen?(F(),U("div",R7,[M("div",I7,[M("button",{type:"button",class:"menu-entry submenu-entry",onClick:a[7]||(a[7]=c=>o.$emit("realtime-terminal")),disabled:!s.isConnected},Q(o.$t("quickdock.realtimeTerminal")),9,P7),M("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},Q(o.$t("quickdock.usageStats")),9,L7),M("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},Q(s.compressing?o.$t("quickdock.compressing"):o.$t("quickdock.compressConversation")),9,O7),M("button",{type:"button",class:"menu-entry submenu-entry",onClick:a[10]||(a[10]=c=>o.$emit("toggle-approval-panel")),disabled:!s.currentConversationId},Q(o.$t("quickdock.approvalPanel")),9,D7),s.executionModeEnabled?(F(),U("button",{key:0,type:"button",class:"menu-entry submenu-entry",onClick:a[11]||(a[11]=c=>o.$emit("open-path-authorization"))},Q(o.$t("quickdock.pathAuthorization")),1)):me("",!0)])])):me("",!0)]),_:1})])):me("",!0)]),_:1}))}}),WL=qt(N7,[["__scopeId","data-v-20682656"]]);function oi(s){this.content=s}oi.prototype={constructor:oi,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 oi(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 oi(t)},addToStart:function(s,e){return new oi([s,e].concat(this.remove(s).content))},addToEnd:function(s,e){var t=this.remove(s).content.slice();return t.push(s,e),new oi(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 oi(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=oi.from(s),s.size?new oi(s.content.concat(this.subtract(s).content)):this},append:function(s){return s=oi.from(s),s.size?new oi(this.subtract(s).content.concat(s.content)):this},subtract:function(s){var e=this;s=oi.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}};oi.from=function(s){if(s instanceof oi)return s;var e=[];if(s)for(var t in s)e.push(t,s[t]);return new oi(e)};function zL(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=zL(i.content,r.content,t+1);if(o!=null)return o}t+=i.nodeSize}}function jL(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=jL(o.content,a.content,t-1,n-1);if(l)return l}t-=c,n-=c}}let He=class Wi{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 Wi(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 Wi(n,i)}cutByIndex(e,t){return e==t?Wi.empty:e==0&&t==this.content.length?this:new Wi(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 Wi(i,r)}addToStart(e){return new Wi([e].concat(this.content),this.size+e.nodeSize)}addToEnd(e){return new Wi(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 zL(this,e,t)}findDiffEnd(e,t=this.size,n=e.size){return jL(this,e,t,n)}findIndex(e){if(e==0)return W_(0,e);if(e==this.size)return W_(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?W_(t+1,r):W_(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 Wi.empty;if(!Array.isArray(t))throw new RangeError("Invalid input for Fragment.fromJSON");return Wi.fromArray(t.map(e.nodeFromJSON))}static fromArray(e){if(!e.length)return Wi.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 Wi(t||e,n)}static from(e){if(!e)return Wi.empty;if(e instanceof Wi)return e;if(Array.isArray(e))return this.fromArray(e);if(e.attrs)return new Wi([e],e.nodeSize);throw new RangeError("Can not convert "+e+" to a Fragment"+(e.nodesBetween?" (looks like multiple versions of prosemirror-model were loaded)":""))}};He.empty=new He([],0);const wC={index:0,offset:0};function W_(s,e){return wC.index=s,wC.offset=e,wC}function LS(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(!LS(s[n],e[n]))return!1}else{for(let n in s)if(!(n in e)||!LS(s[n],e[n]))return!1;for(let n in e)if(!(n in s))return!1}return!0}let As=class GT{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&&LS(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 GT.none;if(e instanceof GT)return[e];let t=e.slice();return t.sort((n,i)=>n.type.rank-i.type.rank),t}};As.none=[];let OS=class extends Error{},tt=class up{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=GL(this.content,e+this.openStart,t,this.openStart+1,this.openEnd+1);return n&&new up(n,this.openStart,this.openEnd)}removeBetween(e,t){return new up(VL(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 up.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 up(He.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 up(e,n,i)}};tt.empty=new tt(He.empty,0,0);function VL(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(VL(r.content,e-i-1,t-i-1)))}function GL(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=GL(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 $7(s,e,t){if(t.openStart>s.depth)throw new OS("Inserted content deeper than insertion position");if(s.depth-t.openStart!=e.depth-t.openEnd)throw new OS("Inconsistent open depths");return KL(s,e,t,0)}function KL(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=KL(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 Ef(o,a.cut(0,s.parentOffset).append(t.content).append(a.cut(e.parentOffset)))}else{let{start:o,end:a}=B7(t,s);return Ef(r,QL(s,o,a,e,n))}else return Ef(r,DS(s,e,n))}function qL(s,e){if(!e.type.compatibleContent(s.type))throw new OS("Cannot join "+e.type.name+" onto "+s.type.name)}function KT(s,e,t){let n=s.node(t);return qL(n,e.node(t)),n}function Af(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 Hv(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&&(Af(s.nodeAfter,n),r++));for(let a=r;a<o;a++)Af(i.child(a),n);e&&e.depth==t&&e.textOffset&&Af(e.nodeBefore,n)}function Ef(s,e){return s.type.checkContent(e),s.copy(e)}function QL(s,e,t,n,i){let r=s.depth>i&&KT(s,e,i+1),o=n.depth>i&&KT(t,n,i+1),a=[];return Hv(null,s,i,a),r&&o&&e.index(i)==t.index(i)?(qL(r,o),Af(Ef(r,QL(s,e,t,n,i+1)),a)):(r&&Af(Ef(r,DS(s,e,i+1)),a),Hv(e,t,i,a),o&&Af(Ef(o,DS(t,n,i+1)),a)),Hv(n,null,i,a),new He(a)}function DS(s,e,t){let n=[];if(Hv(null,s,t,n),s.depth>t){let i=KT(s,e,t+1);Af(Ef(i,DS(s,e,t+1)),n)}return Hv(e,null,t,n),new He(n)}function B7(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(He.from(i));return{start:i.resolveNoCache(s.openStart+t),end:i.resolveNoCache(i.content.size-s.openEnd-t)}}class cy{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 As.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 NS(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 cy(t,n,r)}static resolveCached(e,t){let n=Mx.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 Mx.set(e,n=new F7);let i=n.elts[n.i]=cy.resolve(e,t);return n.i=(n.i+1)%H7,i}}class F7{constructor(){this.elts=[],this.i=0}}const H7=12,Mx=new WeakMap;class NS{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 U7=Object.create(null);let Tc=class qT{constructor(e,t,n,i=As.none){this.type=e,this.attrs=t,this.marks=i,this.content=n||He.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&&LS(this.attrs,t||e.defaultAttrs||U7)&&As.sameSet(this.marks,n||As.none)}copy(e=null){return e==this.content?this:new qT(this.type,this.attrs,e,this.marks)}mark(e){return e==this.marks?this:new qT(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 tt.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 tt(l,i.depth-o,r.depth-o)}replace(e,t,n){return $7(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 cy.resolveCached(this,e)}resolveNoCache(e){return cy.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()+")"),XL(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=He.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=As.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(!As.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=He.fromJSON(e,t.content),r=e.nodeType(t.type).create(t.attrs,i,n);return r.type.checkAttrs(r.attrs),r}};Tc.prototype.text=void 0;class $S extends Tc{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):XL(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 $S(this.type,this.attrs,this.text,e)}withText(e){return e==this.text?this:new $S(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 XL(s,e){for(let t=s.length-1;t>=0;t--)e=s[t].type.name+"("+e+")";return e}class If{constructor(e){this.validEnd=e,this.next=[],this.wrapCache=[]}static parse(e,t){let n=new W7(e,t);if(n.next==null)return If.empty;let i=YL(n);n.next&&n.err("Unexpected trailing text");let r=Q7(q7(i));return X7(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 He.from(a.map(l=>l.createAndFill()));for(let l=0;l<o.next.length;l++){let{type:u,next:d}=o.next[l];if(!(u.isText||u.hasRequiredAttrs())&&i.indexOf(d)==-1){i.push(d);let h=r(d,a.concat(u));if(h)return h}}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(`
|
||
`)}}If.empty=new If(!0);class W7{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 YL(s){let e=[];do e.push(z7(s));while(s.eat("|"));return e.length==1?e[0]:{type:"choice",exprs:e}}function z7(s){let e=[];do e.push(j7(s));while(s.next&&s.next!=")"&&s.next!="|");return e.length==1?e[0]:{type:"seq",exprs:e}}function j7(s){let e=K7(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=V7(s,e);else break;return e}function xx(s){/\D/.test(s.next)&&s.err("Expected number, got '"+s.next+"'");let e=Number(s.next);return s.pos++,e}function V7(s,e){let t=xx(s),n=t;return s.eat(",")&&(s.next!="}"?n=xx(s):n=-1),s.eat("}")||s.err("Unclosed braced range"),{type:"range",min:t,max:n,expr:e}}function G7(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 K7(s){if(s.eat("(")){let e=YL(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=G7(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 q7(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 JL(s,e){return e-s}function Rx(s,e){let t=[];return n(e),t.sort(JL);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 Q7(s){let e=Object.create(null);return t(Rx(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]);Rx(s,c).forEach(u=>{l||i.push([a,l=[]]),l.indexOf(u)==-1&&l.push(u)})})});let r=e[n.join(",")]=new If(n.indexOf(s.length-1)>-1);for(let o=0;o<i.length;o++){let a=i[o][1].sort(JL);r.next.push({type:i[o][0],next:e[a.join(",")]||t(a)})}return r}}function X7(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 ZL(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 e2(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 t2(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 s2(s,e){let t=Object.create(null);if(e)for(let n in e)t[n]=new J7(s,n,e[n]);return t}let Ix=class n2{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=s2(e,n.attrs),this.defaultAttrs=ZL(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==If.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:e2(this.attrs,e)}create(e=null,t,n){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new Tc(this,this.computeAttrs(e),He.from(t),As.setFrom(n))}createChecked(e=null,t,n){return t=He.from(t),this.checkContent(t),new Tc(this,this.computeAttrs(e),t,As.setFrom(n))}createAndFill(e=null,t,n){if(e=this.computeAttrs(e),t=He.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(He.empty,!0);return r?new Tc(this,e,t.append(r),As.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){t2(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:As.none:e}static compile(e,t){let n=Object.create(null);e.forEach((r,o)=>n[r]=new n2(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 Y7(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 J7{constructor(e,t,n){this.hasDefault=Object.prototype.hasOwnProperty.call(n,"default"),this.default=n.default,this.validate=typeof n.validate=="string"?Y7(e,t,n.validate):n.validate}get isRequired(){return!this.hasDefault}}class dk{constructor(e,t,n,i){this.name=e,this.rank=t,this.schema=n,this.spec=i,this.attrs=s2(e,i.attrs),this.excluded=null;let r=ZL(this.attrs);this.instance=r?new As(this,r):null}create(e=null){return!e&&this.instance?this.instance:new As(this,e2(this.attrs,e))}static compile(e,t){let n=Object.create(null),i=0;return e.forEach((r,o)=>n[r]=new dk(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){t2(this.attrs,e,"mark",this.name)}excludes(e){return this.excluded.indexOf(e)>-1}}class i2{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=oi.from(e.nodes),t.marks=oi.from(e.marks||{}),this.nodes=Ix.compile(this.spec.nodes,this),this.marks=dk.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]=If.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?Px(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==""?[]:Px(this,o.split(" "))}this.nodeFromJSON=i=>Tc.fromJSON(this,i),this.markFromJSON=i=>As.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 Ix){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 $S(n,n.defaultAttrs,e,As.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 Px(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 Z7(s){return s.tag!=null}function eV(s){return s.style!=null}let Uv=class QT{constructor(e,t){this.schema=e,this.rules=t,this.tags=[],this.styles=[];let n=this.matchedStyles=[];t.forEach(i=>{if(Z7(i))this.tags.push(i);else if(eV(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 Ox(this,t,!1);return n.addAll(e,As.none,t.from,t.to),n.finish()}parseSlice(e,t={}){let n=new Ox(this,t,!0);return n.addAll(e,As.none,t.from,t.to),tt.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(nV(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=Dx(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=Dx(o)),o.node||o.ignore||o.mark||(o.node=i)})}return t}static fromSchema(e){return e.cached.domParser||(e.cached.domParser=new QT(e,QT.schemaRules(e)))}};const r2={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},tV={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},o2={ol:!0,ul:!0},uy=1,XT=2,Wv=4;function Lx(s,e,t){return e!=null?(e?uy:0)|(e==="full"?XT:0):s&&s.whitespace=="pre"?uy|XT:t&~Wv}class z_{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=As.none,this.match=r||(o&Wv?null:e.contentMatch)}findWrapping(e){if(!this.match){if(!this.type)return[];let t=this.type.contentMatch.fillBefore(He.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&uy)){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=He.from(this.content);return!e&&this.match&&(t=t.append(this.match.fillBefore(He.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&&!r2.hasOwnProperty(e.parentNode.nodeName.toLowerCase())}}class Ox{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=Lx(null,t.preserveWhitespace,0)|(n?Wv:0);i?r=new z_(i.type,i.attrs,As.none,!0,t.topMatch||i.type.contentMatch,o):n?r=new z_(null,null,As.none,!0,null,o):r=new z_(e.schema.topNodeType,null,As.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&XT?"full":this.localPreserveWS||(i.options&uy)>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;o2.hasOwnProperty(o)&&this.parser.normalizeLists&&sV(e);let c=this.options.ruleFromNode&&this.options.ruleFromNode(e)||(a=this.parser.matchTag(e,this,n));e:if(c?c.ignore:tV.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(r2.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 d=c&&c.skip?t:this.readStyles(e,t);d&&this.addAll(e,d),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=As.none;for(let a of i.concat(e.marks))(r.type?r.type.allowsMarkType(a.type):Nx(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=Lx(e,r,o.options);o.options&Wv&&o.content.length==0&&(a|=Wv);let c=As.none;return n=n.filter(l=>(o.type?o.type.allowsMarkType(l.type):Nx(l.type,e))?(c=l.addToSet(c),!1):!0),this.nodes.push(new z_(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|=uy)}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 sV(s){for(let e=s.firstChild,t=null;e;e=e.nextSibling){let n=e.nodeType==1?e.nodeName.toLowerCase():null;n&&o2.hasOwnProperty(n)&&t?(t.appendChild(e),e=t):n=="li"?t=e:n&&(t=null)}}function nV(s,e){return(s.matches||s.msMatchesSelector||s.webkitMatchesSelector||s.mozMatchesSelector).call(s,e)}function Dx(s){let e={};for(let t in s)e[t]=s[t];return e}function Nx(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 Hf{constructor(e,t){this.nodes=e,this.marks=t}serializeFragment(e,t={},n){n||(n=j_(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 j_(t).createTextNode(e.text);let{dom:n,contentDOM:i}=Aw(j_(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&&Aw(j_(n),i(e,t),null,e.attrs)}static renderSpec(e,t,n=null,i){return typeof t=="string"?{dom:e.createTextNode(t)}:Aw(e,t,n,i)}static fromSchema(e){return e.cached.domSerializer||(e.cached.domSerializer=new Hf(this.nodesFromSchema(e),this.marksFromSchema(e)))}static nodesFromSchema(e){let t=$x(e.nodes);return t.text||(t.text=n=>n.text),t}static marksFromSchema(e){return $x(e.marks)}}function $x(s){let e={};for(let t in s){let n=s[t].spec.toDOM;n&&(e[t]=n)}return e}function j_(s){return s.document||window.document}const Bx=new WeakMap;function iV(s){let e=Bx.get(s);return e===void 0&&Bx.set(s,e=rV(s)),e}function rV(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 Aw(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=iV(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 d in l)if(l[d]!=null){let h=d.indexOf(" ");h>0?c.setAttributeNS(d.slice(0,h),d.slice(h+1),l[d]):d=="style"&&c.style?c.style.cssText=l[d]:c.setAttribute(d,l[d])}}for(let d=u;d<e.length;d++){let h=e[d];if(h===0){if(d<e.length-1||d>u)throw new RangeError("Content hole must be the only child of its parent node");return{dom:c,contentDOM:c}}else if(typeof h=="string")c.appendChild(s.createTextNode(h));else{let{dom:p,contentDOM:g}=Aw(s,h,t,n);if(c.appendChild(p),g){if(a)throw new RangeError("Multiple content holes");a=g}}}return{dom:c,contentDOM:a}}const a2=65535,l2=Math.pow(2,16);function oV(s,e){return s+e*l2}function Fx(s){return s&a2}function aV(s){return(s-(s&a2))/l2}const c2=1,u2=2,Ew=4,d2=8;let YT=class{constructor(e,t,n){this.pos=e,this.delInfo=t,this.recover=n}get deleted(){return(this.delInfo&d2)>0}get deletedBefore(){return(this.delInfo&(c2|Ew))>0}get deletedAfter(){return(this.delInfo&(u2|Ew))>0}get deletedAcross(){return(this.delInfo&Ew)>0}},Pf=class dp{constructor(e,t=!1){if(this.ranges=e,this.inverted=t,!e.length&&dp.empty)return dp.empty}recover(e){let t=0,n=Fx(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+aV(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],d=c+l;if(e<=d){let h=l?e==c?-1:e==d?1:t:t,p=c+i+(h<0?0:u);if(n)return p;let g=e==(t<0?c:d)?null:oV(a/3,e-c),v=e==c?u2:e==d?c2:Ew;return(t<0?e!=c:e!=d)&&(v|=d2),new YT(p,v,g)}i+=u-l}return n?e+i:new YT(e+i,0,null)}touches(e,t){let n=0,i=Fx(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 dp(this.ranges,!this.inverted)}toString(){return(this.inverted?"-":"")+JSON.stringify(this.ranges)}static offset(e){return e==0?dp.empty:new dp(e<0?[0,-e,0]:[0,0,e])}};Pf.empty=new Pf([]);class dy{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 dy(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 dy;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 YT(e,i,null)}}const SC=Object.create(null);let Pi=class{getMap(){return Pf.empty}merge(e){return null}static fromJSON(e,t){if(!t||!t.stepType)throw new RangeError("Invalid input for Step.fromJSON");let n=SC[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 SC)throw new RangeError("Duplicate use of step JSON ID "+e);return SC[e]=t,t.prototype.jsonID=e,t}},tr=class Vg{constructor(e,t){this.doc=e,this.failed=t}static ok(e){return new Vg(e,null)}static fail(e){return new Vg(null,e)}static fromReplace(e,t,n,i){try{return Vg.ok(e.replace(t,n,i))}catch(r){if(r instanceof OS)return Vg.fail(r.message);throw r}}};function NE(s,e,t){let n=[];for(let i=0;i<s.childCount;i++){let r=s.child(i);r.content.size&&(r=r.copy(NE(r.content,e,r))),r.isInline&&(r=e(r,t,i)),n.push(r)}return He.fromArray(n)}let $E=class Gg 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 tt(NE(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 tr.fromReplace(e,this.from,this.to,r)}invert(){return new _g(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 Gg(t.pos,n.pos,this.mark)}merge(e){return e instanceof Gg&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new Gg(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 Gg(t.from,t.to,e.markFromJSON(t.mark))}};Pi.jsonID("addMark",$E);let _g=class Kg 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 tt(NE(t.content,i=>i.mark(this.mark.removeFromSet(i.marks)),e),t.openStart,t.openEnd);return tr.fromReplace(e,this.from,this.to,n)}invert(){return new $E(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 Kg(t.pos,n.pos,this.mark)}merge(e){return e instanceof Kg&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new Kg(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 Kg(t.from,t.to,e.markFromJSON(t.mark))}};Pi.jsonID("removeMark",_g);let BE=class qg extends Pi{constructor(e,t){super(),this.pos=e,this.mark=t}apply(e){let t=e.nodeAt(this.pos);if(!t)return tr.fail("No node at mark step's position");let n=t.type.create(t.attrs,null,this.mark.addToSet(t.marks));return tr.fromReplace(e,this.pos,this.pos+1,new tt(He.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 qg(this.pos,t.marks[i]);return new qg(this.pos,this.mark)}}return new BS(this.pos,this.mark)}map(e){let t=e.mapResult(this.pos,1);return t.deletedAfter?null:new qg(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 qg(t.pos,e.markFromJSON(t.mark))}};Pi.jsonID("addNodeMark",BE);let BS=class JT extends Pi{constructor(e,t){super(),this.pos=e,this.mark=t}apply(e){let t=e.nodeAt(this.pos);if(!t)return tr.fail("No node at mark step's position");let n=t.type.create(t.attrs,null,this.mark.removeFromSet(t.marks));return tr.fromReplace(e,this.pos,this.pos+1,new tt(He.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 JT(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 JT(t.pos,e.markFromJSON(t.mark))}};Pi.jsonID("removeNodeMark",BS);let jo=class Qc 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&&ZT(e,this.from,this.to)?tr.fail("Structure replace would overwrite content"):tr.fromReplace(e,this.from,this.to,this.slice)}getMap(){return new Pf([this.from,this.to-this.from,this.slice.size])}invert(e){return new Qc(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&&Qc.MAP_BIAS<0?t:e.mapResult(this.from,1);return n.deletedAcross&&t.deletedAcross?null:new Qc(n.pos,Math.max(n.pos,t.pos),this.slice,this.structure)}merge(e){if(!(e instanceof Qc)||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?tt.empty:new tt(this.slice.content.append(e.slice.content),this.slice.openStart,e.slice.openEnd);return new Qc(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?tt.empty:new tt(e.slice.content.append(this.slice.content),e.slice.openStart,this.slice.openEnd);return new Qc(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 Qc(t.from,t.to,tt.fromJSON(e,t.slice),!!t.structure)}};jo.MAP_BIAS=1;Pi.jsonID("replace",jo);let Tr=class Mw 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&&(ZT(e,this.from,this.gapFrom)||ZT(e,this.gapTo,this.to)))return tr.fail("Structure gap-replace would overwrite content");let t=e.slice(this.gapFrom,this.gapTo);if(t.openStart||t.openEnd)return tr.fail("Gap is not a flat range");let n=this.slice.insertAt(this.insert,t.content);return n?tr.fromReplace(e,this.from,this.to,n):tr.fail("Content does not fit in gap")}getMap(){return new Pf([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 Mw(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 Mw(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 Mw(t.from,t.to,t.gapFrom,t.gapTo,tt.fromJSON(e,t.slice),t.insert,!!t.structure)}};Pi.jsonID("replaceAround",Tr);function ZT(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 lV(s,e,t,n){let i=[],r=[],o,a;s.doc.nodesBetween(e,t,(c,l,u)=>{if(!c.isInline)return;let d=c.marks;if(!n.isInSet(d)&&u.type.allowsMarkType(n.type)){let h=Math.max(l,e),p=Math.min(l+c.nodeSize,t),g=n.addToSet(d);for(let v=0;v<d.length;v++)d[v].isInSet(g)||(o&&o.to==h&&o.mark.eq(d[v])?o.to=p:i.push(o=new _g(h,p,d[v])));a&&a.to==h?a.to=p:r.push(a=new $E(h,p,n))}}),i.forEach(c=>s.step(c)),r.forEach(c=>s.step(c))}function cV(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 dk){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 d=c[u],h;for(let p=0;p<i.length;p++){let g=i[p];g.step==r-1&&d.eq(i[p].style)&&(h=g)}h?(h.to=l,h.step=r):i.push({style:d,from:Math.max(a,e),to:l,step:r})}}}),i.forEach(o=>s.step(new _g(o.from,o.to,o.style)))}function FE(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,d=n.matchType(l.type);if(!d)o.push(new jo(a,u,tt.empty));else{n=d;for(let h=0;h<l.marks.length;h++)t.allowsMarkType(l.marks[h].type)||s.step(new _g(a,u,l.marks[h]));if(i&&l.isText&&t.whitespace!="pre"){let h,p=/\r?\n|\r/g,g;for(;h=p.exec(l.text);)g||(g=new tt(He.from(t.schema.text(" ",t.allowedMarks(l.marks))),0,0)),o.push(new jo(a+h.index,a+h.index+h[0].length,g))}}a=u}if(!n.validEnd){let c=n.fillBefore(He.empty,!0);s.replace(a,a,new tt(c,0,0))}for(let c=o.length-1;c>=0;c--)s.step(o[c])}function uV(s,e,t){return(e==0||s.canReplace(e,s.childCount))&&(t==s.childCount||s.canReplace(0,t))}function wg(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||!uV(o,a,c))break;a&&(i=1),c<o.childCount&&(r=1)}return null}function dV(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=He.empty,d=0;for(let g=r,v=!1;g>t;g--)v||n.index(g)>0?(v=!0,u=He.from(n.node(g).copy(u)),d++):c--;let h=He.empty,p=0;for(let g=r,v=!1;g>t;g--)v||i.after(g+1)<i.end(g)?(v=!0,h=He.from(i.node(g).copy(h)),p++):l++;s.step(new Tr(c,l,o,a,new tt(u.append(h),d,p),u.size-d,!0))}function HE(s,e,t=null,n=s){let i=hV(s,e),r=i&&fV(n,e);return r?i.map(Hx).concat({type:e,attrs:t}).concat(r.map(Hx)):null}function Hx(s){return{type:s,attrs:null}}function hV(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 fV(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 pV(s,e,t){let n=He.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=He.from(t[o].type.create(t[o].attrs,n))}let i=e.start,r=e.end;s.step(new Tr(i,r,i,r,new tt(n,0,0),t.length,!0))}function mV(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)&&gV(s.doc,s.mapping.slice(r).map(a),n)){let l=null;if(n.schema.linebreakReplacement){let p=n.whitespace=="pre",g=!!n.contentMatch.matchType(n.schema.linebreakReplacement);p&&!g?l=!1:!p&&g&&(l=!0)}l===!1&&f2(s,o,a,r),FE(s,s.mapping.slice(r).map(a,1),n,void 0,l===null);let u=s.mapping.slice(r),d=u.map(a,1),h=u.map(a+o.nodeSize,1);return s.step(new Tr(d,h,d+1,h-1,new tt(He.from(n.create(c,null,o.marks)),0,0),1,!0)),l===!0&&h2(s,o,a,r),!1}})}function h2(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 f2(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 gV(s,e,t){let n=s.resolve(e),i=n.index();return n.parent.canReplaceWith(i,i+1,t)}function vV(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 Tr(e,e+r.nodeSize,e+1,e+r.nodeSize-1,new tt(He.from(o),0,0),1,!0))}function Ac(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 d=i.node(l),h=i.index(l);if(d.type.spec.isolating)return!1;let p=d.content.cutByIndex(h,d.childCount),g=n&&n[u+1];g&&(p=p.replaceChild(0,g.type.create(g.attrs)));let v=n&&n[u]||d;if(!d.canReplace(h+1,d.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 yV(s,e,t=1,n){let i=s.doc.resolve(e),r=He.empty,o=He.empty;for(let a=i.depth,c=i.depth-t,l=t-1;a>c;a--,l--){r=He.from(i.node(a).copy(r));let u=n&&n[l];o=He.from(u?u.type.create(u.attrs,o):i.node(a).copy(o))}s.step(new jo(e,e,new tt(r.append(o),t,t),!0))}function vd(s,e){let t=s.resolve(e),n=t.index();return p2(t.nodeBefore,t.nodeAfter)&&t.parent.canReplace(n,n+1)}function bV(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 p2(s,e){return!!(s&&e&&!s.isLeaf&&bV(s,e))}function hk(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&&p2(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 _V(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",d=!!o.contentMatch.matchType(i);u&&!d?n=!1:!u&&d&&(n=!0)}let a=s.steps.length;if(n===!1){let u=s.doc.resolve(e+t);f2(s,u.node(),u.before(),a)}o.inlineContent&&FE(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 jo(l,c.map(e+t,-1),tt.empty,!0)),n===!0){let u=s.doc.resolve(l);h2(s,u.node(),u.before(),s.steps.length)}return s}function wV(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 m2(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 d=l.contentMatchAt(c).findWrapping(i.firstChild.type);u=d&&l.canReplaceWith(c,c,d[0])}if(u)return a==0?n.pos:a<0?n.before(o+1):n.after(o+1)}return null}function fk(s,e,t=e,n=tt.empty){if(e==t&&!n.size)return null;let i=s.resolve(e),r=s.resolve(t);return g2(i,r,n)?new jo(e,t,n):new SV(i,r,n).fit()}function g2(s,e,t){return!t.openStart&&!t.openEnd&&s.start()==e.start()&&s.parent.canReplace(s.index(),e.index(),t.content)}class SV{constructor(e,t,n){this.$from=e,this.$to=t,this.unplaced=n,this.frontier=[],this.placed=He.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=He.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 tt(r,o,a);return e>-1?new Tr(n.pos,e,this.$to.pos,this.$to.end(),c,t):c.size||n.pos!=this.$to.pos?new jo(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=kC(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,d=null;if(t==1&&(o?l.matchType(o.type)||(d=l.fillBefore(He.from(o),!1)):r&&c.compatibleContent(r.type)))return{sliceDepth:n,frontierDepth:a,parent:r,inject:d};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=kC(e,t);return!i.childCount||i.firstChild.isLeaf?!1:(this.unplaced=new tt(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=kC(e,t);if(i.childCount<=1&&t>0){let r=e.size-t<=t+i.size;this.unplaced=new tt(Qg(e,t-1,1),t-1,r?t-1:n)}else this.unplaced=new tt(Qg(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:d,type:h}=this.frontier[t];if(i){for(let v=0;v<i.childCount;v++)u.push(i.child(v));d=d.matchFragment(i)}let p=a.size+e-(o.content.size-o.openEnd);for(;l<a.childCount;){let v=a.child(l),m=d.matchType(v.type);if(!m)break;l++,(l>1||c==0||v.content.size)&&(d=m,u.push(v2(v.mark(h.allowedMarks(v.marks)),l==1?c:0,l==a.childCount?p:-1)))}let g=l==a.childCount;g||(p=-1),this.placed=Xg(this.placed,t,He.from(u)),this.frontier[t].match=d,g&&p<0&&n&&n.type==this.frontier[this.depth].type&&this.frontier.length>1&&this.closeFrontierNode();for(let v=0,m=a;v<p;v++){let y=m.lastChild;this.frontier.push({type:y.type,match:y.contentMatchAt(y.childCount)}),m=y.content}this.unplaced=g?e==0?tt.empty:new tt(Qg(o.content,e-1,1),e-1,p<0?o.openEnd:e-1):new tt(Qg(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=Xg(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=Xg(this.placed,this.depth,He.from(e.create(t,n))),this.frontier.push({type:e,match:e.contentMatch})}closeFrontierNode(){let t=this.frontier.pop().match.fillBefore(He.empty,!0);t.childCount&&(this.placed=Xg(this.placed,this.frontier.length,t))}}function Qg(s,e,t){return e==0?s.cutByIndex(t,s.childCount):s.replaceChild(0,s.firstChild.copy(Qg(s.firstChild.content,e-1,t)))}function Xg(s,e,t){return e==0?s.append(t):s.replaceChild(s.childCount-1,s.lastChild.copy(Xg(s.lastChild.content,e-1,t)))}function kC(s,e){for(let t=0;t<e;t++)s=s.firstChild.content;return s}function v2(s,e,t){if(e<=0)return s;let n=s.content;return e>1&&(n=n.replaceChild(0,v2(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(He.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&&!kV(t,r.content,o)?a:null}function kV(s,e,t){for(let n=t;n<e.childCount;n++)if(!s.allowsMarks(e.child(n).marks))return!0;return!1}function CV(s){return s.spec.defining||s.spec.definingForContent}function TV(s,e,t,n){if(!n.size)return s.deleteRange(e,t);let i=s.doc.resolve(e),r=s.doc.resolve(t);if(g2(i,r,n))return s.step(new jo(e,t,n));let o=b2(i,r);o[o.length-1]==0&&o.pop();let a=-(i.depth+1);o.unshift(a);for(let h=i.depth,p=i.pos-1;h>0;h--,p--){let g=i.node(h).type.spec;if(g.defining||g.definingAsContext||g.isolating)break;o.indexOf(h)>-1?a=h:i.before(h)==p&&o.splice(1,0,-h)}let c=o.indexOf(a),l=[],u=n.openStart;for(let h=n.content,p=0;;p++){let g=h.firstChild;if(l.push(g),p==n.openStart)break;h=g.content}for(let h=u-1;h>=0;h--){let p=l[h],g=CV(p.type);if(g&&!p.sameMarkup(i.node(Math.abs(a)-1)))u=h;else if(g||!p.type.isTextblock)break}for(let h=n.openStart;h>=0;h--){let p=(h+u+1)%(n.openStart+1),g=l[p];if(g)for(let v=0;v<o.length;v++){let m=o[(v+c)%o.length],y=!0;m<0&&(y=!1,m=-m);let _=i.node(m-1),b=i.index(m-1);if(_.canReplaceWith(b,b,g.type,g.marks))return s.replace(i.before(m),y?r.after(m):t,new tt(y2(n.content,0,n.openStart,p),p,n.openEnd))}}let d=s.steps.length;for(let h=o.length-1;h>=0&&(s.replace(e,t,n),!(s.steps.length>d));h--){let p=o[h];p<0||(e=i.before(p),t=r.after(p))}}function y2(s,e,t,n,i){if(e<t){let r=s.firstChild;s=s.replaceChild(0,r.copy(y2(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(He.empty,!0))}return s}function AV(s,e,t,n){if(!n.isInline&&e==t&&s.doc.resolve(e).parent.content.size){let i=wV(s.doc,e,n.type);i!=null&&(e=t=i)}s.replaceRange(e,t,new tt(He.from(n),0,0))}function EV(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=b2(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 b2(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 _2=class xw 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 tr.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 tr.fromReplace(e,this.pos,this.pos+1,new tt(He.from(i),0,t.isLeaf?0:1))}getMap(){return Pf.empty}invert(e){return new xw(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 xw(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 xw(t.pos,t.attr,t.value)}};Pi.jsonID("attr",_2);let w2=class e1 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 tr.ok(n)}getMap(){return Pf.empty}invert(e){return new e1(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 e1(t.attr,t.value)}};Pi.jsonID("docAttr",w2);let og=class extends Error{};og=function s(e){let t=Error.call(this,e);return t.__proto__=s.prototype,t};og.prototype=Object.create(Error.prototype);og.prototype.constructor=og;og.prototype.name="TransformError";class S2{constructor(e){this.doc=e,this.steps=[],this.docs=[],this.mapping=new dy}get before(){return this.docs.length?this.docs[0]:this.doc}step(e){let t=this.maybeStep(e);if(t.failed)throw new og(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=tt.empty){let i=fk(this.doc,e,t,n);return i&&this.step(i),this}replaceWith(e,t,n){return this.replace(e,t,new tt(He.from(n),0,0))}delete(e,t){return this.replace(e,t,tt.empty)}insert(e,t){return this.replaceWith(e,e,t)}replaceRange(e,t,n){return TV(this,e,t,n),this}replaceRangeWith(e,t,n){return AV(this,e,t,n),this}deleteRange(e,t){return EV(this,e,t),this}lift(e,t){return dV(this,e,t),this}join(e,t=1){return _V(this,e,t),this}wrap(e,t){return pV(this,e,t),this}setBlockType(e,t=e,n,i=null){return mV(this,e,t,n,i),this}setNodeMarkup(e,t,n=null,i){return vV(this,e,t,n,i),this}setNodeAttribute(e,t,n){return this.step(new _2(e,t,n)),this}setDocAttribute(e,t){return this.step(new w2(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 As)t.isInSet(n.marks)&&this.step(new BS(e,t));else{let i=n.marks,r,o=[];for(;r=t.isInSet(i);)o.push(new BS(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 yV(this,e,t,n),this}addMark(e,t,n){return lV(this,e,t,n),this}removeMark(e,t,n){return cV(this,e,t,n),this}clearIncompatible(e,t,n){return FE(this,e,t,n),this}}const TC=Object.create(null);let Ht=class{constructor(e,t,n){this.$anchor=e,this.$head=t,this.ranges=n||[new MV(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=tt.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?tt.empty:t),a==0&&zx(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),zx(e,n,t.isInline?-1:1))}}static findFrom(e,t,n=!1){let i=e.parent.inlineContent?new kt(e):hp(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?hp(e.node(0),e.node(r),e.before(r+1),e.index(r),t,n):hp(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 Ec(e.node(0))}static atStart(e){return hp(e,e,0,0,1)||new Ec(e)}static atEnd(e){return hp(e,e,e.content.size,e.childCount,-1)||new Ec(e)}static fromJSON(e,t){if(!t||!t.type)throw new RangeError("Invalid input for Selection.fromJSON");let n=TC[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 TC)throw new RangeError("Duplicate use of selection JSON ID "+e);return TC[e]=t,t.prototype.jsonID=e,t}getBookmark(){return kt.between(this.$anchor,this.$head).getBookmark()}};Ht.prototype.visible=!0;let MV=class{constructor(e,t){this.$from=e,this.$to=t}},Ux=!1;function Wx(s){!Ux&&!s.parent.inlineContent&&(Ux=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+s.parent.type.name+")"))}let kt=class Yg extends Ht{constructor(e,t=e){Wx(e),Wx(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 Ht.near(n);let i=e.resolve(t.map(this.anchor));return new Yg(i.parent.inlineContent?i:n,n)}replace(e,t=tt.empty){if(super.replace(e,t),t==tt.empty){let n=this.$from.marksAcross(this.$to);n&&e.ensureMarks(n)}}eq(e){return e instanceof Yg&&e.anchor==this.anchor&&e.head==this.head}getBookmark(){return new k2(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 Yg(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=Ht.findFrom(t,n,!0)||Ht.findFrom(t,-n,!0);if(r)t=r.$head;else return Ht.near(t,n)}return e.parent.inlineContent||(i==0?e=t:(e=(Ht.findFrom(e,-n,!0)||Ht.findFrom(e,n,!0)).$anchor,e.pos<t.pos!=i<0&&(e=t))),new Yg(e,t)}};Ht.jsonID("text",kt);let k2=class C2{constructor(e,t){this.anchor=e,this.head=t}map(e){return new C2(e.map(this.anchor),e.map(this.head))}resolve(e){return kt.between(e.resolve(this.anchor),e.resolve(this.head))}},_t=class Jg extends Ht{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?Ht.near(r):new Jg(r)}content(){return new tt(He.from(this.node),0,0)}eq(e){return e instanceof Jg&&e.anchor==this.anchor}toJSON(){return{type:"node",anchor:this.anchor}}getBookmark(){return new xV(this.anchor)}static fromJSON(e,t){if(typeof t.anchor!="number")throw new RangeError("Invalid input for NodeSelection.fromJSON");return new Jg(e.resolve(t.anchor))}static create(e,t){return new Jg(e.resolve(t))}static isSelectable(e){return!e.isText&&e.type.spec.selectable!==!1}};_t.prototype.visible=!1;Ht.jsonID("node",_t);let xV=class T2{constructor(e){this.anchor=e}map(e){let{deleted:t,pos:n}=e.mapResult(this.anchor);return t?new k2(n,n):new T2(n)}resolve(e){let t=e.resolve(this.anchor),n=t.nodeAfter;return n&&_t.isSelectable(n)?new _t(t):Ht.near(t)}},Ec=class Rw extends Ht{constructor(e){super(e.resolve(0),e.resolve(e.content.size))}replace(e,t=tt.empty){if(t==tt.empty){e.delete(0,e.doc.content.size);let n=Ht.atStart(e.doc);n.eq(e.selection)||e.setSelection(n)}else super.replace(e,t)}toJSON(){return{type:"all"}}static fromJSON(e){return new Rw(e)}map(e){return new Rw(e)}eq(e){return e instanceof Rw}getBookmark(){return RV}};Ht.jsonID("all",Ec);const RV={map(){return this},resolve(s){return new Ec(s)}};function hp(s,e,t,n,i,r=!1){if(e.inlineContent)return kt.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&&_t.isSelectable(a))return _t.create(s,t-(i<0?a.nodeSize:0))}else{let c=hp(s,a,t+i,i<0?a.childCount:0,i,r);if(c)return c}t+=a.nodeSize*i}return null}function zx(s,e,t){let n=s.steps.length-1;if(n<e)return;let i=s.steps[n];if(!(i instanceof jo||i instanceof Tr))return;let r=s.mapping.maps[n],o;r.forEach((a,c,l,u)=>{o==null&&(o=u)}),s.setSelection(Ht.near(s.doc.resolve(o),t))}const jx=1,V_=2,Vx=4;class IV extends S2{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|jx)&~V_,this.storedMarks=null,this}get selectionSet(){return(this.updated&jx)>0}setStoredMarks(e){return this.storedMarks=e,this.updated|=V_,this}ensureMarks(e){return As.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&V_)>0}addStep(e,t){super.addStep(e,t),this.updated=this.updated&~V_,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)||As.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(Ht.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|=Vx,this}get scrolledIntoView(){return(this.updated&Vx)>0}}function Gx(s,e){return!e||!s?s:s.bind(e)}let Zg=class{constructor(e,t,n){this.name=e,this.init=Gx(t.init,n),this.apply=Gx(t.apply,n)}};const PV=[new Zg("doc",{init(s){return s.doc||s.schema.topNodeType.createAndFill()},apply(s){return s.doc}}),new Zg("selection",{init(s,e){return s.selection||Ht.atStart(e.doc)},apply(s){return s.selection}}),new Zg("storedMarks",{init(s){return s.storedMarks||null},apply(s,e,t,n){return n.selection.$cursor?s.storedMarks:null}}),new Zg("scrollToSelection",{init(){return 0},apply(s,e){return s.scrolledIntoView?e+1:e}})];class AC{constructor(e,t){this.schema=e,this.plugins=[],this.pluginsByKey=Object.create(null),this.fields=PV.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 Zg(n.key,n.spec.state,n))})}}class Tp{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 d=0;d<this.config.plugins.length;d++)i.push(d<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 Tp(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 IV(this)}static create(e){let t=new AC(e.doc?e.doc.type.schema:e.schema,e.plugins),n=new Tp(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 AC(this.schema,e.plugins),n=t.fields,i=new Tp(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 AC(e.schema,e.plugins),r=new Tp(i);return i.fields.forEach(o=>{if(o.name=="doc")r.doc=Tc.fromJSON(e.schema,t.doc);else if(o.name=="selection")r.selection=Ht.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 A2(s,e,t){for(let n in s){let i=s[n];i instanceof Function?i=i.bind(e):n=="handleDOMEvents"&&(i=A2(i,e,{})),t[n]=i}return t}class Gs{constructor(e){this.spec=e,this.props={},e.props&&A2(e.props,this,this.props),this.key=e.key?e.key.key:E2("plugin")}getState(e){return e[this.key]}}const EC=Object.create(null);function E2(s){return s in EC?s+"$"+ ++EC[s]:(EC[s]=0,s+"$")}class _n{constructor(e="key"){this.key=E2(e)}get(e){return e.config.pluginsByKey[this.key]}getState(e){return e[this.key]}}const M2=(s,e)=>s.selection.empty?!1:(e&&e(s.tr.deleteSelection().scrollIntoView()),!0);function x2(s,e){let{$cursor:t}=s.selection;return!t||(e?!e.endOfTextblock("backward",s):t.parentOffset>0)?null:t}const R2=(s,e,t)=>{let n=x2(s,t);if(!n)return!1;let i=UE(n);if(!i){let o=n.blockRange(),a=o&&wg(o);return a==null?!1:(e&&e(s.tr.lift(o,a).scrollIntoView()),!0)}let r=i.nodeBefore;if(F2(s,i,e,-1))return!0;if(n.parent.content.size==0&&(ag(r,"end")||_t.isSelectable(r)))for(let o=n.depth;;o--){let a=fk(s.doc,n.before(o),n.after(o),tt.empty);if(a&&a.slice.size<a.to-a.from){if(e){let c=s.tr.step(a);c.setSelection(ag(r,"end")?Ht.findFrom(c.doc.resolve(c.mapping.map(i.pos,-1)),-1):_t.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},LV=(s,e,t)=>{let n=x2(s,t);if(!n)return!1;let i=UE(n);return i?I2(s,i,e):!1},OV=(s,e,t)=>{let n=L2(s,t);if(!n)return!1;let i=WE(n);return i?I2(s,i,e):!1};function I2(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=fk(s.doc,r,c,tt.empty);if(!l||l.from!=r||l instanceof jo&&l.slice.size>=c-r)return!1;if(t){let u=s.tr.step(l);u.setSelection(kt.create(u.doc,r)),t(u.scrollIntoView())}return!0}function ag(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 P2=(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=UE(n)}let o=r&&r.nodeBefore;return!o||!_t.isSelectable(o)?!1:(e&&e(s.tr.setSelection(_t.create(s.doc,r.pos-o.nodeSize)).scrollIntoView()),!0)};function UE(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 L2(s,e){let{$cursor:t}=s.selection;return!t||(e?!e.endOfTextblock("forward",s):t.parentOffset<t.parent.content.size)?null:t}const O2=(s,e,t)=>{let n=L2(s,t);if(!n)return!1;let i=WE(n);if(!i)return!1;let r=i.nodeAfter;if(F2(s,i,e,1))return!0;if(n.parent.content.size==0&&(ag(r,"start")||_t.isSelectable(r))){let o=fk(s.doc,n.before(),n.after(),tt.empty);if(o&&o.slice.size<o.to-o.from){if(e){let a=s.tr.step(o);a.setSelection(ag(r,"start")?Ht.findFrom(a.doc.resolve(a.mapping.map(i.pos)),1):_t.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},D2=(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=WE(n)}let o=r&&r.nodeAfter;return!o||!_t.isSelectable(o)?!1:(e&&e(s.tr.setSelection(_t.create(s.doc,r.pos)).scrollIntoView()),!0)};function WE(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 DV=(s,e)=>{let t=s.selection,n=t instanceof _t,i;if(n){if(t.node.isTextblock||!vd(s.doc,t.from))return!1;i=t.from}else if(i=hk(s.doc,t.from,-1),i==null)return!1;if(e){let r=s.tr.join(i);n&&r.setSelection(_t.create(r.doc,i-s.doc.resolve(i).nodeBefore.nodeSize)),e(r.scrollIntoView())}return!0},NV=(s,e)=>{let t=s.selection,n;if(t instanceof _t){if(t.node.isTextblock||!vd(s.doc,t.to))return!1;n=t.to}else if(n=hk(s.doc,t.to,1),n==null)return!1;return e&&e(s.tr.join(n).scrollIntoView()),!0},$V=(s,e)=>{let{$from:t,$to:n}=s.selection,i=t.blockRange(n),r=i&&wg(i);return r==null?!1:(e&&e(s.tr.lift(i,r).scrollIntoView()),!0)},N2=(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 zE(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 BV=(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=zE(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(Ht.near(c.doc.resolve(a),1)),e(c.scrollIntoView())}return!0},$2=(s,e)=>{let t=s.selection,{$from:n,$to:i}=t;if(t instanceof Ec||n.parent.inlineContent||i.parent.inlineContent)return!1;let r=zE(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(kt.create(a.doc,o+1)),e(a.scrollIntoView())}return!0},B2=(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(Ac(s.doc,r))return e&&e(s.tr.split(r).scrollIntoView()),!0}let n=t.blockRange(),i=n&&wg(n);return i==null?!1:(e&&e(s.tr.lift(n,i).scrollIntoView()),!0)};function FV(s){return(e,t)=>{let{$from:n,$to:i}=e.selection;if(e.selection instanceof _t&&e.selection.node.isBlock)return!n.parentOffset||!Ac(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=zE(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 kt||e.selection instanceof Ec)&&u.deleteSelection();let d=u.mapping.map(n.pos),h=Ac(u.doc,d,r.length,r);if(h||(r[0]=a?{type:a}:null,h=Ac(u.doc,d,r.length,r)),!h)return!1;if(u.split(d,r.length,r),!c&&l&&n.node(o).type!=a){let p=u.mapping.map(n.before(o)),g=u.doc.resolve(p);a&&n.node(o-1).canReplaceWith(g.index(),g.index()+1,a)&&u.setNodeMarkup(u.mapping.map(n.before(o)),a)}return t&&t(u.scrollIntoView()),!0}}const HV=FV(),UV=(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(_t.create(s.doc,i))),!0)};function WV(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||vd(s.doc,e.pos))?!1:(t&&t(s.tr.join(e.pos).scrollIntoView()),!0)}function F2(s,e,t,n){let i=e.nodeBefore,r=e.nodeAfter,o,a,c=i.type.spec.isolating||r.type.spec.isolating;if(!c&&WV(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,g=He.empty;for(let y=o.length-1;y>=0;y--)g=He.from(o[y].create(null,g));g=He.from(i.copy(g));let v=s.tr.step(new Tr(e.pos-1,p,e.pos,p,new tt(g,1,0),o.length,!0)),m=v.doc.resolve(p+2*o.length);m.nodeAfter&&m.nodeAfter.type==i.type&&vd(v.doc,m.pos)&&v.join(m.pos),t(v.scrollIntoView())}return!0}let u=r.type.spec.isolating||n>0&&c?null:Ht.findFrom(e,1),d=u&&u.$from.blockRange(u.$to),h=d&&wg(d);if(h!=null&&h>=e.depth)return t&&t(s.tr.lift(d,h).scrollIntoView()),!0;if(l&&ag(r,"start",!0)&&ag(i,"end")){let p=i,g=[];for(;g.push(p),!p.isTextblock;)p=p.lastChild;let v=r,m=1;for(;!v.isTextblock;v=v.firstChild)m++;if(p.canReplace(p.childCount,p.childCount,v.content)){if(t){let y=He.empty;for(let b=g.length-1;b>=0;b--)y=He.from(g[b].copy(y));let _=s.tr.step(new Tr(e.pos-g.length,e.pos+r.nodeSize,e.pos+m,e.pos+r.nodeSize-m,new tt(y,g.length,0),0,!0));t(_.scrollIntoView())}return!0}}return!1}function H2(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(kt.create(e.doc,s<0?i.start(r):i.end(r)))),!0):!1}}const zV=H2(-1),jV=H2(1);function VV(s,e=null){return function(t,n){let{$from:i,$to:r}=t.selection,o=i.blockRange(r),a=o&&HE(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),d=u.index();i=u.parent.canReplaceWith(d,d+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 jE(...s){return function(e,t,n){for(let i=0;i<s.length;i++)if(s[i](e,t,n))return!0;return!1}}jE(M2,R2,P2);jE(M2,O2,D2);jE(N2,$2,B2,HV);typeof navigator<"u"?/Mac|iP(hone|[oa]d)/.test(navigator.platform):typeof os<"u"&&os.platform&&os.platform()=="darwin";function GV(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 KV(a,o,s,e)?(n&&n(a.scrollIntoView()),!0):!1}}function KV(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 NS(c,c,e.depth),e.endIndex<e.parent.childCount&&(e=new NS(e.$from,o.resolve(e.$to.end(e.depth)),e.depth)),i=!0}let a=HE(r,t,n,e);return a?(s&&qV(s,e,a,i,t),!0):!1}function qV(s,e,t,n,i){let r=He.empty;for(let u=t.length-1;u>=0;u--)r=He.from(t[u].type.create(t[u].attrs,r));s.step(new Tr(e.start-(n?2:0),e.end,e.start,e.end,new tt(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,d=e.endIndex,h=!0;u<d;u++,h=!1)!h&&Ac(s.doc,c,a)&&(s.split(c,a),c+=2*a),c+=l.child(u).nodeSize;return s}function QV(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?XV(e,t,s,r):YV(e,t,r):!0:!1}}function XV(s,e,t,n){let i=s.tr,r=n.end,o=n.$to.end(n.depth);r<o&&(i.step(new Tr(r-1,o,r,o,new tt(He.from(t.create(null,n.parent.copy())),1,0),1,!0)),n=new NS(i.doc.resolve(n.$from.pos),i.doc.resolve(o),n.depth));const a=wg(n);if(a==null)return!1;i.lift(n,a);let c=i.doc.resolve(i.mapping.map(r,-1)-1);return vd(i.doc,c.pos)&&c.nodeBefore.type==c.nodeAfter.type&&i.join(c.pos),e(i.scrollIntoView()),!0}function YV(s,e,t){let n=s.tr,i=t.parent;for(let p=t.end,g=t.endIndex-1,v=t.startIndex;g>v;g--)p-=i.child(g).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?He.empty:He.from(i))))return!1;let d=r.pos,h=d+o.nodeSize;return n.step(new Tr(d-(a?1:0),h+(c?1:0),d+1,h-1,new tt((a?He.empty:He.from(i.copy(He.empty))).append(c?He.empty:He.from(i.copy(He.empty))),a?0:1,c?0:1),a?0:1)),e(n.scrollIntoView()),!0}function JV(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=He.from(l?s.create():null),d=new tt(He.from(s.create(null,He.from(a.type.create(null,u)))),l?3:1,0),h=r.start,p=r.end;t(e.tr.step(new Tr(h-(l?3:1),p,h,p,d,1,!0)).scrollIntoView())}return!0}}const ci=function(s){for(var e=0;;e++)if(s=s.previousSibling,!s)return e},lg=function(s){let e=s.assignedSlot||s.parentNode;return e&&e.nodeType==11?e.host:e};let t1=null;const Ll=function(s,e,t){let n=t1||(t1=document.createRange());return n.setEnd(s,t??s.nodeValue.length),n.setStart(s,e||0),n},ZV=function(){t1=null},Lf=function(s,e,t,n){return t&&(qx(s,e,t,n,-1)||qx(s,e,t,n,1))},eG=/^(img|br|input|textarea|hr)$/i;function qx(s,e,t,n,i){for(var r;;){if(s==t&&e==n)return!0;if(e==(i<0?0:Bo(s))){let o=s.parentNode;if(!o||o.nodeType!=1||m_(s)||eG.test(s.nodeName)||s.contentEditable=="false")return!1;e=ci(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?Bo(s):0}else return!1}}function Bo(s){return s.nodeType==3?s.nodeValue.length:s.childNodes.length}function tG(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=Bo(s)}else if(s.parentNode&&!m_(s))e=ci(s),s=s.parentNode;else return null}}function sG(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&&!m_(s))e=ci(s)+1,s=s.parentNode;else return null}}function nG(s,e,t){for(let n=e==0,i=e==Bo(s);n||i;){if(s==t)return!0;let r=ci(s);if(s=s.parentNode,!s)return!1;n=n&&r==0,i=i&&r==Bo(s)}}function m_(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 pk=function(s){return s.focusNode&&Lf(s.focusNode,s.focusOffset,s.anchorNode,s.anchorOffset)};function Dd(s,e){let t=document.createEvent("Event");return t.initEvent("keydown",!0,!0),t.keyCode=s,t.key=t.code=e,t}function iG(s){let e=s.activeElement;for(;e&&e.shadowRoot;)e=e.shadowRoot.activeElement;return e}function rG(s,e,t){if(s.caretPositionFromPoint)try{let n=s.caretPositionFromPoint(e,t);if(n)return{node:n.offsetNode,offset:Math.min(Bo(n.offsetNode),n.offset)}}catch{}if(s.caretRangeFromPoint){let n=s.caretRangeFromPoint(e,t);if(n)return{node:n.startContainer,offset:Math.min(Bo(n.startContainer),n.startOffset)}}}const ul=typeof navigator<"u"?navigator:null,Qx=typeof document<"u"?document:null,yd=ul&&ul.userAgent||"",s1=/Edge\/(\d+)/.exec(yd),U2=/MSIE \d/.exec(yd),n1=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(yd),Cr=!!(U2||n1||s1),ld=U2?document.documentMode:n1?+n1[1]:s1?+s1[1]:0,Ho=!Cr&&/gecko\/(\d+)/i.test(yd);Ho&&+(/Firefox\/(\d+)/.exec(yd)||[0,0])[1];const i1=!Cr&&/Chrome\/(\d+)/.exec(yd),hi=!!i1,W2=i1?+i1[1]:0,Ii=!Cr&&!!ul&&/Apple Computer/.test(ul.vendor),cg=Ii&&(/Mobile\/\w+/.test(yd)||!!ul&&ul.maxTouchPoints>2),Do=cg||(ul?/Mac/.test(ul.platform):!1),z2=ul?/Win/.test(ul.platform):!1,wc=/Android \d/.test(yd),g_=!!Qx&&"webkitFontSmoothing"in Qx.documentElement.style,oG=g_?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function aG(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 Tl(s,e){return typeof s=="number"?s:s[e]}function lG(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 Xx(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=lg(o);continue}let a=o,c=a==r.body,l=c?aG(r):lG(a),u=0,d=0;if(e.top<l.top+Tl(n,"top")?d=-(l.top-e.top+Tl(i,"top")):e.bottom>l.bottom-Tl(n,"bottom")&&(d=e.bottom-e.top>l.bottom-l.top?e.top+Tl(i,"top")-l.top:e.bottom-l.bottom+Tl(i,"bottom")),e.left<l.left+Tl(n,"left")?u=-(l.left-e.left+Tl(i,"left")):e.right>l.right-Tl(n,"right")&&(u=e.right-l.right+Tl(i,"right")),u||d)if(c)r.defaultView.scrollBy(u,d);else{let p=a.scrollLeft,g=a.scrollTop;d&&(a.scrollTop+=d),u&&(a.scrollLeft+=u);let v=a.scrollLeft-p,m=a.scrollTop-g;e={left:e.left-v,top:e.top-m,right:e.right-v,bottom:e.bottom-m}}let h=c?"fixed":getComputedStyle(o).position;if(/^(fixed|sticky)$/.test(h))break;o=h=="absolute"?o.offsetParent:lg(o)}}function cG(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:j2(s.dom)}}function j2(s){let e=[],t=s.ownerDocument;for(let n=s;n&&(e.push({dom:n,top:n.scrollTop,left:n.scrollLeft}),s!=t);n=lg(n));return e}function uG({refDOM:s,refTop:e,stack:t}){let n=s?s.getBoundingClientRect().top:0;V2(t,n==0?0:n-e)}function V2(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 sp=null;function dG(s){if(s.setActive)return s.setActive();if(sp)return s.focus(sp);let e=j2(s);s.focus(sp==null?{get preventScroll(){return sp={preventScroll:!0},!0}}:void 0),sp||(sp=!1,V2(e,0))}function G2(s,e){let t,n=2e8,i,r=0,o=e.top,a=e.top,c,l;for(let u=s.firstChild,d=0;u;u=u.nextSibling,d++){let h;if(u.nodeType==1)h=u.getClientRects();else if(u.nodeType==3)h=Ll(u).getClientRects();else continue;for(let p=0;p<h.length;p++){let g=h[p];if(g.top<=o&&g.bottom>=a){o=Math.max(g.bottom,o),a=Math.min(g.top,a);let v=g.left>e.left?g.left-e.left:g.right<e.left?e.left-g.right:0;if(v<n){t=u,n=v,i=v&&t.nodeType==3?{left:g.right<e.left?g.right:g.left,top:e.top}:e,u.nodeType==1&&v&&(r=d+(e.left>=(g.left+g.right)/2?1:0));continue}}else g.top>e.top&&!c&&g.left<=e.left&&g.right>=e.left&&(c=u,l={left:Math.max(g.left,Math.min(g.right,e.left)),top:g.top});!t&&(e.left>=g.right&&e.top>=g.top||e.left>=g.left&&e.top>=g.bottom)&&(r=d+1)}}return!t&&c&&(t=c,i=l,n=0),t&&t.nodeType==3?hG(t,i):!t||n&&t.nodeType==1?{node:s,offset:r}:G2(t,i)}function hG(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=Xc(n,1);if(o.top!=o.bottom&&VE(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 VE(s,e){return s.left>=e.left-1&&s.left<=e.right+1&&s.top>=e.top-1&&s.top<=e.bottom+1}function fG(s,e){let t=s.parentNode;return t&&/^li$/i.test(t.nodeName)&&e.left<s.getBoundingClientRect().left?t:s}function pG(s,e,t){let{node:n,offset:i}=G2(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 mG(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 K2(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(VE(e,l))return K2(o,e,l)}}if((r=(r+1)%n)==i)break}return s}function gG(s,e){let t=s.dom.ownerDocument,n,i=0,r=rG(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(!VE(e,l)||(o=K2(s.dom,e,l),!o))return null}if(Ii)for(let l=o;n&&l;l=lg(l))l.draggable&&(n=void 0);if(o=fG(o,e),n){if(Ho&&n.nodeType==1&&(i=Math.min(i,n.childNodes.length),i<n.childNodes.length)){let u=n.childNodes[i],d;u.nodeName=="IMG"&&(d=u.getBoundingClientRect()).right<=e.left&&d.bottom>e.top&&i++}let l;g_&&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=mG(s,n,i,e))}a==null&&(a=pG(s,o,e));let c=s.docView.nearestDesc(o,!0);return{pos:a,inside:c?c.posAtStart-c.border:-1}}function Yx(s){return s.top<s.bottom||s.left<s.right}function Xc(s,e){let t=s.getClientRects();if(t.length){let n=t[e<0?0:t.length-1];if(Yx(n))return n}return Array.prototype.find.call(t,Yx)||s.getBoundingClientRect()}const vG=/[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;function q2(s,e,t){let{node:n,offset:i,atom:r}=s.docView.domFromPos(e,t<0?-1:1),o=g_||Ho;if(n.nodeType==3)if(o&&(vG.test(n.nodeValue)||(t<0?!i:i==n.nodeValue.length))){let c=Xc(Ll(n,i,i),t);if(Ho&&i&&/\s/.test(n.nodeValue[i-1])&&i<n.nodeValue.length){let l=Xc(Ll(n,i-1,i-1),-1);if(l.top==c.top){let u=Xc(Ll(n,i,i+1),-1);if(u.top!=c.top)return Og(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++,Og(Xc(Ll(n,c,l),u),u<0)}if(!s.state.doc.resolve(e-(r||0)).parent.inlineContent){if(r==null&&i&&(t<0||i==Bo(n))){let c=n.childNodes[i-1];if(c.nodeType==1)return MC(c.getBoundingClientRect(),!1)}if(r==null&&i<Bo(n)){let c=n.childNodes[i];if(c.nodeType==1)return MC(c.getBoundingClientRect(),!0)}return MC(n.getBoundingClientRect(),t>=0)}if(r==null&&i&&(t<0||i==Bo(n))){let c=n.childNodes[i-1],l=c.nodeType==3?Ll(c,Bo(c)-(o?0:1)):c.nodeType==1&&(c.nodeName!="BR"||!c.nextSibling)?c:null;if(l)return Og(Xc(l,1),!1)}if(r==null&&i<Bo(n)){let c=n.childNodes[i];for(;c.pmViewDesc&&c.pmViewDesc.ignoreForCoords;)c=c.nextSibling;let l=c?c.nodeType==3?Ll(c,0,o?0:1):c.nodeType==1?c:null:null;if(l)return Og(Xc(l,-1),!0)}return Og(Xc(n.nodeType==3?Ll(n):n,-t),t>=0)}function Og(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 MC(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 Q2(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 yG(s,e,t){let n=e.selection,i=t=="up"?n.$from:n.$to;return Q2(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=q2(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=Ll(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 bG=/[\u0590-\u08ac]/;function _G(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?!bG.test(n.parent.textContent)||!a.modify?t=="left"||t=="backward"?r:o:Q2(s,e,()=>{let{focusNode:c,focusOffset:l,anchorNode:u,anchorOffset:d}=s.domSelectionRange(),h=a.caretBidiLevel;a.modify("move",t,"character");let p=n.depth?s.docView.domAfterPos(n.before()):s.dom,{focusNode:g,focusOffset:v}=s.domSelectionRange(),m=g&&!p.contains(g.nodeType==1?g:g.parentNode)||c==g&&l==v;try{a.collapse(u,d),c&&(c!=u||l!=d)&&a.extend&&a.extend(c,l)}catch{}return h!=null&&(a.caretBidiLevel=h),m}):n.pos==n.start()||n.pos==n.end()}let Jx=null,Zx=null,eR=!1;function wG(s,e,t){return Jx==e&&Zx==t?eR:(Jx=e,Zx=t,eR=t=="up"||t=="down"?yG(s,e,t):_G(s,e,t))}const Uo=0,tR=1,Ud=2,dl=3;class v_{constructor(e,t,n,i){this.parent=e,this.children=t,this.dom=n,this.contentDOM=i,this.dirty=Uo,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>ci(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 Y2){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 X2&&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?ci(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?ci(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 d=a;d>0;d--){let h=this.children[d-1];if(h.size&&h.dom.parentNode==this.contentDOM&&!h.emptyChildAt(1)){i=ci(h.dom)+1;break}e-=h.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 d=this.children[u];if(d.size&&d.dom.parentNode==this.contentDOM&&!d.emptyChildAt(-1)){r=ci(d.dom);break}t+=d.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,g=0;p<this.children.length;p++){let v=this.children[p],m=g+v.size;if(r>g&&o<m)return v.setSelection(e-g-v.border,t-g-v.border,n,i);g=m}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(),d=!1;if((Ho||Ii)&&e==t){let{node:p,offset:g}=a;if(p.nodeType==3){if(d=!!(g&&p.nodeValue[g-1]==`
|
||
`),d&&g==p.nodeValue.length)for(let v=p,m;v;v=v.parentNode){if(m=v.nextSibling){m.nodeName=="BR"&&(a=c={node:m.parentNode,offset:ci(m)+1});break}let y=v.pmViewDesc;if(y&&y.node&&y.node.isBlock)break}}else{let v=p.childNodes[g-1];d=v&&(v.nodeName=="BR"||v.contentEditable=="false")}}if(Ho&&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||d&&Ii)&&Lf(a.node,a.offset,u.anchorNode,u.anchorOffset)&&Lf(c.node,c.offset,u.focusNode,u.focusOffset))return;let h=!1;if((l.extend||e==t)&&!(d&&Ho)){l.collapse(a.node,a.offset);try{e!=t&&l.extend(c.node,c.offset),h=!0}catch{}}if(!h){if(e>t){let g=a;a=c,c=g}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?Ud:tR,e==a&&t==c&&(r.contentLost||r.dom.parentNode!=this.contentDOM)?r.dirty=dl:r.markDirty(e-a,t-a);return}else r.dirty=r.dom==r.contentDOM&&r.dom.parentNode==this.contentDOM&&!r.children.length?Ud:dl}n=o}this.dirty=Ud}markParentsDirty(){let e=1;for(let t=this.parent;t;t=t.parent,e++){let n=e==1?Ud:tR;t.dirty<n&&(t.dirty=n)}}get domAtom(){return!1}get ignoreForCoords(){return!1}get ignoreForSelection(){return!1}isText(e){return!1}}class X2 extends v_{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==Uo&&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 SG extends v_{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 Of extends v_{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=Hf.renderSpec(document,t.type.spec.toDOM(t,n),null,t.attrs)),new Of(e,t,o.dom,o.contentDOM||o.dom,o)}parseRule(){return this.dirty&dl||this.mark.type.spec.reparseInView?null:{mark:this.mark.type.name,attrs:this.mark.attrs,contentElement:this.contentDOM}}matchesMark(e){return this.dirty!=dl&&this.mark.eq(e)}markDirty(e,t){if(super.markDirty(e,t),this.dirty!=Uo){let n=this.parent;for(;!n.node;)n=n.parent;n.dirty<this.dirty&&(n.dirty=this.dirty),this.dirty=Uo}}slice(e,t,n){let i=Of.create(this.parent,this.mark,!0,n),r=this.children,o=this.size;t<o&&(r=o1(r,t,o,n)),e>0&&(r=o1(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 cd extends v_{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,d=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:d}=Hf.renderSpec(document,t.type.spec.toDOM(t),null,t.attrs));!d&&!t.isText&&u.nodeName!="BR"&&(u.hasAttribute("contenteditable")||(u.contentEditable="false"),t.type.spec.draggable&&(u.draggable=!0));let h=u;return u=eO(u,n,t),l?c=new kG(e,t,n,i,u,d||null,h,l,r,o+1):t.isText?new mk(e,t,n,i,u,h,r):new cd(e,t,n,i,u,d||null,h,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=()=>He.empty)}return e}matchesNode(e,t,n){return this.dirty==Uo&&e.eq(this.node)&&FS(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 TG(this,o&&o.node,e);MG(this.node,this.innerDeco,(l,u,d)=>{l.spec.marks?c.syncToMarks(l.spec.marks,n,e,u):l.type.side>=0&&!d&&c.syncToMarks(u==this.node.childCount?As.none:this.node.child(u).marks,n,e,u),c.placeWidget(l,e,i)},(l,u,d,h)=>{c.syncToMarks(l.marks,n,e,h);let p;c.findNodeMatch(l,u,d,h)||a&&e.state.selection.from>i&&e.state.selection.to<i+l.nodeSize&&(p=c.findIndexWithChild(r.node))>-1&&c.updateNodeAt(l,u,d,p,e)||c.updateNextNode(l,u,d,e,h,i)||c.addNode(l,u,d,e,i),i+=l.nodeSize}),c.syncToMarks([],n,e,0),this.node.isTextblock&&c.addTextblockHacks(),c.destroyRest(),(c.changed||this.dirty==Ud)&&(o&&this.protectLocalComposition(e,o),J2(this.contentDOM,this.children,e),cg&&xG(this.dom))}localCompositionInfo(e,t){let{from:n,to:i}=e.state.selection;if(!(e.state.selection instanceof kt)||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=RG(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 SG(this,r,t,i);e.input.compositionNodes.push(o),this.children=o1(this.children,n,n+i.length,e,o)}update(e,t,n,i){return this.dirty==dl||!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=Uo}updateOuterDeco(e){if(FS(e,this.outerDeco))return;let t=this.nodeDOM.nodeType!=1,n=this.dom;this.dom=Z2(this.dom,this.nodeDOM,r1(this.outerDeco,this.node,t),r1(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 sR(s,e,t,n,i){eO(n,e,s);let r=new cd(void 0,s,e,t,n,n,n,i,0);return r.contentDOM&&r.updateChildren(i,0),r}class mk extends cd{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==dl||this.dirty!=Uo&&!this.inParent()||!e.sameMarkup(this.node)?!1:(this.updateOuterDeco(t),(this.dirty!=Uo||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=Uo,!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 mk(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=dl)}get domAtom(){return!1}isText(e){return this.node.text==e}}class Y2 extends v_{parseRule(){return{ignore:!0}}matchesHack(e){return this.dirty==Uo&&this.dom.nodeName==e}get domAtom(){return!0}get ignoreForCoords(){return this.dom.nodeName=="IMG"}}class kG extends cd{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==dl)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 J2(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=nR(n),i=!0;n=n.nextSibling}else i=!0,s.insertBefore(a,n);if(o instanceof Of){let c=n?n.previousSibling:s.lastChild;J2(o.contentDOM,o.children,t),n=c?c.nextSibling:s.firstChild}}for(;n;)n=nR(n),i=!0;i&&t.trackWrites==s&&(t.trackWrites=null)}const zv=function(s){s&&(this.nodeName=s)};zv.prototype=Object.create(null);const Wd=[new zv];function r1(s,e,t){if(s.length==0)return Wd;let n=t?Wd[0]:new zv,i=[n];for(let r=0;r<s.length;r++){let o=s[r].type.attrs;if(o){o.nodeName&&i.push(n=new zv(o.nodeName));for(let a in o){let c=o[a];c!=null&&(t&&i.length==1&&i.push(n=new zv(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 Z2(s,e,t,n){if(t==Wd&&n==Wd)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=Wd[0]),i=c}CG(i,a||Wd[0],o)}return i}function CG(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 eO(s,e,t){return Z2(s,s,Wd,r1(e,t,s.nodeType!=1))}function FS(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 nR(s){let e=s.nextSibling;return s.parentNode.removeChild(s),e}class TG{constructor(e,t,n){this.lock=t,this.view=n,this.index=0,this.stack=[],this.changed=!1,this.top=e,this.preMatch=AG(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=Uo,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 d=this.top.children[u];if(d.matchesMark(e[o])&&!this.isLocked(d.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=Of.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==dl&&o.dom==o.contentDOM&&(o.dirty=Ud),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 cd){let l=this.preMatch.matched.get(c);if(l!=null&&l!=r)return!1;let u=c.dom,d,h=this.isLocked(u)&&!(e.isText&&c.node&&c.node.isText&&c.nodeDOM.nodeValue==e.text&&c.dirty!=dl&&FS(t,c.outerDeco));if(!h&&c.update(e,t,n,i))return this.destroyBetween(this.index,a),c.dom!=u&&(this.changed=!0),this.index++,!0;if(!h&&(d=this.recreateWrapper(c,e,t,n,i,o)))return this.destroyBetween(this.index,a),this.top.children[this.index]=d,d.contentDOM&&(d.dirty=Ud,d.updateChildren(i,o+1),d.dirty=Uo),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)||!FS(n,e.outerDeco)||!i.eq(e.innerDeco))return null;let a=cd.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=cd.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 X2(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 Of;)t=e,e=t.children[t.children.length-1];(!e||!(e instanceof mk)||/\n$/.test(e.node.text)||this.view.requiresGeckoHackNode&&/\s$/.test(e.node.text))&&((Ii||hi)&&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 Y2(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 AG(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 Of)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 EG(s,e){return s.type.side-e.type.side}function MG(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,d;for(;o<i.length&&i[o].to==r;){let m=i[o++];m.widget&&(u?(d||(d=[u])).push(m):u=m)}if(u)if(d){d.sort(EG);for(let m=0;m<d.length;m++)t(d[m],l,!!c)}else t(u,l,!!c);let h,p;if(c)p=-1,h=c,c=null;else if(l<s.childCount)p=l,h=s.child(l++);else break;for(let m=0;m<a.length;m++)a[m].to<=r&&a.splice(m--,1);for(;o<i.length&&i[o].from<=r&&i[o].to>r;)a.push(i[o++]);let g=r+h.nodeSize;if(h.isText){let m=g;o<i.length&&i[o].from<m&&(m=i[o].from);for(let y=0;y<a.length;y++)a[y].to<m&&(m=a[y].to);m<g&&(c=h.cut(m-r),h=h.cut(0,m-r),g=m,p=-1)}else for(;o<i.length&&i[o].to<g;)o++;let v=h.isInline&&!h.isLeaf?a.filter(m=>!m.inline):a.slice();n(h,v,e.forChild(r,h),p),r=g}}function xG(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 RG(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 o1(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 GE(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(pk(t)){for(c=o;i&&!i.node;)i=i.parent;let d=i.node;if(i&&d.isAtom&&_t.isSelectable(d)&&i.parent&&!(d.isInline&&nG(t.focusNode,t.focusOffset,i.dom))){let h=i.posBefore;l=new _t(o==h?a:n.resolve(h))}}else{if(t instanceof s.dom.ownerDocument.defaultView.Selection&&t.rangeCount>1){let d=o,h=o;for(let p=0;p<t.rangeCount;p++){let g=t.getRangeAt(p);d=Math.min(d,s.docView.posFromDOM(g.startContainer,g.startOffset,1)),h=Math.max(h,s.docView.posFromDOM(g.endContainer,g.endOffset,-1))}if(d<0)return null;[c,o]=h==s.state.selection.anchor?[h,d]:[d,h],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 d=e=="pointer"||s.state.selection.head<a.pos&&!r?1:-1;l=KE(s,u,a,d)}return l}function tO(s){return s.editable?s.hasFocus():nO(s)&&document.activeElement&&document.activeElement.contains(s.dom)}function Mc(s,e=!1){let t=s.state.selection;if(sO(s,t),!!tO(s)){if(!e&&s.input.mouseDown&&s.input.mouseDown.allowDefault&&hi){let n=s.domSelectionRange(),i=s.domObserver.currentSelection;if(n.anchorNode&&i.anchorNode&&Lf(n.anchorNode,n.anchorOffset,i.anchorNode,i.anchorOffset)){s.input.mouseDown.delayedSelectionSync=!0,s.domObserver.setCurSelection();return}}if(s.domObserver.disconnectSelection(),s.cursorWrapper)PG(s);else{let{anchor:n,head:i}=t,r,o;iR&&!(t instanceof kt)&&(t.$from.parent.inlineContent||(r=rR(s,t.from)),!t.empty&&!t.$from.parent.inlineContent&&(o=rR(s,t.to))),s.docView.setSelection(n,i,s,e),iR&&(r&&oR(r),o&&oR(o)),t.visible?s.dom.classList.remove("ProseMirror-hideselection"):(s.dom.classList.add("ProseMirror-hideselection"),"onselectionchange"in document&&IG(s))}s.domObserver.setCurSelection(),s.domObserver.connectSelection()}}const iR=Ii||hi&&W2<63;function rR(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(Ii&&i&&i.contentEditable=="false")return xC(i);if((!i||i.contentEditable=="false")&&(!r||r.contentEditable=="false")){if(i)return xC(i);if(r)return xC(r)}}function xC(s){return s.contentEditable="true",Ii&&s.draggable&&(s.draggable=!1,s.wasDraggable=!0),s}function oR(s){s.contentEditable="false",s.wasDraggable&&(s.draggable=!0,s.wasDraggable=null)}function IG(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(()=>{(!tO(s)||s.state.selection.visible)&&s.dom.classList.remove("ProseMirror-hideselection")},20))})}function PG(s){let e=s.domSelection();if(!e)return;let t=s.cursorWrapper.dom,n=t.nodeName=="IMG";n?e.collapse(t.parentNode,ci(t)+1):e.collapse(t,0),!n&&!s.state.selection.visible&&Cr&&ld<=11&&(t.disabled=!0,t.disabled=!1)}function sO(s,e){if(e instanceof _t){let t=s.docView.descAt(e.from);t!=s.lastSelectedViewDesc&&(aR(s),t&&t.selectNode(),s.lastSelectedViewDesc=t)}else aR(s)}function aR(s){s.lastSelectedViewDesc&&(s.lastSelectedViewDesc.parent&&s.lastSelectedViewDesc.deselectNode(),s.lastSelectedViewDesc=void 0)}function KE(s,e,t,n){return s.someProp("createSelectionBetween",i=>i(s,e,t))||kt.between(e,t,n)}function lR(s){return s.editable&&!s.hasFocus()?!1:nO(s)}function nO(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 LG(s){let e=s.docView.domFromPos(s.state.selection.anchor,0),t=s.domSelectionRange();return Lf(e.node,e.offset,t.anchorNode,t.anchorOffset)}function a1(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&&Ht.findFrom(r,e)}function eu(s,e){return s.dispatch(s.state.tr.setSelection(e).scrollIntoView()),!0}function cR(s,e,t){let n=s.state.selection;if(n instanceof kt)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 eu(s,new kt(n.$anchor,o))}else if(n.empty){if(s.endOfTextblock(e>0?"forward":"backward")){let i=a1(s.state,e);return i&&i instanceof _t?eu(s,i):!1}else if(!(Do&&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?_t.isSelectable(r)?eu(s,new _t(e<0?s.state.doc.resolve(i.pos-r.nodeSize):i)):g_?eu(s,new kt(s.state.doc.resolve(e<0?a:a+r.nodeSize))):!1:!1}}else return!1;else{if(n instanceof _t&&n.node.isInline)return eu(s,new kt(e>0?n.$to:n.$from));{let i=a1(s.state,e);return i?eu(s,i):!1}}}function HS(s){return s.nodeType==3?s.nodeValue.length:s.childNodes.length}function jv(s,e){let t=s.pmViewDesc;return t&&t.size==0&&(e<0||s.nextSibling||s.nodeName!="BR")}function np(s,e){return e<0?OG(s):DG(s)}function OG(s){let e=s.domSelectionRange(),t=e.focusNode,n=e.focusOffset;if(!t)return;let i,r,o=!1;for(Ho&&t.nodeType==1&&n<HS(t)&&jv(t.childNodes[n],-1)&&(o=!0);;)if(n>0){if(t.nodeType!=1)break;{let a=t.childNodes[n-1];if(jv(a,-1))i=t,r=--n;else if(a.nodeType==3)t=a,n=t.nodeValue.length;else break}}else{if(iO(t))break;{let a=t.previousSibling;for(;a&&jv(a,-1);)i=t.parentNode,r=ci(a),a=a.previousSibling;if(a)t=a,n=HS(t);else{if(t=t.parentNode,t==s.dom)break;n=0}}}o?l1(s,t,n):i&&l1(s,i,r)}function DG(s){let e=s.domSelectionRange(),t=e.focusNode,n=e.focusOffset;if(!t)return;let i=HS(t),r,o;for(;;)if(n<i){if(t.nodeType!=1)break;let a=t.childNodes[n];if(jv(a,1))r=t,o=++n;else break}else{if(iO(t))break;{let a=t.nextSibling;for(;a&&jv(a,1);)r=a.parentNode,o=ci(a)+1,a=a.nextSibling;if(a)t=a,n=0,i=HS(t);else{if(t=t.parentNode,t==s.dom)break;n=i=0}}}r&&l1(s,r,o)}function iO(s){let e=s.pmViewDesc;return e&&e.node&&e.node.isBlock}function NG(s,e){for(;s&&e==s.childNodes.length&&!m_(s);)e=ci(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 $G(s,e){for(;s&&!e&&!m_(s);)e=ci(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 l1(s,e,t){if(e.nodeType!=3){let r,o;(o=NG(e,t))?(e=o,t=0):(r=$G(e,t))&&(e=r,t=r.nodeValue.length)}let n=s.domSelection();if(!n)return;if(pk(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&&Mc(s)},50)}function uR(s,e){let t=s.state.doc.resolve(e);if(!(hi||z2)&&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 dR(s,e,t){let n=s.state.selection;if(n instanceof kt&&!n.empty||t.indexOf("s")>-1||Do&&t.indexOf("m")>-1)return!1;let{$from:i,$to:r}=n;if(!i.parent.inlineContent||s.endOfTextblock(e<0?"up":"down")){let o=a1(s.state,e);if(o&&o instanceof _t)return eu(s,o)}if(!i.parent.inlineContent){let o=e<0?i:r,a=n instanceof Ec?Ht.near(o,e):Ht.findFrom(o,e);return a?eu(s,a):!1}return!1}function hR(s,e){if(!(s.state.selection instanceof kt))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 fR(s,e,t){s.domObserver.stop(),e.contentEditable=t,s.domObserver.start()}function BG(s){if(!Ii||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;fR(s,n,"true"),setTimeout(()=>fR(s,n,"false"),20)}return!1}function FG(s){let e="";return s.ctrlKey&&(e+="c"),s.metaKey&&(e+="m"),s.altKey&&(e+="a"),s.shiftKey&&(e+="s"),e}function HG(s,e){let t=e.keyCode,n=FG(e);if(t==8||Do&&t==72&&n=="c")return hR(s,-1)||np(s,-1);if(t==46&&!e.shiftKey||Do&&t==68&&n=="c")return hR(s,1)||np(s,1);if(t==13||t==27)return!0;if(t==37||Do&&t==66&&n=="c"){let i=t==37?uR(s,s.state.selection.from)=="ltr"?-1:1:-1;return cR(s,i,n)||np(s,i)}else if(t==39||Do&&t==70&&n=="c"){let i=t==39?uR(s,s.state.selection.from)=="ltr"?1:-1:1;return cR(s,i,n)||np(s,i)}else{if(t==38||Do&&t==80&&n=="c")return dR(s,-1,n)||np(s,-1);if(t==40||Do&&t==78&&n=="c")return BG(s)||dR(s,1,n)||np(s,1);if(n==(Do?"m":"c")&&(t==66||t==73||t==89||t==90))return!0}return!1}function qE(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")||Hf.fromSchema(s.state.schema),a=uO(),c=a.createElement("div");c.appendChild(o.serializeFragment(n,{document:a}));let l=c.firstChild,u,d=0;for(;l&&l.nodeType==1&&(u=cO[l.nodeName.toLowerCase()]);){for(let p=u.length-1;p>=0;p--){let g=a.createElement(u[p]);for(;c.firstChild;)g.appendChild(c.firstChild);c.appendChild(g),d++}l=c.firstChild}l&&l.nodeType==1&&l.setAttribute("data-pm-slice",`${i} ${r}${d?` -${d}`:""} ${JSON.stringify(t)}`);let h=s.someProp("clipboardTextSerializer",p=>p(e,s))||e.content.textBetween(0,e.content.size,`
|
||
|
||
`);return{dom:c,text:h,slice:e}}function rO(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",h=>{e=h(e,r||n,s)}),r)return a=new tt(He.from(s.state.schema.text(e.replace(/\r\n?/g,`
|
||
`))),0,0),s.someProp("transformPasted",h=>{a=h(a,s,!0)}),a;let d=s.someProp("clipboardTextParser",h=>h(e,i,n,s));if(d)a=d;else{let h=i.marks(),{schema:p}=s.state,g=Hf.fromSchema(p);o=document.createElement("div"),e.split(/(?:\r\n?|\n)+/).forEach(v=>{let m=o.appendChild(document.createElement("p"));v&&m.appendChild(g.serializeNode(p.text(v,h)))})}}else s.someProp("transformPastedHTML",d=>{t=d(t,s)}),o=jG(t),g_&&VG(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 d=+u[3];d>0;d--){let h=o.firstChild;for(;h&&h.nodeType!=1;)h=h.nextSibling;if(!h)break;o=h}if(a||(a=(s.someProp("clipboardParser")||s.someProp("domParser")||Uv.fromSchema(s.state.schema)).parseSlice(o,{preserveWhitespace:!!(c||u),context:i,ruleFromNode(h){return h.nodeName=="BR"&&!h.nextSibling&&h.parentNode&&!UG.test(h.parentNode.nodeName)?{ignore:!0}:null}})),u)a=GG(pR(a,+u[1],+u[2]),u[4]);else if(a=tt.maxOpen(WG(a.content,i),!0),a.openStart||a.openEnd){let d=0,h=0;for(let p=a.content.firstChild;d<a.openStart&&!p.type.spec.isolating;d++,p=p.firstChild);for(let p=a.content.lastChild;h<a.openEnd&&!p.type.spec.isolating;h++,p=p.lastChild);a=pR(a,d,h)}return s.someProp("transformPasted",d=>{a=d(a,s,c)}),a}const UG=/^(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 WG(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&&aO(c,r,a,o[o.length-1],0))o[o.length-1]=l;else{o.length&&(o[o.length-1]=lO(o[o.length-1],r.length));let u=oO(a,c);o.push(u),i=i.matchType(u.type),r=c}}),o)return He.from(o)}return s}function oO(s,e,t=0){for(let n=e.length-1;n>=t;n--)s=e[n].create(null,He.from(s));return s}function aO(s,e,t,n,i){if(i<s.length&&i<e.length&&s[i]==e[i]){let r=aO(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(He.from(oO(t,s,i+1))))}}function lO(s,e){if(e==0)return s;let t=s.content.replaceChild(s.childCount-1,lO(s.lastChild,e-1)),n=s.contentMatchAt(s.childCount).fillBefore(He.empty,!0);return s.copy(t.append(n))}function c1(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=c1(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(He.empty,!0))),s.replaceChild(e<0?0:s.childCount-1,o.copy(a))}function pR(s,e,t){return e<s.openStart&&(s=new tt(c1(s.content,-1,e,s.openStart,0,s.openEnd),e,s.openEnd)),t<s.openEnd&&(s=new tt(c1(s.content,1,t,s.openEnd,0,0),s.openStart,t)),s}const cO={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 mR=null;function uO(){return mR||(mR=document.implementation.createHTMLDocument("title"))}let RC=null;function zG(s){let e=window.trustedTypes;return e?(RC||(RC=e.defaultPolicy||e.createPolicy("ProseMirrorClipboard",{createHTML:t=>t})),RC.createHTML(s)):s}function jG(s){let e=/^(\s*<meta [^>]*>)*/.exec(s);e&&(s=s.slice(e[0].length));let t=uO().createElement("div"),n=/<([a-z][^>\s]+)/i.exec(s),i;if((i=n&&cO[n[1].toLowerCase()])&&(s=i.map(r=>"<"+r+">").join("")+s+i.map(r=>"</"+r+">").reverse().join("")),t.innerHTML=zG(s),i)for(let r=0;r<i.length;r++)t=t.querySelector(i[r])||t;return t}function VG(s){let e=s.querySelectorAll(hi?"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 GG(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=He.from(c.create(n[a+1],i)),r++,o++}return new tt(i,r,o)}const or={},ar={},KG={touchstart:!0,touchmove:!0};class qG{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 QG(s){for(let e in or){let t=or[e];s.dom.addEventListener(e,s.input.eventHandlers[e]=n=>{YG(s,n)&&!QE(s,n)&&(s.editable||!(n.type in ar))&&t(s,n)},KG[e]?{passive:!0}:void 0)}Ii&&s.dom.addEventListener("input",()=>null),u1(s)}function od(s,e){s.input.lastSelectionOrigin=e,s.input.lastSelectionTime=Date.now()}function XG(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 u1(s){s.someProp("handleDOMEvents",e=>{for(let t in e)s.input.eventHandlers[t]||s.dom.addEventListener(t,s.input.eventHandlers[t]=n=>QE(s,n))})}function QE(s,e){return s.someProp("handleDOMEvents",t=>{let n=t[e.type];return n?n(s,e)||e.defaultPrevented:!1})}function YG(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 JG(s,e){!QE(s,e)&&or[e.type]&&(s.editable||!(e.type in ar))&&or[e.type](s,e)}ar.keydown=(s,e)=>{let t=e;if(s.input.shiftKey=t.keyCode==16||t.shiftKey,!hO(s,t)&&(s.input.lastKeyCode=t.keyCode,s.input.lastKeyCodeTime=Date.now(),!(wc&&hi&&t.keyCode==13)))if(t.keyCode!=229&&s.domObserver.forceFlush(),cg&&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,Dd(13,"Enter"))),s.input.lastIOSEnter=0)},200)}else s.someProp("handleKeyDown",n=>n(s,t))||HG(s,t)?t.preventDefault():od(s,"key")};ar.keyup=(s,e)=>{e.keyCode==16&&(s.input.shiftKey=!1)};ar.keypress=(s,e)=>{let t=e;if(hO(s,t)||!t.charCode||t.ctrlKey&&!t.altKey||Do&&t.metaKey)return;if(s.someProp("handleKeyPress",i=>i(s,t))){t.preventDefault();return}let n=s.state.selection;if(!(n instanceof kt)||!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 gk(s){return{left:s.clientX,top:s.clientY}}function ZG(s,e){let t=e.x-s.clientX,n=e.y-s.clientY;return t*t+n*n<100}function XE(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 xp(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 eK(s,e){if(e==-1)return!1;let t=s.state.doc.resolve(e),n=t.nodeAfter;return n&&n.isAtom&&_t.isSelectable(n)?(xp(s,new _t(t)),!0):!1}function tK(s,e){if(e==-1)return!1;let t=s.state.selection,n,i;t instanceof _t&&(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(_t.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?(xp(s,_t.create(s.state.doc,i)),!0):!1}function sK(s,e,t,n,i){return XE(s,"handleClickOn",e,t,n)||s.someProp("handleClick",r=>r(s,e,n))||(i?tK(s,t):eK(s,t))}function nK(s,e,t,n){return XE(s,"handleDoubleClickOn",e,t,n)||s.someProp("handleDoubleClick",i=>i(s,e,n))}function iK(s,e,t,n){return XE(s,"handleTripleClickOn",e,t,n)||s.someProp("handleTripleClick",i=>i(s,e,n))||rK(s,t,n)}function rK(s,e,t){if(t.button!=0)return!1;let n=s.state.doc;if(e==-1)return n.inlineContent?(xp(s,kt.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)xp(s,kt.create(n,a+1,a+1+o.content.size));else if(_t.isSelectable(o))xp(s,_t.create(n,a));else continue;return!0}}function YE(s){return US(s)}const dO=Do?"metaKey":"ctrlKey";or.mousedown=(s,e)=>{let t=e;s.input.shiftKey=t.shiftKey;let n=YE(s),i=Date.now(),r="singleClick";i-s.input.lastClick.time<500&&ZG(t,s.input.lastClick)&&!t[dO]&&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(gk(t));o&&(r=="singleClick"?(s.input.mouseDown&&s.input.mouseDown.done(),s.input.mouseDown=new oK(s,o,t,!!n)):(r=="doubleClick"?nK:iK)(s,o.pos,o.inside,t)?t.preventDefault():od(s,"pointer"))};class oK{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[dO],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 _t&&l.from<=o&&l.to>o)&&(this.mightDrag={node:r,pos:o,addAttr:!!(this.target&&!this.target.draggable),setUneditable:!!(this.target&&Ho&&!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)),od(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(()=>Mc(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(gk(e))),this.updateAllowDefault(e),this.allowDefault||!t?od(this.view,"pointer"):sK(this.view,t.pos,t.inside,e,this.selectNode)?e.preventDefault():e.button==0&&(this.flushed||Ii&&this.mightDrag&&!this.mightDrag.node.isAtom||hi&&!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)?(xp(this.view,Ht.near(this.view.state.doc.resolve(t.pos))),e.preventDefault()):od(this.view,"pointer")}move(e){this.updateAllowDefault(e),od(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)}}or.touchstart=s=>{s.input.lastTouch=Date.now(),YE(s),od(s,"pointer")};or.touchmove=s=>{s.input.lastTouch=Date.now(),od(s,"pointer")};or.contextmenu=s=>YE(s);function hO(s,e){return s.composing?!0:Ii&&Math.abs(e.timeStamp-s.input.compositionEndedAt)<500?(s.input.compositionEndedAt=-2e8,!0):!1}const aK=wc?5e3:-1;ar.compositionstart=ar.compositionupdate=s=>{if(!s.composing){s.domObserver.flush();let{state:e}=s,t=e.selection.$to;if(e.selection instanceof kt&&(e.storedMarks||!t.textOffset&&t.parentOffset&&t.nodeBefore.marks.some(n=>n.type.spec.inclusive===!1)||hi&&z2&&lK(s)))s.markCursor=s.state.storedMarks||t.marks(),US(s,!0),s.markCursor=null;else if(US(s,!e.selection.empty),Ho&&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}fO(s,aK)};function lK(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"}ar.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++,fO(s,20))};function fO(s,e){clearTimeout(s.input.composingTimeout),e>-1&&(s.input.composingTimeout=setTimeout(()=>US(s),e))}function pO(s){for(s.composing&&(s.input.composing=!1,s.input.compositionEndedAt=uK());s.input.compositionNodes.length>0;)s.input.compositionNodes.pop().markParentsDirty()}function cK(s){let e=s.domSelectionRange();if(!e.focusNode)return null;let t=tG(e.focusNode,e.focusOffset),n=sG(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 uK(){let s=document.createEvent("Event");return s.initEvent("event",!0,!0),s.timeStamp}function US(s,e=!1){if(!(wc&&s.domObserver.flushingSoon>=0)){if(s.domObserver.forceFlush(),pO(s),e||s.docView&&s.docView.dirty){let t=GE(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 dK(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 hy=Cr&&ld<15||cg&&oG<604;or.copy=ar.cut=(s,e)=>{let t=e,n=s.state.selection,i=t.type=="cut";if(n.empty)return;let r=hy?null:t.clipboardData,o=n.content(),{dom:a,text:c}=qE(s,o);r?(t.preventDefault(),r.clearData(),r.setData("text/html",a.innerHTML),r.setData("text/plain",c)):dK(s,a),i&&s.dispatch(s.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent","cut"))};function hK(s){return s.openStart==0&&s.openEnd==0&&s.content.childCount==1?s.content.firstChild:null}function fK(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?fy(s,n.value,null,i,e):fy(s,n.textContent,n.innerHTML,i,e)},50)}function fy(s,e,t,n,i){let r=rO(s,e,t,n,s.state.selection.$from);if(s.someProp("handlePaste",c=>c(s,i,r||tt.empty)))return!0;if(!r)return!1;let o=hK(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 mO(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," "):""}ar.paste=(s,e)=>{let t=e;if(s.composing&&!wc)return;let n=hy?null:t.clipboardData,i=s.input.shiftKey&&s.input.lastKeyCode!=45;n&&fy(s,mO(n),n.getData("text/html"),i,t)?t.preventDefault():fK(s,t)};class gO{constructor(e,t,n){this.slice=e,this.move=t,this.node=n}}const pK=Do?"altKey":"ctrlKey";function vO(s,e){let t;return s.someProp("dragCopies",n=>{t=t||n(e)}),t!=null?!t:!e[pK]}or.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(gk(t)),o;if(!(r&&r.pos>=i.from&&r.pos<=(i instanceof _t?i.to-1:i.to))){if(n&&n.mightDrag)o=_t.create(s.state.doc,n.mightDrag.pos);else if(t.target&&t.target.nodeType==1){let d=s.docView.nearestDesc(t.target,!0);d&&d.node.type.spec.draggable&&d!=s.docView&&(o=_t.create(s.state.doc,d.posBefore))}}let a=(o||s.state.selection).content(),{dom:c,text:l,slice:u}=qE(s,a);(!t.dataTransfer.files.length||!hi||W2>120)&&t.dataTransfer.clearData(),t.dataTransfer.setData(hy?"Text":"text/html",c.innerHTML),t.dataTransfer.effectAllowed="copyMove",hy||t.dataTransfer.setData("text/plain",l),s.dragging=new gO(u,vO(s,t),o)};or.dragend=s=>{let e=s.dragging;window.setTimeout(()=>{s.dragging==e&&(s.dragging=null)},50)};ar.dragover=ar.dragenter=(s,e)=>e.preventDefault();ar.drop=(s,e)=>{try{mK(s,e,s.dragging)}finally{s.dragging=null}};function mK(s,e,t){if(!e.dataTransfer)return;let n=s.posAtCoords(gk(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=rO(s,mO(e.dataTransfer),hy?null:e.dataTransfer.getData("text/html"),!1,i);let o=!!(t&&vO(s,e));if(s.someProp("handleDrop",p=>p(s,e,r||tt.empty,o))){e.preventDefault();return}if(!r)return;e.preventDefault();let a=r?m2(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,d=c.doc;if(u?c.replaceRangeWith(l,l,r.content.firstChild):c.replaceRange(l,l,r),c.doc.eq(d))return;let h=c.doc.resolve(l);if(u&&_t.isSelectable(r.content.firstChild)&&h.nodeAfter&&h.nodeAfter.sameMarkup(r.content.firstChild))c.setSelection(new _t(h));else{let p=c.mapping.map(a);c.mapping.maps[c.mapping.maps.length-1].forEach((g,v,m,y)=>p=y),c.setSelection(KE(s,h,c.doc.resolve(p)))}s.focus(),s.dispatch(c.setMeta("uiEvent","drop"))}or.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())&&Mc(s)},20))};or.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)};or.beforeinput=(s,e)=>{if(hi&&wc&&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,Dd(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 ar)or[s]=ar[s];function py(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 WS{constructor(e,t){this.toDOM=e,this.spec=t||Mf,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 Ai(r-n,r-n,this)}valid(){return!0}eq(e){return this==e||e instanceof WS&&(this.spec.key&&this.spec.key==e.spec.key||this.toDOM==e.toDOM&&py(this.spec,e.spec))}destroy(e){this.spec.destroy&&this.spec.destroy(e)}}class ud{constructor(e,t){this.attrs=e,this.spec=t||Mf}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 Ai(r,o,this)}valid(e,t){return t.from<t.to}eq(e){return this==e||e instanceof ud&&py(this.attrs,e.attrs)&&py(this.spec,e.spec)}static is(e){return e.type instanceof ud}destroy(){}}class JE{constructor(e,t){this.attrs=e,this.spec=t||Mf}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 Ai(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 JE&&py(this.attrs,e.attrs)&&py(this.spec,e.spec)}destroy(){}}class Ai{constructor(e,t,n){this.from=e,this.to=t,this.type=n}copy(e,t){return new Ai(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 Ai(e,e,new WS(t,n))}static inline(e,t,n,i){return new Ai(e,t,new ud(n,i))}static node(e,t,n,i){return new Ai(e,t,new JE(n,i))}get spec(){return this.type.spec}get inline(){return this.type instanceof ud}get widget(){return this.type instanceof WS}}const fp=[],Mf={};class js{constructor(e,t){this.local=e.length?e:fp,this.children=t.length?t:fp}static create(e,t){return t.length?zS(t,e,0,Mf):ki}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==ki||e.maps.length==0?this:this.mapInner(e,t,0,0,n||Mf)}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?gK(this.children,o||[],e,t,n,i,r):o?new js(o.sort(xf),fp):ki}add(e,t){return t.length?this==ki?js.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=bO(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,zS(u,a,l+1,Mf)),r+=3}});let o=yO(r?_O(t):t,-n);for(let a=0;a<o.length;a++)o[a].type.valid(e,o[a])||o.splice(a--,1);return new js(o.length?this.local.concat(o).sort(xf):this.local,i||this.children)}remove(e){return e.length==0||this==ki?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,d;u<e.length;u++)(d=e[u])&&d.from>a&&d.to<c&&(e[u]=null,(o||(o=[])).push(d));if(!o)continue;n==this.children&&(n=this.children.slice());let l=n[r+2].removeInner(o,a+1);l!=ki?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 js(i,n):ki}forChild(e,t){if(this==ki)return this;if(t.isLeaf)return js.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 ud){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 js(i.sort(xf),fp);return n?new nu([a,n]):a}return n||ki}eq(e){if(this==e)return!0;if(!(e instanceof js)||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 ZE(this.localsInner(e))}localsInner(e){if(this==ki)return fp;if(e.inlineContent||!this.local.some(ud.is))return this.local;let t=[];for(let n=0;n<this.local.length;n++)this.local[n].type instanceof ud||t.push(this.local[n]);return t}forEachSet(e){e(this)}}js.empty=new js([],[]);js.removeOverlap=ZE;const ki=js.empty;class nu{constructor(e){this.members=e}map(e,t){const n=this.members.map(i=>i.map(e,t,Mf));return nu.from(n)}forChild(e,t){if(t.isLeaf)return js.empty;let n=[];for(let i=0;i<this.members.length;i++){let r=this.members[i].forChild(e,t);r!=ki&&(r instanceof nu?n=n.concat(r.members):n.push(r))}return nu.from(n)}eq(e){if(!(e instanceof nu)||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?ZE(n?t:t.sort(xf)):fp}static from(e){switch(e.length){case 0:return ki;case 1:return e[0];default:return new nu(e.every(t=>t instanceof js)?e:e.reduce((t,n)=>t.concat(n instanceof js?n:n.members),[]))}}forEachSet(e){for(let t=0;t<this.members.length;t++)this.members[t].forEachSet(e)}}function gK(s,e,t,n,i,r,o){let a=s.slice();for(let l=0,u=r;l<t.maps.length;l++){let d=0;t.maps[l].forEach((h,p,g,v)=>{let m=v-g-(p-h);for(let y=0;y<a.length;y+=3){let _=a[y+1];if(_<0||h>_+u-d)continue;let b=a[y]+u-d;p>=b?a[y+1]=h<=b?-2:-1:h>=u&&m&&(a[y]+=m,a[y+1]+=m)}d+=m}),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),d=u-i;if(d<0||d>=n.content.size){c=!0;continue}let h=t.map(s[l+1]+r,-1),p=h-i,{index:g,offset:v}=n.content.findIndex(d),m=n.maybeChild(g);if(m&&v==d&&v+m.nodeSize==p){let y=a[l+2].mapInner(t,m,u+1,s[l]+r+1,o);y!=ki?(a[l]=d,a[l+1]=p,a[l+2]=y):(a[l+1]=-2,c=!0)}else c=!0}if(c){let l=vK(a,s,e,t,i,r,o),u=zS(l,n,0,o);e=u.local;for(let d=0;d<a.length;d+=3)a[d+1]<0&&(a.splice(d,3),d-=3);for(let d=0,h=0;d<u.children.length;d+=3){let p=u.children[d];for(;h<a.length&&a[h]<p;)h+=3;a.splice(h,0,u.children[d],u.children[d+1],u.children[d+2])}}return new js(e.sort(xf),a)}function yO(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 Ai(i.from+e,i.to+e,i.type))}return t}function vK(s,e,t,n,i,r,o){function a(c,l){for(let u=0;u<c.local.length;u++){let d=c.local[u].map(n,i,l);d?t.push(d):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 bO(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 _O(s){let e=[];for(let t=0;t<s.length;t++)s[t]!=null&&e.push(s[t]);return e}function zS(s,e,t,n){let i=[],r=!1;e.forEach((a,c)=>{let l=bO(s,a,c+t);if(l){r=!0;let u=zS(l,a,t+c+1,n);u!=ki&&i.push(c,c+a.nodeSize,u)}});let o=yO(r?_O(s):s,-t).sort(xf);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 js(o,i):ki}function xf(s,e){return s.from-e.from||s.to-e.to}function ZE(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),gR(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),gR(e,i,n.copy(r.from,n.to)));break}}}return e}function gR(s,e,t){for(;e<s.length&&xf(t,s[e])>0;)e++;s.splice(e,0,t)}function IC(s){let e=[];return s.someProp("decorations",t=>{let n=t(s.state);n&&n!=ki&&e.push(n)}),s.cursorWrapper&&e.push(js.create(s.state.doc,[s.cursorWrapper.deco])),nu.from(e)}const yK={childList:!0,characterData:!0,characterDataOldValue:!0,attributes:!0,attributeOldValue:!0,subtree:!0},bK=Cr&&ld<=11;class _K{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 wK{constructor(e,t){this.view=e,this.handleDOMChange=t,this.queue=[],this.flushingSoon=-1,this.observer=null,this.currentSelection=new _K,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]);Cr&&ld<=11&&n.some(i=>i.type=="childList"&&i.removedNodes.length||i.type=="characterData"&&i.oldValue.length>i.target.nodeValue.length)?this.flushSoon():Ii&&e.composing&&n.some(i=>i.type=="childList"&&i.target.nodeName=="TR")?(e.input.badSafariComposition=!0,this.flushSoon()):this.flush()}),bK&&(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,yK)),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(lR(this.view)){if(this.suppressingSelectionUpdates)return Mc(this.view);if(Cr&&ld<=11&&!this.view.state.selection.empty){let e=this.view.domSelectionRange();if(e.focusNode&&Lf(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=lg(r))t.add(r);for(let r=e.anchorNode;r;r=lg(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)&&lR(e)&&!this.ignoreSelectionChange(n),r=-1,o=-1,a=!1,c=[];if(e.editable)for(let u=0;u<t.length;u++){let d=this.registerMutation(t[u],c);d&&(r=r<0?d.from:Math.min(d.from,r),o=o<0?d.to:Math.max(d.to,o),d.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 d=u.nextSibling;for(;d&&d.nodeType==1;){if(d.contentEditable=="false"){u.parentNode.removeChild(u);break}d=d.firstChild}}}else if(Ho&&c.length){let u=c.filter(d=>d.nodeName=="BR");if(u.length==2){let[d,h]=u;d.parentNode&&d.parentNode.parentNode==h.parentNode?h.remove():d.remove()}else{let{focusNode:d}=this.currentSelection;for(let h of u){let p=h.parentNode;p&&p.nodeName=="LI"&&(!d||CK(e,d)!=p)&&h.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&&pk(n)&&(l=GE(e))&&l.eq(Ht.near(e.state.doc.resolve(0),1))?(e.input.lastFocus=0,Mc(e),this.currentSelection.set(n),e.scrollToSelection()):(r>-1||i)&&(r>-1&&(e.docView.markDirty(r,o),SK(e)),e.input.badSafariComposition&&(e.input.badSafariComposition=!1,TK(e,c)),this.handleDOMChange(r,o,a,c),e.docView&&e.docView.dirty?e.updateState(e.state):this.currentSelection.eq(n)||Mc(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 d=e.addedNodes[u];t.push(d),d.nodeType==3&&(this.lastChangedTextNode=d)}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(Cr&&ld<=11&&e.addedNodes.length)for(let u=0;u<e.addedNodes.length;u++){let{previousSibling:d,nextSibling:h}=e.addedNodes[u];(!d||Array.prototype.indexOf.call(e.addedNodes,d)<0)&&(i=d),(!h||Array.prototype.indexOf.call(e.addedNodes,h)<0)&&(r=h)}let o=i&&i.parentNode==e.target?ci(i)+1:0,a=n.localPosFromDOM(e.target,o,-1),c=r&&r.parentNode==e.target?ci(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 vR=new WeakMap,yR=!1;function SK(s){if(!vR.has(s)&&(vR.set(s,null),["normal","nowrap","pre-line"].indexOf(getComputedStyle(s.dom).whiteSpace)!==-1)){if(s.requiresGeckoHackNode=Ho,yR)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."),yR=!0}}function bR(s,e){let t=e.startContainer,n=e.startOffset,i=e.endContainer,r=e.endOffset,o=s.domAtPos(s.state.selection.anchor);return Lf(o.node,o.offset,i,r)&&([t,n,i,r]=[i,r,t,n]),{anchorNode:t,anchorOffset:n,focusNode:i,focusOffset:r}}function kK(s,e){if(e.getComposedRanges){let i=e.getComposedRanges(s.root)[0];if(i)return bR(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?bR(s,t):null}function CK(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 TK(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 AK(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}],pk(c)||l.push({node:c.focusNode,offset:c.focusOffset})),hi&&s.input.lastKeyCode===8)for(let m=r;m>i;m--){let y=n.childNodes[m-1],_=y.pmViewDesc;if(y.nodeName=="BR"&&!_){r=m;break}if(!_||_.size)break}let d=s.state.doc,h=s.someProp("domParser")||Uv.fromSchema(s.state.schema),p=d.resolve(o),g=null,v=h.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:EK,context:p});if(l&&l[0].pos!=null){let m=l[0].pos,y=l[1]&&l[1].pos;y==null&&(y=m),g={anchor:m+o,head:y+o}}return{doc:v,sel:g,from:o,to:a}}function EK(s){let e=s.pmViewDesc;if(e)return e.parseRule();if(s.nodeName=="BR"&&s.parentNode){if(Ii&&/^(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||Ii&&/^(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 MK=/^(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 xK(s,e,t,n,i){let r=s.input.compositionPendingChanges||(s.composing?s.input.compositionID:0);if(s.input.compositionPendingChanges=0,e<0){let A=s.input.lastSelectionTime>Date.now()-50?s.input.lastSelectionOrigin:null,C=GE(s,A);if(C&&!s.state.selection.eq(C)){if(hi&&wc&&s.input.lastKeyCode===13&&Date.now()-100<s.input.lastKeyCodeTime&&s.someProp("handleKeyDown",x=>x(s,Dd(13,"Enter"))))return;let E=s.state.tr.setSelection(C);A=="pointer"?E.setMeta("pointer",!0):A=="key"&&E.scrollIntoView(),r&&E.setMeta("composition",r),s.dispatch(E)}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=AK(s,e,t),u=s.state.doc,d=u.slice(l.from,l.to),h,p;s.input.lastKeyCode===8&&Date.now()-100<s.input.lastKeyCodeTime?(h=s.state.selection.to,p="end"):(h=s.state.selection.from,p="start"),s.input.lastKeyCode=null;let g=PK(d.content,l.doc.content,l.from,h,p);if(g&&s.input.domChangeCount++,(cg&&s.input.lastIOSEnter>Date.now()-225||wc)&&i.some(A=>A.nodeType==1&&!MK.test(A.nodeName))&&(!g||g.endA>=g.endB)&&s.someProp("handleKeyDown",A=>A(s,Dd(13,"Enter")))){s.input.lastIOSEnter=0;return}if(!g)if(n&&c instanceof kt&&!c.empty&&c.$head.sameParent(c.$anchor)&&!s.composing&&!(l.sel&&l.sel.anchor!=l.sel.head))g={start:c.from,endA:c.to,endB:c.to};else{if(l.sel){let A=_R(s,s.state.doc,l.sel);if(A&&!A.eq(s.state.selection)){let C=s.state.tr.setSelection(A);r&&C.setMeta("composition",r),s.dispatch(C)}}return}s.state.selection.from<s.state.selection.to&&g.start==g.endB&&s.state.selection instanceof kt&&(g.start>s.state.selection.from&&g.start<=s.state.selection.from+2&&s.state.selection.from>=l.from?g.start=s.state.selection.from:g.endA<s.state.selection.to&&g.endA>=s.state.selection.to-2&&s.state.selection.to<=l.to&&(g.endB+=s.state.selection.to-g.endA,g.endA=s.state.selection.to)),Cr&&ld<=11&&g.endB==g.start+1&&g.endA==g.start&&g.start>l.from&&l.doc.textBetween(g.start-l.from-1,g.start-l.from+1)==" "&&(g.start--,g.endA--,g.endB--);let v=l.doc.resolveNoCache(g.start-l.from),m=l.doc.resolveNoCache(g.endB-l.from),y=u.resolve(g.start),_=v.sameParent(m)&&v.parent.inlineContent&&y.end()>=g.endA;if((cg&&s.input.lastIOSEnter>Date.now()-225&&(!_||i.some(A=>A.nodeName=="DIV"||A.nodeName=="P"))||!_&&v.pos<l.doc.content.size&&(!v.sameParent(m)||!v.parent.inlineContent)&&v.pos<m.pos&&!/\S/.test(l.doc.textBetween(v.pos,m.pos,"","")))&&s.someProp("handleKeyDown",A=>A(s,Dd(13,"Enter")))){s.input.lastIOSEnter=0;return}if(s.state.selection.anchor>g.start&&IK(u,g.start,g.endA,v,m)&&s.someProp("handleKeyDown",A=>A(s,Dd(8,"Backspace")))){wc&&hi&&s.domObserver.suppressSelectionUpdates();return}hi&&g.endB==g.start&&(s.input.lastChromeDelete=Date.now()),wc&&!_&&v.start()!=m.start()&&m.parentOffset==0&&v.depth==m.depth&&l.sel&&l.sel.anchor==l.sel.head&&l.sel.head==g.endA&&(g.endB-=2,m=l.doc.resolveNoCache(g.endB-l.from),setTimeout(()=>{s.someProp("handleKeyDown",function(A){return A(s,Dd(13,"Enter"))})},20));let b=g.start,k=g.endA,w=A=>{let C=A||s.state.tr.replace(b,k,l.doc.slice(g.start-l.from,g.endB-l.from));if(l.sel){let E=_R(s,C.doc,l.sel);E&&!(hi&&s.composing&&E.empty&&(g.start!=g.endB||s.input.lastChromeDelete<Date.now()-100)&&(E.head==b||E.head==C.mapping.map(k)-1)||Cr&&E.empty&&E.head==b)&&C.setSelection(E)}return r&&C.setMeta("composition",r),C.scrollIntoView()},T;if(_)if(v.pos==m.pos){Cr&&ld<=11&&v.parentOffset==0&&(s.domObserver.suppressSelectionUpdates(),setTimeout(()=>Mc(s),20));let A=w(s.state.tr.delete(b,k)),C=u.resolve(g.start).marksAcross(u.resolve(g.endA));C&&A.ensureMarks(C),s.dispatch(A)}else if(g.endA==g.endB&&(T=RK(v.parent.content.cut(v.parentOffset,m.parentOffset),y.parent.content.cut(y.parentOffset,g.endA-y.start())))){let A=w(s.state.tr);T.type=="add"?A.addMark(b,k,T.mark):A.removeMark(b,k,T.mark),s.dispatch(A)}else if(v.parent.child(v.index()).isText&&v.index()==m.index()-(m.textOffset?0:1)){let A=v.parent.textBetween(v.parentOffset,m.parentOffset),C=()=>w(s.state.tr.insertText(A,b,k));s.someProp("handleTextInput",E=>E(s,b,k,A,C))||s.dispatch(C())}else s.dispatch(w());else s.dispatch(w())}function _R(s,e,t){return Math.max(t.anchor,t.head)>e.content.size?null:KE(s,e.resolve(t.anchor),e.resolve(t.head))}function RK(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(He.from(l).eq(s))return{mark:a,type:o}}function IK(s,e,t,n,i){if(t-e<=i.pos-n.pos||PC(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(PC(r,!0,!0));return!o.parent.isTextblock||o.pos>t||PC(o,!0,!1)<t?!1:n.parent.content.cut(n.parentOffset).eq(o.parent.content)}function PC(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 PK(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&&wR(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&&wR(s.textBetween(r-1,r+1))&&(r+=c?1:-1),o=r+(o-a),a=r}return{start:r,endA:o,endB:a}}function wR(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 wO{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 qG,this.prevDirectPlugins=[],this.pluginViews=[],this.requiresGeckoHackNode=!1,this.dragging=null,this._props=t,this.state=t.state,this.directPlugins=t.plugins||[],this.directPlugins.forEach(AR),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=CR(this),kR(this),this.nodeViews=TR(this),this.docView=sR(this.state.doc,SR(this),IC(this),this.dom,this),this.domObserver=new wK(this,(n,i,r,o)=>xK(this,n,i,r,o)),this.domObserver.start(),QG(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&&u1(this);let t=this._props;this._props=e,e.plugins&&(e.plugins.forEach(AR),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&&(pO(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=TR(this);OK(p,this.nodeViews)&&(this.nodeViews=p,r=!0)}(a||t.handleDOMEvents!=this._props.handleDOMEvents)&&u1(this),this.editable=CR(this),kR(this);let c=IC(this),l=SR(this),u=i.plugins!=e.plugins&&!i.doc.eq(e.doc)?"reset":e.scrollToSelection>i.scrollToSelection?"to selection":"preserve",d=r||!this.docView.matchesNode(e.doc,l,c);(d||!e.selection.eq(i.selection))&&(o=!0);let h=u=="preserve"&&o&&this.dom.style.overflowAnchor==null&&cG(this);if(o){this.domObserver.stop();let p=d&&(Cr||hi)&&!this.composing&&!i.selection.empty&&!e.selection.empty&&LK(i.selection,e.selection);if(d){let g=hi?this.trackWrites=this.domSelectionRange().focusNode:null;this.composing&&(this.input.compositionNode=cK(this)),(r||!this.docView.update(e.doc,l,c,this))&&(this.docView.updateOuterDeco(l),this.docView.destroy(),this.docView=sR(e.doc,l,c,this.dom,this)),g&&(!this.trackWrites||!this.dom.contains(this.trackWrites))&&(p=!0)}p||!(this.input.mouseDown&&this.domObserver.currentSelection.eq(this.domSelectionRange())&&LG(this))?Mc(this,p):(sO(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():h&&uG(h)}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 _t){let t=this.docView.domAfterPos(this.state.selection.from);t.nodeType==1&&Xx(this,t.getBoundingClientRect(),e)}else Xx(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 gO(e.slice,e.move,i<0?void 0:_t.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(Cr){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&&dG(this.dom),Mc(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 gG(this,e)}coordsAtPos(e,t=1){return q2(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 wG(this,t||this.state,e)}pasteHTML(e,t){return fy(this,"",e,!1,t||new ClipboardEvent("paste"))}pasteText(e,t){return fy(this,e,null,!0,t||new ClipboardEvent("paste"))}serializeForClipboard(e){return qE(this,e)}destroy(){this.docView&&(XG(this),this.destroyPluginViews(),this.mounted?(this.docView.update(this.state.doc,[],IC(this),this),this.dom.textContent=""):this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom),this.docView.destroy(),this.docView=null,ZV())}get isDestroyed(){return this.docView==null}dispatchEvent(e){return JG(this,e)}domSelectionRange(){let e=this.domSelection();return e?Ii&&this.root.nodeType===11&&iG(this.dom.ownerDocument)==this.dom&&kK(this,e)||e:{focusNode:null,focusOffset:0,anchorNode:null,anchorOffset:0}}domSelection(){return this.root.getSelection()}}wO.prototype.dispatch=function(s){let e=this._props.dispatchTransaction;e?e.call(this,s):this.updateState(this.state.apply(s))};function SR(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"),[Ai.node(0,s.state.doc.content.size,e)]}function kR(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:Ai.widget(s.state.selection.from,e,{raw:!0,marks:s.markCursor})}}else s.cursorWrapper=null}function CR(s){return!s.someProp("editable",e=>e(s.state)===!1)}function LK(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 TR(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 OK(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 AR(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 hd={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:"'"},jS={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},DK=typeof navigator<"u"&&/Mac/.test(navigator.platform),NK=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);for(var ui=0;ui<10;ui++)hd[48+ui]=hd[96+ui]=String(ui);for(var ui=1;ui<=24;ui++)hd[ui+111]="F"+ui;for(var ui=65;ui<=90;ui++)hd[ui]=String.fromCharCode(ui+32),jS[ui]=String.fromCharCode(ui);for(var LC in hd)jS.hasOwnProperty(LC)||(jS[LC]=hd[LC]);function $K(s){var e=DK&&s.metaKey&&s.shiftKey&&!s.ctrlKey&&!s.altKey||NK&&s.shiftKey&&s.key&&s.key.length==1||s.key=="Unidentified",t=!e&&s.key||(s.shiftKey?jS:hd)[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 BK=typeof navigator<"u"&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),FK=typeof navigator<"u"&&/Win/.test(navigator.platform);function HK(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))BK?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 UK(s){let e=Object.create(null);for(let t in s)e[HK(t)]=s[t];return e}function OC(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 WK(s){return new Gs({props:{handleKeyDown:SO(s)}})}function SO(s){let e=UK(s);return function(t,n){let i=$K(n),r,o=e[OC(i,n)];if(o&&o(t.state,t.dispatch,t))return!0;if(i.length==1&&i!=" "){if(n.shiftKey){let a=e[OC(i,n,!1)];if(a&&a(t.state,t.dispatch,t))return!0}if((n.altKey||n.metaKey||n.ctrlKey)&&!(FK&&n.ctrlKey&&n.altKey)&&(r=hd[n.keyCode])&&r!=i){let a=e[OC(r,n)];if(a&&a(t.state,t.dispatch,t))return!0}}return!1}}var zK=Object.defineProperty,eM=(s,e)=>{for(var t in e)zK(s,t,{get:e[t],enumerable:!0})};function vk(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 yk=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 d=c(...u)(o);return!r.getMeta("preventDispatch")&&!this.hasCustomState&&i.dispatch(r),d}]))}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(h=>h===!0)),d={...Object.fromEntries(Object.entries(n).map(([h,p])=>[h,(...v)=>{const m=this.buildProps(l,t),y=p(...v)(m);return a.push(y),d}])),run:u};return d}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:vk({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}},kO={};eM(kO,{blur:()=>jK,clearContent:()=>VK,clearNodes:()=>GK,command:()=>KK,createParagraphNear:()=>qK,cut:()=>QK,deleteCurrentNode:()=>XK,deleteNode:()=>YK,deleteRange:()=>JK,deleteSelection:()=>tq,enter:()=>sq,exitCode:()=>nq,extendMarkRange:()=>iq,first:()=>rq,focus:()=>aq,forEach:()=>lq,insertContent:()=>cq,insertContentAt:()=>hq,joinBackward:()=>mq,joinDown:()=>pq,joinForward:()=>gq,joinItemBackward:()=>vq,joinItemForward:()=>yq,joinTextblockBackward:()=>bq,joinTextblockForward:()=>_q,joinUp:()=>fq,keyboardShortcut:()=>Sq,lift:()=>kq,liftEmptyBlock:()=>Cq,liftListItem:()=>Tq,newlineInCode:()=>Aq,resetAttributes:()=>Eq,scrollIntoView:()=>Mq,selectAll:()=>xq,selectNodeBackward:()=>Rq,selectNodeForward:()=>Iq,selectParentNode:()=>Pq,selectTextblockEnd:()=>Lq,selectTextblockStart:()=>Oq,setContent:()=>Dq,setMark:()=>sQ,setMeta:()=>nQ,setNode:()=>iQ,setNodeSelection:()=>rQ,setTextDirection:()=>oQ,setTextSelection:()=>aQ,sinkListItem:()=>lQ,splitBlock:()=>cQ,splitListItem:()=>uQ,toggleList:()=>hQ,toggleMark:()=>fQ,toggleNode:()=>pQ,toggleWrap:()=>mQ,undoInputRule:()=>gQ,unsetAllMarks:()=>vQ,unsetMark:()=>yQ,unsetTextDirection:()=>bQ,updateAttributes:()=>_Q,wrapIn:()=>wQ,wrapInList:()=>SQ});var jK=()=>({editor:s,view:e})=>(requestAnimationFrame(()=>{var t;s.isDestroyed||(e.dom.blur(),(t=window==null?void 0:window.getSelection())==null||t.removeAllRanges())}),!0),VK=(s=!0)=>({commands:e})=>e.setContent("",{emitUpdate:s}),GK=()=>({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,d=l.resolve(u.map(c)),h=l.resolve(u.map(c+a.nodeSize)),p=d.blockRange(h);if(!p)return;const g=wg(p);if(a.type.isTextblock){const{defaultType:v}=d.parent.contentMatchAt(d.index());e.setNodeMarkup(p.start,v)}(g||g===0)&&e.lift(p,g)})}),!0},KK=s=>e=>s(e),qK=()=>({state:s,dispatch:e})=>$2(s,e),QK=(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 kt(n.doc.resolve(Math.max(o-1,0)))),!0},XK=()=>({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 Mn(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 YK=s=>({tr:e,state:t,dispatch:n})=>{const i=Mn(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},JK=s=>({tr:e,dispatch:t})=>{const{from:n,to:i}=s;return t&&e.delete(n,i),!0},ZK=s=>s.content?/^text(\*|\+)/.test(s.content):!1,ER=(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 ZK(n)?t==="left"?s.start()-1:s.end()+1:s.pos},eq=(s,e,t)=>{const n=ER(s,t,"left"),i=ER(e,t,"right");return{from:n,to:i}},tq=()=>({state:s,dispatch:e})=>{const{$from:t,$to:n}=s.selection;if(s.selection.empty)return!1;const{from:i,to:r}=eq(t,n,s.schema);return e&&(s.tr.deleteRange(i,r).scrollIntoView(),e(s.tr)),!0},sq=()=>({commands:s})=>s.keyboardShortcut("Enter"),nq=()=>({state:s,dispatch:e})=>BV(s,e);function tM(s){return Object.prototype.toString.call(s)==="[object RegExp]"}function VS(s,e,t={strict:!0}){const n=Object.keys(e);return n.length?n.every(i=>t.strict?e[i]===s[i]:tM(e[i])?e[i].test(s[i]):e[i]===s[i]):!0}function CO(s,e,t={}){return s.find(n=>n.type===e&&VS(Object.fromEntries(Object.keys(t).map(i=>[i,n.attrs[i]])),t))}function MR(s,e,t={}){return!!CO(s,e,t)}function sM(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(!CO([...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&&MR([...s.parent.child(r-1).marks],e,t);)r-=1,o-=s.parent.child(r).nodeSize;for(;a<s.parent.childCount&&MR([...s.parent.child(a).marks],e,t);)c+=s.parent.child(a).nodeSize,a+=1;return{from:o,to:c}}function $c(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 iq=(s,e)=>({tr:t,state:n,dispatch:i})=>{const r=$c(s,n.schema),{doc:o,selection:a}=t,{$from:c,from:l,to:u}=a;if(i){const d=sM(c,r,e);if(d&&d.from<=l&&d.to>=u){const h=kt.create(o,d.from,d.to);t.setSelection(h)}}return!0},rq=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 TO(s){return s instanceof kt}function zd(s=0,e=0,t=0){return Math.min(Math.max(s,e),t)}function AO(s,e=null){if(!e)return null;const t=Ht.atStart(s),n=Ht.atEnd(s);if(e==="start"||e===!0)return t;if(e==="end")return n;const i=t.from,r=n.to;return e==="all"?kt.create(s,zd(0,i,r),zd(s.content.size,i,r)):kt.create(s,zd(e,i,r),zd(e,i,r))}function xR(){return navigator.platform==="Android"||/android/i.test(navigator.userAgent)}function GS(){return["iPad Simulator","iPhone Simulator","iPod Simulator","iPad","iPhone","iPod"].includes(navigator.platform)||navigator.userAgent.includes("Mac")&&"ontouchend"in document}function oq(){return typeof navigator<"u"?/^((?!chrome|android).)*safari/i.test(navigator.userAgent):!1}var aq=(s=null,e={})=>({editor:t,view:n,tr:i,dispatch:r})=>{e={scrollIntoView:!0,...e};const o=()=>{(GS()||xR())&&n.dom.focus(),oq()&&!GS()&&!xR()&&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&&!TO(t.state.selection))return o(),!0;const a=AO(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},lq=(s,e)=>t=>s.every((n,i)=>e(n,{...t,index:i})),cq=(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 G_(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 my(s,e,t){if(s instanceof Tc||s instanceof He)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 He.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),my("",e,t)}if(i){if(t.errorOnInvalidContent){let o=!1,a="";const c=new i2({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?Uv.fromSchema(c).parseSlice(G_(s),t.parseOptions):Uv.fromSchema(c).parse(G_(s),t.parseOptions),t.errorOnInvalidContent&&o)throw new Error("[tiptap error]: Invalid HTML content",{cause:new Error(`Invalid element found: ${a}`)})}const r=Uv.fromSchema(e);return t.slice?r.parseSlice(G_(s),t.parseOptions).content:r.parse(G_(s),t.parseOptions)}return my("",e,t)}function uq(s,e,t){const n=s.steps.length-1;if(n<e)return;const i=s.steps[n];if(!(i instanceof jo||i instanceof Tr))return;const r=s.mapping.maps[n];let o=0;r.forEach((a,c,l,u)=>{o===0&&(o=u)}),s.setSelection(Ht.near(s.doc.resolve(o),t))}var dq=s=>!("type"in s),hq=(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=m=>{r.emit("contentError",{editor:r,error:m,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{my(e,r.schema,{parseOptions:l,errorOnInvalidContent:!0})}catch(m){c(m)}try{a=my(e,r.schema,{parseOptions:l,errorOnInvalidContent:(o=t.errorOnInvalidContent)!=null?o:r.options.enableContentCheck})}catch(m){return c(m),!1}let{from:u,to:d}=typeof s=="number"?{from:s,to:s}:{from:s.from,to:s.to},h=!0,p=!0;if((dq(a)?a:[a]).forEach(m=>{m.check(),h=h?m.isText&&m.marks.length===0:!1,p=p?m.isBlock:!1}),u===d&&p){const{parent:m}=n.doc.resolve(u);m.isTextblock&&!m.type.spec.code&&!m.childCount&&(u-=1,d+=1)}let v;if(h){if(Array.isArray(e))v=e.map(m=>m.text||"").join("");else if(e instanceof He){let m="";e.forEach(y=>{y.text&&(m+=y.text)}),v=m}else typeof e=="object"&&e&&e.text?v=e.text:v=e;n.insertText(v,u,d)}else{v=a;const m=n.doc.resolve(u),y=m.node(),_=m.parentOffset===0,b=y.isText||y.isTextblock,k=y.content.size>0;_&&b&&k&&p&&(u=Math.max(0,u-1)),n.replaceWith(u,d,v)}t.updateSelection&&uq(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},fq=()=>({state:s,dispatch:e})=>DV(s,e),pq=()=>({state:s,dispatch:e})=>NV(s,e),mq=()=>({state:s,dispatch:e})=>R2(s,e),gq=()=>({state:s,dispatch:e})=>O2(s,e),vq=()=>({state:s,dispatch:e,tr:t})=>{try{const n=hk(s.doc,s.selection.$from.pos,-1);return n==null?!1:(t.join(n,2),e&&e(t),!0)}catch{return!1}},yq=()=>({state:s,dispatch:e,tr:t})=>{try{const n=hk(s.doc,s.selection.$from.pos,1);return n==null?!1:(t.join(n,2),e&&e(t),!0)}catch{return!1}},bq=()=>({state:s,dispatch:e})=>LV(s,e),_q=()=>({state:s,dispatch:e})=>OV(s,e);function MO(){return typeof navigator<"u"?/Mac/.test(navigator.platform):!1}function wq(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))GS()||MO()?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 Sq=s=>({editor:e,view:t,tr:n,dispatch:i})=>{const r=wq(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 fd(s,e,t={}){const{from:n,to:i,empty:r}=s.selection,o=e?Mn(e,s.schema):null,a=[];s.doc.nodesBetween(n,i,(d,h)=>{if(d.isText)return;const p=Math.max(n,h),g=Math.min(i,h+d.nodeSize);a.push({node:d,from:p,to:g})});const c=i-n,l=a.filter(d=>o?o.name===d.node.type.name:!0).filter(d=>VS(d.node.attrs,t,{strict:!1}));return r?!!l.length:l.reduce((d,h)=>d+h.to-h.from,0)>=c}var kq=(s,e={})=>({state:t,dispatch:n})=>{const i=Mn(s,t.schema);return fd(t,i,e)?$V(t,n):!1},Cq=()=>({state:s,dispatch:e})=>B2(s,e),Tq=s=>({state:e,dispatch:t})=>{const n=Mn(s,e.schema);return QV(n)(e,t)},Aq=()=>({state:s,dispatch:e})=>N2(s,e);function bk(s,e){return e.nodes[s]?"node":e.marks[s]?"mark":null}function RR(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 Eq=(s,e)=>({tr:t,state:n,dispatch:i})=>{let r=null,o=null;const a=bk(typeof s=="string"?s:s.name,n.schema);if(!a)return!1;a==="node"&&(r=Mn(s,n.schema)),a==="mark"&&(o=$c(s,n.schema));let c=!1;return t.selection.ranges.forEach(l=>{n.doc.nodesBetween(l.$from.pos,l.$to.pos,(u,d)=>{r&&r===u.type&&(c=!0,i&&t.setNodeMarkup(d,void 0,RR(u.attrs,e))),o&&u.marks.length&&u.marks.forEach(h=>{o===h.type&&(c=!0,i&&t.addMark(d,d+u.nodeSize,o.create(RR(h.attrs,e))))})})}),c},Mq=()=>({tr:s,dispatch:e})=>(e&&s.scrollIntoView(),!0),xq=()=>({tr:s,dispatch:e})=>{if(e){const t=new Ec(s.doc);s.setSelection(t)}return!0},Rq=()=>({state:s,dispatch:e})=>P2(s,e),Iq=()=>({state:s,dispatch:e})=>D2(s,e),Pq=()=>({state:s,dispatch:e})=>UV(s,e),Lq=()=>({state:s,dispatch:e})=>jV(s,e),Oq=()=>({state:s,dispatch:e})=>zV(s,e);function d1(s,e,t={},n={}){return my(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=d1(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 xO(s,e){const t=$c(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 RO(s,e){const t=new S2(s);return e.forEach(n=>{n.steps.forEach(i=>{t.step(i)})}),t}function Nq(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 $q(s,e,t){const n=[];return s.nodesBetween(e.from,e.to,(i,r)=>{t(i)&&n.push({node:i,pos:r})}),n}function Bq(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 _k(s){return e=>Bq(e.$from,s)}function dt(s,e,t){return s.config[e]===void 0&&s.parent?dt(s.parent,e,t):typeof s.config[e]=="function"?s.config[e].bind({...t,parent:s.parent?dt(s.parent,e,t):null}):s.config[e]}function nM(s){return s.map(e=>{const t={name:e.name,options:e.options,storage:e.storage},n=dt(e,"addExtensions",t);return n?[e,...nM(n())]:e}).flat(10)}function iM(s,e){const t=Hf.fromSchema(e).serializeFragment(s),i=document.implementation.createHTMLDocument().createElement("div");return i.appendChild(t),i.innerHTML}function IO(s){return typeof s=="function"}function ls(s,e=void 0,...t){return IO(s)?e?s.bind(e)(...t):s(...t):s}function Fq(s={}){return Object.keys(s).length===0&&s.constructor===Object}function ug(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 PO(s){const e=[],{nodeExtensions:t,markExtensions:n}=ug(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},d=dt(l,"addGlobalAttributes",u);if(!d)return;d().forEach(p=>{let g;Array.isArray(p.types)?g=p.types:p.types==="*"?g=c:p.types==="nodes"?g=o:p.types==="marks"?g=a:g=[],g.forEach(v=>{Object.entries(p.attributes).forEach(([m,y])=>{e.push({type:v,name:m,attribute:{...r,...y}})})})})}),i.forEach(l=>{const u={name:l.name,options:l.options,storage:l.storage},d=dt(l,"addAttributes",u);if(!d)return;const h=d();Object.entries(h).forEach(([p,g])=>{const v={...r,...g};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 Hq(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 IR(s){const e=[],t=Hq(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 Vs(...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([...IR(n[i]),...IR(r)]);n[i]=Array.from(a.entries()).map(([c,l])=>`${c}: ${l}`).join("; ")}else n[i]=r}),n},{})}function gy(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)=>Vs(t,n),{})}function Uq(s){return typeof s!="string"?s:s.match(/^[+-]?(?:\d*\.)?\d+$/)?Number(s):s==="true"?!0:s==="false"?!1:s}function PR(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):Uq(t.getAttribute(o.name));return a==null?r:{...r,[o.name]:a}},{});return{...n,...i}}}}function LR(s){return Object.fromEntries(Object.entries(s).filter(([e,t])=>e==="attrs"&&Fq(t)?!1:t!=null))}function OR(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 Wq(s,e){var t;const n=PO(s),{nodeExtensions:i,markExtensions:r}=ug(s),o=(t=i.find(l=>dt(l,"topNode")))==null?void 0:t.name,a=Object.fromEntries(i.map(l=>{const u=n.filter(y=>y.type===l.name),d={name:l.name,options:l.options,storage:l.storage,editor:e},h=s.reduce((y,_)=>{const b=dt(_,"extendNodeSchema",d);return{...y,...b?b(l):{}}},{}),p=LR({...h,content:ls(dt(l,"content",d)),marks:ls(dt(l,"marks",d)),group:ls(dt(l,"group",d)),inline:ls(dt(l,"inline",d)),atom:ls(dt(l,"atom",d)),selectable:ls(dt(l,"selectable",d)),draggable:ls(dt(l,"draggable",d)),code:ls(dt(l,"code",d)),whitespace:ls(dt(l,"whitespace",d)),linebreakReplacement:ls(dt(l,"linebreakReplacement",d)),defining:ls(dt(l,"defining",d)),isolating:ls(dt(l,"isolating",d)),attrs:Object.fromEntries(u.map(OR))}),g=ls(dt(l,"parseHTML",d));g&&(p.parseDOM=g.map(y=>PR(y,u)));const v=dt(l,"renderHTML",d);v&&(p.toDOM=y=>v({node:y,HTMLAttributes:gy(y,u)}));const m=dt(l,"renderText",d);return m&&(p.toText=m),[l.name,p]})),c=Object.fromEntries(r.map(l=>{const u=n.filter(m=>m.type===l.name),d={name:l.name,options:l.options,storage:l.storage,editor:e},h=s.reduce((m,y)=>{const _=dt(y,"extendMarkSchema",d);return{...m,..._?_(l):{}}},{}),p=LR({...h,inclusive:ls(dt(l,"inclusive",d)),excludes:ls(dt(l,"excludes",d)),group:ls(dt(l,"group",d)),spanning:ls(dt(l,"spanning",d)),code:ls(dt(l,"code",d)),attrs:Object.fromEntries(u.map(OR))}),g=ls(dt(l,"parseHTML",d));g&&(p.parseDOM=g.map(m=>PR(m,u)));const v=dt(l,"renderHTML",d);return v&&(p.toDOM=m=>v({mark:m,HTMLAttributes:gy(m,u)})),[l.name,p]}));return new i2({topNode:o,nodes:a,marks:c})}function zq(s){const e=s.filter((t,n)=>s.indexOf(t)!==n);return Array.from(new Set(e))}function Vv(s){return s.sort((t,n)=>{const i=dt(t,"priority")||100,r=dt(n,"priority")||100;return i>r?-1:i<r?1:0})}function LO(s){const e=Vv(nM(s)),t=zq(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 OO(s,e,t){const{from:n,to:i}=e,{blockSeparator:r=`
|
||
|
||
`,textSerializers:o={}}=t||{};let a="";return s.nodesBetween(n,i,(c,l,u,d)=>{var h;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:d,range:e})),!1;c.isText&&(a+=(h=c==null?void 0:c.text)==null?void 0:h.slice(Math.max(n,l)-l,i-l))}),a}function jq(s,e){const t={from:0,to:s.content.size};return OO(s,t,e)}function DO(s){return Object.fromEntries(Object.entries(s.nodes).filter(([,e])=>e.spec.toText).map(([e,t])=>[e,t.spec.toText]))}function Vq(s,e){const t=Mn(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 NO(s,e){const t=bk(typeof e=="string"?e:e.name,s.schema);return t==="node"?Vq(s,e):t==="mark"?xO(s,e):{}}function Gq(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 Kq(s){const e=Gq(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 $O(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),d=e.invert().map(l,-1),h=e.invert().map(u);n.push({oldRange:{from:d,to:h},newRange:{from:l,to:u}})})}),Kq(n)}function rM(s,e,t){const n=[];return s===e?t.resolve(s).marks().forEach(i=>{const r=t.resolve(s),o=sM(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 qq=(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 Dg(s,e){return e.nodes[s]||e.marks[s]||null}function Iw(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 Qq=(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 h1(s,e,t={}){const{empty:n,ranges:i}=s.selection,r=e?$c(e,s.schema):null;if(n)return!!(s.storedMarks||s.selection.$from.marks()).filter(d=>r?r.name===d.type.name:!0).find(d=>VS(d.attrs,t,{strict:!1}));let o=0;const a=[];if(i.forEach(({$from:d,$to:h})=>{const p=d.pos,g=h.pos;s.doc.nodesBetween(p,g,(v,m)=>{if(r&&v.inlineContent&&!v.type.allowsMarkType(r))return!1;if(!v.isText&&!v.marks.length)return;const y=Math.max(p,m),_=Math.min(g,m+v.nodeSize),b=_-y;o+=b,a.push(...v.marks.map(k=>({mark:k,from:y,to:_})))})}),o===0)return!1;const c=a.filter(d=>r?r.name===d.mark.type.name:!0).filter(d=>VS(d.mark.attrs,t,{strict:!1})).reduce((d,h)=>d+h.to-h.from,0),l=a.filter(d=>r?d.mark.type!==r&&d.mark.type.excludes(r):!0).reduce((d,h)=>d+h.to-h.from,0);return(c>0?c+l:c)>=o}function Xq(s,e,t={}){if(!e)return fd(s,null,t)||h1(s,null,t);const n=bk(e,s.schema);return n==="node"?fd(s,e,t):n==="mark"?h1(s,e,t):!1}var Yq=(s,e)=>{const{$from:t,$to:n,$anchor:i}=s.selection;if(e){const r=_k(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)},Jq=s=>{const{$from:e,$to:t}=s.selection;return!(e.parentOffset>0||e.pos!==t.pos)};function DR(s,e){return Array.isArray(e)?e.some(t=>(typeof t=="string"?t:t.name)===s.name):e}function DC(s,e){const{nodeExtensions:t}=ug(e),n=t.find(o=>o.name===s);if(!n)return!1;const i={name:n.name,options:n.options,storage:n.storage},r=ls(dt(n,"group",i));return typeof r!="string"?!1:r.split(" ").includes("list")}function vy(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&&(vy(r,{ignoreWhitespace:t,checkChildren:e})||(i=!1))}),i}return!1}function BO(s){return s instanceof _t}var FO=class HO{constructor(e){this.position=e}static fromJSON(e){return new HO(e.position)}toJSON(){return{position:this.position}}};function Zq(s,e){const t=e.mapping.mapResult(s.position);return{position:new FO(t.pos),mapResult:t}}function eQ(s){return new FO(s)}function tQ(s,e,t){var n;const{selection:i}=e;let r=null;if(TO(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,d,h)=>{if(l)return!1;if(u.isInline){const p=!h||h.type.allowsMarkType(t),g=!!t.isInSet(u.marks)||!u.marks.some(v=>v.type.excludes(t));l=p&&g}return!l}),l})}var sQ=(s,e={})=>({tr:t,state:n,dispatch:i})=>{const{selection:r}=t,{empty:o,ranges:a}=r,c=$c(s,n.schema);if(i)if(o){const l=xO(n,c);t.addStoredMark(c.create({...l,...e}))}else a.forEach(l=>{const u=l.$from.pos,d=l.$to.pos;n.doc.nodesBetween(u,d,(h,p)=>{const g=Math.max(p,u),v=Math.min(p+h.nodeSize,d);h.marks.find(y=>y.type===c)?h.marks.forEach(y=>{c===y.type&&t.addMark(g,v,c.create({...y.attrs,...e}))}):t.addMark(g,v,c.create(e))})});return tQ(n,t,c)},nQ=(s,e)=>({tr:t})=>(t.setMeta(s,e),!0),iQ=(s,e={})=>({state:t,dispatch:n,chain:i})=>{const r=Mn(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)},rQ=s=>({tr:e,dispatch:t})=>{if(t){const{doc:n}=e,i=zd(s,0,n.content.size),r=_t.create(n,i);e.setSelection(r)}return!0},oQ=(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},aQ=s=>({tr:e,dispatch:t})=>{if(t){const{doc:n}=e,{from:i,to:r}=typeof s=="number"?{from:s,to:s}:s,o=kt.atStart(n).from,a=kt.atEnd(n).to,c=zd(i,o,a),l=zd(r,o,a),u=kt.create(n,c,l);e.setSelection(u)}return!0},lQ=s=>({state:e,dispatch:t})=>{const n=Mn(s,e.schema);return JV(n)(e,t)};function NR(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 cQ=({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=Iw(l,a.node().type.name,a.node().attrs);if(r instanceof _t&&r.node.isBlock)return!a.parentOffset||!Ac(o,a.pos)?!1:(n&&(s&&NR(t,i.extensionManager.splittableMarks),e.split(a.pos).scrollIntoView()),!0);if(!a.parent.isBlock)return!1;const d=c.parentOffset===c.parent.content.size,h=a.depth===0?void 0:Nq(a.node(-1).contentMatchAt(a.indexAfter(-1)));let p=d&&h?[{type:h,attrs:u}]:void 0,g=Ac(e.doc,e.mapping.map(a.pos),1,p);if(!p&&!g&&Ac(e.doc,e.mapping.map(a.pos),1,h?[{type:h}]:void 0)&&(g=!0,p=h?[{type:h,attrs:u}]:void 0),n){if(g&&(r instanceof kt&&e.deleteSelection(),e.split(e.mapping.map(a.pos),1,p),h&&!d&&!a.parentOffset&&a.parent.type!==h)){const v=e.mapping.map(a.before()),m=e.doc.resolve(v);a.node(-1).canReplaceWith(m.index(),m.index()+1,h)&&e.setNodeMarkup(e.mapping.map(a.before()),h)}s&&NR(t,i.extensionManager.splittableMarks),e.scrollIntoView()}return g},uQ=(s,e={})=>({tr:t,state:n,dispatch:i,editor:r})=>{var o;const a=Mn(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 d=c.node(-1);if(d.type!==a)return!1;const h=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=He.empty;const _=c.index(-1)?1:c.index(-2)?2:3;for(let C=c.depth-_;C>=c.depth-3;C-=1)y=He.from(c.node(C).copy(y));const b=c.indexAfter(-1)<c.node(-2).childCount?1:c.indexAfter(-2)<c.node(-3).childCount?2:3,k={...Iw(h,c.node().type.name,c.node().attrs),...e},w=((o=a.contentMatch.defaultType)==null?void 0:o.createAndFill(k))||void 0;y=y.append(He.from(a.createAndFill(null,w)||void 0));const T=c.before(c.depth-(_-1));t.replace(T,c.after(-b),new tt(y,4-_,0));let A=-1;t.doc.nodesBetween(T,t.doc.content.size,(C,E)=>{if(A>-1)return!1;C.isTextblock&&C.content.size===0&&(A=E+1)}),A>-1&&t.setSelection(kt.near(t.doc.resolve(A))),t.scrollIntoView()}return!0}const p=l.pos===c.end()?d.contentMatchAt(0).defaultType:null,g={...Iw(h,d.type.name,d.attrs),...e},v={...Iw(h,c.node().type.name,c.node().attrs),...e};t.delete(c.pos,l.pos);const m=p?[{type:a,attrs:g},{type:p,attrs:v}]:[{type:a,attrs:g}];if(!Ac(t.doc,c.pos,2))return!1;if(i){const{selection:y,storedMarks:_}=n,{splittableMarks:b}=r.extensionManager,k=_||y.$to.parentOffset&&y.$from.marks();if(t.split(c.pos,2,m).scrollIntoView(),!k||!i)return!0;const w=k.filter(T=>b.includes(T.type.name));t.ensureMarks(w)}return!0},NC=(s,e)=>{const t=_k(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)&&vd(s.doc,t.pos)&&s.join(t.pos),!0},$C=(s,e)=>{const t=_k(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)&&vd(s.doc,n)&&s.join(n),!0};function dQ(s){const e=s.doc,t=e.firstChild;if(!t)return null;const n=e.resolve(1),i=e.resolve(t.nodeSize-1);return kt.between(n,i)}var hQ=(s,e,t,n={})=>({editor:i,tr:r,state:o,dispatch:a,chain:c,commands:l,can:u})=>{const{extensions:d,splittableMarks:h}=i.extensionManager,p=Mn(s,o.schema),g=Mn(e,o.schema),{selection:v,storedMarks:m}=o,{$from:y,$to:_}=v,b=y.blockRange(_),k=m||v.$to.parentOffset&&v.$from.marks();if(!b)return!1;const w=_k(O=>DC(O.type.name,d))(v),T=v.from===0&&v.to===o.doc.content.size,A=o.doc.content.content,C=A.length===1?A[0]:null,E=T&&C&&DC(C.type.name,d)?{node:C,pos:0}:null,x=w??E,D=!!w&&b.depth>=1&&b.depth-w.depth<=1,N=!!E;if((D||N)&&x){if(x.node.type===p)return T&&N?c().command(({tr:O,dispatch:G})=>{const Z=dQ(O);return Z?(O.setSelection(Z),G&&G(O),!0):!1}).liftListItem(g).run():l.liftListItem(g);if(DC(x.node.type.name,d)&&p.validContent(x.node.content))return c().command(()=>(r.setNodeMarkup(x.pos,p),!0)).command(()=>NC(r,p)).command(()=>$C(r,p)).run()}return!t||!k||!a?c().command(()=>u().wrapInList(p,n)?!0:l.clearNodes()).wrapInList(p,n).command(()=>NC(r,p)).command(()=>$C(r,p)).run():c().command(()=>{const O=u().wrapInList(p,n),G=k.filter(Z=>h.includes(Z.type.name));return r.ensureMarks(G),O?!0:l.clearNodes()}).wrapInList(p,n).command(()=>NC(r,p)).command(()=>$C(r,p)).run()},fQ=(s,e={},t={})=>({state:n,commands:i})=>{const{extendEmptyMarkRange:r=!1}=t,o=$c(s,n.schema);return h1(n,o,e)?i.unsetMark(o,{extendEmptyMarkRange:r}):i.setMark(o,e)},pQ=(s,e,t={})=>({state:n,commands:i})=>{const r=Mn(s,n.schema),o=Mn(e,n.schema),a=fd(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})},mQ=(s,e={})=>({state:t,commands:n})=>{const i=Mn(s,t.schema);return fd(t,i,e)?n.lift(i):n.wrapIn(i,e)},gQ=()=>({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},vQ=(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 d of l)e.removeMark(u.$from.pos,u.$to.pos,d)})}return!0},yQ=(s,e={})=>({tr:t,state:n,dispatch:i})=>{var r;const{extendEmptyMarkRange:o=!1}=e,{selection:a}=t,c=$c(s,n.schema),{$from:l,empty:u,ranges:d}=a;if(!i)return!0;if(u&&o){let{from:h,to:p}=a;const g=(r=l.marks().find(m=>m.type===c))==null?void 0:r.attrs,v=sM(l,c,g);v&&(h=v.from,p=v.to),t.removeMark(h,p,c)}else d.forEach(h=>{t.removeMark(h.$from.pos,h.$to.pos,c)});return t.removeStoredMark(c),!0},bQ=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},_Q=(s,e={})=>({tr:t,state:n,dispatch:i})=>{let r=null,o=null;const a=bk(typeof s=="string"?s:s.name,n.schema);if(!a)return!1;a==="node"&&(r=Mn(s,n.schema)),a==="mark"&&(o=$c(s,n.schema));let c=!1;return t.selection.ranges.forEach(l=>{const u=l.$from.pos,d=l.$to.pos;let h,p,g,v;t.selection.empty?n.doc.nodesBetween(u,d,(m,y)=>{r&&r===m.type&&(c=!0,g=Math.max(y,u),v=Math.min(y+m.nodeSize,d),h=y,p=m)}):n.doc.nodesBetween(u,d,(m,y)=>{y<u&&r&&r===m.type&&(c=!0,g=Math.max(y,u),v=Math.min(y+m.nodeSize,d),h=y,p=m),y>=u&&y<=d&&(r&&r===m.type&&(c=!0,i&&t.setNodeMarkup(y,void 0,{...m.attrs,...e})),o&&m.marks.length&&m.marks.forEach(_=>{if(o===_.type&&(c=!0,i)){const b=Math.max(y,u),k=Math.min(y+m.nodeSize,d);t.addMark(b,k,o.create({..._.attrs,...e}))}}))}),p&&(h!==void 0&&i&&t.setNodeMarkup(h,void 0,{...p.attrs,...e}),o&&p.marks.length&&p.marks.forEach(m=>{o===m.type&&i&&t.addMark(g,v,o.create({...m.attrs,...e}))}))}),c},wQ=(s,e={})=>({state:t,dispatch:n})=>{const i=Mn(s,t.schema);return VV(i,e)(t,n)},SQ=(s,e={})=>({state:t,dispatch:n})=>{const i=Mn(s,t.schema);return GV(i,e)(t,n)},kQ=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={}}},wk=class{constructor(s){var e;this.find=s.find,this.handler=s.handler,this.undoable=(e=s.undoable)!=null?e:!0}},CQ=(s,e)=>{if(tM(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 K_(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(h=>h.type.spec.code))return!1;let u=!1;const d=Qq(l)+r;return o.forEach(h=>{if(u)return;const p=CQ(d,h.find);if(!p)return;const g=c.state.tr,v=vk({state:c.state,transaction:g}),m={from:n-(p[0].length-r.length),to:i},{commands:y,chain:_,can:b}=new yk({editor:t,state:v});h.handler({state:v,range:m,match:p,commands:y,chain:_,can:b})===null||!g.steps.length||(h.undoable&&g.setMeta(a,{transform:g,from:n,to:i,text:r}),c.dispatch(g),u=!0)}),u}function TQ(s){const{editor:e,rules:t}=s,n=new Gs({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=iM(He.from(u),o.schema);const{from:d}=c,h=d+u.length;K_({editor:e,from:d,to:h,text:u,rules:t,plugin:n})}),i.selectionSet||i.docChanged?null:r}},props:{handleTextInput(i,r,o,a){return K_({editor:e,from:r,to:o,text:a,rules:t,plugin:n})},handleDOMEvents:{compositionend:i=>(setTimeout(()=>{const{$cursor:r}=i.state.selection;r&&K_({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?K_({editor:e,from:o.pos,to:o.pos,text:`
|
||
`,rules:t,plugin:n}):!1}},isInputRules:!0});return n}function AQ(s){return Object.prototype.toString.call(s).slice(8,-1)}function q_(s){return AQ(s)!=="Object"?!1:s.constructor===Object&&Object.getPrototypeOf(s)===Object.prototype}function UO(s,e){const t={...s};return q_(s)&&q_(e)&&Object.keys(e).forEach(n=>{q_(e[n])&&q_(s[n])?t[n]=UO(s[n],e[n]):t[n]=e[n]}),t}var oM=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{...ls(dt(this,"addOptions",{name:this.name}))}}get storage(){return{...ls(dt(this,"addStorage",{name:this.name,options:this.options}))}}configure(s={}){const e=this.extend({...this.config,addOptions:()=>UO(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}},Uf=class WO extends oM{constructor(){super(...arguments),this.type="mark"}static create(e={}){const t=typeof e=="function"?e():e;return new WO(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 EQ(s){return typeof s=="number"}var MQ=class{constructor(s){this.find=s.find,this.handler=s.handler}},xQ=(s,e,t)=>{if(tM(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 RQ(s){const{editor:e,state:t,from:n,to:i,rule:r,pasteEvent:o,dropEvent:a}=s,{commands:c,chain:l,can:u}=new yk({editor:e,state:t}),d=[];return t.doc.nodesBetween(n,i,(p,g)=>{var v,m,y,_,b;if((m=(v=p.type)==null?void 0:v.spec)!=null&&m.code||!(p.isText||p.isTextblock||p.isInline))return;const k=(b=(_=(y=p.content)==null?void 0:y.size)!=null?_:p.nodeSize)!=null?b:0,w=Math.max(n,g),T=Math.min(i,g+k);if(w>=T)return;const A=p.isText?p.text||"":p.textBetween(w-g,T-g,void 0,"");xQ(A,r.find,o).forEach(E=>{if(E.index===void 0)return;const x=w+E.index+1,D=x+E[0].length,N={from:t.tr.mapping.map(x),to:t.tr.mapping.map(D)},O=r.handler({state:t,range:N,match:E,commands:c,chain:l,can:u,pasteEvent:o,dropEvent:a});d.push(O)})}),d.every(p=>p!==null)}var Q_=null,IQ=s=>{var e;const t=new ClipboardEvent("paste",{clipboardData:new DataTransfer});return(e=t.clipboardData)==null||e.setData("text/html",s),t};function PQ(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:d,to:h,rule:p,pasteEvt:g})=>{const v=u.tr,m=vk({state:u,transaction:v});if(!(!RQ({editor:e,state:m,from:Math.max(d-1,0),to:h.b-1,rule:p,pasteEvent:g,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 Gs({view(d){const h=g=>{var v;n=(v=d.dom.parentElement)!=null&&v.contains(g.target)?d.dom.parentElement:null,n&&(Q_=e)},p=()=>{Q_&&(Q_=null)};return window.addEventListener("dragstart",h),window.addEventListener("dragend",p),{destroy(){window.removeEventListener("dragstart",h),window.removeEventListener("dragend",p)}}},props:{handleDOMEvents:{drop:(d,h)=>{if(r=n===d.dom.parentElement,a=h,!r){const p=Q_;p!=null&&p.isEditable&&setTimeout(()=>{const g=p.state.selection;g&&p.commands.deleteRange({from:g.from,to:g.to})},10)}return!1},paste:(d,h)=>{var p;const g=(p=h.clipboardData)==null?void 0:p.getData("text/html");return o=h,i=!!(g!=null&&g.includes("data-pm-slice")),!1}}},appendTransaction:(d,h,p)=>{const g=d[0],v=g.getMeta("uiEvent")==="paste"&&!i,m=g.getMeta("uiEvent")==="drop"&&!r,y=g.getMeta("applyPasteRules"),_=!!y;if(!v&&!m&&!_)return;if(_){let{text:w}=y;typeof w=="string"?w=w:w=iM(He.from(w),p.schema);const{from:T}=y,A=T+w.length,C=IQ(w);return c({rule:u,state:p,from:T,to:{b:A},pasteEvt:C})}const b=h.doc.content.findDiffStart(p.doc.content),k=h.doc.content.findDiffEnd(p.doc.content);if(!(!EQ(b)||!k||b===k.b))return c({rule:u,state:p,from:b,to:k,pasteEvt:o})}}))}var Sk=class{constructor(s,e){this.splittableMarks=[],this.nonClearableMarks=[],this.editor=e,this.baseExtensions=s,this.extensions=LO(s),this.schema=Wq(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:Dg(e.name,this.schema)},n=dt(e,"addCommands",t);return n?{...s,...n()}:s},{})}get plugins(){const{editor:s}=this;return Vv([...this.extensions].reverse()).flatMap(n=>{const i={name:n.name,options:n.options,storage:this.editor.extensionStorage[n.name],editor:s,type:Dg(n.name,this.schema)},r=[],o=dt(n,"addKeyboardShortcuts",i);let a={};if(n.type==="mark"&&dt(n,"exitable",i)&&(a.ArrowRight=()=>Uf.handleExit({editor:s,mark:n})),o){const h=Object.fromEntries(Object.entries(o()).map(([p,g])=>[p,()=>g({editor:s})]));a={...a,...h}}const c=WK(a);r.push(c);const l=dt(n,"addInputRules",i);if(DR(n,s.options.enableInputRules)&&l){const h=l();if(h&&h.length){const p=TQ({editor:s,rules:h}),g=Array.isArray(p)?p:[p];r.push(...g)}}const u=dt(n,"addPasteRules",i);if(DR(n,s.options.enablePasteRules)&&u){const h=u();if(h&&h.length){const p=PQ({editor:s,rules:h});r.push(...p)}}const d=dt(n,"addProseMirrorPlugins",i);if(d){const h=d();r.push(...h)}return r})}get attributes(){return PO(this.extensions)}get nodeViews(){const{editor:s}=this,{nodeExtensions:e}=ug(this.extensions);return Object.fromEntries(e.filter(t=>!!dt(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:Mn(t.name,this.schema)},r=dt(t,"addNodeView",i);if(!r)return[];const o=r();if(!o)return[];const a=(c,l,u,d,h)=>{const p=gy(c,n);return o({node:c,view:l,getPos:u,decorations:d,innerDecorations:h,editor:s,extension:t,HTMLAttributes:p})};return[t.name,a]}))}dispatchTransaction(s){const{editor:e}=this;return Vv([...this.extensions].reverse()).reduceRight((n,i)=>{const r={name:i.name,options:i.options,storage:this.editor.extensionStorage[i.name],editor:e,type:Dg(i.name,this.schema)},o=dt(i,"dispatchTransaction",r);return o?a=>{o.call(r,{transaction:a,next:n})}:n},s)}transformPastedHTML(s){const{editor:e}=this;return Vv([...this.extensions]).reduce((n,i)=>{const r={name:i.name,options:i.options,storage:this.editor.extensionStorage[i.name],editor:e,type:Dg(i.name,this.schema)},o=dt(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}=ug(this.extensions);return Object.fromEntries(e.filter(t=>!!dt(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:$c(t.name,this.schema)},r=dt(t,"addMarkView",i);if(!r)return[];const o=(a,c,l)=>{const u=gy(a,n);return r()({mark:a,view:c,inline:l,editor:s,extension:t,HTMLAttributes:u,updateAttributes:d=>{VQ(a,s,d)}})};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:Dg(e.name,this.schema)};e.type==="mark"&&(((t=ls(dt(e,"keepOnSplit",i)))==null||t)&&this.splittableMarks.push(e.name),(n=ls(dt(e,"clearable",i)))==null||n||this.nonClearableMarks.push(e.name));const r=dt(e,"onBeforeCreate",i),o=dt(e,"onCreate",i),a=dt(e,"onUpdate",i),c=dt(e,"onSelectionUpdate",i),l=dt(e,"onTransaction",i),u=dt(e,"onFocus",i),d=dt(e,"onBlur",i),h=dt(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),d&&this.editor.on("blur",d),h&&this.editor.on("destroy",h)})}};Sk.resolve=LO;Sk.sort=Vv;Sk.flatten=nM;var LQ={};eM(LQ,{ClipboardTextSerializer:()=>jO,Commands:()=>VO,Delete:()=>GO,Drop:()=>KO,Editable:()=>qO,FocusEvents:()=>XO,Keymap:()=>YO,Paste:()=>JO,Tabindex:()=>ZO,TextDirection:()=>eD,focusEventsPluginKey:()=>QO});var fn=class zO extends oM{constructor(){super(...arguments),this.type="extension"}static create(e={}){const t=typeof e=="function"?e():e;return new zO(t)}configure(e){return super.configure(e)}extend(e){const t=typeof e=="function"?e():e;return super.extend(t)}},jO=fn.create({name:"clipboardTextSerializer",addOptions(){return{blockSeparator:void 0}},addProseMirrorPlugins(){return[new Gs({key:new _n("clipboardTextSerializer"),props:{clipboardTextSerializer:()=>{const{editor:s}=this,{state:e,schema:t}=s,{doc:n,selection:i}=e,r=DO(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})=>OO(n,{from:l.pos,to:u.pos},a)).join(o??`
|
||
|
||
`)}}})]}}),VO=fn.create({name:"commands",addCommands(){return{...kO}}}),GO=fn.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=RO(s.before,[s,...e]);$O(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,(g,v)=>{const m=v+g.nodeSize-2,y=p.oldRange.from<=v&&m<=p.oldRange.to;this.editor.emit("delete",{type:"node",node:g,from:v,to:m,newFrom:u.mapping.map(v),newTo:u.mapping.map(m),deletedRange:p.oldRange,newRange:p.newRange,partial:!y,editor:this.editor,transaction:s,combinedTransform:u})})});const h=u.mapping;u.steps.forEach((p,g)=>{var v,m;if(p instanceof _g){const y=h.slice(g).map(p.from,-1),_=h.slice(g).map(p.to),b=h.invert().map(y,-1),k=h.invert().map(_),w=y>0?(v=u.doc.nodeAt(y-1))==null?void 0:v.marks.some(A=>A.eq(p.mark)):!1,T=(m=u.doc.nodeAt(_))==null?void 0:m.marks.some(A=>A.eq(p.mark));this.editor.emit("delete",{type:"mark",mark:p.mark,from:p.from,to:p.to,deletedRange:{from:b,to:k},newRange:{from:y,to:_},partial:!!(T||w),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()}}),KO=fn.create({name:"drop",addProseMirrorPlugins(){return[new Gs({key:new _n("tiptapDrop"),props:{handleDrop:(s,e,t,n)=>{this.editor.emit("drop",{editor:this.editor,event:e,slice:t,moved:n})}}})]}}),qO=fn.create({name:"editable",addProseMirrorPlugins(){return[new Gs({key:new _n("editable"),props:{editable:()=>this.editor.options.editable}})]}}),QO=new _n("focusEvents"),XO=fn.create({name:"focusEvents",addProseMirrorPlugins(){const{editor:s}=this;return[new Gs({key:QO,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}}}})]}}),YO=fn.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:d}=c,{pos:h,parent:p}=d,g=d.parent.isTextblock&&h>0?a.doc.resolve(h-1):d,v=g.parent.type.spec.isolating,m=d.pos-d.parentOffset,y=v&&g.parent.childCount===1?m===d.pos:Ht.atStart(l).from===h;return!u||!p.type.isTextblock||p.textContent.length||!y||y&&d.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 GS()||MO()?r:i},addProseMirrorPlugins(){return[new Gs({key:new _n("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=Ht.atStart(e.doc).from,l=Ht.atEnd(e.doc).to;if(r||!(o===c&&a===l)||!vy(t.doc))return;const h=t.tr,p=vk({state:t,transaction:h}),{commands:g}=new yk({editor:this.editor,state:p});if(g.clearNodes(),!!h.steps.length)return h}})]}}),JO=fn.create({name:"paste",addProseMirrorPlugins(){return[new Gs({key:new _n("tiptapPaste"),props:{handlePaste:(s,e,t)=>{this.editor.emit("paste",{editor:this.editor,event:e,slice:t})}}})]}}),ZO=fn.create({name:"tabindex",addOptions(){return{value:void 0}},addProseMirrorPlugins(){return[new Gs({key:new _n("tabindex"),props:{attributes:()=>{var s;return!this.editor.isEditable&&this.options.value===void 0?{}:{tabindex:(s=this.options.value)!=null?s:"0"}}}})]}}),eD=fn.create({name:"textDirection",addOptions(){return{direction:void 0}},addGlobalAttributes(){if(!this.options.direction)return[];const{nodeExtensions:s}=ug(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 Gs({key:new _n("textDirection"),props:{attributes:()=>{const s=this.options.direction;return s?{dir:s}:{}}}})]}}),OQ=class ev{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 can’t 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 ev(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 ev(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 ev(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 ev(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)}},DQ=`.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 tD(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 NQ=class extends kQ{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:Zq,createMappablePosition:eQ},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=AO(t,this.options.autofocus);this.editorState=Tp.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=tD(DQ,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?[qO,jO.configure({blockSeparator:(t=(e=this.options.coreExtensionOptions)==null?void 0:e.clipboardTextSerializer)==null?void 0:t.blockSeparator}),VO,XO,YO,ZO.configure({value:(i=(n=this.options.coreExtensionOptions)==null?void 0:n.tabindex)==null?void 0:i.value}),KO,JO,GO,eD.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 Sk(o,this)}createCommandManager(){this.commandManager=new yk({editor:this})}createSchema(){this.schema=this.extensionManager.schema}createDoc(){let e;try{e=d1(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=d1(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 wO(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 d;return(d=this.capturedTransaction)==null?void 0:d.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 NO(this.state,e)}isActive(e,t){const n=typeof e=="string"?e:null,i=typeof e=="string"?t:e;return Xq(this.state,n,i)}getJSON(){return this.state.doc.toJSON()}getHTML(){return iM(this.state.doc.content,this.schema)}getText(e){const{blockSeparator:t=`
|
||
|
||
`,textSerializers:n={}}=e||{};return jq(this.state.doc,{blockSeparator:t,textSerializers:{...DO(this.schema),...n}})}get isEmpty(){return vy(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 OQ(t,this,!1,n)}get $doc(){return this.$pos(0)}};function dg(s){return new wk({find:s.find,handler:({state:e,range:t,match:n})=>{const i=ls(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(rM(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 h=t.from+c+o.length;r.addMark(t.from+c,h,s.type.create(i||{})),r.removeStoredMark(s.type)}},undoable:s.undoable})}function $Q(s){return new wk({find:s.find,handler:({state:e,range:t,match:n})=>{const i=ls(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 d=n[0][n[0].length-1];r.insertText(d,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 f1(s){return new wk({find:s.find,handler:({state:e,range:t,match:n})=>{const i=e.doc.resolve(t.from),r=ls(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 hg(s){return new wk({find:s.find,handler:({state:e,range:t,match:n,chain:i})=>{const r=ls(s.getAttributes,void 0,n)||{},o=e.tr.delete(t.from,t.to),c=o.doc.resolve(t.from).blockRange(),l=c&&HE(c,s.type,r);if(!l)return null;if(o.wrap(c,l),s.keepMarks&&s.editor){const{selection:d,storedMarks:h}=e,{splittableMarks:p}=s.editor.extensionManager,g=h||d.$to.parentOffset&&d.$from.marks();if(g){const v=g.filter(m=>p.includes(m.type.name));o.ensureMarks(v)}}if(s.keepAttributes){const d=s.type.name==="bulletList"||s.type.name==="orderedList"?"listItem":"taskList";i().updateAttributes(d,r).run()}const u=o.doc.resolve(t.from-1).nodeBefore;u&&u.type===s.type&&vd(o.doc,t.from-1)&&(!s.joinPredicate||s.joinPredicate(n,u))&&o.join(t.from-1)},undoable:s.undoable})}function BQ(s,e){const{selection:t}=s,{$from:n}=t;if(t instanceof _t){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 FQ(s){return s.replace(/[-/\\^$*+?.()|[\]{}]/g,"\\$&")}var HQ={};eM(HQ,{createAtomBlockMarkdownSpec:()=>UQ,createBlockMarkdownSpec:()=>WQ,createInlineMarkdownSpec:()=>sD,parseAttributes:()=>aM,parseIndentedBlocks:()=>p1,renderNestedMarkdownContent:()=>cM,serializeAttributes:()=>lM});function aM(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 d;const h=parseInt(((d=u.match(/__QUOTED_(\d+)__/))==null?void 0:d[1])||"0",10),p=t[h];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 lM(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 UQ(s){const{nodeName:e,name:t,parseAttributes:n=aM,serializeAttributes:i=lM,defaultAttributes:r={},requiredAttributes:o=[],allowedAttributes:a}=s,c=t||e,l=u=>{if(!a)return u;const d={};return a.forEach(h=>{h in u&&(d[h]=u[h])}),d};return{parseMarkdown:(u,d)=>{const h={...r,...u.attributes};return d.createNode(e,h,[])},markdownTokenizer:{name:e,level:"block",start(u){var d;const h=new RegExp(`^:::${c}(?:\\s|$)`,"m"),p=(d=u.match(h))==null?void 0:d.index;return p!==void 0?p:-1},tokenize(u,d,h){const p=new RegExp(`^:::${c}(?:\\s+\\{([^}]*)\\})?\\s*:::(?:\\n|$)`),g=u.match(p);if(!g)return;const v=g[1]||"",m=n(v);if(!o.find(_=>!(_ in m)))return{type:e,raw:g[0],attributes:m}}},renderMarkdown:u=>{const d=l(u.attrs||{}),h=i(d),p=h?` {${h}}`:"";return`:::${c}${p} :::`}}}function WQ(s){const{nodeName:e,name:t,getContent:n,parseAttributes:i=aM,serializeAttributes:r=lM,defaultAttributes:o={},content:a="block",allowedAttributes:c}=s,l=t||e,u=d=>{if(!c)return d;const h={};return c.forEach(p=>{p in d&&(h[p]=d[p])}),h};return{parseMarkdown:(d,h)=>{let p;if(n){const v=n(d);p=typeof v=="string"?[{type:"text",text:v}]:v}else a==="block"?p=h.parseChildren(d.tokens||[]):p=h.parseInline(d.tokens||[]);const g={...o,...d.attributes};return h.createNode(e,g,p)},markdownTokenizer:{name:e,level:"block",start(d){var h;const p=new RegExp(`^:::${l}`,"m"),g=(h=d.match(p))==null?void 0:h.index;return g!==void 0?g:-1},tokenize(d,h,p){var g;const v=new RegExp(`^:::${l}(?:\\s+\\{([^}]*)\\})?\\s*\\n`),m=d.match(v);if(!m)return;const[y,_=""]=m,b=i(_);let k=1;const w=y.length;let T="";const A=/^:::([\w-]*)(\s.*)?/gm,C=d.slice(w);for(A.lastIndex=0;;){const E=A.exec(C);if(E===null)break;const x=E.index,D=E[1];if(!((g=E[2])!=null&&g.endsWith(":::"))){if(D)k+=1;else if(k-=1,k===0){const N=C.slice(0,x);T=N.trim();const O=d.slice(0,w+x+E[0].length);let G=[];if(T)if(a==="block")for(G=p.blockTokens(N),G.forEach(Z=>{Z.text&&(!Z.tokens||Z.tokens.length===0)&&(Z.tokens=p.inlineTokens(Z.text))});G.length>0;){const Z=G[G.length-1];if(Z.type==="paragraph"&&(!Z.text||Z.text.trim()===""))G.pop();else break}else G=p.inlineTokens(T);return{type:e,raw:O,attributes:b,content:T,tokens:G}}}}}},renderMarkdown:(d,h)=>{const p=u(d.attrs||{}),g=r(p),v=g?` {${g}}`:"",m=h.renderChildren(d.content||[],`
|
||
|
||
`);return`:::${l}${v}
|
||
|
||
${m}
|
||
|
||
:::`}}}function zQ(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 jQ(s){return Object.entries(s).filter(([,e])=>e!=null).map(([e,t])=>`${e}="${t}"`).join(" ")}function sD(s){const{nodeName:e,name:t,getContent:n,parseAttributes:i=zQ,serializeAttributes:r=jQ,defaultAttributes:o={},selfClosing:a=!1,allowedAttributes:c}=s,l=t||e,u=h=>{if(!c)return h;const p={};return c.forEach(g=>{const v=typeof g=="string"?g:g.name,m=typeof g=="string"?void 0:g.skipIfDefault;if(v in h){const y=h[v];if(m!==void 0&&y===m)return;p[v]=y}}),p},d=l.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return{parseMarkdown:(h,p)=>{const g={...o,...h.attributes};if(a)return p.createNode(e,g);const v=n?n(h):h.content||"";return v?p.createNode(e,g,[p.createTextNode(v)]):p.createNode(e,g,[])},markdownTokenizer:{name:e,level:"inline",start(h){const p=a?new RegExp(`\\[${d}\\s*[^\\]]*\\]`):new RegExp(`\\[${d}\\s*[^\\]]*\\][\\s\\S]*?\\[\\/${d}\\]`),g=h.match(p),v=g==null?void 0:g.index;return v!==void 0?v:-1},tokenize(h,p,g){const v=a?new RegExp(`^\\[${d}\\s*([^\\]]*)\\]`):new RegExp(`^\\[${d}\\s*([^\\]]*)\\]([\\s\\S]*?)\\[\\/${d}\\]`),m=h.match(v);if(!m)return;let y="",_="";if(a){const[,k]=m;_=k}else{const[,k,w]=m;_=k,y=w||""}const b=i(_.trim());return{type:e,raw:m[0],content:y.trim(),attributes:b}}},renderMarkdown:h=>{let p="";n?p=n(h):h.content&&h.content.length>0&&(p=h.content.filter(y=>y.type==="text").map(y=>y.text).join(""));const g=u(h.attrs||{}),v=r(g),m=v?` ${v}`:"";return a?`[${l}${m}]`:`[${l}${m}]${p}[/${l}]`}}}function p1(s,e,t){var n,i,r,o;const a=s.split(`
|
||
`),c=[];let l="",u=0;const d=e.baseIndentSize||2;for(;u<a.length;){const h=a[u],p=h.match(e.itemPattern);if(!p){if(c.length>0)break;if(h.trim()===""){u+=1,l=`${l}${h}
|
||
`;continue}else return}const g=e.extractItemData(p),{indentLevel:v,mainContent:m}=g;l=`${l}${h}
|
||
`;const y=[m];for(u+=1;u<a.length;){const w=a[u];if(w.trim()===""){const A=a.slice(u+1).findIndex(x=>x.trim()!=="");if(A===-1)break;if((((i=(n=a[u+1+A].match(/^(\s*)/))==null?void 0:n[1])==null?void 0:i.length)||0)>v){y.push(w),l=`${l}${w}
|
||
`,u+=1;continue}else break}if((((o=(r=w.match(/^(\s*)/))==null?void 0:r[1])==null?void 0:o.length)||0)>v)y.push(w),l=`${l}${w}
|
||
`,u+=1;else break}let _;const b=y.slice(1);if(b.length>0){const w=b.map(T=>T.slice(v+d)).join(`
|
||
`);w.trim()&&(e.customNestedParser?_=e.customNestedParser(w):_=t.blockTokens(w))}const k=e.createToken(g,_);c.push(k)}if(c.length!==0)return{items:c,raw:l}}function cM(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 d,h;const p=(h=(d=e.renderChild)==null?void 0:d.call(e,l,u+1))!=null?h:e.renderChildren([l]);if(p!=null){const g=p.split(`
|
||
`).map(v=>v?e.indent(v):e.indent("")).join(`
|
||
`);c+=l.type==="paragraph"?`
|
||
|
||
${g}`:`
|
||
${g}`}}),c}function VQ(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 d=null;if(a.marks.forEach(p=>{if(p!==o)return!1;d=p}),!d)return;let h=!1;if(Object.keys(t).forEach(p=>{t[p]!==d.attrs[p]&&(h=!0)}),h){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 Ar=class nD extends oM{constructor(){super(...arguments),this.type="node"}static create(e={}){const t=typeof e=="function"?e():e;return new nD(t)}configure(e){return super.configure(e)}extend(e){const t=typeof e=="function"?e():e;return super.extend(t)}};function Df(s){return new MQ({find:s.find,handler:({state:e,range:t,match:n,pasteEvent:i})=>{const r=ls(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/),d=t.from+c.indexOf(a),h=d+a.length;if(rM(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>d).length)return null;h<t.to&&o.delete(h,t.to),d>t.from&&o.delete(t.from+u,d),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 $R(s){return iF((e,t)=>({get(){return e(),s},set(n){s=n,requestAnimationFrame(()=>{requestAnimationFrame(()=>{t()})})}}))}var GQ=class extends NQ{constructor(s={}){return super(s),this.contentComponent=null,this.appContext=null,this.reactiveState=$R(this.view.state),this.reactiveExtensionStorage=$R(this.extensionStorage),this.on("beforeTransaction",({nextState:e})=>{this.reactiveState.value=e,this.reactiveExtensionStorage.value=this.extensionStorage}),CE(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}},KQ=ct({name:"EditorContent",props:{editor:{default:null,type:Object}},setup(s){const e=ge(),t=rF();return jP(()=>{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=Ne(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()})}),Rn(()=>{const n=s.editor;n&&(n.contentComponent=null,n.appContext=null)}),{rootEl:e}},render(){return sF("div",{ref:s=>{this.rootEl=s}})}}),qQ=(s={})=>{const e=nF();return dn(()=>{e.value=new GQ(s)}),Rn(()=>{var t;(t=e.value)==null||t.destroy()}),e},KS=(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 iD(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=iD(i.content,r.content,t+1);if(o!=null)return o}t+=i.nodeSize}}function rD(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=rD(o.content,a.content,t-1,n-1);if(l)return l}t-=c,n-=c}}var Lc=class zi{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 zi(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 zi(n,i)}cutByIndex(e,t){return e==t?zi.empty:e==0&&t==this.content.length?this:new zi(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 zi(i,r)}addToStart(e){return new zi([e].concat(this.content),this.size+e.nodeSize)}addToEnd(e){return new zi(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 iD(this,e,t)}findDiffEnd(e,t=this.size,n=e.size){return rD(this,e,t,n)}findIndex(e){if(e==0)return X_(0,e);if(e==this.size)return X_(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?X_(t+1,r):X_(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 zi.empty;if(!Array.isArray(t))throw new RangeError("Invalid input for Fragment.fromJSON");return zi.fromArray(t.map(e.nodeFromJSON))}static fromArray(e){if(!e.length)return zi.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 zi(t||e,n)}static from(e){if(!e)return zi.empty;if(e instanceof zi)return e;if(Array.isArray(e))return this.fromArray(e);if(e.attrs)return new zi([e],e.nodeSize);throw new RangeError("Can not convert "+e+" to a Fragment"+(e.nodesBetween?" (looks like multiple versions of prosemirror-model were loaded)":""))}};Lc.empty=new Lc([],0);var BC={index:0,offset:0};function X_(s,e){return BC.index=s,BC.offset=e,BC}var QQ=class extends Error{},Tn=class pp{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=aD(this.content,e+this.openStart,t,this.openStart+1,this.openEnd+1);return n&&new pp(n,this.openStart,this.openEnd)}removeBetween(e,t){return new pp(oD(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 pp.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 pp(Lc.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 pp(e,n,i)}};Tn.empty=new Tn(Lc.empty,0,0);function oD(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(oD(r.content,e-i-1,t-i-1)))}function aD(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=aD(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 lD=65535,cD=Math.pow(2,16);function XQ(s,e){return s+e*cD}function BR(s){return s&lD}function YQ(s){return(s-(s&lD))/cD}var uD=1,dD=2,Pw=4,hD=8,FR=class{constructor(s,e,t){this.pos=s,this.delInfo=e,this.recover=t}get deleted(){return(this.delInfo&hD)>0}get deletedBefore(){return(this.delInfo&(uD|Pw))>0}get deletedAfter(){return(this.delInfo&(dD|Pw))>0}get deletedAcross(){return(this.delInfo&Pw)>0}},Nf=class mp{constructor(e,t=!1){if(this.ranges=e,this.inverted=t,!e.length&&mp.empty)return mp.empty}recover(e){let t=0,n=BR(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+YQ(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],d=c+l;if(e<=d){let h=l?e==c?-1:e==d?1:t:t,p=c+i+(h<0?0:u);if(n)return p;let g=e==(t<0?c:d)?null:XQ(a/3,e-c),v=e==c?dD:e==d?uD:Pw;return(t<0?e!=c:e!=d)&&(v|=hD),new FR(p,v,g)}i+=u-l}return n?e+i:new FR(e+i,0,null)}touches(e,t){let n=0,i=BR(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 mp(this.ranges,!this.inverted)}toString(){return(this.inverted?"-":"")+JSON.stringify(this.ranges)}static offset(e){return e==0?mp.empty:new mp(e<0?[0,-e,0]:[0,0,e])}};Nf.empty=new Nf([]);var FC=Object.create(null),Li=class{getMap(){return Nf.empty}merge(s){return null}static fromJSON(s,e){if(!e||!e.stepType)throw new RangeError("Invalid input for Step.fromJSON");let t=FC[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 FC)throw new RangeError("Duplicate use of step JSON ID "+s);return FC[s]=e,e.prototype.jsonID=s,e}},sr=class tv{constructor(e,t){this.doc=e,this.failed=t}static ok(e){return new tv(e,null)}static fail(e){return new tv(null,e)}static fromReplace(e,t,n,i){try{return tv.ok(e.replace(t,n,i))}catch(r){if(r instanceof QQ)return tv.fail(r.message);throw r}}};function uM(s,e,t){let n=[];for(let i=0;i<s.childCount;i++){let r=s.child(i);r.content.size&&(r=r.copy(uM(r.content,e,r))),r.isInline&&(r=e(r,t,i)),n.push(r)}return Lc.fromArray(n)}var fD=class sv extends Li{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 Tn(uM(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 sr.fromReplace(e,this.from,this.to,r)}invert(){return new pD(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 sv(t.pos,n.pos,this.mark)}merge(e){return e instanceof sv&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new sv(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 sv(t.from,t.to,e.markFromJSON(t.mark))}};Li.jsonID("addMark",fD);var pD=class nv extends Li{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 Tn(uM(t.content,i=>i.mark(this.mark.removeFromSet(i.marks)),e),t.openStart,t.openEnd);return sr.fromReplace(e,this.from,this.to,n)}invert(){return new fD(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 nv(t.pos,n.pos,this.mark)}merge(e){return e instanceof nv&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new nv(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 nv(t.from,t.to,e.markFromJSON(t.mark))}};Li.jsonID("removeMark",pD);var mD=class iv extends Li{constructor(e,t){super(),this.pos=e,this.mark=t}apply(e){let t=e.nodeAt(this.pos);if(!t)return sr.fail("No node at mark step's position");let n=t.type.create(t.attrs,null,this.mark.addToSet(t.marks));return sr.fromReplace(e,this.pos,this.pos+1,new Tn(Lc.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 iv(this.pos,t.marks[i]);return new iv(this.pos,this.mark)}}return new gD(this.pos,this.mark)}map(e){let t=e.mapResult(this.pos,1);return t.deletedAfter?null:new iv(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 iv(t.pos,e.markFromJSON(t.mark))}};Li.jsonID("addNodeMark",mD);var gD=class m1 extends Li{constructor(e,t){super(),this.pos=e,this.mark=t}apply(e){let t=e.nodeAt(this.pos);if(!t)return sr.fail("No node at mark step's position");let n=t.type.create(t.attrs,null,this.mark.removeFromSet(t.marks));return sr.fromReplace(e,this.pos,this.pos+1,new Tn(Lc.from(n),0,t.isLeaf?0:1))}invert(e){let t=e.nodeAt(this.pos);return!t||!this.mark.isInSet(t.marks)?this:new mD(this.pos,this.mark)}map(e){let t=e.mapResult(this.pos,1);return t.deletedAfter?null:new m1(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 m1(t.pos,e.markFromJSON(t.mark))}};Li.jsonID("removeNodeMark",gD);var dM=class Yc extends Li{constructor(e,t,n,i=!1){super(),this.from=e,this.to=t,this.slice=n,this.structure=i}apply(e){return this.structure&&g1(e,this.from,this.to)?sr.fail("Structure replace would overwrite content"):sr.fromReplace(e,this.from,this.to,this.slice)}getMap(){return new Nf([this.from,this.to-this.from,this.slice.size])}invert(e){return new Yc(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&&Yc.MAP_BIAS<0?t:e.mapResult(this.from,1);return n.deletedAcross&&t.deletedAcross?null:new Yc(n.pos,Math.max(n.pos,t.pos),this.slice,this.structure)}merge(e){if(!(e instanceof Yc)||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?Tn.empty:new Tn(this.slice.content.append(e.slice.content),this.slice.openStart,e.slice.openEnd);return new Yc(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?Tn.empty:new Tn(e.slice.content.append(this.slice.content),e.slice.openStart,this.slice.openEnd);return new Yc(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 Yc(t.from,t.to,Tn.fromJSON(e,t.slice),!!t.structure)}};dM.MAP_BIAS=1;Li.jsonID("replace",dM);var vD=class Lw extends Li{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&&(g1(e,this.from,this.gapFrom)||g1(e,this.gapTo,this.to)))return sr.fail("Structure gap-replace would overwrite content");let t=e.slice(this.gapFrom,this.gapTo);if(t.openStart||t.openEnd)return sr.fail("Gap is not a flat range");let n=this.slice.insertAt(this.insert,t.content);return n?sr.fromReplace(e,this.from,this.to,n):sr.fail("Content does not fit in gap")}getMap(){return new Nf([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 Lw(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 Lw(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 Lw(t.from,t.to,t.gapFrom,t.gapTo,Tn.fromJSON(e,t.slice),t.insert,!!t.structure)}};Li.jsonID("replaceAround",vD);function g1(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 JQ=class Ow extends Li{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 sr.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 sr.fromReplace(e,this.pos,this.pos+1,new Tn(Lc.from(i),0,t.isLeaf?0:1))}getMap(){return Nf.empty}invert(e){return new Ow(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 Ow(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 Ow(t.pos,t.attr,t.value)}};Li.jsonID("attr",JQ);var ZQ=class v1 extends Li{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 sr.ok(n)}getMap(){return Nf.empty}invert(e){return new v1(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 v1(t.attr,t.value)}};Li.jsonID("docAttr",ZQ);var yy=class extends Error{};yy=function s(e){let t=Error.call(this,e);return t.__proto__=s.prototype,t};yy.prototype=Object.create(Error.prototype);yy.prototype.constructor=yy;yy.prototype.name="TransformError";var HC=Object.create(null),Qn=class{constructor(s,e,t){this.$anchor=s,this.$head=e,this.ranges=t||[new eX(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=Tn.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?Tn.empty:e),o==0&&WR(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),WR(s,t,e.isInline?-1:1))}}static findFrom(s,e,t=!1){let n=s.parent.inlineContent?new fg(s):gp(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?gp(s.node(0),s.node(i),s.before(i+1),s.index(i),e,t):gp(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 Gv(s.node(0))}static atStart(s){return gp(s,s,0,0,1)||new Gv(s)}static atEnd(s){return gp(s,s,s.content.size,s.childCount,-1)||new Gv(s)}static fromJSON(s,e){if(!e||!e.type)throw new RangeError("Invalid input for Selection.fromJSON");let t=HC[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 HC)throw new RangeError("Duplicate use of selection JSON ID "+s);return HC[s]=e,e.prototype.jsonID=s,e}getBookmark(){return fg.between(this.$anchor,this.$head).getBookmark()}};Qn.prototype.visible=!0;var eX=class{constructor(s,e){this.$from=s,this.$to=e}},HR=!1;function UR(s){!HR&&!s.parent.inlineContent&&(HR=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+s.parent.type.name+")"))}var fg=class rv extends Qn{constructor(e,t=e){UR(e),UR(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 rv(i.parent.inlineContent?i:n,n)}replace(e,t=Tn.empty){if(super.replace(e,t),t==Tn.empty){let n=this.$from.marksAcross(this.$to);n&&e.ensureMarks(n)}}eq(e){return e instanceof rv&&e.anchor==this.anchor&&e.head==this.head}getBookmark(){return new yD(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 rv(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 rv(e,t)}};Qn.jsonID("text",fg);var yD=class bD{constructor(e,t){this.anchor=e,this.head=t}map(e){return new bD(e.map(this.anchor),e.map(this.head))}resolve(e){return fg.between(e.resolve(this.anchor),e.resolve(this.head))}},pg=class ov 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 ov(r)}content(){return new Tn(Lc.from(this.node),0,0)}eq(e){return e instanceof ov&&e.anchor==this.anchor}toJSON(){return{type:"node",anchor:this.anchor}}getBookmark(){return new tX(this.anchor)}static fromJSON(e,t){if(typeof t.anchor!="number")throw new RangeError("Invalid input for NodeSelection.fromJSON");return new ov(e.resolve(t.anchor))}static create(e,t){return new ov(e.resolve(t))}static isSelectable(e){return!e.isText&&e.type.spec.selectable!==!1}};pg.prototype.visible=!1;Qn.jsonID("node",pg);var tX=class _D{constructor(e){this.anchor=e}map(e){let{deleted:t,pos:n}=e.mapResult(this.anchor);return t?new yD(n,n):new _D(n)}resolve(e){let t=e.resolve(this.anchor),n=t.nodeAfter;return n&&pg.isSelectable(n)?new pg(t):Qn.near(t)}},Gv=class Dw extends Qn{constructor(e){super(e.resolve(0),e.resolve(e.content.size))}replace(e,t=Tn.empty){if(t==Tn.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 Dw(e)}map(e){return new Dw(e)}eq(e){return e instanceof Dw}getBookmark(){return sX}};Qn.jsonID("all",Gv);var sX={map(){return this},resolve(s){return new Gv(s)}};function gp(s,e,t,n,i,r=!1){if(e.inlineContent)return fg.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&&pg.isSelectable(a))return pg.create(s,t-(i<0?a.nodeSize:0))}else{let c=gp(s,a,t+i,i<0?a.childCount:0,i,r);if(c)return c}t+=a.nodeSize*i}return null}function WR(s,e,t){let n=s.steps.length-1;if(n<e)return;let i=s.steps[n];if(!(i instanceof dM||i instanceof vD))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 zR(s,e){return!e||!s?s:s.bind(e)}var Y_=class{constructor(s,e,t){this.name=s,this.init=zR(e.init,t),this.apply=zR(e.apply,t)}};new Y_("doc",{init(s){return s.doc||s.schema.topNodeType.createAndFill()},apply(s){return s.doc}}),new Y_("selection",{init(s,e){return s.selection||Qn.atStart(e.doc)},apply(s){return s.selection}}),new Y_("storedMarks",{init(s){return s.storedMarks||null},apply(s,e,t,n){return n.selection.$cursor?s.storedMarks:null}}),new Y_("scrollToSelection",{init(){return 0},apply(s,e){return s.scrolledIntoView?e+1:e}});var nX=(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 d=o.before(),p=d-1-1,{tr:g}=n;return g.delete(d,o.after()).insert(p,o.parent.content),g.setSelection(fg.create(g.doc,p)),i.dispatch(g.scrollIntoView()),!0},iX=/^\s*>\s$/,rX=Ar.create({name:"blockquote",addOptions(){return{HTMLAttributes:{}}},content:"block+",group:"block",defining:!0,parseHTML(){return[{tag:"blockquote"}]},renderHTML({HTMLAttributes:s}){return KS("blockquote",{...Vs(this.options.HTMLAttributes,s),children:KS("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(d=>d.trim()===""?t:`${t} ${d}`);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:()=>nX(this.editor,this.type)}},addInputRules(){return[hg({find:iX,type:this.type})]}}),oX=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))$/,aX=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))/g,lX=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))$/,cX=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))/g,uX=Uf.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 KS("strong",{...Vs(this.options.HTMLAttributes,s),children:KS("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[dg({find:oX,type:this.type}),dg({find:lX,type:this.type})]},addPasteRules(){return[Df({find:aX,type:this.type}),Df({find:cX,type:this.type})]}}),dX=s=>{const e=/`([^`]+)`(?!`)$/.exec(s);return!e||e.index>0&&s[e.index-1]==="`"?null:{index:e.index,text:e[0],replaceWith:e[1]}},hX=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},fX=Uf.create({name:"code",addOptions(){return{HTMLAttributes:{}}},excludes:"_",code:!0,exitable:!0,parseHTML(){return[{tag:"code"}]},renderHTML({HTMLAttributes:s}){return["code",Vs(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[dg({find:dX,type:this.type})]},addPasteRules(){return[Df({find:hX,type:this.type})]}}),UC=4,pX=/^```([a-z]+)?[\s\n]$/,mX=/^~~~([a-z]+)?[\s\n]$/,gX=Ar.create({name:"codeBlock",addOptions(){return{languageClassPrefix:"language-",exitOnTripleEnter:!0,exitOnArrowDown:!0,defaultLanguage:null,enableTabIndentation:!1,tabSize:UC,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",Vs(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:UC,{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(g=>a+g).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:UC,{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(),d=r.end(),p=n.doc.textBetween(u,d,`
|
||
`,`
|
||
`).split(`
|
||
`);let g=0,v=0;const m=l-u;for(let T=0;T<p.length;T+=1){if(v+p[T].length>=m){g=T;break}v+=p[T].length+1}const _=((c=p[g].match(/^ */))==null?void 0:c[0])||"",b=Math.min(_.length,t);if(b===0)return!0;let k=u;for(let T=0;T<g;T+=1)k+=p[T].length+1;return a.delete(k,k+b),l-k<=b&&a.setSelection(kt.create(a.doc,k)),!0}):s.commands.command(({tr:a})=>{const{from:c,to:l}=i,h=n.doc.textBetween(c,l,`
|
||
`,`
|
||
`).split(`
|
||
`).map(p=>{var g;const v=((g=p.match(/^ */))==null?void 0:g[0])||"",m=Math.min(v.length,t);return p.slice(m)}).join(`
|
||
`);return a.replaceWith(c,l,n.schema.text(h)),!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(Ht.near(n.resolve(a))),!0)):s.commands.exitCode()}}},addInputRules(){return[f1({find:pX,type:this.type,getAttributes:s=>({language:s[1]})}),f1({find:mX,type:this.type,getAttributes:s=>({language:s[1]})})]},addProseMirrorPlugins(){return[new Gs({key:new _n("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(kt.near(o.doc.resolve(Math.max(0,o.selection.from-2)))),o.setMeta("paste",!0),s.dispatch(o),!0}}})]}}),vX=Ar.create({name:"doc",topNode:!0,content:"block+",renderMarkdown:(s,e)=>s.content?e.renderChildren(s.content,`
|
||
|
||
`):""}),yX=Ar.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",Vs(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 d=c.filter(h=>a.includes(h.type.name));l.ensureMarks(d)}return!0}).run()})])}},addKeyboardShortcuts(){return{"Mod-Enter":()=>this.editor.commands.setHardBreak(),"Shift-Enter":()=>this.editor.commands.setHardBreak()}}}),bX=Ar.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]}`,Vs(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=>f1({find:new RegExp(`^(#{${Math.min(...this.options.levels)},${s}})\\s$`),type:this.type,getAttributes:{level:s}}))}}),_X=Ar.create({name:"horizontalRule",addOptions(){return{HTMLAttributes:{},nextNodeType:"paragraph"}},group:"block",parseHTML(){return[{tag:"hr"}]},renderHTML({HTMLAttributes:s}){return["hr",Vs(this.options.HTMLAttributes,s)]},markdownTokenName:"hr",parseMarkdown:(s,e)=>e.createNode("horizontalRule"),renderMarkdown:()=>"---",addCommands(){return{setHorizontalRule:()=>({chain:s,state:e})=>{if(!BQ(e,e.schema.nodes[this.name]))return!1;const{selection:t}=e,{$to:n}=t,i=s();return BO(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(kt.create(o.doc,c.pos+1)):c.nodeAfter.isBlock?o.setSelection(_t.create(o.doc,c.pos)):o.setSelection(kt.create(o.doc,c.pos));else{const u=r.schema.nodes[this.options.nextNodeType]||c.parent.type.contentMatch.defaultType,d=u==null?void 0:u.create();d&&(o.insert(l,d),o.setSelection(kt.create(o.doc,l+1)))}o.scrollIntoView()}return!0}).run()}}},addInputRules(){return[$Q({find:/^(?:---|—-|___\s|\*\*\*\s)$/,type:this.type})]}}),wX=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/,SX=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g,kX=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/,CX=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g,TX=Uf.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",Vs(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[dg({find:wX,type:this.type}),dg({find:kX,type:this.type})]},addPasteRules(){return[Df({find:SX,type:this.type}),Df({find:CX,type:this.type})]}});const AX="aaa1rp3bb0ott3vie4c1le2ogado5udhabi7c0ademy5centure6ountant0s9o1tor4d0s1ult4e0g1ro2tna4f0l1rica5g0akhan5ency5i0g1rbus3force5tel5kdn3l0ibaba4pay4lfinanz6state5y2sace3tom5m0azon4ericanexpress7family11x2fam3ica3sterdam8nalytics7droid5quan4z2o0l2partments8p0le4q0uarelle8r0ab1mco4chi3my2pa2t0e3s0da2ia2sociates9t0hleta5torney7u0ction5di0ble3o3spost5thor3o0s4w0s2x0a2z0ure5ba0by2idu3namex4d1k2r0celona5laycard4s5efoot5gains6seball5ketball8uhaus5yern5b0c1t1va3cg1n2d1e0ats2uty4er2rlin4st0buy5t2f1g1h0arti5i0ble3d1ke2ng0o3o1z2j1lack0friday9ockbuster8g1omberg7ue3m0s1w2n0pparibas9o0ats3ehringer8fa2m1nd2o0k0ing5sch2tik2on4t1utique6x2r0adesco6idgestone9oadway5ker3ther5ussels7s1t1uild0ers6siness6y1zz3v1w1y1z0h3ca0b1fe2l0l1vinklein9m0era3p2non3petown5ital0one8r0avan4ds2e0er0s4s2sa1e1h1ino4t0ering5holic7ba1n1re3c1d1enter4o1rn3f0a1d2g1h0anel2nel4rity4se2t2eap3intai5ristmas6ome4urch5i0priani6rcle4sco3tadel4i0c2y3k1l0aims4eaning6ick2nic1que6othing5ud3ub0med6m1n1o0ach3des3ffee4llege4ogne5m0mbank4unity6pany2re3uter5sec4ndos3struction8ulting7tact3ractors9oking4l1p2rsica5untry4pon0s4rses6pa2r0edit0card4union9icket5own3s1uise0s6u0isinella9v1w1x1y0mru3ou3z2dad1nce3ta1e1ing3sun4y2clk3ds2e0al0er2s3gree4livery5l1oitte5ta3mocrat6ntal2ist5si0gn4v2hl2iamonds6et2gital5rect0ory7scount3ver5h2y2j1k1m1np2o0cs1tor4g1mains5t1wnload7rive4tv2ubai3pont4rban5vag2r2z2earth3t2c0o2deka3u0cation8e1g1mail3erck5nergy4gineer0ing9terprises10pson4quipment8r0icsson6ni3s0q1tate5t1u0rovision8s2vents5xchange6pert3osed4ress5traspace10fage2il1rwinds6th3mily4n0s2rm0ers5shion4t3edex3edback6rrari3ero6i0delity5o2lm2nal1nce1ial7re0stone6mdale6sh0ing5t0ness6j1k1lickr3ghts4r2orist4wers5y2m1o0o0d1tball6rd1ex2sale4um3undation8x2r0ee1senius7l1ogans4ntier7tr2ujitsu5n0d2rniture7tbol5yi3ga0l0lery3o1up4me0s3p1rden4y2b0iz3d0n2e0a1nt0ing5orge5f1g0ee3h1i0ft0s3ves2ing5l0ass3e1obal2o4m0ail3bh2o1x2n1odaddy5ld0point6f2odyear5g0le4p1t1v2p1q1r0ainger5phics5tis4een3ipe3ocery4up4s1t1u0cci3ge2ide2tars5ru3w1y2hair2mburg5ngout5us3bo2dfc0bank7ealth0care8lp1sinki6re1mes5iphop4samitsu7tachi5v2k0t2m1n1ockey4ldings5iday5medepot5goods5s0ense7nda3rse3spital5t0ing5t0els3mail5use3w2r1sbc3t1u0ghes5yatt3undai7ibm2cbc2e1u2d1e0ee3fm2kano4l1m0amat4db2mo0bilien9n0c1dustries8finiti5o2g1k1stitute6urance4e4t0ernational10uit4vestments10o1piranga7q1r0ish4s0maili5t0anbul7t0au2v3jaguar4va3cb2e0ep2tzt3welry6io2ll2m0p2nj2o0bs1urg4t1y2p0morgan6rs3uegos4niper7kaufen5ddi3e0rryhotels6properties14fh2g1h1i0a1ds2m1ndle4tchen5wi3m1n1oeln3matsu5sher5p0mg2n2r0d1ed3uokgroup8w1y0oto4z2la0caixa5mborghini8er3nd0rover6xess5salle5t0ino3robe5w0yer5b1c1ds2ease3clerc5frak4gal2o2xus4gbt3i0dl2fe0insurance9style7ghting6ke2lly3mited4o2ncoln4k2ve1ing5k1lc1p2oan0s3cker3us3l1ndon4tte1o3ve3pl0financial11r1s1t0d0a3u0ndbeck6xe1ury5v1y2ma0drid4if1son4keup4n0agement7go3p1rket0ing3s4riott5shalls7ttel5ba2c0kinsey7d1e0d0ia3et2lbourne7me1orial6n0u2rck0msd7g1h1iami3crosoft7l1ni1t2t0subishi9k1l0b1s2m0a2n1o0bi0le4da2e1i1m1nash3ey2ster5rmon3tgage6scow4to0rcycles9v0ie4p1q1r1s0d2t0n1r2u0seum3ic4v1w1x1y1z2na0b1goya4me2vy3ba2c1e0c1t0bank4flix4work5ustar5w0s2xt0direct7us4f0l2g0o2hk2i0co2ke1on3nja3ssan1y5l1o0kia3rton4w0ruz3tv4p1r0a1w2tt2u1yc2z2obi1server7ffice5kinawa6layan0group9lo3m0ega4ne1g1l0ine5oo2pen3racle3nge4g0anic5igins6saka4tsuka4t2vh3pa0ge2nasonic7ris2s1tners4s1y3y2ccw3e0t2f0izer5g1h0armacy6d1ilips5one2to0graphy6s4ysio5ics1tet2ures6d1n0g1k2oneer5zza4k1l0ace2y0station9umbing5s3m1n0c2ohl2ker3litie5rn2st3r0axi3ess3ime3o0d0uctions8f1gressive8mo2perties3y5tection8u0dential9s1t1ub2w0c2y2qa1pon3uebec3st5racing4dio4e0ad1lestate6tor2y4cipes5d0umbrella9hab3ise0n3t2liance6n0t0als5pair3ort3ublican8st0aurant8view0s5xroth6ich0ardli6oh3l1o1p2o0cks3deo3gers4om3s0vp3u0gby3hr2n2w0e2yukyu6sa0arland6fe0ty4kura4le1on3msclub4ung5ndvik0coromant12ofi4p1rl2s1ve2xo3b0i1s2c0b1haeffler7midt4olarships8ol3ule3warz5ience5ot3d1e0arch3t2cure1ity6ek2lect4ner3rvices6ven3w1x0y3fr2g1h0angrila6rp3ell3ia1ksha5oes2p0ping5uji3w3i0lk2na1gles5te3j1k0i0n2y0pe4l0ing4m0art3ile4n0cf3o0ccer3ial4ftbank4ware6hu2lar2utions7ng1y2y2pa0ce3ort2t3r0l2s1t0ada2ples4r1tebank4farm7c0group6ockholm6rage3e3ream4udio2y3yle4u0cks3pplies3y2ort5rf1gery5zuki5v1watch4iss4x1y0dney4stems6z2tab1ipei4lk2obao4rget4tamotors6r2too4x0i3c0i2d0k2eam2ch0nology8l1masek5nnis4va3f1g1h0d1eater2re6iaa2ckets5enda4ps2res2ol4j0maxx4x2k0maxx5l1m0all4n1o0day3kyo3ols3p1ray3shiba5tal3urs3wn2yota3s3r0ade1ing4ining5vel0ers0insurance16ust3v2t1ube2i1nes3shu4v0s2w1z2ua1bank3s2g1k1nicom3versity8o2ol2ps2s1y1z2va0cations7na1guard7c1e0gas3ntures6risign5mögensberater2ung14sicherung10t2g1i0ajes4deo3g1king4llas4n1p1rgin4sa1ion4va1o3laanderen9n1odka3lvo3te1ing3o2yage5u2wales2mart4ter4ng0gou5tch0es6eather0channel12bcam3er2site5d0ding5ibo2r3f1hoswho6ien2ki2lliamhill9n0dows4e1ners6me2oodside6rk0s2ld3w2s1tc1f3xbox3erox4ihuan4n2xx2yz3yachts4hoo3maxun5ndex5e1odobashi7ga2kohama6u0tube6t1un3za0ppos4ra3ero3ip2m1one3uerich6w2",EX="ελ1υ2бг1ел3дети4ею2католик6ом3мкд2он1сква6онлайн5рг3рус2ф2сайт3рб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همراه5پاکستان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",y1="numeric",b1="ascii",_1="alpha",Kv="asciinumeric",av="alphanumeric",w1="domain",wD="emoji",MX="scheme",xX="slashscheme",WC="whitespace";function RX(s,e){return s in e||(e[s]=[]),e[s]}function jd(s,e,t){e[y1]&&(e[Kv]=!0,e[av]=!0),e[b1]&&(e[Kv]=!0,e[_1]=!0),e[Kv]&&(e[av]=!0),e[_1]&&(e[av]=!0),e[av]&&(e[w1]=!0),e[wD]&&(e[w1]=!0);for(const n in e){const i=RX(n,t);i.indexOf(s)<0&&i.push(s)}}function IX(s,e){const t={};for(const n in e)e[n].indexOf(s)>=0&&(t[n]=!0);return t}function Sr(s=null){this.j={},this.jr=[],this.jd=null,this.t=s}Sr.groups={};Sr.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||Sr.groups;let i;return e&&e.j?i=e:(i=new Sr(e),t&&n&&jd(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||Sr.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 Sr,Object.assign(o.j,a.j),o.jr.push.apply(o.jr,a.jr),o.jd=a.jd,o.t=a.t):o=new Sr,r){if(n)if(o.t&&typeof o.t=="string"){const c=Object.assign(IX(o.t,n),t);jd(r,c,n)}else t&&jd(r,t,n);o.t=r}return i.j[s]=o,o}};const Ut=(s,e,t,n,i)=>s.ta(e,t,n,i),tn=(s,e,t,n,i)=>s.tr(e,t,n,i),jR=(s,e,t,n,i)=>s.ts(e,t,n,i),$e=(s,e,t,n,i)=>s.tt(e,t,n,i),Rl="WORD",S1="UWORD",SD="ASCIINUMERICAL",kD="ALPHANUMERICAL",by="LOCALHOST",k1="TLD",C1="UTLD",Nw="SCHEME",vp="SLASH_SCHEME",hM="NUM",T1="WS",fM="NL",qv="OPENBRACE",Qv="CLOSEBRACE",qS="OPENBRACKET",QS="CLOSEBRACKET",XS="OPENPAREN",YS="CLOSEPAREN",JS="OPENANGLEBRACKET",ZS="CLOSEANGLEBRACKET",e0="FULLWIDTHLEFTPAREN",t0="FULLWIDTHRIGHTPAREN",s0="LEFTCORNERBRACKET",n0="RIGHTCORNERBRACKET",i0="LEFTWHITECORNERBRACKET",r0="RIGHTWHITECORNERBRACKET",o0="FULLWIDTHLESSTHAN",a0="FULLWIDTHGREATERTHAN",l0="AMPERSAND",c0="APOSTROPHE",u0="ASTERISK",tu="AT",d0="BACKSLASH",h0="BACKTICK",f0="CARET",Vd="COLON",pM="COMMA",p0="DOLLAR",Ia="DOT",m0="EQUALS",mM="EXCLAMATION",_o="HYPHEN",Xv="PERCENT",g0="PIPE",v0="PLUS",y0="POUND",Yv="QUERY",gM="QUOTE",CD="FULLWIDTHMIDDLEDOT",vM="SEMI",Pa="SLASH",Jv="TILDE",b0="UNDERSCORE",TD="EMOJI",_0="SYM";var AD=Object.freeze({__proto__:null,ALPHANUMERICAL:kD,AMPERSAND:l0,APOSTROPHE:c0,ASCIINUMERICAL:SD,ASTERISK:u0,AT:tu,BACKSLASH:d0,BACKTICK:h0,CARET:f0,CLOSEANGLEBRACKET:ZS,CLOSEBRACE:Qv,CLOSEBRACKET:QS,CLOSEPAREN:YS,COLON:Vd,COMMA:pM,DOLLAR:p0,DOT:Ia,EMOJI:TD,EQUALS:m0,EXCLAMATION:mM,FULLWIDTHGREATERTHAN:a0,FULLWIDTHLEFTPAREN:e0,FULLWIDTHLESSTHAN:o0,FULLWIDTHMIDDLEDOT:CD,FULLWIDTHRIGHTPAREN:t0,HYPHEN:_o,LEFTCORNERBRACKET:s0,LEFTWHITECORNERBRACKET:i0,LOCALHOST:by,NL:fM,NUM:hM,OPENANGLEBRACKET:JS,OPENBRACE:qv,OPENBRACKET:qS,OPENPAREN:XS,PERCENT:Xv,PIPE:g0,PLUS:v0,POUND:y0,QUERY:Yv,QUOTE:gM,RIGHTCORNERBRACKET:n0,RIGHTWHITECORNERBRACKET:r0,SCHEME:Nw,SEMI:vM,SLASH:Pa,SLASH_SCHEME:vp,SYM:_0,TILDE:Jv,TLD:k1,UNDERSCORE:b0,UTLD:C1,UWORD:S1,WORD:Rl,WS:T1});const Al=/[a-z]/,Ng=new RegExp("\\p{L}","u"),zC=new RegExp("\\p{Emoji}","u"),El=/\d/,jC=/\s/,VR="\r",VC=`
|
||
`,PX="️",LX="",GC="";let J_=null,Z_=null;function OX(s=[]){const e={};Sr.groups=e;const t=new Sr;J_==null&&(J_=GR(AX)),Z_==null&&(Z_=GR(EX)),$e(t,"'",c0),$e(t,"{",qv),$e(t,"}",Qv),$e(t,"[",qS),$e(t,"]",QS),$e(t,"(",XS),$e(t,")",YS),$e(t,"<",JS),$e(t,">",ZS),$e(t,"(",e0),$e(t,")",t0),$e(t,"「",s0),$e(t,"」",n0),$e(t,"『",i0),$e(t,"』",r0),$e(t,"<",o0),$e(t,">",a0),$e(t,"&",l0),$e(t,"*",u0),$e(t,"@",tu),$e(t,"`",h0),$e(t,"^",f0),$e(t,":",Vd),$e(t,",",pM),$e(t,"$",p0),$e(t,".",Ia),$e(t,"=",m0),$e(t,"!",mM),$e(t,"-",_o),$e(t,"%",Xv),$e(t,"|",g0),$e(t,"+",v0),$e(t,"#",y0),$e(t,"?",Yv),$e(t,'"',gM),$e(t,"/",Pa),$e(t,";",vM),$e(t,"~",Jv),$e(t,"_",b0),$e(t,"\\",d0),$e(t,"・",CD);const n=tn(t,El,hM,{[y1]:!0});tn(n,El,n);const i=tn(n,Al,SD,{[Kv]:!0}),r=tn(n,Ng,kD,{[av]:!0}),o=tn(t,Al,Rl,{[b1]:!0});tn(o,El,i),tn(o,Al,o),tn(i,El,i),tn(i,Al,i);const a=tn(t,Ng,S1,{[_1]:!0});tn(a,Al),tn(a,El,r),tn(a,Ng,a),tn(r,El,r),tn(r,Al),tn(r,Ng,r);const c=$e(t,VC,fM,{[WC]:!0}),l=$e(t,VR,T1,{[WC]:!0}),u=tn(t,jC,T1,{[WC]:!0});$e(t,GC,u),$e(l,VC,c),$e(l,GC,u),tn(l,jC,u),$e(u,VR),$e(u,VC),tn(u,jC,u),$e(u,GC,u);const d=tn(t,zC,TD,{[wD]:!0});$e(d,"#"),tn(d,zC,d),$e(d,PX,d);const h=$e(d,LX);$e(h,"#"),tn(h,zC,d);const p=[[Al,o],[El,i]],g=[[Al,null],[Ng,a],[El,r]];for(let v=0;v<J_.length;v++)Gc(t,J_[v],k1,Rl,p);for(let v=0;v<Z_.length;v++)Gc(t,Z_[v],C1,S1,g);jd(k1,{tld:!0,ascii:!0},e),jd(C1,{utld:!0,alpha:!0},e),Gc(t,"file",Nw,Rl,p),Gc(t,"mailto",Nw,Rl,p),Gc(t,"http",vp,Rl,p),Gc(t,"https",vp,Rl,p),Gc(t,"ftp",vp,Rl,p),Gc(t,"ftps",vp,Rl,p),jd(Nw,{scheme:!0,ascii:!0},e),jd(vp,{slashscheme:!0,ascii:!0},e),s=s.sort((v,m)=>v[0]>m[0]?1:-1);for(let v=0;v<s.length;v++){const m=s[v][0],_=s[v][1]?{[MX]:!0}:{[xX]:!0};m.indexOf("-")>=0?_[w1]=!0:Al.test(m)?El.test(m)?_[Kv]=!0:_[b1]=!0:_[y1]=!0,jR(t,m,m,_)}return jR(t,"localhost",by,{ascii:!0}),t.jd=new Sr(_0),{start:t,tokens:Object.assign({groups:e},AD)}}function ED(s,e){const t=DX(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,d=-1,h=-1;for(;o<n&&(c=a.go(t[o]));)a=c,a.accepts()?(d=0,h=0,u=a):d>=0&&(d+=t[o].length,h++),l+=t[o].length,r+=t[o].length,o++;r-=d,o-=h,l-=d,i.push({t:u.t,v:e.slice(r-l,r),s:r-l,e:r})}return i}function DX(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 Gc(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 Sr(n),r.jr=i.slice(),s.j[c]=r),s=r}return r=new Sr(t),r.jr=i.slice(),s.j[e[o-1]]=r,r}function GR(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 _y={defaultProtocol:"http",events:null,format:KR,formatHref:KR,nl2br:!1,tagName:"a",target:null,rel:null,validate:!0,truncate:1/0,className:null,attributes:null,ignoreTags:[],render:null};function yM(s,e=null){let t=Object.assign({},_y);s&&(t=Object.assign(t,s instanceof yM?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}yM.prototype={o:_y,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]:_y[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 KR(s){return s}function MD(s,e){this.t="token",this.v=s,this.tk=e}MD.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=_y.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),d=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:d}}};function kk(s,e){class t extends MD{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 NX=kk("email",{isLink:!0,toHref(){return"mailto:"+this.toString()}}),qR=kk("text"),$X=kk("nl"),ew=kk("url",{isLink:!0,toHref(s=_y.defaultProtocol){return this.hasProtocol()?this.v:`${s}://${this.v}`},hasProtocol(){const s=this.tk;return s.length>=2&&s[0].t!==by&&s[1].t===Vd}}),mo=s=>new Sr(s);function BX({groups:s}){const e=s.domain.concat([l0,u0,tu,d0,h0,f0,p0,m0,_o,hM,Xv,g0,v0,y0,Pa,_0,Jv,b0]),t=[c0,Vd,pM,Ia,mM,Xv,Yv,gM,vM,JS,ZS,qv,Qv,QS,qS,XS,YS,e0,t0,s0,n0,i0,r0,o0,a0],n=[l0,c0,u0,d0,h0,f0,p0,m0,_o,qv,Qv,Xv,g0,v0,y0,Yv,Pa,_0,Jv,b0],i=mo(),r=$e(i,Jv);Ut(r,n,r),Ut(r,s.domain,r);const o=mo(),a=mo(),c=mo();Ut(i,s.domain,o),Ut(i,s.scheme,a),Ut(i,s.slashscheme,c),Ut(o,n,r),Ut(o,s.domain,o);const l=$e(o,tu);$e(r,tu,l),$e(a,tu,l),$e(c,tu,l);const u=$e(r,Ia);Ut(u,n,r),Ut(u,s.domain,r);const d=mo();Ut(l,s.domain,d),Ut(d,s.domain,d);const h=$e(d,Ia);Ut(h,s.domain,d);const p=mo(NX);Ut(h,s.tld,p),Ut(h,s.utld,p),$e(l,by,p);const g=$e(d,_o);$e(g,_o,g),Ut(g,s.domain,d),Ut(p,s.domain,d),$e(p,Ia,h),$e(p,_o,g);const v=$e(o,_o),m=$e(o,Ia);$e(v,_o,v),Ut(v,s.domain,o),Ut(m,n,r),Ut(m,s.domain,o);const y=mo(ew);Ut(m,s.tld,y),Ut(m,s.utld,y),Ut(y,s.domain,o),Ut(y,n,r),$e(y,Ia,m),$e(y,_o,v),$e(y,tu,l);const _=$e(y,Vd),b=mo(ew);Ut(_,s.numeric,b);const k=mo(ew),w=mo();Ut(k,e,k),Ut(k,t,w),Ut(w,e,k),Ut(w,t,w),$e(y,Pa,k),$e(b,Pa,k);const T=$e(a,Vd),A=$e(c,Vd),C=$e(A,Pa),E=$e(C,Pa);Ut(a,s.domain,o),$e(a,Ia,m),$e(a,_o,v),Ut(c,s.domain,o),$e(c,Ia,m),$e(c,_o,v),Ut(T,s.domain,k),$e(T,Pa,k),$e(T,Yv,k),Ut(E,s.domain,k),Ut(E,e,k),$e(E,Pa,k);const x=[[qv,Qv],[qS,QS],[XS,YS],[JS,ZS],[e0,t0],[s0,n0],[i0,r0],[o0,a0]];for(let D=0;D<x.length;D++){const[N,O]=x[D],G=$e(k,N);$e(w,N,G);const Z=mo(ew);Ut(G,e,Z);const q=mo();Ut(G,t,q),$e(G,O,k),Ut(Z,e,Z),Ut(Z,t,q),Ut(q,e,Z),Ut(q,t,q),$e(Z,O,k),$e(q,O,k)}return $e(i,by,y),$e(i,fM,$X),{start:i,tokens:AD}}function FX(s,e,t){let n=t.length,i=0,r=[],o=[];for(;i<n;){let a=s,c=null,l=null,u=0,d=null,h=-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()?(h=0,d=a):h>=0&&h++,i++,u++;if(h<0)i-=u,i<n&&(o.push(t[i]),i++);else{o.length>0&&(r.push(KC(qR,e,o)),o=[]),i-=h,u-=h;const p=d.t,g=t.slice(i-u,i);r.push(KC(p,e,g))}}return o.length>0&&r.push(KC(qR,e,o)),r}function KC(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 HX=typeof console<"u"&&console&&console.warn||(()=>{}),UX="until manual call of linkify.init(). Register all schemes and plugins before invoking linkify the first time.",Ns={scanner:null,parser:null,tokenQueue:[],pluginQueue:[],customSchemes:[],initialized:!1};function WX(){return Sr.groups={},Ns.scanner=null,Ns.parser=null,Ns.tokenQueue=[],Ns.pluginQueue=[],Ns.customSchemes=[],Ns.initialized=!1,Ns}function QR(s,e=!1){if(Ns.initialized&&HX(`linkifyjs: already initialized - will not register custom scheme "${s}" ${UX}`),!/^[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`);Ns.customSchemes.push([s,e])}function zX(){Ns.scanner=OX(Ns.customSchemes);for(let s=0;s<Ns.tokenQueue.length;s++)Ns.tokenQueue[s][1]({scanner:Ns.scanner});Ns.parser=BX(Ns.scanner.tokens);for(let s=0;s<Ns.pluginQueue.length;s++)Ns.pluginQueue[s][1]({scanner:Ns.scanner,parser:Ns.parser});return Ns.initialized=!0,Ns}function bM(s){return Ns.initialized||zX(),FX(Ns.parser.start,s,ED(Ns.scanner.start,s))}bM.scan=ED;function xD(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 yM(t),i=bM(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 _M="[\0- -\u2029 ]",jX=new RegExp(_M),VX=new RegExp(`${_M}$`),GX=new RegExp(_M,"g");function KX(s){return s.length===1?s[0].isLink:s.length===3&&s[1].isLink?["()","[]"].includes(s[0].value+s[2].value):!1}function qX(s){return new Gs({key:new _n("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=RO(t.doc,[...e]);if($O(a).forEach(({newRange:l})=>{const u=$q(n.doc,l,p=>p.isTextblock);let d,h;if(u.length>1)d=u[0],h=n.doc.textBetween(d.pos,d.pos+d.node.nodeSize,void 0," ");else if(u.length){const p=n.doc.textBetween(l.from,l.to," "," ");if(!VX.test(p))return;d=u[0],h=n.doc.textBetween(d.pos,l.to,void 0," ")}if(d&&h){const p=h.split(jX).filter(Boolean);if(p.length<=0)return!1;const g=p[p.length-1],v=d.pos+h.lastIndexOf(g);if(!g)return!1;const m=bM(g).map(y=>y.toObject(s.defaultProtocol));if(!KX(m))return!1;m.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=>{rM(y.from,y.to,n.doc).some(_=>_.mark.type===s.type)||o.addMark(y.from,y.to,s.type.create({href:y.href}))})}}),!!o.steps.length)return o}})}function QX(s){return new Gs({key:new _n("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=NO(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 XX(s){return new Gs({key:new _n("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=xD(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 Ad(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(GX,"").match(new RegExp(`^(?:(?:${t.join("|")}):|[^a-z]|[a-z0-9+.-]+(?:[^a-z+.-:]|$))`,"i"))}var YX=Uf.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"){QR(s);return}QR(s.scheme,s.optionalSlashes)})},onDestroy(){WX()},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)=>!!Ad(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=>!!Ad(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=>!!Ad(e,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?["a",Vs(this.options.HTMLAttributes,s),0]:["a",Vs(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=>!!Ad(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=>!!Ad(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[Df({find:s=>{const e=[];if(s){const{protocols:t,defaultProtocol:n}=this.options,i=xD(s).filter(r=>r.isLink&&this.options.isAllowedUri(r.value,{defaultValidate:o=>!!Ad(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(qX({type:this.type,defaultProtocol:this.options.defaultProtocol,validate:n=>this.options.isAllowedUri(n,{defaultValidate:i=>!!Ad(i,e),protocols:e,defaultProtocol:t}),shouldAutoLink:this.options.shouldAutoLink})),s.push(QX({type:this.type,editor:this.editor,openOnClick:this.options.openOnClick==="whenNotEditable"?!0:this.options.openOnClick,enableClickSelection:this.options.enableClickSelection})),this.options.linkOnPaste&&s.push(XX({editor:this.editor,defaultProtocol:this.options.defaultProtocol,type:this.type,shouldAutoLink:this.options.shouldAutoLink})),s}}),JX=Object.defineProperty,ZX=(s,e)=>{for(var t in e)JX(s,t,{get:e[t],enumerable:!0})},eY="listItem",XR="textStyle",YR=/^\s*([-+*])\s$/,RD=Ar.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",Vs(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(eY,this.editor.getAttributes(XR)).run():s.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-8":()=>this.editor.commands.toggleBulletList()}},addInputRules(){let s=hg({find:YR,type:this.type});return(this.options.keepMarks||this.options.keepAttributes)&&(s=hg({find:YR,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:()=>this.editor.getAttributes(XR),editor:this.editor})),[s]}}),tY=(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 d=s.doc.resolve(i.after()).nodeAfter;if(!d||!t.includes(d.type.name))return null;const h=[];return d.forEach(p=>{h.push(p)}),h.length===0?null:{listItemDepth:r,nestedList:d,nestedListPos:i.after(),insertPos:i.after(r),items:h}},sY=(s,e,t,n)=>{const i=tY(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 d=u.mapping.map(c);return u.insert(d,He.from(l)),u.setSelection(r.map(u.doc,u.mapping)),e&&e(u),!0},nY=(s,e,t)=>sY(s.state,s.view.dispatch,e,t),ID=(s,e)=>fn.create({name:`${s}BranchingDeleteKeymap`,priority:101,addKeyboardShortcuts(){const t=()=>nY(this.editor,s,e);return{Delete:t,"Mod-Delete":t}}});function iY(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 rY(s,e){return e.tokenizeInline?e.parseInline(e.tokenizeInline(s)):e.parseInline([{type:"text",raw:s,text:s}])}var PD=Ar.create({name:"listItem",addOptions(){return{HTMLAttributes:{},bulletListTypeName:"bulletList",orderedListTypeName:"orderedList"}},content:"paragraph block*",defining:!0,parseHTML(){return[{tag:"li"}]},renderHTML({HTMLAttributes:s}){return["li",Vs(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(iY(s))return{type:"listItem",content:[{type:"paragraph",content:rY(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)=>cM(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)}}}),oY={};ZX(oY,{findListItemPos:()=>Ck,getNextListDepth:()=>wM,handleBackspace:()=>A1,handleDelete:()=>E1,hasListBefore:()=>LD,hasListItemAfter:()=>aY,hasListItemBefore:()=>lY,listItemHasSubList:()=>cY,nextListIsDeeper:()=>OD,nextListIsHigher:()=>DD});var Ck=(s,e)=>{const{$from:t}=e.selection,n=Mn(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}},wM=(s,e)=>{const t=Ck(s,e);if(!t)return!1;const[,n]=qq(e,s,t.$pos.pos+4);return n},LD=(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))},A1=(s,e,t)=>{if(s.commands.undoInputRule())return!0;if(s.state.selection.from!==s.state.selection.to)return!1;if(!fd(s.state,e)&&LD(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!fd(s.state,e)||!Jq(s.state)?!1:s.chain().liftListItem(e).run()},OD=(s,e)=>{const t=wM(s,e),n=Ck(s,e);return!n||!t?!1:t>n.depth},DD=(s,e)=>{const t=wM(s,e),n=Ck(s,e);return!n||!t?!1:t<n.depth},E1=(s,e)=>{if(!fd(s.state,e)||!Yq(s.state,e))return!1;const{selection:t}=s.state,{$from:n,$to:i}=t;return!t.empty&&n.sameParent(i)?!1:OD(e,s.state)?s.chain().focus(s.state.selection.from+4).lift(e).joinBackward().run():DD(e,s.state)?s.chain().joinForward().joinBackward().run():s.commands.joinItemForward()},aY=(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)},lY=(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)},cY=(s,e,t)=>{if(!t)return!1;const n=Mn(s,e.schema);let i=!1;return t.descendants(r=>{r.type===n&&(i=!0)}),i},ND=fn.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&&E1(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&&E1(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&&A1(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&&A1(s,t,n)&&(e=!0)}),e}}}}),JR=/^(\s*)(\d+)\.\s+(.*)$/,uY=/^\s/;function dY(s){const e=s.trimStart();return/^[-+*]\s+/.test(e)||/^\d+\.\s+/.test(e)||/^>\s?/.test(e)||/^```/.test(e)||/^~~~/.test(e)}function hY(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&&dY(i)){n=!0,t.push(i);return}e.push(i)}),{paragraphLines:e,blockLines:t}}function fY(s){const e=[];let t=0,n=0;for(;t<s.length;){const i=s[t],r=i.match(JR);if(!r)break;const[,o,a,c]=r,l=o.length,u=[c];let d=t+1;const h=[i];let p=!1;for(;d<s.length;){const g=s[d];if(g.match(JR))break;if(g.trim()==="")h.push(g),u.push(""),p=!0,d+=1;else if(g.match(uY))h.push(g),u.push(g.slice(l+2)),d+=1;else{if(p)break;h.push(g),u.push(g),d+=1}}e.push({indent:l,number:parseInt(a,10),content:u.join(`
|
||
`).trim(),contentLines:u,raw:h.join(`
|
||
`)}),n=d,t=d}return[e,n]}function $D(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}=hY(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 d=i+1;const h=[];for(;d<s.length&&s[d].indent>e;)h.push(s[d]),d+=1;if(h.length>0){const p=Math.min(...h.map(v=>v.indent)),g=$D(h,p,t);l.push({type:"list",ordered:!0,start:h[0].number,items:g,raw:h.map(v=>v.raw).join(`
|
||
`)})}n.push({type:"list_item",raw:r.raw,tokens:l}),i=d}else i+=1}return n}function pY(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 mY="listItem",ZR="textStyle",eI=/^(\d+)\.\s$/,BD=Ar.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",Vs(this.options.HTMLAttributes,t),0]:["ol",Vs(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?pY(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]=fY(i);if(r.length===0)return;const a=$D(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(mY,this.editor.getAttributes(ZR)).run():s.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-7":()=>this.editor.commands.toggleOrderedList()}},addInputRules(){let s=hg({find:eI,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=hg({find:eI,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:e=>({start:+e[1],...this.editor.getAttributes(ZR)}),joinPredicate:(e,t)=>t.childCount+t.attrs.start===+e[1],editor:this.editor})),[s]}}),gY=/^\s*(\[([( |x])?\])\s$/,vY=Ar.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",Vs(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 cM(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=d=>{var h,p;a.ariaLabel=((p=(h=this.options.a11y)==null?void 0:h.checkboxLabel)==null?void 0:p.call(h,d,a.checked))||`Task item checkbox for ${d.textContent||"empty task item"}`};l(s),r.contentEditable="false",a.type="checkbox",a.addEventListener("mousedown",d=>d.preventDefault()),a.addEventListener("change",d=>{if(!n.isEditable&&!this.options.onReadOnlyChecked){a.checked=!a.checked;return}const{checked:h}=d.target;n.isEditable&&typeof t=="function"&&n.chain().focus(void 0,{scrollIntoView:!1}).command(({tr:p})=>{const g=t();if(typeof g!="number")return!1;const v=p.doc.nodeAt(g);return p.setNodeMarkup(g,void 0,{...v==null?void 0:v.attrs,checked:h}),!0}).run(),!n.isEditable&&this.options.onReadOnlyChecked&&(this.options.onReadOnlyChecked(s,h)||(a.checked=!a.checked))}),Object.entries(this.options.HTMLAttributes).forEach(([d,h])=>{i.setAttribute(d,h)}),i.dataset.checked=s.attrs.checked,a.checked=s.attrs.checked,r.append(a,o),i.append(r,c),Object.entries(e).forEach(([d,h])=>{i.setAttribute(d,h)});let u=new Set(Object.keys(e));return{dom:i,contentDOM:c,update:d=>{if(d.type!==this.type)return!1;i.dataset.checked=d.attrs.checked,a.checked=d.attrs.checked,l(d);const h=n.extensionManager.attributes,p=gy(d,h),g=new Set(Object.keys(p)),v=this.options.HTMLAttributes;return u.forEach(m=>{g.has(m)||(m in v?i.setAttribute(m,v[m]):i.removeAttribute(m))}),Object.entries(p).forEach(([m,y])=>{y==null?m in v?i.setAttribute(m,v[m]):i.removeAttribute(m):i.setAttribute(m,y)}),u=g,!0}}}},addInputRules(){return[hg({find:gY,type:this.type,getAttributes:s=>({checked:s[s.length-1]==="x"})})]}}),yY=Ar.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",Vs(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=p1(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=p1(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()}}});fn.create({name:"listKit",addExtensions(){const s=[];return this.options.bulletList!==!1&&s.push(RD.configure(this.options.bulletList)),this.options.listItem!==!1&&s.push(PD.configure(this.options.listItem)),this.options.listKeymap!==!1&&s.push(ND.configure(this.options.listKeymap)),this.options.orderedList!==!1&&s.push(BD.configure(this.options.orderedList)),this.options.taskItem!==!1&&s.push(vY.configure(this.options.taskItem)),this.options.taskList!==!1&&s.push(yY.configure(this.options.taskList)),s}});var tw=" ",qC=" ",bY=Ar.create({name:"paragraph",priority:1e3,addOptions(){return{HTMLAttributes:{}}},group:"block",content:"inline*",parseHTML(){return[{tag:"p"}]},renderHTML({HTMLAttributes:s}){return["p",Vs(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===tw||t[0].text===tw||t[0].raw===qC||t[0].text===qC)&&n.length===1&&n[0].type==="text"&&(n[0].text===tw||n[0].text===qC)?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?tw:""}return e.renderChildren(r)},addCommands(){return{setParagraph:()=>({commands:s})=>s.setNode(this.name)}},addKeyboardShortcuts(){return{"Mod-Alt-0":()=>this.editor.commands.setParagraph()}}}),_Y=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))$/,wY=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))/g,SY=Uf.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",Vs(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[dg({find:_Y,type:this.type})]},addPasteRules(){return[Df({find:wY,type:this.type})]}}),kY=Ar.create({name:"text",group:"inline",parseMarkdown:s=>({type:"text",text:s.text||""}),renderMarkdown:s=>s.text||""}),CY=Uf.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",Vs(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 TY(s={}){return new Gs({view(e){return new AY(e,s)}})}class AY{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 d=e.nodeBefore,h=e.nodeAfter;if(d||h){let p=this.editorView.nodeDOM(this.cursorPos-(d?d.nodeSize:0));if(p){let g=p.getBoundingClientRect(),v=d?g.bottom:g.top;d&&h&&(v=(v+this.editorView.nodeDOM(this.cursorPos).getBoundingClientRect().top)/2);let m=this.width/2*a;n={left:g.left,right:g.right,top:v-m,bottom:v+m}}}}if(!n){let d=this.editorView.coordsAtPos(this.cursorPos),h=this.width/2*o;n={left:d.left-h,right:d.left+h,top:d.top,bottom:d.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 d=c.getBoundingClientRect(),h=d.width/c.offsetWidth,p=d.height/c.offsetHeight;l=d.left-c.scrollLeft*h,u=d.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=m2(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 un extends Ht{constructor(e){super(e,e)}map(e,t){let n=e.resolve(t.map(this.head));return un.valid(n)?new un(n):Ht.near(n)}content(){return tt.empty}eq(e){return e instanceof un&&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 un(e.resolve(t.pos))}getBookmark(){return new SM(this.anchor)}static valid(e){let t=e.parent;if(t.inlineContent||!EY(e)||!MY(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&&un.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(un.valid(c))return c}for(;;){let o=t>0?r.firstChild:r.lastChild;if(!o){if(r.isAtom&&!r.isText&&!_t.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(un.valid(a))return a}return null}}}un.prototype.visible=!1;un.findFrom=un.findGapCursorFrom;Ht.jsonID("gapcursor",un);class SM{constructor(e){this.pos=e}map(e){return new SM(e.map(this.pos))}resolve(e){let t=e.resolve(this.pos);return un.valid(t)?new un(t):Ht.near(t)}}function FD(s){return s.isAtom||s.spec.isolating||s.spec.createGapCursor}function EY(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||FD(i.type))return!0;if(i.inlineContent)return!1}}return!0}function MY(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||FD(i.type))return!0;if(i.inlineContent)return!1}}return!0}function xY(){return new Gs({props:{decorations:LY,createSelectionBetween(s,e,t){return e.pos==t.pos&&un.valid(t)?new un(t):null},handleClick:IY,handleKeyDown:RY,handleDOMEvents:{beforeinput:PY}}})}const RY=SO({ArrowLeft:sw("horiz",-1),ArrowRight:sw("horiz",1),ArrowUp:sw("vert",-1),ArrowDown:sw("vert",1)});function sw(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 kt){if(!r.endOfTextblock(t)||a.depth==0)return!1;c=!1,a=n.doc.resolve(e>0?a.after():a.before())}let l=un.findGapCursorFrom(a,e,c);return l?(i&&i(n.tr.setSelection(new un(l))),!0):!1}}function IY(s,e,t){if(!s||!s.editable)return!1;let n=s.state.doc.resolve(e);if(!un.valid(n))return!1;let i=s.posAtCoords({left:t.clientX,top:t.clientY});return i&&i.inside>-1&&_t.isSelectable(s.state.doc.nodeAt(i.inside))?!1:(s.dispatch(s.state.tr.setSelection(new un(n))),!0)}function PY(s,e){if(e.inputType!="insertCompositionText"||!(s.state.selection instanceof un))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=He.empty;for(let o=n.length-1;o>=0;o--)i=He.from(n[o].createAndFill(null,i));let r=s.state.tr.replace(t.pos,t.pos,new tt(i,0,0));return r.setSelection(kt.near(r.doc.resolve(t.pos+1))),s.dispatch(r),!1}function LY(s){if(!(s.selection instanceof un))return null;let e=document.createElement("div");return e.className="ProseMirror-gapcursor",js.create(s.doc,[Ai.widget(s.selection.head,e,{key:"gapcursor"})])}var w0=200,Xn=function(){};Xn.prototype.append=function(e){return e.length?(e=Xn.from(e),!this.length&&e||e.length<w0&&this.leafAppend(e)||this.length<w0&&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 OY(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 HD(e):Xn.empty};var HD=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<=w0)return new e(this.values.concat(i.flatten()))},e.prototype.leafPrepend=function(i){if(this.length+i.length<=w0)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 HD([]);var OY=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 DY=500;class ya{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((d,h)=>{if(!d.step){i||(i=this.remapping(n,h+1),r=i.maps.length),r--,u.push(d);return}if(i){u.push(new La(d.map));let p=d.step.map(i.slice(r)),g;p&&o.maybeStep(p).doc&&(g=o.mapping.maps[o.mapping.maps.length-1],l.push(new La(g,void 0,void 0,l.length+u.length))),r--,g&&i.appendMap(g,r)}else o.maybeStep(d.step);if(d.selection)return a=i?d.selection.map(i.slice(r)):d.selection,c=new ya(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 d=e.steps[u].invert(e.docs[u]),h=new La(e.mapping.maps[u],d,t),p;(p=c&&c.merge(h))&&(h=p,u?r.pop():a=a.slice(0,a.length-1)),r.push(h),t&&(o++,t=void 0),i||(c=h)}let l=o-n.depth;return l>$Y&&(a=NY(a,l),o-=l),new ya(a.append(r),o)}remapping(e,t){let n=new dy;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 ya(this.items.append(e.map(t=>new La(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(h=>{h.selection&&a--},i);let c=t;this.items.forEach(h=>{let p=r.getMirror(--c);if(p==null)return;o=Math.min(o,p);let g=r.maps[p];if(h.step){let v=e.steps[p].invert(e.docs[p]),m=h.selection&&h.selection.map(r.slice(c+1,p));m&&a++,n.push(new La(g,v,m))}else n.push(new La(g))},i);let l=[];for(let h=t;h<o;h++)l.push(new La(r.maps[h]));let u=this.items.slice(0,i).append(l).append(n),d=new ya(u,a);return d.emptyItemCount()>DY&&(d=d.compress(this.items.length-n.length)),d}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 d=new La(l.invert(),c,u),h,p=i.length-1;(h=i.length&&i[p].merge(d))?i[p]=h:i.push(d)}}else o.map&&n--},this.items.length,0),new ya(Xn.from(i.reverse()),r)}}ya.empty=new ya(Xn.empty,0);function NY(s,e){let t;return s.forEach((n,i)=>{if(n.selection&&e--==0)return t=i,!1}),s.slice(t)}class La{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 La(t.getMap().invert(),t,this.selection)}}}class su{constructor(e,t,n,i,r){this.done=e,this.undone=t,this.prevRanges=n,this.prevTime=i,this.prevComposition=r}}const $Y=20;function BY(s,e,t,n){let i=t.getMeta(Rf),r;if(i)return i.historyState;t.getMeta(UY)&&(s=new su(s.done,s.undone,null,0,-1));let o=t.getMeta("appendedTransaction");if(t.steps.length==0)return s;if(o&&o.getMeta(Rf))return o.getMeta(Rf).redo?new su(s.done.addTransform(t,void 0,n,$w(e)),s.undone,tI(t.mapping.maps),s.prevTime,s.prevComposition):new su(s.done,s.undone.addTransform(t,void 0,n,$w(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||!FY(t,s.prevRanges)),l=o?QC(s.prevRanges,t.mapping):tI(t.mapping.maps);return new su(s.done.addTransform(t,c?e.selection.getBookmark():void 0,n,$w(e)),ya.empty,l,t.time,a??s.prevComposition)}else return(r=t.getMeta("rebased"))?new su(s.done.rebased(t,r),s.undone.rebased(t,r),QC(s.prevRanges,t.mapping),s.prevTime,s.prevComposition):new su(s.done.addMaps(t.mapping.maps),s.undone.addMaps(t.mapping.maps),QC(s.prevRanges,t.mapping),s.prevTime,s.prevComposition)}function FY(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 tI(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 QC(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 HY(s,e,t){let n=$w(e),i=Rf.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 su(t?a:r.remaining,t?r.remaining:a,null,0,-1);return r.transform.setSelection(o).setMeta(Rf,{redo:t,historyState:c})}let XC=!1,sI=null;function $w(s){let e=s.plugins;if(sI!=e){XC=!1,sI=e;for(let t=0;t<e.length;t++)if(e[t].spec.historyPreserveItems){XC=!0;break}}return XC}const Rf=new _n("history"),UY=new _n("closeHistory");function WY(s={}){return s={depth:s.depth||100,newGroupDelay:s.newGroupDelay||500},new Gs({key:Rf,state:{init(){return new su(ya.empty,ya.empty,null,0,-1)},apply(e,t,n){return BY(t,n,e,s)}},config:s,props:{handleDOMEvents:{beforeinput(e,t){let n=t.inputType,i=n=="historyUndo"?WD:n=="historyRedo"?zD:null;return!i||!e.editable?!1:(t.preventDefault(),i(e.state,e.dispatch))}}}})}function UD(s,e){return(t,n)=>{let i=Rf.getState(t);if(!i||(s?i.undone:i.done).eventCount==0)return!1;if(n){let r=HY(i,t,s);r&&n(e?r.scrollIntoView():r)}return!0}}const WD=UD(!1,!0),zD=UD(!0,!0);fn.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 Gs({key:new _n("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 zY=fn.create({name:"dropCursor",addOptions(){return{color:"currentColor",width:1,class:void 0}},addProseMirrorPlugins(){return[TY(this.options)]}});fn.create({name:"focus",addOptions(){return{className:"has-focus",mode:"all"}},addProseMirrorPlugins(){return[new Gs({key:new _n("focus"),props:{decorations:({doc:s,selection:e})=>{const{isEditable:t,isFocused:n}=this.editor,{anchor:i}=e,r=[];if(!t||!n)return js.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(Ai.node(l,l+c.nodeSize,{class:this.options.className}))}),js.create(s,r)}}})]}});var jY=fn.create({name:"gapCursor",addProseMirrorPlugins(){return[xY()]},extendNodeSchema(s){var e;const t={name:s.name,options:s.options,storage:s.storage};return{allowGapCursor:(e=ls(dt(s,"allowGapCursor",t)))!=null?e:null}}}),jD="placeholder",wy=new _n("tiptap__placeholder"),nI=200;function iI(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),Ai.node(i,i+r.nodeSize,{class:u.join(" "),[n]:typeof t=="function"?t({editor:e,node:r,pos:i,hasAnchor:a}):t})}function rI(s,e){return typeof s=="function"?s(e):s}function VY({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 h=n.resolve(c),p=h.depth>0?h.node(1):h.nodeAfter,g=h.depth>0?h.before(1):c;if(p&&p.type.isTextblock&&vy(p)){const v=c>=g&&c<=g+p.nodeSize;l.push(iI({editor:s,isEmptyDoc:u,dataAttribute:t,hasAnchor:v,placeholder:e.placeholder,classes:{emptyEditor:e.emptyEditorClass,emptyNode:rI(e.emptyNodeClass,{editor:s,node:p,pos:g,hasAnchor:v})},node:p,pos:g}))}}else{const h=wy.getState(s.state),p=(r=h==null?void 0:h.topPos)!=null?r:0,g=(o=h==null?void 0:h.bottomPos)!=null?o:n.content.size;n.nodesBetween(p,g,(v,m)=>{const y=c>=m&&c<=m+v.nodeSize,_=!v.isLeaf&&vy(v);return v.type.isTextblock&&(y||!e.showOnlyCurrent)&&_&&l.push(iI({editor:s,isEmptyDoc:u,dataAttribute:t,hasAnchor:y,placeholder:e.placeholder,classes:{emptyEditor:e.emptyEditorClass,emptyNode:rI(e.emptyNodeClass,{editor:s,node:v,pos:m,hasAnchor:y})},node:v,pos:m})),e.includeChildren})}return js.create(n,l)}function GY(s){return s.replace(/\s+/g,"-").replace(/[^a-zA-Z0-9-]/g,"").replace(/^[0-9-]+/,"").replace(/^-+/,"").toLowerCase()}function KY(s){const e=getComputedStyle(s),t=`${e.overflow} ${e.overflowY} ${e.overflowX}`;return/auto|scroll|overlay/.test(t)}function qY(s){let e=s;for(;e;){if(KY(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 QY(s){return s===window?{top:0,bottom:window.innerHeight}:s.getBoundingClientRect()}function XY({doc:s,view:e,scrollContainer:t}){const n=e.dom.getBoundingClientRect(),i=t?QY(t):{top:0,bottom:window.innerHeight},r=Math.max(n.top,i.top)-nI,o=Math.min(n.bottom,i.bottom)+nI;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 YY={init(){return{topPos:null,bottomPos:null}},apply(s,e){const t=s.getMeta(wy);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 JY(s){const e=qY(s.dom),t=()=>{const a=XY({view:s,doc:s.state.doc,scrollContainer:e}),c=wy.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(wy,{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 ZY({editor:s,options:e}){const t=e.dataAttribute?`data-${GY(e.dataAttribute)}`:`data-${jD}`;return new Gs({key:wy,state:YY,view:JY,props:{decorations:({doc:n,selection:i})=>VY({editor:s,options:e,dataAttribute:t,doc:n,selection:i})}})}var eJ=fn.create({name:"placeholder",addOptions(){return{emptyEditorClass:"is-editor-empty",emptyNodeClass:"is-empty",dataAttribute:jD,placeholder:"Write something …",showOnlyWhenEditable:!0,showOnlyCurrent:!0,includeChildren:!1}},addProseMirrorPlugins(){return[ZY({editor:this.editor,options:this.options})]}}),tJ=`.ProseMirror:not(.ProseMirror-focused) *::selection {
|
||
background: transparent;
|
||
}
|
||
|
||
.ProseMirror:not(.ProseMirror-focused) *::-moz-selection {
|
||
background: transparent;
|
||
}`;fn.create({name:"selection",addOptions(){return{className:"selection"}},addProseMirrorPlugins(){const{editor:s,options:e}=this;return s.options.injectCSS&&typeof document<"u"&&tD(tJ,s.options.injectNonce,"selection"),[new Gs({key:new _n("selection"),props:{decorations(t){return t.selection.empty||s.isFocused||!s.isEditable||BO(t.selection)||s.view.dragging?null:js.create(t.doc,[Ai.inline(t.selection.from,t.selection.to,{class:e.className})])}}})]}});var sJ="skipTrailingNode";function oI({types:s,node:e}){return e&&Array.isArray(s)&&s.includes(e.type)||(e==null?void 0:e.type)===s}var nJ=fn.create({name:"trailingNode",addOptions(){return{node:void 0,notAfter:[]}},addProseMirrorPlugins(){var s;const e=new _n(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 Gs({key:e,appendTransaction:(i,r,o)=>{const{doc:a,tr:c,schema:l}=o,u=e.getState(o),d=a.content.size,h=l.nodes[t];if(!i.some(p=>p.getMeta(sJ))&&u)return c.insert(d,h.create())},state:{init:(i,r)=>{const o=r.tr.doc.lastChild;return!oI({node:o,types:n})},apply:(i,r)=>{if(!i.docChanged||i.getMeta("__uniqueIDTransaction"))return r;const o=i.doc.lastChild;return!oI({node:o,types:n})}}})]}}),iJ=fn.create({name:"undoRedo",addOptions(){return{depth:100,newGroupDelay:500}},addCommands(){return{undo:()=>({state:s,dispatch:e})=>WD(s,e),redo:()=>({state:s,dispatch:e})=>zD(s,e)}},addProseMirrorPlugins(){return[WY(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()}}}),rJ=fn.create({name:"starterKit",addExtensions(){var s,e,t,n;const i=[];return this.options.bold!==!1&&i.push(uX.configure(this.options.bold)),this.options.blockquote!==!1&&i.push(rX.configure(this.options.blockquote)),this.options.bulletList!==!1&&i.push(RD.configure(this.options.bulletList)),this.options.code!==!1&&i.push(fX.configure(this.options.code)),this.options.codeBlock!==!1&&i.push(gX.configure(this.options.codeBlock)),this.options.document!==!1&&i.push(vX.configure(this.options.document)),this.options.dropcursor!==!1&&i.push(zY.configure(this.options.dropcursor)),this.options.gapcursor!==!1&&i.push(jY.configure(this.options.gapcursor)),this.options.hardBreak!==!1&&i.push(yX.configure(this.options.hardBreak)),this.options.heading!==!1&&i.push(bX.configure(this.options.heading)),this.options.undoRedo!==!1&&i.push(iJ.configure(this.options.undoRedo)),this.options.horizontalRule!==!1&&i.push(_X.configure(this.options.horizontalRule)),this.options.italic!==!1&&i.push(TX.configure(this.options.italic)),this.options.listItem!==!1&&i.push(PD.configure(this.options.listItem)),this.options.listKeymap!==!1&&i.push(ND.configure((s=this.options)==null?void 0:s.listKeymap)),this.options.link!==!1&&i.push(YX.configure((e=this.options)==null?void 0:e.link)),this.options.orderedList!==!1&&i.push(BD.configure(this.options.orderedList)),this.options.paragraph!==!1&&i.push(bY.configure(this.options.paragraph)),this.options.strike!==!1&&i.push(SY.configure(this.options.strike)),this.options.text!==!1&&i.push(kY.configure(this.options.text)),this.options.underline!==!1&&i.push(CY.configure((t=this.options)==null?void 0:t.underline)),this.options.trailingNode!==!1&&i.push(nJ.configure((n=this.options)==null?void 0:n.trailingNode)),i}}),oJ=rJ;function aJ(s){var e;const{char:t,allowSpaces:n,allowToIncludeChar:i,allowedPrefixes:r,startOfLine:o,$position:a}=s,c=n&&!i,l=FQ(t),u=new RegExp(`\\s${l}$`),d=o?"^":"",h=i?"":l,p=c?new RegExp(`${d}${l}.*?(?=\\s${h}|$)`,"gm"):new RegExp(`${d}(?:^)?${l}[^\\s${h}]*`,"gm"),g=((e=a.nodeBefore)==null?void 0:e.isText)&&a.nodeBefore.text;if(!g)return null;const v=a.pos-g.length,m=Array.from(g.matchAll(p)).pop();if(!m||m.input===void 0||m.index===void 0)return null;const y=m.input.slice(Math.max(0,m.index-1),m.index),_=new RegExp(`^[${r==null?void 0:r.join("")}\0]?$`).test(y);if(r!==null&&!_)return null;const b=v+m.index;let k=b+m[0].length;return c&&u.test(g.slice(k-1,k+1))&&(m[0]+=" ",k+=1),b<a.pos&&k>=a.pos?{range:{from:b,to:k},query:m[0].slice(t.length),text:m[0]}:null}function lJ(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 cJ=new _n("suggestion");function uJ({pluginKey:s=cJ,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:d=()=>null,items:h=()=>[],render:p=()=>({}),allow:g=()=>!0,findSuggestionMatch:v=aJ,shouldShow:m,shouldResetDismissed:y}){let _;const b=p==null?void 0:p(),k=n&&!i,w=()=>{const x=e.state.selection.$anchor.pos,D=e.view.coordsAtPos(x),{top:N,right:O,bottom:G,left:Z}=D;try{return new DOMRect(Z,N,O-Z,G-N)}catch{return null}},T=(x,D)=>D?()=>{const N=s.getState(e.state),O=N==null?void 0:N.decorationId,G=x.dom.querySelector(`[data-decoration-id="${O}"]`);return(G==null?void 0:G.getBoundingClientRect())||null}:w,A=({match:x,dismissedRange:D,state:N,transaction:O})=>y!=null&&y({editor:e,state:N,range:D,match:x,transaction:O,allowSpaces:k})?!1:k?x.range.from===D.from:x.range.from===D.from&&!lJ(O);function C(x,D){var N;try{const G=s.getState(x.state),Z=G!=null&&G.decorationId?x.dom.querySelector(`[data-decoration-id="${G.decorationId}"]`):null,q={editor:e,range:(G==null?void 0:G.range)||{from:0,to:0},query:(G==null?void 0:G.query)||null,text:(G==null?void 0:G.text)||null,items:[],command:V=>d({editor:e,range:(G==null?void 0:G.range)||{from:0,to:0},props:V}),decorationNode:Z,clientRect:T(x,Z)};(N=b==null?void 0:b.onExit)==null||N.call(b,q)}catch{}const O=x.state.tr.setMeta(D,{exit:!0});x.dispatch(O)}const E=new Gs({key:s,view(){return{update:async(x,D)=>{var N,O,G,Z,q,V,I;const $=(N=this.key)==null?void 0:N.getState(D),L=(O=this.key)==null?void 0:O.getState(x.state),K=$.active&&L.active&&$.range.from!==L.range.from,se=!$.active&&L.active,oe=$.active&&!L.active,ve=!se&&!oe&&$.query!==L.query,le=se||K&&ve,ue=ve||K,P=oe||K&&ve;if(!le&&!ue&&!P)return;const X=P&&!le?$:L,J=x.dom.querySelector(`[data-decoration-id="${X.decorationId}"]`);_={editor:e,range:X.range,query:X.query,text:X.text,items:[],command:ne=>d({editor:e,range:X.range,props:ne}),decorationNode:J,clientRect:T(x,J)},le&&((G=b==null?void 0:b.onBeforeStart)==null||G.call(b,_)),ue&&((Z=b==null?void 0:b.onBeforeUpdate)==null||Z.call(b,_)),(ue||le)&&(_.items=await h({editor:e,query:X.query})),P&&((q=b==null?void 0:b.onExit)==null||q.call(b,_)),ue&&((V=b==null?void 0:b.onUpdate)==null||V.call(b,_)),le&&((I=b==null?void 0:b.onStart)==null||I.call(b,_))},destroy:()=>{var x;_&&((x=b==null?void 0:b.onExit)==null||x.call(b,_))}}},state:{init(){return{active:!1,range:{from:0,to:0},query:null,text:null,composing:!1,dismissedRange:null}},apply(x,D,N,O){const{isEditable:G}=e,{composing:Z}=e.view,{selection:q}=x,{empty:V,from:I}=q,$={...D},L=x.getMeta(s);if(L&&L.exit)return $.active=!1,$.decorationId=null,$.range={from:0,to:0},$.query=null,$.text=null,$.dismissedRange=D.active?{...D.range}:D.dismissedRange,$;if($.composing=Z,x.docChanged&&$.dismissedRange!==null&&($.dismissedRange={from:x.mapping.map($.dismissedRange.from),to:x.mapping.map($.dismissedRange.to)}),G&&(V||e.view.composing)){(I<D.range.from||I>D.range.to)&&!Z&&!D.composing&&($.active=!1);const K=v({char:t,allowSpaces:n,allowToIncludeChar:i,allowedPrefixes:r,startOfLine:o,$position:q.$from}),se=`id_${Math.floor(Math.random()*4294967295)}`;K&&g({editor:e,state:O,range:K.range,isActive:D.active})&&(!m||m({editor:e,range:K.range,query:K.query,text:K.text,transaction:x}))?($.dismissedRange!==null&&!A({match:K,dismissedRange:$.dismissedRange,state:O,transaction:x})&&($.dismissedRange=null),$.dismissedRange===null?($.active=!0,$.decorationId=D.decorationId?D.decorationId:se,$.range=K.range,$.query=K.query,$.text=K.text):$.active=!1):(K||($.dismissedRange=null),$.active=!1)}else $.active=!1;return $.active||($.decorationId=null,$.range={from:0,to:0},$.query=null,$.text=null),$}},props:{handleKeyDown(x,D){var N,O;const{active:G,range:Z}=E.getState(x.state);if(!G)return!1;if(D.key==="Escape"||D.key==="Esc"){const V=E.getState(x.state);return(N=b==null?void 0:b.onKeyDown)==null||N.call(b,{view:x,event:D,range:V.range}),C(x,s),!0}return((O=b==null?void 0:b.onKeyDown)==null?void 0:O.call(b,{view:x,event:D,range:Z}))||!1},decorations(x){const{active:D,range:N,decorationId:O,query:G}=E.getState(x);if(!D)return null;const Z=!(G!=null&&G.length),q=[c];return Z&&q.push(u),js.create(x.doc,[Ai.inline(N.from,N.to,{nodeName:a,class:q.join(" "),"data-decoration-id":O,"data-decoration-content":l})])}}});return E}function dJ({editor:s,overrideSuggestionOptions:e,extensionName:t,char:n="@"}){const i=new _n;return{editor:s,char:n,pluginKey:i,command:({editor:r,range:o,props:a})=>{var c,l,u;const d=r.view.state.selection.$to.nodeAfter;((c=d==null?void 0:d.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 VD(s){return(s.options.suggestions.length?s.options.suggestions:[s.options.suggestion]).map(e=>dJ({editor:s.editor,overrideSuggestionOptions:e,extensionName:s.name,char:e.char}))}function aI(s,e){const t=VD(s),n=t.find(i=>i.char===e);return n||(t.length?t[0]:null)}var hJ=Ar.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",Vs(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=aI(this,s.attrs.mentionSuggestionChar);if(this.options.renderLabel!==void 0)return console.warn("renderLabel is deprecated use renderText and renderHTML instead"),["span",Vs({"data-type":this.name},this.options.HTMLAttributes,e),this.options.renderLabel({options:this.options,node:s,suggestion:t})];const n={...this.options};n.HTMLAttributes=Vs({"data-type":this.name},this.options.HTMLAttributes,e);const i=this.options.renderHTML({options:n,node:s,suggestion:t});return typeof i=="string"?["span",Vs({"data-type":this.name},this.options.HTMLAttributes,e),i]:i},...sD({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:aI(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 Tc,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 VD(this).map(uJ)}}),fJ=hJ,pJ=eJ;const mJ=["aria-label"],gJ=["aria-selected"],vJ={class:"file-at-item__name"},yJ={class:"file-at-item__description"},bJ=["aria-selected","onMouseenter","onMousedown"],_J={class:"file-at-item__name"},wJ={class:"file-at-item__description"},SJ={key:1,class:"file-at-empty"},kJ={key:2,class:"file-at-empty"},CJ=ct({__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=ge(null),i=be(()=>t.hostMode),r=be(()=>t.items||[]),o=u=>i.value?u+1:u;Ke(()=>t.visible,()=>{t.visible&&ft(()=>{const u=n.value;u&&(u.scrollTop=0)})});const a=u=>{const d=n.value;if(!d)return;const h=31,p=u*h,g=p+h;p<d.scrollTop?d.scrollTop=p:g>d.scrollTop+d.clientHeight&&(d.scrollTop=g-d.clientHeight)};return e({focusActive:()=>{ft(()=>{a(t.activeIndex)})},setManualScroll:()=>{}}),(u,d)=>(F(),Ft(gs,{name:"file-at-menu-motion"},{default:Gt(()=>[s.visible?(F(),U("div",{key:0,class:"file-at-menu-wrapper",role:"listbox","aria-label":u.$t("quickdock.atMenuAria"),style:qe(s.menuStyle),onClick:d[2]||(d[2]=De(()=>{},["stop"]))},[M("div",{ref_key:"fileAtList",ref:n,class:"file-at-menu"},[s.hostMode?(F(),U("button",{key:0,type:"button",class:Ce(["file-at-item file-at-item--picker",{"file-at-item--active":s.activeIndex===0}]),role:"option","aria-selected":s.activeIndex===0,onMouseenter:d[0]||(d[0]=h=>u.$emit("hover",0)),onMousedown:d[1]||(d[1]=De(h=>u.$emit("select",0),["prevent"]))},[M("span",vJ,Q(u.$t("quickdock.atMenuPicker")),1),M("span",yJ,Q(u.$t("quickdock.atMenuPickerDesc")),1)],42,gJ)):me("",!0),(F(!0),U(Ie,null,Ze(r.value,(h,p)=>(F(),U("button",{key:h.path,type:"button",class:Ce(["file-at-item",{"file-at-item--active":o(p)===s.activeIndex}]),role:"option","aria-selected":o(p)===s.activeIndex,onMouseenter:g=>u.$emit("hover",o(p)),onMousedown:De(g=>u.$emit("select",o(p)),["prevent"])},[M("span",_J,Q(h.name),1),M("span",wJ,Q(h.path),1)],42,bJ))),128)),!s.hostMode&&!r.value.length&&!s.loading?(F(),U("div",SJ,Q(u.$t("quickdock.atMenuNoMatch")),1)):me("",!0),s.loading?(F(),U("div",kJ,Q(u.$t("quickdock.atMenuSearching")),1)):me("",!0)],512)],12,mJ)):me("",!0)]),_:1}))}}),TJ=qt(CJ,[["__scopeId","data-v-a1cb8c9d"]]),AJ={class:"rolling-number"},EJ={class:"rolling-number__cell"},MJ={class:"rolling-number__cell"},lI=38,xJ=360,RJ=ct({__name:"RollingNumber",props:{value:{}},setup(s){const e=s,t=ge([]),n=new Map;let i=!1,r=0;const o=new Set,a=new Map;function c(d){const h=Math.max(0,Math.trunc(Number(d)||0)).toString(),p=h.length,g=new Map;for(let v=0;v<p;v++)g.set(p-1-v,Number(h[v]));return g}const l=be(()=>t.value.map(d=>({place:d,state:n.get(d)})).filter(d=>!!d.state));function u(d){t.value=[...new Set(d)].sort((h,p)=>p-h)}return Ke(()=>e.value,async d=>{const h=c(d),p=++r;if(!i){i=!0,n.clear();for(const[k,w]of h)n.set(k,oy({top:w,bottom:w,offset:0,animate:!1,delay:0}));u(h.keys());return}const g=new Set([...n.keys(),...h.keys()]),v=Math.max(...g,0),m=[],y=[];for(const k of h.keys()){const w=a.get(k);w&&(window.clearTimeout(w),a.delete(k))}for(const k of g){const w=(v-k)*lI,T=h.get(k);if(T===void 0)continue;const A=n.get(k);if(!A){n.set(k,oy({top:T,bottom:T,offset:0,animate:!1,delay:w}));continue}A.delay=w;const C=A.top;if(C===T){A.bottom=T,A.offset=0,A.animate=!1;continue}C<T?(A.animate=!1,A.top=C,A.bottom=T,A.offset=0,m.push(A)):(A.animate=!1,A.top=T,A.bottom=C,A.offset=1,y.push(A))}u(h.keys());for(const k of[...n.keys()])if(!h.has(k)&&!a.has(k)){const w=window.setTimeout(()=>{a.delete(k),n.delete(k)},260);a.set(k,w)}await ft(),requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(p===r){for(const k of m)k.animate=!0,k.offset=1;for(const k of y)k.animate=!0,k.offset=0}})});const _=v*lI+xJ+80,b=window.setTimeout(()=>{if(o.delete(b),p===r)for(const[k,w]of h){const T=n.get(k);T&&(T.animate=!1,T.top=w,T.bottom=w,T.offset=0)}},_);o.add(b)},{immediate:!0}),Rn(()=>{o.forEach(d=>window.clearTimeout(d)),o.clear(),a.forEach(d=>window.clearTimeout(d)),a.clear()}),(d,h)=>(F(),U("span",AJ,[We(ay,{name:"rn-place",tag:"span",class:"rolling-number__track"},{default:Gt(()=>[(F(!0),U(Ie,null,Ze(l.value,p=>(F(),U("span",{key:p.place,class:"rolling-number__digit"},[M("span",{class:Ce(["rolling-number__strip",{"is-animating":p.state.animate}]),style:qe({"--rn-offset":p.state.offset,transitionDelay:p.state.delay+"ms"})},[M("span",EJ,Q(p.state.top),1),M("span",MJ,Q(p.state.bottom),1)],6)]))),128))]),_:1})]))}}),cI=qt(RJ,[["__scopeId","data-v-492eb155"]]),IJ={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"},PJ=["clip-path"],LJ=["innerHTML"],OJ=150,DJ=210,uI="transform 0.55s cubic-bezier(0.22, 1, 0.36, 1)",dI="transform 0.22s cubic-bezier(0.65, 0, 0.35, 1)",NJ=ct({__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=ge(null),o=ge(null),a=ge(null),c=ge(null),l=ge(null),u=ge(!0),d=[{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 h(xe){if(xe.raw)return xe.motion==="bob"?`<g class="sa-bob">${xe.raw}</g>`:xe.raw;const he=`<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"}">${he}</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"},g={x:84,y:96},v={x:116,y:96},m={x:82,y:96},y={x:118,y:96},_={x:117,y:100};let b="idle",k="idle";function w(xe,pe,he,ye){const ke=3*xe,Le=3*(he-xe)-ke,st=1-ke-Le,gt=3*pe,Wt=3*(ye-pe)-gt,jt=1-gt-Wt,ht=Qt=>((st*Qt+Le)*Qt+ke)*Qt;return Qt=>{let It=Qt;for(let ns=0;ns<8;ns++){const ot=ht(It)-Qt;if(Math.abs(ot)<1e-6)return((jt*It+Wt)*It+gt)*It;const $s=(3*st*It+2*Le)*It+ke;if(Math.abs($s)<1e-6)break;It-=ot/$s}return((jt*It+Wt)*It+gt)*It}}const T=w(.22,1,.36,1),A=w(.65,0,.35,1);function C(xe){return(xe.match(/[-\d.]+/g)||[]).map(Number)}function E(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 x=new Map;function D(xe,pe,he,ye=550,ke=T){if(!xe)return;xe.setAttribute("d",p[pe]);const Le=C(p[pe]),st=C(p[he]),gt=performance.now(),Wt=x.get(xe);Wt&&cancelAnimationFrame(Wt);const jt=ht=>{const Qt=Math.min((ht-gt)/ye,1),It=ke(Qt),ns=Le.map((ot,$s)=>ot+(st[$s]-ot)*It);xe.setAttribute("d",E(ns)),Qt<1?x.set(xe,requestAnimationFrame(jt)):x.delete(xe)};x.set(xe,requestAnimationFrame(jt))}function N(){a.value&&(a.value.style.transition=uI,a.value.style.transform=`translate(${_.x}px, ${_.y}px) rotate(${OJ}deg)`),c.value&&(c.value.style.transition=uI,c.value.style.transform=`translate(${_.x}px, ${_.y}px) rotate(${DJ}deg)`)}function O(xe=!0){a.value&&(xe||(a.value.style.transition="none"),a.value.style.transform=`translate(${g.x}px, ${g.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 G(){a.value&&(a.value.style.transition=dI,a.value.style.transform=`translate(${m.x}px, ${m.y}px)`),c.value&&(c.value.style.transition=dI,c.value.style.transform=`translate(${y.x}px, ${y.y}px)`)}let Z=0,q=0,V=0,I=0,$=null;function L(xe){Z=xe.clientX,q=xe.clientY}function K(){$&&cancelAnimationFrame($),$=null,o.value&&(o.value.style.transform="translate(0px, 0px)")}function se(){const xe=P.value||t.mode;if(!(t.tracking&&(xe==="idle"||xe==="nervous"))||!r.value){K();return}const pe=r.value.getBoundingClientRect(),he=pe.left+pe.width/2,ye=pe.top+pe.height/2,ke=Z-he,Le=q-ye,st=Math.sqrt(ke*ke+Le*Le),gt=Math.atan2(Le,ke),Wt=Math.min(st/180,1),jt=Math.cos(gt)*10*Wt,ht=Math.sin(gt)*10*Wt;V+=(jt-V)*.15,I+=(ht-I)*.15,o.value&&(o.value.style.transform=`translate(${V}px, ${I}px)`),$=requestAnimationFrame(se)}let oe=null,ve=null,le=null,ue=!1;const P=ge(null);function X(){oe&&clearTimeout(oe),oe=null}function J(){ve&&clearTimeout(ve),ve=null}function ne(){le&&clearTimeout(le),le=null}function ce(xe){return new Promise(pe=>window.setTimeout(pe,xe))}function _e(){if(J(),t.mode!=="idle"||P.value)return;const xe=2800+Math.random()*3600;ve=window.setTimeout(async()=>{await Pe(),_e()},xe)}async function Pe(){if(t.mode!=="idle"||P.value||ue)return;ue=!0;const xe=Math.random()<.5?1:2;for(let pe=0;pe<xe;pe++){if(D(a.value,"idle","blink",150,A),D(c.value,"idle","blink",150,A),await ce(120),t.mode!=="idle"||P.value){ue=!1;return}await ce(45),D(a.value,"blink","idle",210,A),D(c.value,"blink","idle",210,A),await ce(pe===xe-1?200:250)}ue=!1}function it(){t.mode==="idle"&&(P.value="nervous",J(),ne(),K(),X(),l.value=null,u.value=!0,G(),D(a.value,b,"nervousLeft",220,A),D(c.value,k,"nervousRight",220,A),b="nervousLeft",k="nervousRight",t.tracking&&se(),le=window.setTimeout(()=>{P.value==="nervous"&&(P.value=null)},500))}function at(){t.mode==="idle"&&(n("poke"),it())}function rt(xe,pe=!0){const he=u.value&&!l.value;if(u.value=!1,!pe||l.value===xe){l.value=xe;return}if(he){l.value=null,X(),oe=window.setTimeout(()=>{l.value=xe,oe=null},160);return}if(!l.value){l.value=xe;return}l.value=null,X(),oe=window.setTimeout(()=>{l.value=xe,oe=null},160)}function Oe(){t.mode!=="idle"&&P.value&&(P.value=null,ne());const xe=P.value||t.mode;if(xe!=="idle"&&J(),xe==="tool"){K();const ke=(t.toolKeys||[]).filter(Boolean);rt(ke.length?ke[0]:"command");return}if(X(),xe==="think"){K(),rt("think");return}if(xe==="nervous")return;const pe=xe==="work"?"work":"idle",he=!!l.value;l.value=null;const ye=()=>{u.value=!0,D(a.value,b,pe),D(c.value,k,pe),pe==="work"?N():O(),b=pe,k=pe};he?oe=window.setTimeout(()=>{ye(),oe=null},160):ye(),pe==="idle"&&t.tracking?(K(),se(),_e()):(K(),J())}return Ke(()=>[t.mode,(t.toolKeys||[]).join(""),t.tracking,P.value],()=>Oe()),dn(()=>{O(!1),document.addEventListener("mousemove",L),Oe()}),Rn(()=>{document.removeEventListener("mousemove",L),K(),X(),J(),ne(),x.forEach(xe=>cancelAnimationFrame(xe)),x.clear()}),(xe,pe)=>(F(),U("svg",{ref_key:"svgRef",ref:r,class:Ce(["status-avatar",`status-avatar--${t.mode||"idle"}`]),style:qe({width:s.size+"px",height:s.size+"px"}),viewBox:"0 0 200 200","aria-hidden":"true",onClick:at},[t.hexBackground?(F(),U("path",IJ)):me("",!0),pe[3]||(pe[3]=M("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)),M("defs",null,[M("clipPath",{id:i},[...pe[0]||(pe[0]=[M("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)])])]),M("g",{class:"sa-face",ref_key:"faceRef",ref:o},[M("g",{class:Ce(["sa-fc sa-shared",{hidden:!u.value}])},[M("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),M("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),M("g",{class:Ce(["sa-fc sa-icon",{active:l.value==="think"}])},[...pe[1]||(pe[1]=[M("circle",{class:"sa-think-dot",cx:"80",cy:"100",r:"7"},null,-1),M("circle",{class:"sa-think-dot",cx:"100",cy:"100",r:"7"},null,-1),M("circle",{class:"sa-think-dot",cx:"120",cy:"100",r:"7"},null,-1)])],2),M("g",{class:Ce(["sa-fc sa-icon",{active:l.value==="subagent"}]),"clip-path":`url(#${i})`},[...pe[2]||(pe[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,PJ),(F(),U(Ie,null,Ze(d,he=>M("g",{key:he.key,class:Ce(["sa-fc sa-icon",{active:l.value===he.key}]),innerHTML:h(he)},null,10,LJ)),64))],512)],6))}}),GD=qt(NJ,[["__scopeId","data-v-05190602"]]),$J=["data-runtime-queue-id"],BJ={class:"runtime-queue-item__text"},FJ=["onClick"],HJ=["onClick"],UJ=["aria-label"],WJ=["aria-selected","disabled","onMousedown"],zJ={class:"skill-slash-item__name"},jJ={class:"skill-slash-item__description"},VJ={key:0,class:"skill-slash-empty"},GJ={key:0,class:"floating-project-status__left"},KJ={class:"floating-project-status__menu-wrap"},qJ={class:"floating-project-status__menu-wrap"},QJ={class:"floating-project-status__right"},XJ={key:0,class:"floating-project-status__notice"},YJ={key:1,class:"floating-project-status__notice"},JJ={class:"floating-project-status__add"},ZJ={class:"floating-project-status__del"},eZ={class:"input-stack"},tZ={key:0,class:"image-inline-row"},sZ=["onClick"],nZ=["src","alt"],iZ=["onClick"],rZ={key:1,class:"image-inline-row video-inline-row"},oZ=["src","alt"],aZ=["onClick"],lZ={class:"input-row"},cZ={class:"stadium-input-rich"},uZ={class:"input-actions"},dZ={class:"input-actions-left"},hZ=["disabled","aria-label"],fZ=["disabled","aria-expanded"],pZ=["onClick"],mZ={class:"agent-type-switcher__menu-label"},gZ={class:"agent-type-switcher__menu-desc"},vZ=["disabled","aria-expanded","title"],yZ=["onClick"],bZ={class:"agent-type-switcher__menu-label"},_Z={class:"agent-type-switcher__menu-desc"},wZ={class:"input-actions-right"},SZ=["disabled","title"],kZ={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"},CZ={key:1,class:"voice-wave"},TZ=["disabled"],AZ={key:0,class:"stop-icon"},EZ={key:1,class:"send-icon"},MZ=["disabled"],xZ=["disabled","title"],RZ={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"},IZ={class:"permission-switcher__group-title"},PZ={key:0,class:"permission-switcher__group-lock"},LZ=["disabled","onClick"],OZ={class:"permission-switcher__item-label"},DZ={class:"permission-switcher__item-desc"},NZ={class:"permission-switcher__group-title"},$Z={key:0,class:"permission-switcher__group-lock"},BZ={key:1,class:"permission-switcher__group-lock"},FZ=["disabled","onClick"],HZ={class:"permission-switcher__item-desc"},UZ={class:"permission-switcher__group-title"},WZ=["disabled","onClick"],zZ={class:"permission-switcher__item-desc"},jZ=["disabled"],VZ={class:"context-usage-switcher__tooltip"},YC=300,GZ="cubic-bezier(0.25, 0.8, 0.25, 1)",KZ=ct({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:{},planApprovalMinimized:{type:Boolean},pendingPlanApprovalCount:{},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","restore-plan-approval","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=lk(),o=Js(),a=ge(null),c=ge(null),l=ge(null),u=ge(null),d=ge(null),h=ge(0),p=ge([]),g=ge([]),v=ge(!1),m=ge(!1),y=ge(!1),_=ge(""),b=ge(0),k=ge(null),w=ge("root"),T=ge(0),A=ge(!1),C=ge(4),E=ge(!1),x=ge(null),D=ge(!1),N=yg(),O=ge([]),G=ge(!1),Z=ge(!1),q=ge(!1);let V=null,I=!1,$=null,L=0;const K=ge(null),se=ge(!1),oe=ge(null),ve=ge(0),le=ge([]),ue=ge(!1),P=ge({}),X=ge(!1);let J=null;const ne=ge("");let ce=null;const _e=be(()=>(lt.value,[S("input.pokeStop"),S("input.pokeHalt"),S("input.pokeDontPoke"),S("input.pokeOops"),S("input.pokeYouPokedMe"),S("input.pokeGentle"),S("input.pokeNotButton"),S("input.pokeNoClicking"),S("input.pokeWhimper"),S("input.pokeHexagonHurt"),S("input.pokeDeform"),S("input.pokeNervous"),S("input.pokePretendCalm"),S("input.pokeTokensFell"),S("input.pokeContextMessy"),S("input.pokeAntiPokeFailed"),S("input.pokeSystemHint"),S("input.pokeWarning"),S("input.pokeRemembered"),S("input.pokePokeBack")])),Pe=be(()=>{var j;if(E.value)return{display:"none"};const W=b.value===0&&((j=k.value)==null?void 0:j.scrollTop)===0;return{top:`${C.value}px`,...W?{borderTopLeftRadius:"calc(var(--skill-slash-radius) - var(--skill-slash-gap))",borderTopRightRadius:"calc(var(--skill-slash-radius) - var(--skill-slash-gap))"}:{}}}),it=(W,j)=>{const ee=V!==null;ee&&cancelAnimationFrame(V),I=!0,$=j;const Te=W.scrollTop,Re=C.value,Ve=j-Te,Ye=4+b.value*31-j-Re,Xe=ee?60:180,xt=performance.now(),Ot=Jt=>{const Ta=Math.max(0,Jt-xt),Cl=Math.min(Ta/Xe,1),L_=1-Math.pow(1-Cl,3);W.scrollTop=Te+Ve*L_,C.value=Re+Ye*L_,Cl<1?V=requestAnimationFrame(Ot):(V=null,I=!1,L=performance.now())};V=requestAnimationFrame(Ot)},at=()=>{if(I||V!==null)return;const W=k.value;if(!W)return;const j=performance.now();$!==null&&j-L<150&&Math.abs(W.scrollTop-$)<1||(E.value=!0)};let rt=null,Oe=!1;const xe=W=>{if(!W)return"";const j=W.split(/[/\\]/);return j[j.length-1]||W},pe=W=>{const j=he(W);j&&Is().openImagePreview({url:j,name:xe(W)})},he=W=>W?`/api/gui/files/download?path=${encodeURIComponent(W)}`:"",ye=(W,j)=>{r.setInputLineCount(W),r.setInputMultiline(j)},ke=be(()=>(Array.isArray(i.runtimeQueuedMessages)?i.runtimeQueuedMessages:[]).filter(j=>j&&j.id&&j.text).map(j=>({...j,text:String(j.text||"").replace(/[\r\n\u2028\u2029]+/g," ")}))),Le=be(()=>{var Re;if(((Re=o==null?void 0:o.form)==null?void 0:Re.show_git_status_bar)===!1)return null;const W=i.projectGitSummary;if(!(W!=null&&W.has_git))return null;const j=String(W.project_name||"").trim(),ee=String(W.branch||"").trim();return!j||!ee?null:{projectName:j,projectPath:String(W.project_path||"").trim(),branch:ee,additions:Math.max(0,Number(W.additions||0)),deletions:Math.max(0,Number(W.deletions||0))}}),st=be(()=>yl.value||se.value||i.quickMenuOpen||ke.value.length>0||i.hasPendingRuntimeGuidance?!1:!!Le.value||!!i.goalRunning||!!i.goalModeArmed||Number(i.pendingUserQuestionCount||0)>0||!!i.planApprovalMinimized&&Number(i.pendingPlanApprovalCount||0)>0||Number(i.activeSubAgentCount||0)>0),gt=be(()=>yl.value||se.value||i.quickMenuOpen||ke.value.length>0||i.hasPendingRuntimeGuidance?!1:!!i.avatarStatus),Wt=be(()=>i.avatarStatus&&(i.avatarStatus.mode==="tool"||i.avatarStatus.mode==="think"||i.avatarStatus.mode==="work"&&i.avatarStatus.apiWaiting)&&i.avatarStatus.text||""),jt=be(()=>{var j;const W=i.avatarStatus;return W?W.mode==="tool"?`avatar-tool-${((j=W.toolKeys)==null?void 0:j[0])||""}`:W.mode==="work"&&W.apiWaiting?"avatar-work-api-waiting":`avatar-${W.mode}`:"avatar-none"}),ht=ge(null),Qt=()=>{ht.value=null},It=W=>{ht.value=ht.value===W?null:W},ns=async W=>{var ee;const j=String(W||"").trim();!j||typeof navigator>"u"||!((ee=navigator.clipboard)!=null&&ee.writeText)||(await navigator.clipboard.writeText(j),Qt())},ot=()=>{var W;ns(((W=Le.value)==null?void 0:W.projectPath)||"")},$s=()=>{var W;ns(((W=Le.value)==null?void 0:W.branch)||"")},Er=async()=>{try{await fetch("/api/project/open-in-file-manager",{method:"POST"})}catch(W){console.warn("打开项目文件管理器失败:",W)}finally{Qt()}},In=()=>{const W=rs.value;if(!W)return null;const{state:j}=W,{$from:ee}=j.selection;ee.start();const Te=ee.parent.textBetween(0,ee.parentOffset,`
|
||
`,`
|
||
`),Re=/(^|[ \n])(\/{1,2})([^\s/]*)$/.exec(Te);if(!Re)return null;const Ve=Re[2]||"/",Ue=Re[3]||"",Ye=ee.pos-Ue.length-Ve.length,Xe=ee.pos;return{start:Ye,end:Xe,query:Ue,doubleSlash:Ve.length===2}},Ko=()=>{const W=rs.value;if(!W)return null;const{state:j}=W,{$from:ee}=j.selection,Te=ee.parent.textBetween(0,ee.parentOffset,`
|
||
`,`
|
||
`),Re=/(^|[ \n])@([^\s@]*)$/.exec(Te);if(!Re)return null;const Ve=Re[2]||"",Ue=ee.pos-Ve.length-1,Ye=ee.pos;return{start:Ue,end:Ye,query:Ve,charStart:Ue}},ao=()=>{V!==null&&(cancelAnimationFrame(V),V=null),I=!1,$=null,L=0,y.value=!1,_.value="",b.value=0,w.value="root",T.value=0,C.value=4,E.value=!1,x.value=null,D.value=!1},Pn=()=>{se.value=!1,oe.value=null,ve.value=0,le.value=[],ue.value=!1,P.value={},J!==null&&(window.clearTimeout(J),J=null)},qo=()=>{ce!==null&&(window.clearTimeout(ce),ce=null),ne.value=""},Yn=()=>{if(!i.avatarStatus||i.avatarStatus.mode!=="idle")return;const W=_e.value;ne.value=W[Math.floor(Math.random()*W.length)]||S("input.pokeStop"),ce!==null&&window.clearTimeout(ce),ce=window.setTimeout(()=>{ne.value="",ce=null},1800)},Oi=W=>{ft(()=>{const j=rs.value;if(j)try{const ee=j.view.coordsAtPos(W),Te=window.innerWidth,Re=window.innerHeight,Ve=280,Ue=250,Ye=4;let Xe=ee.right,xt=ee.top-Ue;Xe+Ve>Te-Ye&&(Xe=Math.max(Ye,Te-Ve-Ye)),xt<Ye&&(xt=ee.bottom),xt+Ue>Re-Ye&&(xt=Math.max(Ye,Re-Ue-Ye)),P.value={left:`${Xe}px`,top:`${xt}px`,width:`${Ve}px`,maxHeight:`${Ue}px`}}catch{P.value={}}})},Mr=W=>{var ee;if(!W)return!1;const j=((ee=W.split(".").pop())==null?void 0:ee.toLowerCase())||"";return["jpg","jpeg","png","gif","webp","bmp","ico"].includes(j)},Di=async W=>{var j;ue.value=!0;try{const ee=`/api/project/files/search?q=${encodeURIComponent(W)}&limit=50`,Te=await fetch(ee),Re=await Te.json().catch(()=>({}));if(!Te.ok||!(Re!=null&&Re.success)){le.value=[];return}le.value=Array.isArray((j=Re==null?void 0:Re.data)==null?void 0:j.items)?Re.data.items:[]}catch(ee){console.warn("[FileAt] 搜索文件失败:",ee),le.value=[]}finally{ue.value=!1}},gl=W=>{J!==null&&window.clearTimeout(J),J=window.setTimeout(()=>{Di(W)},120)},Qo=()=>{const W=Ko();if(!W||!i.isConnected||i.inputLocked){Pn();return}Qt();const j=oe.value!==W.query;se.value=!0,(j||le.value.length===0)&&(ve.value=0,oe.value=W.query,gl(W.query)),Oi(W.end)},lo=W=>{const j=Ko(),ee=rs.value;if(!j||!ee)return;const{state:Te,view:Re,schema:Ve}=ee,Ue=Ve.nodes.mention;if(!Ue)return;const Ye=Ue.create({id:`file://${W.path}`,label:W.name});let Xe=Te.tr.delete(j.start,j.end);Xe=Xe.insert(j.start,Ye);const xt=j.start+Ye.nodeSize;Xe=Xe.insertText(" ",xt),Xe=Xe.setSelection(kt.near(Xe.doc.resolve(xt+1))),Re.dispatch(Xe),Re.focus(),Pn(),ft(()=>{Ir()})},fi=()=>{var W;Pn(),i.hostMode&&(X.value=!0,(W=d.value)==null||W.click())},Ni=W=>{const j=!!i.hostMode;if(j&&W===0){fi();return}const ee=j?W-1:W,Te=le.value[ee];if(Te){if(Te.type==="file"&&Mr(Te.path)){Pn(),n("pick-images");return}lo(Te)}},wa=W=>{var Te,Re,Ve,Ue;if(!se.value)return!1;const ee=(!!i.hostMode?1:0)+le.value.length;return ee<=0?!1:W.key==="ArrowDown"?(W.preventDefault(),(Te=K.value)==null||Te.setManualScroll(!1),ve.value=(ve.value+1)%ee,(Re=K.value)==null||Re.focusActive(),!0):W.key==="ArrowUp"?(W.preventDefault(),(Ve=K.value)==null||Ve.setManualScroll(!1),ve.value=(ve.value-1+ee)%ee,(Ue=K.value)==null||Ue.focusActive(),!0):W.key==="Enter"?(W.preventDefault(),Ni(ve.value),!0):W.key==="Escape"?(W.preventDefault(),Pn(),!0):!1},vl=()=>{const W=In(),j=rs.value;if(!W||!j)return;const{state:ee,view:Te}=j;let Re=ee.tr.delete(W.start,W.end);Re=Re.setSelection(kt.near(Re.doc.resolve(Math.max(0,W.start)))),Te.dispatch(Re),Te.focus(),ft(()=>{Ir()})},re=()=>{ft(()=>{const W=k.value;if(!W)return;const j=getComputedStyle(W),ee=parseFloat(j.getPropertyValue("--skill-slash-row-height")),Te=parseFloat(j.getPropertyValue("--skill-slash-gap")),Re=(Number.isFinite(ee)?ee:38)+(Number.isFinite(Te)?Te:5),Ve=Math.max(1,Math.floor(W.clientHeight/Re)||5),Ue=Math.floor(Ve/2),Ye=Math.max(0,W.scrollHeight-W.clientHeight),Xe=Math.max(0,Math.min(Ye,(b.value-Ue)*Re));it(W,Xe)})},we=be(()=>{const W=_.value.trim().toLowerCase(),j=Array.isArray(p.value)?p.value:[];return(W?j.filter(Te=>String(Te.name||"").toLowerCase().includes(W)):j).slice(0,100)}),Ae=be(()=>{var j;const W=(j=i.modelOptions)==null?void 0:j.find(ee=>ee.key===i.currentModelKey);return!!(W!=null&&W.supportsImage)}),bt=be(()=>{var j;const W=(j=i.modelOptions)==null?void 0:j.find(ee=>ee.key===i.currentModelKey);return!!(W!=null&&W.supportsVideo)}),hs=async W=>{o.applyTheme(W),o.updateField({key:"theme",value:W});try{const j=await fetch("/api/personalization",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({theme:W})}),ee=await j.json().catch(()=>({}));(!j.ok||!ee.success)&&console.warn("保存主题到后端失败:",ee==null?void 0:ee.error)}catch(j){console.warn("保存主题到后端失败:",j)}},Ps=W=>{vl(),ao(),W()},is=be(()=>{var ee;lt.value;const W=[{id:"new",label:S("common.newConversation"),description:S("input.newConversationDesc"),disabled:!i.isConnected,action:()=>n("new-conversation")},{id:"upload",label:S("input.uploadFile"),description:i.uploading?S("input.uploadingDesc"):S("input.selectFileDesc"),disabled:!i.isConnected||i.uploading||i.blockUpload,action:()=>n("quick-upload")},{id:"image",label:S("input.sendImage"),description:Ae.value?S("input.sendImageDesc"):S("input.imageNotSupported"),disabled:!i.isConnected||i.streamingMessage||!Ae.value,action:()=>n("pick-images")},{id:"video",label:S("input.sendVideo"),description:bt.value?S("input.sendVideoDesc"):S("input.videoNotSupported"),disabled:!i.isConnected||i.streamingMessage||!bt.value,action:()=>n("pick-video")},{id:"compress",label:S("input.compressConversation"),description:i.compressing?S("input.compressingDesc"):S("input.compressDesc"),disabled:!i.isConnected||i.compressing||i.streamingMessage||i.blockCompressConversation,action:()=>n("compress-conversation")},{id:"skills",label:S("input.selectAgentSkill"),description:S("input.selectAgentSkillDesc"),mode:"skills"},{id:"workflows",label:S("input.workflows"),description:N.isActive?S("input.workflowRunningDesc",{name:N.snapshot.name}):S("input.workflowActivateDesc"),disabled:!i.isConnected,mode:"workflows"},{id:"conversation-type",label:S("input.conversationType"),description:S("input.conversationTypeDesc"),disabled:!i.isConnected,mode:"conversation-type"},{id:"work-mode",label:S("input.switchWorkMode"),description:S("input.switchWorkModeDesc"),disabled:!i.isConnected||i.streamingMessage,mode:"work-mode"},{id:"theme",label:S("input.switchTheme"),description:S("input.switchThemeDesc"),mode:"theme"},{id:"review",label:S("input.conversationReview"),description:S("input.conversationReviewDesc"),disabled:!i.isConnected||i.streamingMessage||i.blockConversationReview,action:()=>n("open-review")},{id:"tokens",label:S("input.usageStats"),description:S("input.usageStatsDesc"),disabled:!i.currentConversationId||i.blockTokenPanel,action:()=>n("toggle-token-panel",!0)},{id:"goal",label:S("input.goalMode"),description:i.goalRunning?S("input.goalModeRunning"):i.goalModeArmed?S("input.goalModeArmed"):S("input.goalModeToggleDesc"),disabled:!i.isConnected,action:()=>n("toggle-goal-mode")},{id:"personalization",label:S("input.personalSettings"),description:S("input.personalSettingsDesc"),action:()=>{o.openDrawer()}},{id:"terminal",label:S("input.realtimeTerminal"),description:S("input.realtimeTerminalDesc"),disabled:!i.isConnected||i.blockRealtimeTerminal,action:()=>n("realtime-terminal")},{id:"model",label:S("input.switchModel"),description:S("input.switchModelDesc"),disabled:!i.isConnected||i.streamingMessage,mode:"model"},{id:"run-mode",label:S("input.thinkingMode"),description:S("input.thinkingModeDesc"),disabled:!i.isConnected||i.streamingMessage,mode:"run-mode"},{id:"permission",label:S("input.permissionMode"),description:S("input.permissionModeDesc"),disabled:!i.isConnected||i.streamingMessage,mode:"permission"},{id:"network",label:S("input.networkPermission"),description:i.networkPermissionEnabled?S("input.networkPermissionDesc"):S("input.networkUnsupportedDesc"),disabled:!i.isConnected||i.streamingMessage||!i.networkPermissionEnabled,mode:"network"},...i.executionModeEnabled?[{id:"execution",label:S("input.executionEnv"),description:S("input.executionEnvDesc"),disabled:!i.isConnected||i.streamingMessage,mode:"execution"}]:[],...i.workspaceKind?[{id:"workspace",label:i.workspaceKind==="project"?S("input.switchProject"):S("input.switchWorkspace"),description:S("input.workspaceDesc"),disabled:!i.isConnected||i.streamingMessage,mode:"workspace"}]:[],{id:"versioning",label:S("input.versionControl"),description:i.versioningEnabled?S("input.versioningOn"):S("input.versioningOff"),disabled:!i.isConnected||i.streamingMessage,action:()=>n("open-versioning-dialog")},{id:"git-bar",label:S("input.gitStatusBar"),description:((ee=o==null?void 0:o.form)==null?void 0:ee.show_git_status_bar)!==!1?S("input.gitStatusBarShown"):S("input.gitStatusBarHidden"),action:()=>{var Ve;const Re=!(((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=Re),fetch("/api/personalization",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({show_git_status_bar:Re})}).catch(()=>{})}},{id:"path-auth",label:S("input.pathAuth"),description:S("input.pathAuthDesc"),disabled:!i.isConnected,action:()=>n("open-path-authorization")},{id:"approval",label:S("input.approvalPanel"),description:S("input.approvalPanelDesc"),disabled:!i.isConnected,action:()=>n("toggle-approval-panel")}],j=_.value.trim().toLowerCase();return j?W.filter(Te=>`${Te.label} ${Te.description} ${Te.id}`.toLowerCase().includes(j)):W}),en=be(()=>(lt.value,[{id:"theme-classic",label:S("input.themeClassic"),description:S("input.themeClassicDesc"),theme:"classic"},{id:"theme-light",label:S("input.themeLight"),description:S("input.themeLightDesc"),theme:"light"},{id:"theme-dark",label:S("input.themeDark"),description:S("input.themeDarkDesc"),theme:"dark"}].map(j=>({...j,action:()=>{hs(j.theme)}})))),ut=be(()=>{lt.value;const W=i.permissionOptions||[],j=String(i.currentPermissionMode||""),ee=i.currentWorkMode==="plan";return W.map(Te=>({id:`perm:${Te.value}`,label:S(Te.labelKey),description:ee?S("input.permissionLockedReadonlyDesc"):Te.value===j?S("input.optionWithCurrent",{desc:S(Te.descriptionKey)}):S(Te.descriptionKey),disabled:ee,action:()=>n("change-permission-mode",Te.value)}))}),pn=be(()=>{lt.value;const W=i.executionModeOptions||[],j=String(i.currentExecutionMode||""),ee=i.currentWorkMode==="plan";return W.map(Te=>({id:`exec:${Te.value}`,label:S(Te.labelKey),description:ee?S("input.executionLockedSandboxDesc"):Te.value===j?S("input.optionWithCurrent",{desc:S(Te.descriptionKey)}):S(Te.descriptionKey),disabled:ee,action:()=>n("change-execution-mode",Te.value)}))}),co=be(()=>{lt.value;const W=Array.isArray(i.modelOptions)?i.modelOptions:[],j=String(i.currentModelKey||"");return W.map(ee=>({id:`model:${ee.key}`,label:ee.label,description:ee.key===j?S("input.optionWithCurrent",{desc:ee.description||""}):ee.description||"",disabled:!!ee.disabled,action:()=>n("select-model",ee.key)}))}),$i=be(()=>{lt.value;const W=[{value:"fast",label:S("input.runModeFast")},{value:"thinking",label:S("input.runModeThinking")}],j=String(i.runMode||"");return W.map(ee=>({id:`runmode:${ee.value}`,label:ee.label,description:ee.value===j?S("input.currentMark"):"",action:()=>n("select-run-mode",ee.value)}))}),Bc=be(()=>{lt.value;const W=i.networkPermissionOptions||[],j=String(i.currentNetworkPermission||"");return W.map(ee=>({id:`network:${ee.value}`,label:S(ee.labelKey),description:ee.value===j?S("input.optionWithCurrent",{desc:S(ee.descriptionKey)}):S(ee.descriptionKey),action:()=>n("change-network-permission",ee.value)}))}),xr=be(()=>{lt.value;const W=i.workModeOptions||[],j=String(i.currentWorkMode||"");return W.map(ee=>({id:`workmode:${ee.value}`,label:S(ee.labelKey),description:ee.value===j?S("input.optionWithCurrent",{desc:S(ee.descriptionKey)}):S(ee.descriptionKey),action:()=>n("change-work-mode",ee.value)}))}),Bi=be(()=>{lt.value;const W=Array.isArray(i.hostWorkspaces)?i.hostWorkspaces:[],j=String(i.currentHostWorkspaceId||""),ee=!!i.hostWorkspaceSwitching;return W.map(Te=>({id:`workspace:${Te.workspace_id}`,label:Te.label,description:Te.workspace_id===j?S("input.optionWithCurrent",{desc:Te.path||""}):Te.path||"",disabled:ee||Te.workspace_id===j,action:()=>n("switch-host-workspace",Te.workspace_id)}))}),Fc=be(()=>{lt.value;const W=kd.value,j=String(i.newConversationType||"agent");return R_.value.map(ee=>({id:`convtype:${ee.value}`,label:ee.label,description:W?S("input.conversationTypeLockedDesc"):ee.value===j?S("input.optionWithCurrent",{desc:ee.description||""}):ee.description||"",disabled:W,action:()=>n("select-new-conversation-type",ee.value)}))}),Fi=be(()=>we.value.map(W=>({id:`skill:${W.path}`,label:W.name,description:W.description,skill:W}))),mn=be(()=>w.value==="skills"?Fi.value:w.value==="workflows"?ae.value:w.value==="theme"?en.value:w.value==="permission"?ut.value:w.value==="execution"?pn.value:w.value==="model"?co.value:w.value==="run-mode"?$i.value:w.value==="network"?Bc.value:w.value==="work-mode"?xr.value:w.value==="workspace"?Bi.value:w.value==="conversation-type"?Fc.value:is.value),Hi=be(()=>(lt.value,w.value==="skills"?S("input.slashSkillsAria"):w.value==="workflows"?S("input.slashWorkflowsAria"):w.value==="theme"?S("input.slashThemeAria"):w.value==="permission"?S("input.slashPermissionAria"):w.value==="execution"?S("input.slashExecutionAria"):w.value==="model"?S("input.slashModelAria"):w.value==="run-mode"?S("input.slashRunModeAria"):w.value==="network"?S("input.slashNetworkAria"):w.value==="work-mode"?S("input.slashWorkModeAria"):w.value==="workspace"?i.workspaceKind==="project"?S("input.slashProjectAria"):S("input.slashWorkspaceAria"):w.value==="conversation-type"?S("input.slashConversationTypeAria"):S("input.slashRootAria"))),Sa=be(()=>(lt.value,w.value==="skills"?m.value?S("input.skillsLoadingEmpty"):S("input.skillsEmpty"):w.value==="workflows"?Z.value?S("input.workflowsLoadingEmpty"):S("input.workflowsEmpty"):w.value==="permission"?S("input.permissionEmpty"):w.value==="execution"?S("input.executionEmpty"):w.value==="model"?S("input.modelEmpty"):w.value==="network"?S("input.networkEmpty"):w.value==="work-mode"?S("input.workModeEmpty"):w.value==="workspace"?i.workspaceKind==="project"?S("input.projectEmpty"):S("input.workspaceEmpty"):w.value==="conversation-type"?S("input.conversationTypeEmpty"):S("input.commandEmpty"))),yl=be(()=>y.value&&(m.value||mn.value.length>=0)),Hc=async()=>{if(!(v.value||m.value)){m.value=!0;try{const W=await fetch("/api/skills"),j=await W.json().catch(()=>({}));if(!W.ok||!(j!=null&&j.success))throw new Error((j==null?void 0:j.error)||S("input.loadSkillsFailed"));p.value=Array.isArray(j.skills)?j.skills.filter(ee=>ee&&ee.name&&ee.path).map(ee=>({name:String(ee.name||""),description:String(ee.description||""),path:String(ee.path||"")})):[],v.value=!0}catch(W){p.value=[],v.value=!1,console.warn("[SkillSlash] 加载 skills 失败:",W)}finally{m.value=!1}}},Xo=async(W=!1)=>{if(!(G.value&&!W||Z.value)){Z.value=!0;try{const j=await fetch("/api/workflows"),ee=await j.json().catch(()=>({}));if(!j.ok)throw new Error((ee==null?void 0:ee.error)||S("input.loadWorkflowsFailed"));O.value=Array.isArray(ee.workflows)?ee.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)})):[],G.value=!0}catch(j){O.value=[],G.value=!1,console.warn("[WorkflowSlash] 加载工作流列表失败:",j)}finally{Z.value=!1}}},Yo=async W=>{if(q.value)return;const j=String(i.currentConversationId||"").trim();q.value=!0;try{const ee={name:W};j&&(ee.conversation_id=j);const Te=await fetch("/api/workflow/activate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(ee)}),Re=await Te.json().catch(()=>({}));if(!Te.ok||!(Re!=null&&Re.success))throw new Error((Re==null?void 0:Re.error)||S("input.activateWorkflowFailed"));Re!=null&&Re.snapshot&&N.setWorkflow(Re.snapshot,!0),Is().pushToast({title:S("input.workflowActivated",{name:W}),type:"success"});const Ve=String((Re==null?void 0:Re.conversation_id)||"").trim();Ve&&Ve!==j&&n("workflow-activated",Ve)}catch(ee){Is().pushToast({title:S("input.activateWorkflowFailed"),message:String((ee==null?void 0:ee.message)||ee||""),type:"error"})}finally{q.value=!1}},et=async()=>{if(q.value)return;const W=String(i.currentConversationId||"").trim();if(W){q.value=!0;try{const j=await fetch("/api/workflow/deactivate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({conversation_id:W})}),ee=await j.json().catch(()=>({}));if(!j.ok||!(ee!=null&&ee.success))throw new Error((ee==null?void 0:ee.error)||S("input.exitWorkflowFailed"));N.setWorkflow(null,!0),Is().pushToast({title:S("input.workflowExited",{name:(ee==null?void 0:ee.workflow_name)||""}),type:"success"})}catch(j){Is().pushToast({title:S("input.exitWorkflowFailed"),message:String((j==null?void 0:j.message)||j||""),type:"error"})}finally{q.value=!1}}},ae=be(()=>{lt.value;const W=[],j=N.isActive?String(N.snapshot.name||""):"";j&&W.push({id:"workflow-deactivate",label:S("input.exitCurrentWorkflow"),description:S("input.workflowRunningExitDesc",{name:j}),disabled:q.value,action:()=>{et()}});const ee=!i.isConnected||i.streamingMessage||q.value||!!j;for(const Te of O.value){const Re=j&&Te.name===j;W.push({id:`workflow-activate-${Te.name}`,label:Te.name,description:Re?S("input.workflowCurrentActive"):S("input.workflowItemDesc",{desc:Te.description||S("input.workflowNoDesc"),builtinSuffix:Te.source==="builtin"?S("input.workflowBuiltinSuffix"):""}),disabled:ee||!!Re,action:()=>{Yo(Te.name)}})}return W}),Me=()=>{const W=In();if(!W||!i.isConnected||i.inputLocked){ao();return}Qt(),y.value=!0,_.value!==W.query&&(b.value=0),_.value=W.query,W.doubleSlash&&w.value==="root"&&!D.value?(w.value="skills",x.value="typed",b.value=0):!W.doubleSlash&&w.value==="skills"&&x.value==="typed"&&(w.value="root",x.value=null,b.value=0),w.value==="skills"&&Hc(),b.value=Math.min(b.value,Math.max(0,mn.value.length-1)),re()},Ge=(W=b.value)=>{const j=In(),ee=we.value[W],Te=rs.value;if(!j||!ee||!Te)return;g.value=[...g.value.filter(Jt=>Jt.path!==ee.path),ee];const{state:Re,view:Ve,schema:Ue}=Te,Ye=Ue.nodes.mention;if(!Ye)return;const Xe=Ye.create({id:ee.path,label:ee.name,path:ee.path,description:ee.description||"",mentionSuggestionChar:""});let xt=Re.tr.delete(j.start,j.end);xt=xt.insert(j.start,Xe);const Ot=j.start+Xe.nodeSize;xt=xt.insertText(" ",Ot),xt=xt.setSelection(kt.near(xt.doc.resolve(Ot+1))),Ve.dispatch(xt),Ve.focus(),ao(),ft(()=>{Ir()})},Bt=(W=b.value)=>{const j=mn.value[W];if(!(!j||j.disabled)){if(j.mode){T.value=W,w.value=j.mode,b.value=0,x.value=j.mode==="skills"?"menu":null,j.mode==="skills"&&Hc(),j.mode==="workflows"&&Xo(),j.mode==="workspace"&&n("fetch-host-workspaces"),re();return}if(j.skill){const ee=we.value.findIndex(Te=>{var Re;return Te.path===((Re=j.skill)==null?void 0:Re.path)});Ge(ee>=0?ee:W);return}j.action&&Ps(j.action)}},Tt=W=>{if(W.ctrlKey&&W.key==="Enter")return!1;if(y.value){if(W.key==="ArrowDown"){W.preventDefault(),E.value=!1;const j=mn.value.length;return j>0&&(b.value=(b.value+1)%j,re()),!0}if(W.key==="ArrowUp"){W.preventDefault(),E.value=!1;const j=mn.value.length;return j>0&&(b.value=(b.value-1+j)%j,re()),!0}if(W.key==="Enter")return mn.value.length>0&&(W.preventDefault(),Bt(b.value)),!0;if(W.key==="Escape")return W.preventDefault(),w.value!=="root"?(w.value==="skills"&&x.value==="typed"&&(D.value=!0),x.value=null,w.value="root",b.value=Math.min(T.value,Math.max(0,mn.value.length-1)),re()):ao(),!0}return!1},Zt=W=>wa(W)||Tt(W)?!0:(requestAnimationFrame(()=>{Me(),Qo()}),!1),Cs=()=>{n("input-blur"),window.setTimeout(()=>{ao(),Pn()},120)},pi=W=>{const j=W.clipboardData;if(!j)return[];const ee=[];if(j.items&&j.items.length)for(const Te of Array.from(j.items)){if(Te.kind!=="file")continue;const Re=Te.getAsFile();Re&&ee.push(Re)}return!ee.length&&j.files&&j.files.length&&ee.push(...Array.from(j.files)),ee},mi=(W="")=>{const j=String(W||"").split(`
|
||
`);return{type:"doc",content:(j.length?j:[""]).map(ee=>({type:"paragraph",content:ee?[{type:"text",text:ee}]:void 0}))}},fs=()=>{const W=rs.value;return W?W.getText({blockSeparator:`
|
||
`}):i.inputMessage||""},Es=W=>{const j=[],ee=Ve=>{if(!Ve)return"";if(Ve.type==="text")return Ve.text||"";if(Ve.type==="mention"){const Ue=Ve.attrs||{},Ye=String(Ue.id||""),Xe=String(Ue.label||Ye).trim();if(Ye.startsWith("file://")){const Ta=Ye.slice(7);return Xe&&Ta?`[${Xe}](file://${Ta})`:Xe}const Ot=Xe,Jt=String(Ue.path||Ye).trim();return Ot&&Jt&&!j.some(Ta=>Ta.path===Jt)&&j.push({name:Ot,path:Jt}),Ot&&Jt?`[$${Ot}](${Jt})`:Ot}return Ve.type==="hardBreak"?`
|
||
`:Array.isArray(Ve.content)?Ve.content.map(ee).join(""):""};return{message:(Array.isArray(W==null?void 0:W.content)?W.content:[]).map(Ve=>ee(Ve)).join(`
|
||
`).trim(),skillRefs:j}},rs=qQ({content:mi(i.inputMessage||""),editable:i.isConnected&&!i.inputLocked,extensions:[oJ.configure({codeBlock:!1,heading:!1,blockquote:!1,bulletList:!1,orderedList:!1,listItem:!1,horizontalRule:!1}),pJ.configure({placeholder:S("input.messagePlaceholder")}),fJ.configure({HTMLAttributes:{class:"skill-md-link"},deleteTriggerWithBackspace:!0,renderText({node:W}){return String(W.attrs.label||W.attrs.id||"")},renderHTML({node:W,HTMLAttributes:j}){const ee=j||{},Te=String(W.attrs.id||""),Re=Te.startsWith("file://"),Ve=Re?`${ee.class||""} file-md-link`.trim():`${ee.class||""} skill-md-link`.trim(),Ue=Re?"data-file-path":"data-skill-path",Ye=Re?Te.slice(7):W.attrs.path||W.attrs.id||"";return["span",{...ee,class:Ve,[Ue]:Ye},String(W.attrs.label||W.attrs.id||"")]},suggestion:{char:"\0"}})],editorProps:{attributes:{class:"stadium-input-editor","data-placeholder":S("input.messagePlaceholder")},handleKeyDown(W,j){return j.ctrlKey&&j.key==="Enter"?(j.preventDefault(),n("send-or-stop"),!0):Zt(j)},handlePaste(W,j){const ee=pi(j);return ee.length?(j.preventDefault(),n("paste-files",ee),!0):!1}},onUpdate(){Oe||(n("update:input-message",fs()),n("input-change"),ft(()=>{Ir(),Me(),Qo()}))},onFocus(){n("input-focus")}}),Ln=ge(!1),bd=ge(null);let cr=0,Ui=0;const Rr=ge("idle"),Sg=ge(0),Uc=ge(""),_d=be(()=>typeof window>"u"?!1:!!window.AndroidVoiceBridge),k_=be(()=>(lt.value,Rr.value==="downloading"?S("input.voiceModelDownloading",{percent:Sg.value}):Rr.value==="model_not_ready"?S("input.voiceModelNotReady"):Ln.value?S("input.stopRecording"):S("input.voiceInput"))),C_=()=>{typeof window>"u"||(window.__onVoiceResult=W=>{const j=window.AndroidVoiceBridge;if(j==null||j.debugLog("__onVoiceResult 被调用, text="+JSON.stringify(W)),!W){j==null||j.debugLog("__onVoiceResult: text 为空,跳过");return}const ee=rs.value;if(!ee){j==null||j.debugLog("__onVoiceResult: editor.value 为 null"),console.warn("[VoiceInput] editor is null");return}j==null||j.debugLog("__onVoiceResult: editor.value 存在,准备插入文字"),j==null||j.debugLog("__onVoiceResult: voiceAnchorPos="+cr+" lastVoiceTextLength="+Ui);const{state:Te,view:Re}=ee,Ve=Te.doc.content.size,Ue=Math.max(0,Math.min(cr,Ve)),Ye=Math.min(Ue+Ui,Ve);j==null||j.debugLog("__onVoiceResult: docSize="+Ve+" safeAnchor="+Ue+" oldEnd="+Ye);try{let Xe=Te.tr;Ye>Ue&&(Xe=Xe.delete(Ue,Ye)),Xe=Xe.insertText(W,Ue);const xt=Math.min(Ue+W.length,Xe.doc.content.size),Ot=window.TextSelection;Ot&&(Xe=Xe.setSelection(Ot.create(Xe.doc,xt))),Re.dispatch(Xe),Re.focus(),Ui=W.length,n("update:input-message",fs()),n("input-change"),ft(()=>Ir()),j==null||j.debugLog("__onVoiceResult: 文字插入成功")}catch(Xe){j==null||j.debugLog("__onVoiceResult: 插入异常 "+(Xe.message||String(Xe)))}},window.__onVoiceStatus=W=>{W==="listening"||W==="processing"||W==="initializing"?Ln.value=!0:W==="idle"?(Ln.value=!1,cr=0,Ui=0):W==="model_not_ready"&&(Rr.value="model_not_ready")},window.__onVoiceError=W=>{console.warn("[VoiceInput] 错误:",W),Ln.value=!1,cr=0,Ui=0},window.__onVoiceDownloadProgress=(W,j)=>{Rr.value="downloading",Sg.value=W,Uc.value=j,W>=100&&(Rr.value="ready")},window.__onVoiceModelReady=()=>{Rr.value="ready"})};if(typeof window<"u"){C_();const W=window.AndroidVoiceBridge;if(W&&typeof W.isModelReady=="function")try{Rr.value=W.isModelReady()?"ready":"model_not_ready"}catch{Rr.value="idle"}}const Fk=()=>typeof window>"u"?null:window.SpeechRecognition||window.webkitSpeechRecognition||null,Wc=()=>{if(bd.value){try{bd.value.stop()}catch(W){console.warn("[VoiceInput] recognition.stop() error:",W)}bd.value=null}Ln.value=!1,cr=0,Ui=0},Hk=()=>{const W=Fk();if(!W)return null;const j=new W;j.lang="zh-CN",j.continuous=!0,j.interimResults=!0,j.maxAlternatives=1;const ee=rs.value;return ee?cr=ee.state.selection.from:cr=0,Ui=0,j.onresult=Te=>{let Re="";for(let Cl=0;Cl<Te.results.length;Cl++){const L_=Te.results[Cl];Re+=L_[0].transcript}if(!Re)return;const Ve=rs.value;if(!Ve){console.warn("[VoiceInput] editor is null");return}const{state:Ue,view:Ye}=Ve,Xe=Ue.doc.content.size,xt=Math.max(0,Math.min(cr,Xe)),Ot=Math.min(xt+Ui,Xe);let Jt=Ue.tr;Ot>xt&&(Jt=Jt.delete(xt,Ot)),Jt=Jt.insertText(Re,xt);const Ta=Math.min(xt+Re.length,Jt.doc.content.size);Jt=Jt.setSelection(kt.create(Jt.doc,Ta)),Ye.dispatch(Jt),Ye.focus(),Ui=Re.length,n("update:input-message",fs()),n("input-change"),ft(()=>{Ir()})},j.onerror=Te=>{console.warn("[VoiceInput] onerror:",{error:Te.error,message:Te.message}),Te.error!=="aborted"&&(console.warn("[VoiceInput] stopping due to error:",Te.error),Wc())},j.onstart=()=>{},j.onaudiostart=()=>{},j.onsoundstart=()=>{},j.onspeechstart=()=>{},j.onspeechend=()=>{},j.onsoundend=()=>{},j.onaudioend=()=>{},j.onend=()=>{Ln.value=!1,bd.value=null,cr=0,Ui=0},j},T_=()=>{const W=window.AndroidVoiceBridge;if(W){if(Ln.value){W.stopListening();return}const ee=rs.value;cr=ee?ee.state.selection.from:0,Ui=0,W.startListening();return}if(Ln.value){Wc();return}const j=Hk();if(!j){console.warn("[VoiceInput] 浏览器不支持语音识别");return}try{j.start(),bd.value=j,Ln.value=!0}catch(ee){console.warn("[VoiceInput] 启动语音识别失败:",ee),Wc()}},jf=ge(null),bl=new Map,uo=[],ka=new Map,zc=new Map,jc=new Map,kg=new WeakMap,Vf=ge(!1);let Cg=!1,ur=null;const Tg=W=>j=>{W&&(j instanceof HTMLElement?bl.set(W,j):bl.delete(W))},_l=W=>{const j=Math.round(W.getBoundingClientRect().height);return j>0?j:W.offsetHeight>0?W.offsetHeight:34},Gf=()=>ke.value.map(W=>String((W==null?void 0:W.id)||"").trim()).filter(W=>!!W),Uk=()=>{Vf.value=!0,ur!==null&&window.clearTimeout(ur),ur=window.setTimeout(()=>{Vf.value=!1,ur=null,Ks()},YC+40)},wd=W=>{const j=kg.get(W);j&&(clearTimeout(j),kg.delete(W)),W.style.removeProperty("transition"),W.style.removeProperty("transform"),W.style.removeProperty("opacity")},Ag=(W,j,ee,Te,Re)=>{const Ve=()=>{W.style.removeProperty("transition"),j.forEach(Ue=>W.style.removeProperty(Ue)),Re==null||Re()};W.style.transition="none",Object.entries(ee).forEach(([Ue,Ye])=>{W.style.setProperty(Ue,Ye)}),requestAnimationFrame(()=>{W.style.transition=j.map(Ye=>`${Ye} ${YC}ms ${GZ}`).join(", "),Object.entries(Te).forEach(([Ye,Xe])=>{W.style.setProperty(Ye,Xe)});const Ue=window.setTimeout(Ve,YC+40);kg.set(W,Ue)})};let ho=[];oF(()=>{uo.splice(0,uo.length,...ho),ka.clear(),zc.clear(),ho.forEach(W=>{const j=bl.get(W);j!=null&&j.isConnected&&(ka.set(W,j.getBoundingClientRect()),zc.set(W,j))})}),PT(()=>{const W=jf.value,j=Gf();if(!Cg){Cg=!0,ho=[...j],uo.splice(0,uo.length),ka.clear(),zc.clear();return}Uk();const ee=new Set(uo),Te=new Set(j),Re=j.filter(Ue=>!ee.has(Ue)),Ve=uo.filter(Ue=>!Te.has(Ue));!Re.length&&!Ve.length||(Ve.forEach(Ue=>{const Ye=zc.get(Ue),Xe=ka.get(Ue);if(!Ye||!Xe||!(W!=null&&W.isConnected))return;wd(Ye);const xt=jc.get(Ue);xt&&(wd(xt),xt.remove(),jc.delete(Ue));const Ot=Ye.cloneNode(!0),Jt=W.getBoundingClientRect();Ot.style.position="absolute",Ot.style.left="0",Ot.style.top=`${Math.round(Xe.top-Jt.top)}px`,Ot.style.width=`${Math.round(Xe.width>0?Xe.width:Jt.width)}px`,Ot.style.pointerEvents="none",Ot.style.zIndex="0",Ot.style.margin="0",Ot.style.opacity="1",Ot.querySelectorAll("button").forEach(Cl=>{Cl instanceof HTMLButtonElement&&(Cl.disabled=!0)}),W.appendChild(Ot),jc.set(Ue,Ot);const Ta=_l(Ot);Ag(Ot,["transform"],{transform:"translateY(0)"},{transform:`translateY(${Ta}px)`},()=>{jc.delete(Ue),Ot.remove()}),bl.delete(Ue)}),j.forEach(Ue=>{const Ye=bl.get(Ue);if(!(Ye!=null&&Ye.isConnected))return;if(wd(Ye),Re.includes(Ue)){const Jt=_l(Ye);Ag(Ye,["transform"],{transform:`translateY(${Jt}px)`},{transform:"translateY(0)"});return}const Xe=ka.get(Ue);if(!Xe)return;const xt=Ye.getBoundingClientRect(),Ot=Xe.top-xt.top;Math.abs(Ot)<.5||Ag(Ye,["transform"],{transform:`translateY(${Ot}px)`},{transform:"translateY(0)"})}),uo.splice(0,uo.length),ka.clear(),zc.clear(),ho=[...j])});const A_=be(()=>{const W=!!(i.inputMessage||"").trim();if(i.streamingMessage)return W;const j=Array.isArray(i.selectedImages)&&i.selectedImages.length>0,ee=Array.isArray(i.selectedVideos)&&i.selectedVideos.length>0;return W||j||ee}),Wk=be(()=>!!i.streamingMessage&&!A_.value),Eg=be(()=>i.isConnected?i.streamingMessage?!1:i.inputLocked||i.mediaUploading?!0:!A_.value:!0),E_=be(()=>{const W=ke.value.length>0,j=Array.isArray(i.selectedImages)&&i.selectedImages.length>0,ee=Array.isArray(i.selectedVideos)&&i.selectedVideos.length>0,Te=Array.isArray(i.selectedFiles)&&i.selectedFiles.length>0;return W||st.value||gt.value||y.value||se.value||j||ee||Te||!!i.inputIsMultiline||!!i.goalModeArmed||!!i.goalRunning||Kf.value}),Kf=be(()=>{var W;return String(((W=i.goalProgress)==null?void 0:W.status)||"").toLowerCase()==="done"}),Mg=()=>{A.value=!0},xg=()=>{A.value=!1,Ks()},Sd=()=>{A.value=!1,Ks()},zk=be(()=>ke.value.length>0||Vf.value||yl.value||A.value),jk=()=>{const W=a.value,j=l.value;if(!W||!j)return 0;let ee=j.offsetTop,Te=j.offsetTop+j.offsetHeight;const Re=W.querySelector(".skill-slash-menu");if(Re instanceof HTMLElement){const Ue=Re.offsetTop,Ye=Re.offsetTop+Re.offsetHeight;return Math.max(0,Math.max(Te,Ye)-Math.min(ee,Ue))}return W.querySelectorAll(".runtime-queue-list:not(.runtime-queue-list--empty), .floating-status-row, .composer-avatar").forEach(Ue=>{Ue instanceof HTMLElement&&(Ue.classList.contains("floating-status-row")&&!st.value||Ue.classList.contains("composer-avatar")&&!gt.value||(ee=Math.min(ee,Ue.offsetTop),Te=Math.max(Te,Ue.offsetTop+Ue.offsetHeight)))}),Math.max(0,Te-ee)},M_=()=>{const W=l.value;return W?Math.max(0,W.getBoundingClientRect().height):0},Ks=()=>{const W=jk();if(!W)return;const j=M_();E_.value?h.value<=0&&j>0?h.value=j:h.value>0&&j>0?h.value=Math.min(h.value,j):h.value<=0&&(h.value=W):h.value=W;const ee=h.value||W,Te=Math.max(0,W-ee),Ve=Math.ceil(123+Te);n("composer-height-change",{reservedHeight:Ve,visualHeight:W,growth:Te})},Ir=()=>{var Ot;const W=(Ot=a.value)==null?void 0:Ot.querySelector(".stadium-input-editor");if(!W)return;const j=W,ee=j.scrollTop,Te=document.activeElement===j||j.contains(document.activeElement);j.style.height="auto";const Re=window.getComputedStyle(j),Ve=parseFloat(Re.lineHeight||"20")||20,Ue=Ve*10,Ye=Math.min(j.scrollHeight,Ue),Xe=Math.max(1,Math.round(Ye/Ve)),xt=Ye>Ve*1.4;ye(Xe,xt),j.style.height=`${Ye}px`,Vk(j,{previousScrollTop:ee,selectionShouldStayVisible:Te,padding:Math.max(4,Ve*.3)}),ft(()=>{Ks()})},Vk=(W,j)=>{const ee=Math.max(0,W.scrollHeight-W.clientHeight);if(ee<=0){W.scrollTop=0;return}if(!j.selectionShouldStayVisible){W.scrollTop=Math.min(ee,Math.max(0,j.previousScrollTop));return}requestAnimationFrame(()=>{const Te=rs.value;if(!Te){W.scrollTop=Math.min(ee,Math.max(0,j.previousScrollTop));return}try{const Re=Te.view.coordsAtPos(Te.state.selection.head),Ve=W.getBoundingClientRect(),Ue=j.padding,Ye=Math.max(0,W.scrollHeight-W.clientHeight);let Xe=W.scrollTop;Re.bottom>Ve.bottom-Ue?Xe+=Re.bottom-Ve.bottom+Ue:Re.top<Ve.top+Ue&&(Xe-=Ve.top+Ue-Re.top),W.scrollTop=Math.min(Ye,Math.max(0,Xe))}catch{W.scrollTop=Math.min(ee,Math.max(0,j.previousScrollTop))}})},x_=(W,j)=>{const ee=Ko(),Te=rs.value;if(!Te||!ee)return;const Re=Te.schema.nodes.mention;if(!Re)return;const Ve=Re.create({id:`file://${W}`,label:j}),{state:Ue,view:Ye}=Te;let Xe=Ue.tr.delete(ee.start,ee.end);Xe=Xe.insert(ee.start,Ve);const xt=ee.start+Ve.nodeSize;Xe=Xe.insertText(" ",xt),Xe=Xe.setSelection(kt.near(Xe.doc.resolve(xt+1))),Ye.dispatch(Xe),Ye.focus(),Pn(),ft(()=>{Ir()})},Gk=async W=>{var Te;const j=W.target,ee=(j==null?void 0:j.files)||null;if(X.value&&ee&&ee.length>0){X.value=!1;const Re=ee[0];try{const Ue=await(await fetch(`/api/project/files/search?q=${encodeURIComponent(Re.name)}&limit=10`)).json().catch(()=>({})),Ye=Array.isArray((Te=Ue==null?void 0:Ue.data)==null?void 0:Te.items)?Ue.data.items:[],Xe=Ye.find(xt=>xt.name===Re.name)||Ye[0];Xe?lo(Xe):x_(Re.name,Re.name)}catch(Ve){console.warn("[FileAt] 通过文件选择器查找路径失败:",Ve),x_(Re.name,Re.name)}j&&(j.value="");return}n("file-selected",ee),j&&(j.value="")},Kk=()=>{var W;return Es((W=rs.value)==null?void 0:W.getJSON())},Vc=()=>{var W,j;return{editor_json:((W=rs.value)==null?void 0:W.getJSON())||null,skill_refs:Es((j=rs.value)==null?void 0:j.getJSON()).skillRefs}},wl=W=>{const j=rs.value;j&&W!=null&&W.editor_json&&typeof W.editor_json=="object"&&(Oe=!0,j.commands.setContent(W.editor_json),Oe=!1,n("update:input-message",fs()),ft(Ir))},qf=()=>{!i.isConnected||i.uploading||n("quick-upload")},qk=be(()=>{lt.value;const W=(i.permissionOptions||[]).find(j=>j.value===i.currentPermissionMode);return W?S(W.labelKey):i.currentPermissionMode}),R_=be(()=>(lt.value,[{value:"agent",label:S("input.agentType"),description:S("input.agentTypeDesc")},{value:"multi_agent",label:S("input.multiAgentType"),description:S("input.multiAgentTypeDesc")}])),kd=be(()=>!!i.currentConversationId),I_=be(()=>(lt.value,i.currentConversationId?i.currentConversationType==="multi_agent"?S("input.multiAgentType"):S("input.agentType"):i.newConversationType==="multi_agent"?S("input.multiAgentType"):S("input.agentType"))),Cd=be(()=>!!i.streamingMessage),z=be(()=>{lt.value;const W=(i.workModeOptions||[]).find(j=>j.value===i.currentWorkMode);return W?S(W.labelKey):i.currentWorkMode||S("input.workModePlanFallback")}),ie=be(()=>i.currentWorkMode==="plan"),te=be(()=>i.currentPermissionMode!=="unrestricted"),de=be(()=>ie.value||te.value),Ee=ge(null),fe=ge(null),Qe=ge(!1),vt=ge("0px");async function Pt(){if(Qe.value=!1,!i.permissionMenuOpen||!window.matchMedia("(max-width: 768px)").matches)return;await ft();const W=Ee.value,j=fe.value;if(!W||!j)return;const ee=W.getBoundingClientRect(),Te=j.offsetWidth;if(ee.right-Te<8){const Ve=(window.innerWidth-Te)/2-ee.left;vt.value=`${Math.round(Ve)}px`,Qe.value=!0}}function Lt(){i.permissionMenuOpen&&Pt()}Ke(()=>i.permissionMenuOpen,W=>{W&&Pt()});const Bs=be(()=>{lt.value;const W=String(i.currentExecutionMode||"");return W==="direct"?S("input.executionFullAccess"):W==="sandbox"?S("input.executionSandbox"):W}),Fs=be(()=>{const j=(Array.isArray(i.modelOptions)?i.modelOptions:[]).find(ee=>ee.key===i.currentModelKey);return Number((j==null?void 0:j.contextWindow)||0)}),fo=be(()=>{var W;return!!((W=o==null?void 0:o.form)!=null&&W.auto_deep_compress_enabled)}),Jo=be(()=>{var j;const W=Number(((j=o==null?void 0:o.form)==null?void 0:j.deep_compress_trigger_tokens)||0);return W>0?W:15e4}),Sl=be(()=>fo.value?Jo.value:Fs.value>0?Fs.value:0),Ca=be(()=>{const W=Number(Sl.value||0);if(W<=0)return 0;const j=Math.max(0,Number(i.currentContextTokens||0));return Math.max(0,Math.min(100,j/W*100))}),kl=be(()=>`${Math.round(Ca.value)}%`),po=be(()=>{const W=Ca.value;return W<40?"var(--state-success)":W<=80?"var(--state-warning)":"var(--state-danger)"}),Rg=W=>{const j=Math.max(0,Number(W||0));if(j>=1e3){const ee=j/1e3;return`${ee>=100?Math.round(ee).toString():ee.toFixed(1).replace(/\.0$/,"")}k`}return`${Math.round(j)}`},P_=be(()=>{const W=Rg(i.currentContextTokens||0),j=Number(Sl.value||0);return j<=0?`${W}/--`:`${W}/${Rg(j)}`});return e({inputAreaRoot:a,stadiumShellOuter:c,compactInputShell:l,stadiumInput:u,fileUploadInput:d,emitComposerHeight:Ks,prepareMessageForSend:Kk,getComposerDraftMeta:Vc,restoreComposerDraftMeta:wl}),Ke(()=>i.inputMessage,async()=>{const W=rs.value;W&&!Oe&&fs()!==(i.inputMessage||"")&&(Oe=!0,W.commands.setContent(mi(i.inputMessage||"")),Oe=!1),await ft(),Ir(),Me()}),Ke(()=>i.isConnected,async W=>{var j,ee;(j=rs.value)==null||j.setEditable(!!W&&!i.inputLocked),W||(ee=rs.value)==null||ee.commands.blur(),await ft(),Ir()}),Ke(()=>i.inputLocked,W=>{var j;(j=rs.value)==null||j.setEditable(i.isConnected&&!W)}),Ke(()=>i.currentConversationId,async()=>{h.value=0,await ft(),Ks()}),Ke(()=>i.runtimeQueuedMessages,async()=>{await ft(),Ks()},{deep:!0}),Ke(()=>i.projectGitSummary,async()=>{Le.value||Qt(),await ft(),Ks()},{deep:!0}),Ke(st,async()=>{await ft(),Ks(),window.setTimeout(()=>{Ks()},280)}),Ke(gt,async()=>{await ft(),Ks(),window.setTimeout(()=>{Ks()},280)}),Ke(()=>{var W;return(W=i.avatarStatus)==null?void 0:W.mode},()=>{var W;((W=i.avatarStatus)==null?void 0:W.mode)!=="idle"&&qo()}),Ke(()=>{var W,j;return[((W=i.selectedImages)==null?void 0:W.length)||0,((j=i.selectedVideos)==null?void 0:j.length)||0]},async()=>{await ft(),Ks()}),Ke(zk,async()=>{await ft(),Ks()}),Ke(()=>i.streamingMessage||i.inputLocked,W=>{W&&Ln.value&&Wc()}),dn(()=>{document.addEventListener("click",Qt),window.addEventListener("resize",Lt),Ir(),ft(()=>{Ks(),typeof ResizeObserver<"u"&&(rt=new ResizeObserver(()=>{Ks()}),a.value&&rt.observe(a.value),c.value&&rt.observe(c.value),l.value&&rt.observe(l.value))})}),Rn(()=>{var W;Wc(),document.removeEventListener("click",Qt),window.removeEventListener("resize",Lt),(W=rs.value)==null||W.destroy(),bl.forEach(j=>{j&&wd(j)}),jc.forEach(j=>{wd(j),j.remove()}),jc.clear(),bl.clear(),uo.splice(0,uo.length),ka.clear(),zc.clear(),Cg=!1,ho=[],ur!==null&&(window.clearTimeout(ur),ur=null),Vf.value=!1,rt&&(rt.disconnect(),rt=null),qo()}),(W,j)=>(F(),U("div",{class:"input-area compact-input-area",ref_key:"inputAreaRoot",ref:a},[M("div",{class:"stadium-input-wrapper",ref_key:"stadiumShellOuter",ref:c},[M("div",{class:Ce(["runtime-queue-list",{"runtime-queue-list--empty":!ke.value.length}]),ref_key:"runtimeQueueList",ref:jf},[(F(!0),U(Ie,null,Ze(ke.value,(ee,Te)=>(F(),U("div",{key:ee.id,class:Ce(["runtime-queue-item",{"runtime-queue-item--top":Te===0}]),"data-runtime-queue-id":ee.id||"",ref_for:!0,ref:Tg(ee.id)},[M("span",BJ,Q(ee.text||""),1),M("button",{type:"button",class:"runtime-queue-item__action",onClick:De(Re=>W.$emit("guide-runtime-message",ee.id),["stop"])},Q(W.$t("input.guide")),9,FJ),M("button",{type:"button",class:"runtime-queue-item__action runtime-queue-item__action--danger",onClick:De(Re=>W.$emit("delete-runtime-message",ee.id),["stop"])},Q(W.$t("common.delete")),9,HJ)],10,$J))),128))],2),We(gs,{name:"skill-slash-menu-motion",onBeforeEnter:Mg,onBeforeLeave:Mg,onAfterEnter:xg,onAfterLeave:Sd},{default:Gt(()=>[yl.value?(F(),U("div",{key:w.value,class:"skill-slash-menu-wrapper",role:"listbox","aria-label":Hi.value},[M("div",{ref_key:"skillSlashList",ref:k,class:"skill-slash-menu",onScroll:at},[(F(!0),U(Ie,null,Ze(mn.value,(ee,Te)=>(F(),U("button",{key:ee.id,type:"button",class:Ce(["skill-slash-item",{"skill-slash-item--active":Te===b.value&&!E.value,"skill-slash-item--disabled":ee.disabled}]),role:"option","aria-selected":Te===b.value,disabled:ee.disabled,onMousedown:De(Re=>Bt(Te),["prevent"])},[M("span",zJ,Q(ee.label),1),M("span",jJ,Q(ee.description),1)],42,WJ))),128)),mn.value.length?me("",!0):(F(),U("div",VJ,Q(Sa.value),1))],544),M("div",{class:"skill-slash-menu__highlight",style:qe(Pe.value)},null,4)],8,UJ)):me("",!0)]),_:1}),We(TJ,{ref_key:"fileAtMenuRef",ref:K,visible:se.value,items:le.value,"active-index":ve.value,loading:ue.value,"host-mode":!!i.hostMode,"menu-style":P.value,onSelect:Ni,onHover:j[0]||(j[0]=ee=>ve.value=ee)},null,8,["visible","items","active-index","loading","host-mode","menu-style"]),We(gs,{name:"floating-status-motion"},{default:Gt(()=>[gt.value?(F(),U("div",{key:0,class:"composer-avatar",onClick:De(Yn,["stop"])},[We(GD,{mode:i.avatarStatus.mode,"tool-keys":i.avatarStatus.toolKeys||[],tracking:i.avatarStatus.tracking!==!1,size:45,"hex-background":""},null,8,["mode","tool-keys","tracking"]),We(gs,{name:"composer-avatar-text-fade",mode:"out-in"},{default:Gt(()=>[ne.value?(F(),U("span",{key:`poke-${ne.value}`,class:Ce(["composer-avatar__text",{"composer-avatar__text--right":!st.value,"composer-avatar__text--top":st.value}])},Q(ne.value),3)):Wt.value?(F(),U("span",{key:jt.value,class:Ce(["composer-avatar__text",{"composer-avatar__text--right":!st.value,"composer-avatar__text--top":st.value}])},Q(Wt.value),3)):me("",!0)]),_:1})])):me("",!0)]),_:1}),We(gs,{name:"floating-status-motion"},{default:Gt(()=>[st.value?(F(),U("div",{key:0,class:"floating-status-row",onClick:j[11]||(j[11]=De(()=>{},["stop"]))},[M("div",{class:"floating-project-status",onClick:j[10]||(j[10]=De(()=>{},["stop"]))},[Le.value?(F(),U("span",GJ,[M("span",KJ,[M("button",{type:"button",class:Ce(["floating-project-status__button floating-project-status__button--project",{"floating-project-status__button--active":ht.value==="project"}]),onClick:j[1]||(j[1]=De(ee=>It("project"),["stop"]))},Q(Le.value.projectName),3),ht.value==="project"?(F(),U("div",{key:0,class:"floating-project-status__submenu floating-project-status__submenu--project",onClick:j[2]||(j[2]=De(()=>{},["stop"]))},[M("button",{type:"button",onClick:De(Er,["stop"])},Q(W.$t("input.openInFileManager")),1),M("button",{type:"button",onClick:De(ot,["stop"])},Q(W.$t("input.copyPath")),1)])):me("",!0)]),M("span",qJ,[M("button",{type:"button",class:Ce(["floating-project-status__button floating-project-status__button--branch",{"floating-project-status__button--active":ht.value==="branch"}]),onClick:j[3]||(j[3]=De(ee=>It("branch"),["stop"]))},Q(Le.value.branch),3),ht.value==="branch"?(F(),U("div",{key:0,class:"floating-project-status__submenu floating-project-status__submenu--branch",onClick:j[4]||(j[4]=De(()=>{},["stop"]))},[M("button",{type:"button",onClick:De($s,["stop"])},Q(W.$t("input.copyBranchName")),1)])):me("",!0)])])):me("",!0),M("span",QJ,[s.goalRunning?(F(),U("span",XJ,Q(W.$t("input.goalModeRunning")),1)):s.goalModeArmed?(F(),U("span",YJ,Q(W.$t("input.goalModeReady")),1)):me("",!0),s.pendingUserQuestionCount>0?(F(),U("button",{key:2,type:"button",class:"floating-project-status__notice floating-project-status__notice--button",onClick:j[5]||(j[5]=De(ee=>W.$emit("restore-user-question"),["stop"]))},Q(W.$t("input.waitingForQuestion")),1)):me("",!0),s.planApprovalMinimized&&(s.pendingPlanApprovalCount||0)>0?(F(),U("button",{key:3,type:"button",class:"floating-project-status__notice floating-project-status__notice--button",onClick:j[6]||(j[6]=De(ee=>W.$emit("restore-plan-approval"),["stop"]))},Q(W.$t("input.planApprovalPending")),1)):me("",!0),(s.activeSubAgentCount||0)>0?(F(),U("button",{key:4,type:"button",class:"floating-project-status__notice floating-project-status__notice--button",onClick:j[7]||(j[7]=De(ee=>W.$emit("stop-all-sub-agents"),["stop"]))},Q(W.$t("input.subAgentsRunning",{n:s.activeSubAgentCount})),1)):me("",!0),s.terminalCount>0?(F(),U("button",{key:5,type:"button",class:"floating-project-status__terminal",onClick:j[8]||(j[8]=De(ee=>W.$emit("realtime-terminal"),["stop"]))},Q(W.$t("input.terminalsRunning",{n:s.terminalCount})),1)):me("",!0),Le.value?(F(),U("button",{key:6,type:"button",class:"floating-project-status__stats",onClick:j[9]||(j[9]=De(ee=>W.$emit("open-git-changes-panel"),["stop"]))},[M("span",JJ,[j[42]||(j[42]=cn("+",-1)),We(cI,{value:Le.value.additions},null,8,["value"])]),M("span",ZJ,[j[43]||(j[43]=cn("-",-1)),We(cI,{value:Le.value.deletions},null,8,["value"])])])):me("",!0)])])])):me("",!0)]),_:1}),M("div",{class:Ce(["stadium-shell",{"is-multiline":s.inputIsMultiline,"is-focused":s.inputIsFocused,"has-text":(s.inputMessage||"").trim().length>0}]),ref_key:"compactInputShell",ref:l},[M("input",{type:"file",ref_key:"fileUploadInput",ref:d,class:"file-input-hidden",multiple:"",onChange:Gk},null,544),M("div",eZ,[s.selectedImages&&s.selectedImages.length||s.selectedFiles&&s.selectedFiles.length?(F(),U("div",tZ,[(F(!0),U(Ie,null,Ze(s.selectedImages,ee=>(F(),U("div",{class:"image-thumbnail-wrapper",key:ee,onClick:De(Te=>pe(ee),["stop"])},[M("img",{src:he(ee),alt:xe(ee),class:"image-thumbnail"},null,8,nZ),M("button",{type:"button",class:"image-remove-btn-hover",onClick:De(Te=>W.$emit("remove-image",ee),["stop"])},[...j[44]||(j[44]=[M("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none","aria-hidden":"true"},[M("path",{d:"M2.5 2.5l5 5M7.5 2.5l-5 5",stroke:"currentColor","stroke-width":"1.5","stroke-linecap":"round"})],-1)])],8,iZ)],8,sZ))),128)),s.selectedFiles&&s.selectedFiles.length?(F(),Ft(AL,{key:0,files:s.selectedFiles,removable:"",onRemove:j[12]||(j[12]=ee=>W.$emit("remove-file",ee))},null,8,["files"])):me("",!0)])):me("",!0),s.selectedVideos&&s.selectedVideos.length?(F(),U("div",rZ,[(F(!0),U(Ie,null,Ze(s.selectedVideos,ee=>(F(),U("div",{class:"image-thumbnail-wrapper",key:ee},[M("img",{src:he(ee),alt:xe(ee),class:"image-thumbnail"},null,8,oZ),M("button",{type:"button",class:"image-remove-btn-hover",onClick:De(Te=>W.$emit("remove-video",ee),["stop"])},[...j[45]||(j[45]=[M("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none","aria-hidden":"true"},[M("path",{d:"M2.5 2.5l5 5M7.5 2.5l-5 5",stroke:"currentColor","stroke-width":"1.5","stroke-linecap":"round"})],-1)])],8,aZ)]))),128))])):me("",!0),M("div",lZ,[M("div",cZ,[We(Ne(KQ),{editor:Ne(rs),class:Ce(["stadium-input stadium-input-tiptap",{"is-disabled":!s.isConnected||s.inputLocked}]),onFocusin:j[13]||(j[13]=ee=>W.$emit("input-focus")),onFocusout:Cs},null,8,["editor","class"])])]),M("div",uZ,[M("div",dZ,[M("button",{type:"button",class:"stadium-btn add-btn","data-tutorial":"quick-menu-open",onClick:j[14]||(j[14]=De(ee=>W.$emit("toggle-quick-menu"),["stop"])),disabled:!s.isConnected,"aria-label":W.$t("input.quickMenuAriaLabel")},[...j[46]||(j[46]=[M("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"},[M("path",{d:"M5 12h14"}),M("path",{d:"M12 5v14"})],-1)])],8,hZ),M("div",{class:Ce(["agent-type-switcher",{"is-disabled":kd.value}])},[M("button",{type:"button",class:"agent-type-switcher__btn",onClick:j[15]||(j[15]=De(ee=>W.$emit("toggle-agent-type-menu"),["stop"])),disabled:!s.isConnected||kd.value,"aria-expanded":s.agentTypeMenuOpen,"aria-haspopup":"true"},[M("span",null,Q(I_.value),1),M("span",{class:Ce(["agent-type-switcher__caret",{open:s.agentTypeMenuOpen}]),"aria-hidden":"true"},"›",2)],8,fZ),s.agentTypeMenuOpen&&!kd.value?(F(),U("div",{key:0,class:"agent-type-switcher__menu",onClick:j[16]||(j[16]=De(()=>{},["stop"]))},[(F(!0),U(Ie,null,Ze(R_.value,ee=>(F(),U("button",{key:ee.value,type:"button",class:Ce(["agent-type-switcher__menu-item",{"is-active":ee.value===s.newConversationType}]),onClick:De(Te=>W.$emit("select-new-conversation-type",ee.value),["stop"])},[M("span",mZ,Q(ee.label),1),M("span",gZ,Q(ee.description),1)],10,pZ))),128))])):me("",!0)],2),M("div",{class:Ce(["agent-type-switcher work-mode-switcher",{"is-disabled":Cd.value}])},[M("button",{type:"button",class:"agent-type-switcher__btn",onClick:j[17]||(j[17]=De(ee=>W.$emit("toggle-work-mode-menu"),["stop"])),disabled:!s.isConnected||Cd.value,"aria-expanded":s.workModeMenuOpen,"aria-haspopup":"true",title:Cd.value?W.$t("input.workModeLockedTitle"):W.$t("input.workModeTitle")},[M("span",null,Q(z.value),1),M("span",{class:Ce(["agent-type-switcher__caret",{open:s.workModeMenuOpen}]),"aria-hidden":"true"},"›",2)],8,vZ),s.workModeMenuOpen&&!Cd.value?(F(),U("div",{key:0,class:"agent-type-switcher__menu",onClick:j[18]||(j[18]=De(()=>{},["stop"]))},[(F(!0),U(Ie,null,Ze(s.workModeOptions,ee=>(F(),U("button",{key:ee.value,type:"button",class:Ce(["agent-type-switcher__menu-item",{"is-active":ee.value===s.currentWorkMode}]),onClick:De(Te=>W.$emit("change-work-mode",ee.value),["stop"])},[M("span",bZ,Q(W.$t(ee.labelKey)),1),M("span",_Z,Q(W.$t(ee.descriptionKey)),1)],10,yZ))),128))])):me("",!0)],2)]),M("div",wZ,[_d.value?(F(),U("button",{key:0,type:"button",class:Ce(["stadium-btn voice-btn",{"voice-btn--recording":Ln.value,"voice-btn--disabled":Rr.value==="downloading"||Rr.value==="model_not_ready"}]),onClick:T_,disabled:!s.isConnected||s.inputLocked,title:k_.value},[Ln.value?(F(),U("div",CZ,[...j[48]||(j[48]=[M("span",{class:"voice-wave-bar"},null,-1),M("span",{class:"voice-wave-bar"},null,-1),M("span",{class:"voice-wave-bar"},null,-1),M("span",{class:"voice-wave-bar"},null,-1)])])):(F(),U("svg",kZ,[...j[47]||(j[47]=[M("path",{d:"M12 19v3m7-12v2a7 7 0 0 1-14 0v-2"},null,-1),M("rect",{width:"6",height:"13",x:"9",y:"2",rx:"3"},null,-1)])]))],10,SZ)):me("",!0),M("button",{type:"button",class:"stadium-btn send-btn",onClick:j[19]||(j[19]=ee=>W.$emit("send-or-stop")),disabled:Eg.value},[Wk.value?(F(),U("span",AZ)):(F(),U("span",EZ))],8,TZ)])])])],2),We(WL,{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:qf,onPickImages:j[20]||(j[20]=ee=>W.$emit("pick-images")),onPickVideo:j[21]||(j[21]=ee=>W.$emit("pick-video")),onToggleToolMenu:j[22]||(j[22]=ee=>W.$emit("toggle-tool-menu")),onToggleSettings:j[23]||(j[23]=ee=>W.$emit("toggle-settings")),onToggleModeMenu:j[24]||(j[24]=ee=>W.$emit("toggle-mode-menu")),onSelectRunMode:j[25]||(j[25]=ee=>W.$emit("select-run-mode",ee)),onToggleModelMenu:j[26]||(j[26]=ee=>W.$emit("toggle-model-menu")),onSelectModel:j[27]||(j[27]=ee=>W.$emit("select-model",ee)),onUpdateToolCategory:j[28]||(j[28]=(ee,Te)=>W.$emit("update-tool-category",ee,Te)),onRealtimeTerminal:j[29]||(j[29]=ee=>W.$emit("realtime-terminal")),onToggleFocusPanel:j[30]||(j[30]=ee=>W.$emit("toggle-focus-panel")),onToggleTokenPanel:j[31]||(j[31]=ee=>W.$emit("toggle-token-panel",ee)),onCompressConversation:j[32]||(j[32]=ee=>W.$emit("compress-conversation")),onToggleApprovalPanel:j[33]||(j[33]=ee=>W.$emit("toggle-approval-panel")),onOpenReview:j[34]||(j[34]=ee=>W.$emit("open-review")),onOpenPathAuthorization:j[35]||(j[35]=ee=>W.$emit("open-path-authorization")),onToggleGoalMode:j[36]||(j[36]=ee=>W.$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"]),M("div",{class:"permission-switcher",onClick:j[39]||(j[39]=De(()=>{},["stop"]))},[M("button",{type:"button",class:"permission-switcher__btn",disabled:!s.isConnected||s.streamingMessage,onClick:j[37]||(j[37]=ee=>W.$emit("open-versioning-dialog"))},[M("span",null,Q(W.$t("input.versionControl")),1)],8,MZ),M("div",{ref_key:"permissionBlockEl",ref:Ee,class:"permission-switcher__block"},[M("button",{type:"button",class:"permission-switcher__btn",disabled:!s.isConnected,title:ie.value?W.$t("input.permissionLockedByPlanTitle"):te.value?W.$t("input.executionLockedRestrictedTitle"):"",onClick:j[38]||(j[38]=ee=>W.$emit("toggle-permission-menu"))},[ie.value||te.value?(F(),U("svg",RZ,[...j[49]||(j[49]=[M("rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2"},null,-1),M("path",{d:"M7 11V7a5 5 0 0 1 10 0v4"},null,-1)])])):me("",!0),M("span",null,Q(qk.value),1),s.executionModeEnabled?(F(),U("span",{key:1,class:Ce(["permission-switcher__exec",{"permission-switcher__exec--warn":s.currentExecutionMode==="direct"}])},Q(Bs.value),3)):me("",!0),M("span",{class:Ce(["permission-switcher__caret",{open:s.permissionMenuOpen}])},"›",2)],8,xZ),s.permissionMenuOpen?(F(),U("div",{key:0,ref_key:"permissionMenuEl",ref:fe,class:Ce(["permission-switcher__menu",{"permission-switcher__menu--split":s.executionModeEnabled,"permission-switcher__menu--centered":Qe.value}]),style:qe(Qe.value?{left:vt.value,right:"auto"}:void 0)},[M("div",{class:Ce(["permission-switcher__group",{"permission-switcher__group--disabled":ie.value}])},[M("div",IZ,[cn(Q(W.$t("input.permissionGroup")),1),ie.value?(F(),U("span",PZ,Q(W.$t("input.planModeLocked")),1)):me("",!0)]),(F(!0),U(Ie,null,Ze(s.permissionOptions,ee=>(F(),U("button",{key:`permission-${ee.value}`,type:"button",class:Ce(["permission-switcher__item",{active:ee.value===s.currentPermissionMode}]),disabled:ie.value,onClick:Te=>W.$emit("change-permission-mode",ee.value)},[M("span",OZ,Q(W.$t(ee.labelKey)),1),M("span",DZ,Q(W.$t(ee.descriptionKey)),1)],10,LZ))),128))],2),s.executionModeEnabled?(F(),U("div",{key:0,class:Ce(["permission-switcher__group",{"permission-switcher__group--disabled":de.value}])},[M("div",NZ,[cn(Q(W.$t("input.executionEnv"))+" ",1),ie.value?(F(),U("span",$Z,Q(W.$t("input.planModeLocked")),1)):te.value?(F(),U("span",BZ,Q(W.$t("input.restrictedModeLocked")),1)):me("",!0)]),(F(!0),U(Ie,null,Ze(s.executionModeOptions,ee=>(F(),U("button",{key:`execution-${ee.value}`,type:"button",class:Ce(["permission-switcher__item",{active:ee.value===s.currentExecutionMode}]),disabled:de.value,onClick:Te=>W.$emit("change-execution-mode",ee.value)},[M("span",{class:Ce(["permission-switcher__item-label",{"permission-switcher__item-label--warn":ee.value==="direct"}])},Q(W.$t(ee.labelKey)),3),M("span",HZ,Q(W.$t(ee.descriptionKey)),1)],10,FZ))),128))],2)):me("",!0),s.networkPermissionEnabled?(F(),U("div",{key:1,class:Ce(["permission-switcher__group",{"permission-switcher__group--disabled":s.currentExecutionMode==="direct"}])},[M("div",UZ,Q(W.$t("input.networkPermission")),1),(F(!0),U(Ie,null,Ze(s.networkPermissionOptions,ee=>(F(),U("button",{key:`network-${ee.value}`,type:"button",class:Ce(["permission-switcher__item",{active:ee.value===s.currentNetworkPermission}]),disabled:s.currentExecutionMode==="direct",onClick:Te=>W.$emit("change-network-permission",ee.value)},[M("span",{class:Ce(["permission-switcher__item-label",{"permission-switcher__item-label--warn":ee.value==="full"}])},Q(W.$t(ee.labelKey)),3),M("span",zZ,Q(W.$t(ee.descriptionKey)),1)],10,WZ))),128))],2)):me("",!0)],6)):me("",!0)],512)]),M("div",{class:"context-usage-switcher",onClick:j[41]||(j[41]=De(()=>{},["stop"]))},[M("button",{type:"button",class:"context-usage-switcher__btn",disabled:!s.isConnected,onClick:j[40]||(j[40]=ee=>W.$emit("toggle-token-panel"))},[M("span",{class:"context-usage-ring",style:qe({"--context-progress":`${Ca.value}%`,"--context-ring-color":po.value}),"aria-hidden":"true"},[...j[50]||(j[50]=[M("span",{class:"context-usage-ring__inner"},null,-1)])],4)],8,jZ),M("div",VZ,[M("div",null,Q(W.$t("input.usedPercent",{n:kl.value})),1),M("div",null,Q(P_.value),1)])])],512)],512))}}),qZ=qt(KZ,[["__scopeId","data-v-e9e814be"]]),QZ={class:"effort-header"},XZ={class:"header-state header-idle"},YZ={class:"header-title"},JZ={class:"default-label"},ZZ={class:"header-state header-drag"},eee={class:"slider-zone"},tee={class:"level-labels"},go=20,see=200,nee=ct({__name:"EffortSlider",props:{modelValue:{}},emits:["update:modelValue"],setup(s,{emit:e}){const t=["low","medium","high","xhigh","max"],n=s,i=e,r=ge(null),o=ge(null),a=ge(null),c=[],l=(L,K)=>{c[K]=L??null},u=ge(0),d=ge(2),h=ge(2),p=ge(!1),g=ge(!1);let v=0,m=0,y=0;const _=be(()=>n.modelValue===null),b=L=>L/(t.length-1),k=L=>`calc(${go}px + (100% - ${go*2}px) * ${b(L)})`,w=L=>go+(u.value-go*2)*b(L),T=L=>{const K=u.value;if(K<=go*2)return 0;const se=(L-go)/(K-go*2);return Math.max(0,Math.min(t.length-1,Math.round(se*(t.length-1))))},A=L=>{const K=r.value;if(!K)return go;const se=K.getBoundingClientRect(),oe=L-se.left;return Math.max(go,Math.min(se.width-go,oe))},C=L=>L<.5?2*L*L:1-(-2*L+2)**2/2,E=L=>{const K=u.value>go*2,se=K?`${L}px`:k(d.value),oe=o.value;oe&&(oe.style.transform=`translate(calc(${se} - 50%), -50%)`);const ve=a.value;ve&&(ve.style.clipPath=`inset(0 calc(100% - (${se})) 0 0 round 17px)`);for(let le=0;le<t.length;le++){const ue=c[le];if(!ue)continue;const P=K?w(le)<=L:le<=d.value;ue.classList.toggle("covered",P)}},x=()=>{m&&(cancelAnimationFrame(m),m=0)},D=L=>{x(),y=L,E(L)},N=L=>{const K=y;if(K===L)return;x();const se=performance.now(),oe=ve=>{const le=Math.min(1,(ve-se)/see);y=K+(L-K)*C(le),E(y),le<1?m=requestAnimationFrame(oe):m=0};m=requestAnimationFrame(oe)},O=(L=!1)=>{const K=w(d.value);h.value=d.value,L&&u.value>go*2?N(K):D(K)},G=()=>{i("update:modelValue",t[d.value])},Z=L=>{var K;p.value=!0,g.value=!1,v=L.clientX,(K=r.value)==null||K.setPointerCapture(L.pointerId),d.value=T(A(L.clientX)),G(),O(!0)},q=L=>{if(p.value&&(!g.value&&Math.abs(L.clientX-v)>3&&(g.value=!0),g.value)){const K=A(L.clientX);x(),y=K,E(K),h.value=T(K)}},V=L=>{if(p.value){if(p.value=!1,g.value){g.value=!1,d.value=T(A(L.clientX)),G(),O(!0);return}O(!0)}},I=()=>{i("update:modelValue",_.value?t[d.value]:null)},$=()=>{var L;u.value=((L=r.value)==null?void 0:L.clientWidth)??0,O()};return Ke(()=>n.modelValue,L=>{if(L===null)return;const K=t.indexOf(L);K<0||K===d.value||(d.value=K,O(!1))},{immediate:!0}),dn(()=>{$(),window.addEventListener("resize",$)}),Rn(()=>{x(),window.removeEventListener("resize",$)}),(L,K)=>(F(),U("div",{class:Ce(["effort-slider",{"is-default":_.value,"live-drag":g.value}])},[M("div",QZ,[M("div",XZ,[M("span",YZ,Q(L.$t("quickdock.effortTitle")),1),M("span",{class:Ce(["default-toggle",{checked:_.value}]),onClick:De(I,["stop"])},[M("span",JZ,Q(L.$t("quickdock.effortDefault")),1),We(mF,{checked:_.value,size:14},null,8,["checked"])],2)]),M("div",ZZ,[M("span",null,Q(L.$t("quickdock.effortMoreEfficient")),1),M("span",null,Q(L.$t("quickdock.effortMoreIntelligent")),1)])]),M("div",eee,[M("div",{ref_key:"trackRef",ref:r,class:"track",onPointerdown:Z,onPointermove:q,onPointerup:V,onPointercancel:V},[M("div",{ref_key:"fillRef",ref:a,class:"fill-stack"},[(F(),U(Ie,null,Ze(t,(se,oe)=>M("div",{key:`lv-${oe}`,class:Ce(["fill-layer",[`lv-${oe}`,{on:oe===h.value}]])},null,2)),64))],512),(F(),U(Ie,null,Ze(t,(se,oe)=>M("div",{key:`dot-${oe}`,class:"dot",ref_for:!0,ref:ve=>l(ve,oe),style:qe({left:k(oe)})},null,4)),64)),M("div",{ref_key:"knobRef",ref:o,class:"knob"},null,512)],544),M("div",tee,[(F(),U(Ie,null,Ze(t,(se,oe)=>M("span",{key:`label-${oe}`,class:Ce(["level-label",{active:oe===h.value}]),style:qe({left:k(oe)})},Q(se),7)),64))])])],2))}}),iee=qt(nee,[["__scopeId","data-v-c614d0e4"]]),ree={class:"confirm-modal"},oee={class:"confirm-title"},aee={class:"confirm-message"},lee={key:0,class:"confirm-warning"},cee=ct({__name:"ConfirmDialog",setup(s){const e=Is(),{confirmDialog:t}=xi(e),n=i=>e.resolveConfirm(i);return(i,r)=>(F(),Ft(gs,{name:"confirm-dialog-fade"},{default:Gt(()=>{var o;return[(o=Ne(t))!=null&&o.visible?(F(),U("div",{key:0,class:"confirm-overlay",onClick:r[2]||(r[2]=De(a=>{var c;return((c=Ne(t))==null?void 0:c.closeOnBackdrop)!==!1&&n(!1)},["self"]))},[M("div",ree,[M("div",oee,Q(Ne(t).title||i.$t("shell.confirmOperation")),1),M("div",aee,Q(Ne(t).message),1),Ne(t).warningText?(F(),U("div",lee,Q(Ne(t).warningText),1)):me("",!0),M("div",{class:Ce(["confirm-actions",{"confirm-actions--confirm-left":Ne(t).confirmOnLeft}])},[M("button",{type:"button",class:"confirm-button confirm-button--cancel",onClick:r[0]||(r[0]=a=>n(!1))},Q(Ne(t).cancelText||i.$t("common.cancel")),1),M("button",{type:"button",class:Ce(["confirm-button confirm-button--confirm",Ne(t).confirmVariant==="danger"?"confirm-button--danger":"confirm-button--primary"]),onClick:r[1]||(r[1]=a=>n(!0))},Q(Ne(t).confirmText||i.$t("common.confirm")),3)],2)])])):me("",!0)]}),_:1}))}});let nw=null;function lv(){const s=Is(),e=o=>{nw=o,o||t()},t=()=>{const o=s.easterEgg;o.cleanupTimer&&clearTimeout(o.cleanupTimer);const a=nw;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:nw})}catch(d){return console.warn("销毁彩蛋时发生错误:",d),s.setEasterEggState({destroying:!1}),t(),Promise.resolve()}const u=()=>{s.setEasterEggState({destroyPromise:null,destroying:!1}),t()};if(l&&typeof l.then=="function"){const d=l.then(()=>{u()}).catch(h=>{console.warn("彩蛋清理失败:",h),u()});return s.setEasterEggState({destroyPromise:d}),d}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=nw;if(!u){console.warn("未找到彩蛋根节点");return}await n(!0),s.setEasterEggState({active:!0,effect:o,payload:a});const d=l.start(o,{root:u,payload:a,app:c});if(!d){t();return}s.setEasterEggState({instance:d,destroyPromise:null,destroying:!1}),s.easterEgg.cleanupTimer&&clearTimeout(s.easterEgg.cleanupTimer);const h=Math.max(8,Number(a==null?void 0:a.duration_seconds)||45),p=setTimeout(()=>{const g=n(!1);g&&typeof g.catch=="function"&&g.catch(()=>{})},h*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 uee=ct({__name:"EasterEggOverlay",setup(s){const e=Is(),{easterEgg:t}=xi(e),n=ge(null),i=lv();return dn(()=>{i.registerOverlayRoot(n.value)}),Rn(()=>{i.registerOverlayRoot(null)}),(r,o)=>(F(),U("div",{class:Ce(["easter-egg-overlay",{active:Ne(t).active}]),"aria-hidden":"true",ref_key:"overlayRoot",ref:n},null,2))}}),dee=["disabled"],hee=ct({__name:"FileContextMenu",props:{downloadFile:{type:Function},downloadFolder:{type:Function}},setup(s){const e=s,t=Pc(),{contextMenu:n}=xi(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 dn(()=>{document.addEventListener("click",o),window.addEventListener("scroll",a,!0),document.addEventListener("keydown",c)}),Rn(()=>{document.removeEventListener("click",o),window.removeEventListener("scroll",a,!0),document.removeEventListener("keydown",c)}),(l,u)=>Ne(n).visible?(F(),U("div",{key:0,class:"context-menu",style:qe({top:Ne(n).y+"px",left:Ne(n).x+"px"}),onClick:u[0]||(u[0]=De(()=>{},["stop"]))},[Ne(n).node&&Ne(n).node.type==="file"?(F(),U("button",{key:0,type:"button",onClick:De(i,["stop"])},Q(l.$t("shell.downloadFile")),1)):me("",!0),Ne(n).node&&Ne(n).node.type==="folder"?(F(),U("button",{key:1,type:"button",disabled:!Ne(n).node.path,onClick:De(r,["stop"])},Q(l.$t("shell.downloadArchive")),9,dee)):me("",!0)],4)):me("",!0)}}),fee={key:0,class:"quota-toast"},pee={class:"quota-toast-label"},mee=ct({__name:"QuotaToast",setup(s){const e=Is(),{quotaToast:t}=xi(e),n=()=>e.dismissQuotaToast();return(i,r)=>(F(),Ft(gs,{name:"quota-toast-fade"},{default:Gt(()=>[Ne(t)?(F(),U("div",fee,[M("span",pee,Q(Ne(t).message),1),We(ml,{size:"sm",label:i.$t("shell.closeNotification"),onClick:n},null,8,["label"])])):me("",!0)]),_:1}))}}),gee={class:"app-toast-body"},vee={key:0,class:"app-toast-title"},yee={class:"app-toast-message"},bee=ct({__name:"ToastStack",setup(s){const e=Is(),{toastQueue:t}=xi(e),n=i=>e.dismissToast(i);return(i,r)=>(F(),U("div",{class:Ce(["toast-stack",{"toast-stack--empty":!Ne(t).length}])},[We(ay,{name:"quota-toast-fade",tag:"div"},{default:Gt(()=>[(F(!0),U(Ie,null,Ze(Ne(t),o=>(F(),U("div",{key:o.id,class:Ce(["app-toast",o.type?`app-toast--${o.type}`:""])},[M("div",gee,[o.title?(F(),U("div",vee,Q(o.title),1)):me("",!0),M("div",yee,Q(o.message),1)]),o.closable!==!1?(F(),Ft(ml,{key:0,size:"sm",label:i.$t("shell.closeNotification"),onClick:a=>n(o.id)},null,8,["label","onClick"])):me("",!0)],2))),128))]),_:1})],2))}}),_ee={class:"app-root"},wee=ct({__name:"AppShell",props:{downloadFile:{type:Function},downloadFolder:{type:Function}},setup(s){return(e,t)=>(F(),U("div",_ee,[We(mee),We(bee),We(cee),aF(e.$slots,"default"),We(uee),We(hee,{"download-file":s.downloadFile,"download-folder":s.downloadFolder},null,8,["download-file","download-folder"])]))}}),See=rr(()=>St(()=>import("./PersonalizationDrawer.js"),__vite__mapDeps([0,1,2,3,4,5,6]))),kee=rr(()=>St(()=>import("./ImagePicker.js"),__vite__mapDeps([7,1,2,3,4,8]))),Cee=rr(()=>St(()=>import("./ConversationReviewDialog.js"),__vite__mapDeps([9,1,2,3,4,10]))),Tee=rr(()=>St(()=>import("./SubAgentActivityDialog.js"),__vite__mapDeps([11,1,2,3,4,5,12]))),Aee=rr(()=>St(()=>import("./BackgroundCommandDialog.js"),__vite__mapDeps([13,1,2,3,4,5]))),Eee=rr(()=>St(()=>import("./VersioningDialog.js"),__vite__mapDeps([14,1,2,3,4,15]))),Mee=rr(()=>St(()=>import("./UserQuestionDialog.js"),__vite__mapDeps([16,1,2,3,4,17]))),xee=rr(()=>St(()=>import("./PlanApprovalDialog.js"),__vite__mapDeps([18,1,2,3,4,5,19]))),Ree=rr(()=>St(()=>import("./SandboxSetupDialog.js"),__vite__mapDeps([20,1,2,3,4,5,21]))),Iee=rr(()=>St(()=>import("./TutorialOverlay.js"),__vite__mapDeps([22,1,3,5,2,4]))),Pee=rr(()=>St(()=>import("./NewUserTutorialPrompt.js"),__vite__mapDeps([23,1,3,24]))),Lee=rr(()=>St(()=>import("./GoalProgressDialog.js"),__vite__mapDeps([25,1,2,3,4,26]))),Oee=rr(()=>St(()=>import("./WorkflowDemoShell.js"),__vite__mapDeps([27,1,2,3,4,28]))),Dee={ChatArea:ZU,ConversationSidebar:oz,ToolApprovalPanel:Dz,GitChangesPanel:gj,TerminalPanel:y9,TokenDrawer:f7,PersonalizationDrawer:See,QuickMenu:WL,InputComposer:qZ,EffortSlider:iee,AppShell:wee,StatusAvatar:GD,ImagePicker:kee,ConversationReviewDialog:Cee,SubAgentActivityDialog:Tee,BackgroundCommandDialog:Aee,VersioningDialog:Eee,UserQuestionDialog:Mee,PlanApprovalDialog:xee,SandboxSetupDialog:Ree,TutorialOverlay:Iee,NewUserTutorialPrompt:Pee,GoalProgressDialog:Lee,WorkflowDemoShell:Oee},KD="agents_workspace_mode",Nee=()=>{try{const s=window.localStorage.getItem(KD);return s==="host"||s==="docker"?s:null}catch{return null}},M1=s=>{try{window.localStorage.setItem(KD,s?"host":"docker")}catch{}},qD="agents_new_conversation_type",$ee=()=>{try{return window.localStorage.getItem(qD)==="multi_agent"?"multi_agent":"agent"}catch{return"agent"}},QD=s=>{try{window.localStorage.setItem(qD,s)}catch{}},hI=Nee(),Bee=$ee();function Fee(){return{initialRouteResolved:!1,dropToolEvents:!1,workflowDemoRoute:"",currentConversationType:null,newConversationType:Bee,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,apiRequestPending:!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:[S("appCore.welcomeHelp"),S("appCore.welcomeHot"),S("appCore.welcomeHomework"),S("appCore.welcomeCode"),S("appCore.welcomeChat"),S("appCore.welcomeOrganize"),S("appCore.welcomeTool"),S("appCore.welcomeContinue"),S("appCore.welcomeDraw"),S("appCore.welcomeCat"),S("appCore.welcomePuzzle"),S("appCore.welcomeFun"),S("appCore.welcomeNeed")],mobileViewportQuery:null,modeMenuOpen:!1,modelMenuOpen:!1,permissionMenuOpen:!1,currentPermissionMode:"unrestricted",pendingPermissionMode:"",executionModeEnabled:!1,currentExecutionMode:"sandbox",pendingExecutionMode:"",networkPermissionEnabled:!1,currentNetworkPermission:"restricted",pendingNetworkPermission:"",networkPermissionOptions:[{value:"restricted",labelKey:"appUi.networkRestricted",descriptionKey:"appCore.networkRestrictedDesc"},{value:"full",labelKey:"appUi.networkFull",descriptionKey:"appCore.networkFullDesc"}],workModeMenuOpen:!1,currentWorkMode:"plan",workModeOptions:[{value:"plan",labelKey:"appUi.workModePlan",descriptionKey:"appCore.workModePlanDesc"},{value:"ask",labelKey:"appUi.workModeAsk",descriptionKey:"appCore.workModeAskDesc"},{value:"execute",labelKey:"appUi.workModeExecute",descriptionKey:"appCore.workModeExecuteDesc"}],pathAuthorizationDialogOpen:!1,pathAuthorizationMode:"writable",pathAuthorizationWritableDraft:"",pathAuthorizationReadableDraft:"",pathAuthorizationDraft:"",pathAuthorizationSaving:!1,versioningHostMode:hI==="host",dockerProjectMode:hI==="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",labelKey:"personalization.permissionReadonly",descriptionKey:"appCore.permissionReadonlyDesc"},{value:"approval",labelKey:"appCore.permissionApproval",descriptionKey:"appCore.permissionApprovalDesc"},{value:"auto_approval",labelKey:"appCore.permissionAutoApproval",descriptionKey:"appCore.permissionAutoApprovalDesc"},{value:"unrestricted",labelKey:"appCore.permissionUnrestricted",descriptionKey:"appCore.permissionUnrestrictedDesc"}],executionModeOptions:[{value:"sandbox",labelKey:"input.executionSandbox",descriptionKey:"appCore.executionSandboxDesc"},{value:"direct",labelKey:"input.executionFullAccess",descriptionKey:"appCore.executionDirectDesc"}],pendingToolApprovals:[],decidingApprovalIds:[],pendingUserQuestions:[],pendingPlanApprovals:[],answeringPlanApprovalIds:[],planApprovalMinimized:!1,userQuestionDialogVisible:!1,userQuestionMinimized:!1,userQuestionActiveIndex:0,answeringUserQuestionIds:[],userQuestionOriginalTitle:"",userQuestionTitleBlinkTimer:null,userQuestionTitleBlinkRed:!0,autoApprovalFeedLines:[],autoApprovalFinalMessage:"",autoApprovalTitle:S("appTasks.autoApprovalRecordTitle"),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:vF,toolCategoryIcons:gF,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 Hee={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 Uee(s){const e=String(s||"");return e.startsWith("mcp__")?"mcp":Hee[e]||"command"}function Wee(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 fI=new Set(["preparing","running","pending","queued","awaiting_approval","pending_approval","awaiting_user_answer"]),zee=new Set(["completed","failed","timeout","terminated","cancelled"]),jee={...Zo(fL,["isConnected","socket","stopRequested","projectPath","agentVersion","thinkingMode","runMode","reasoningEffort"]),...O_(Pc,["contextMenu","fileTree","expandedFolders","todoList"]),...O_(oo,{qdHasContent:"hasContent",qdExpanded:"expanded"}),...Zo(oo,{qdUserCollapsed:"userCollapsed"}),...Zo(Is,["sidebarCollapsed","chatDisplayMode","rightWidth","rightCollapsed","isResizing","resizingPanel","minPanelWidth","maxPanelWidth","quotaToast","toastQueue","confirmDialog","easterEgg","isMobileViewport","mobileOverlayMenuOpen","activeMobileOverlay"]),...Zo(kr,["conversations","conversationsLoading","hasMoreConversations","loadingMoreConversations","currentConversationId","currentConversationTitle","searchQuery","searchTimer","searchResults","searchGroups","conversationInsertAnimations","conversationListAnimationMode","pendingDeletingConversationIds","searchActive","searchInProgress","searchMoreAvailable","searchOffset","searchTotal","conversationsOffset","conversationsLimit","runningWorkspaceTasks","acknowledgedCompletedTaskIds","workspaceGroups"]),...Zo(er,["currentModelKey"]),...O_(er,["models"]),...Zo(TE,["messages","currentMessageIndex","streamingMessage","expandedBlocks","autoScrollEnabled","userScrolling","thinkingScrollLocks"]),...Zo(lk,["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 lt.value,[{value:"fast",label:S("appCore.fastMode"),desc:S("appCore.fastModeDesc")},{value:"thinking",label:S("input.thinkingMode"),desc:S("appCore.thinkingModeDesc")}]},headerRunModeLabel(){lt.value;const s=this.headerRunModeOptions.find(e=>e.value===this.resolvedRunMode);return s?s.label:S("appCore.fastMode")},showEffortSlider(){var e;const s=er();return this.resolvedRunMode==="thinking"&&!!((e=s.currentModel)!=null&&e.supportsReasoningEffort)},currentModelLabel(){var e;const s=er();return lt.value,((e=s.currentModel)==null?void 0:e.label)||S("appCore.modelNotSelected")},policyUiBlocks(){return zo().uiBlocks||{}},adminDisabledModels(){return zo().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`}},...Zo(eL,["preparingTools","activeTools","toolActionIndex","toolStacks","toolSettings","toolSettingsLoading"]),...Zo(tL,["tokenPanelCollapsed","currentContextTokens","currentConversationTokens","projectStorage","containerStatus","containerNetRate","usageQuota"]),...Zo(oL,["focusedFiles"]),...Zo(rL,["uploading","mediaUploading"]),...O_(pL,{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=dd(),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=Js().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,g,v,m,y,_;lt.value;const s=Array.isArray(this.messages)?this.messages:[],e=(()=>{var b;for(let k=s.length-1;k>=0;k--)if(((b=s[k])==null?void 0:b.role)==="assistant")return s[k];return null})(),t=dd(),n=vg(),i=b=>(Array.isArray(b)?b:[]).filter(k=>{if(!k)return!1;const w=String((k==null?void 0:k.status)||"").toLowerCase();return w?!zee.has(w):!0}).length,r=i(t.subAgents),o=i(n.commands),a=(()=>{const b=[];return o>0&&b.push(S("appCore.backgroundCommandCount",{n:o,count:o})),r>0&&b.push(S("appCore.backgroundAgentCount",{n:r,count:r})),b.length?`${b.join(",")}${S("appCore.backgroundRunning")}`:""})(),c=!!((p=Js().form)!=null&&p.tool_intent_enabled),l=!!e&&(this.taskInProgress||this.streamingMessage)&&(e.currentStreamingType==="thinking"||e.activeThinkingId!=null);let u=[];e&&(u=Wee(e.actions||[]).filter(k=>{var T,A;const w=String(((T=k==null?void 0:k.tool)==null?void 0:T.status)||"").toLowerCase();return((A=k==null?void 0:k.tool)==null?void 0:A.awaiting_content)||!w||fI.has(w)})),u.length===0&&(u=[...Array.from(((v=(g=this.preparingTools)==null?void 0:g.values)==null?void 0:v.call(g))||[]),...Array.from(((y=(m=this.activeTools)==null?void 0:m.values)==null?void 0:y.call(m))||[])].map(k=>(k==null?void 0:k.type)==="tool"?k:{type:"tool",tool:k}).filter(k=>{const w=k==null?void 0:k.tool;if(!w)return!1;const T=String((w==null?void 0:w.status)||"").toLowerCase();return(w==null?void 0:w.awaiting_content)||!T||fI.has(T)}));const d=this.preparingTools&&this.preparingTools.size>0||this.activeTools&&this.activeTools.size>0,h=this.streamingMessage||this.taskInProgress||this.waitingForSubAgent||this.waitingForBackgroundCommand||this.stopRequested||d||u.length>0||r>0||o>0;if(l)return{mode:"think",toolKeys:[],toolTexts:[],text:S("appCore.thinking"),tracking:!1};if(u.length>0){const b=u.map(A=>{var C;return Uee((C=A==null?void 0:A.tool)==null?void 0:C.name)}),k=A=>{if(!A)return"";const C=A.intent_full||"",E=A.intent_rendered||"";return C&&E===C?C:""},w=u.map(A=>c?k(A==null?void 0:A.tool):"");let T=w[0]||"";return u.length>1?T=w[0]||"":T||(T=c?k((_=u[0])==null?void 0:_.tool):""),{mode:"tool",toolKeys:b,toolTexts:w,text:T,tracking:!1}}if(h){let b=a;if(!b&&this.apiRequestPending)return{mode:"work",toolKeys:[],toolTexts:[],text:S("appCore.waitingApiResponse"),tracking:!1,apiWaiting:!0};if(!b){const k=e&&e.awaitingFirstContent?e:null;k&&(b=typeof k.generatingLabel=="string"&&k.generatingLabel.trim()||"")}return{mode:"work",toolKeys:[],toolTexts:[],text:b,tracking:!1}}return{mode:"idle",toolKeys:[],toolTexts:[],text:"",tracking:!0}}};function Be(...s){}const al=(...s)=>{};function Vee(){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 pI=0;function Cn(s,e={}){if(Vee())try{pI+=1;const t={event:s,seq:pI,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 Gee={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()||"",i=c=>c==="新对话"||c==="New Chat",r=!n||i(n),o=!t||i(t),a=r&&!o;this.startTitleTyping(t,{animate:a})},currentConversationId:{immediate:!1,handler(s,e){if(s!==e){kr().setCurrentConversationId(s||null),s||(this.currentConversationType=null,kr().$patch({multiAgentMode:!1}));const t=oo();t.resetTransient(),s||(t.setEditedFiles([]),Pc().setTodoList(null))}if(Be("currentConversationId 变化",{oldValue:e,newValue:s,skipConversationHistoryReload:this.skipConversationHistoryReload}),al("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)}}},Kee={pushToast:()=>{},autoResizeInput:()=>{},focusComposer:()=>{},isConnected:()=>!1,executeCommand:async()=>({success:!1,message:S("stores.commandChannelUnavailable")}),downloadResource:async()=>{}};function qee(s){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(s):s.replace(/["\\]/g,"\\$&")}function Qee(s){const e=document.createElement("textarea");return e.innerHTML=s,e.value}const Xee=hn("chatActions",{state:()=>({dependencies:{...Kee}}),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:S("common.copyFailed"),message:S("stores.copyContentNotFound"),type:"warning"}),!1;try{return await this.copyText(t),this.dependencies.pushToast({title:S("common.copied"),message:e?S("stores.blockCopied",{id:e}):S("stores.contentCopied"),type:"success"}),!0}catch(i){return console.warn("复制失败:",i),this.dependencies.pushToast({title:S("common.copyFailed"),message:S("stores.copyBlockedByBrowser"),type:"error"}),!1}},async copyCodeBlock(s){if(!s)return!1;const e=`[data-code-id="${qee(s)}"]`,t=document.querySelector(e);if(!t)return this.dependencies.pushToast({title:S("common.copyFailed"),message:S("stores.codeBlockNotFound"),type:"warning"}),!1;const n=t.getAttribute("data-original-code"),i=n?Qee(n):t.textContent||"";if(!i.trim())return this.dependencies.pushToast({title:S("common.copyFailed"),message:S("stores.codeContentEmpty"),type:"warning"}),!1;try{return await this.copyText(i),this.dependencies.pushToast({title:S("common.copied"),message:S("stores.codeCopied"),type:"success"}),!0}catch(r){return console.warn("复制代码失败:",r),this.dependencies.pushToast({title:S("common.copyFailed"),message:S("stores.copyBlockedManual"),type:"error"}),!1}},applyActionContent(s){return!s||!s.content?(this.dependencies.pushToast({title:S("stores.applyFailed"),message:S("stores.applyContentMissing"),type:"warning"}),!1):(lk().setInputMessage(s.content),this.dependencies.autoResizeInput(),this.dependencies.focusComposer(),this.dependencies.pushToast({title:S("stores.filled"),message:S("stores.checkContentBeforeSend"),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:S("stores.cannotExecute"),message:S("stores.commandContentMissing"),type:"warning"}),!1;if(!this.dependencies.isConnected())return this.dependencies.pushToast({title:S("stores.connectionLost"),message:S("stores.reconnectAndRetry"),type:"error"}),!1;try{const n=await this.dependencies.executeCommand(e);return n&&n.success===!1?(this.dependencies.pushToast({title:S("stores.commandFailed"),message:n.message||S("common.retryLater"),type:"error"}),!1):(this.dependencies.pushToast({title:S("stores.commandExecuted"),message:e,type:"success"}),!0)}catch(n){return this.dependencies.pushToast({title:S("stores.commandFailed"),message:(n==null?void 0:n.message)||S("common.retryLater"),type:"error"}),!1}},async downloadActionAttachment(s){return!s||!s.path?(this.dependencies.pushToast({title:S("common.downloadFailed"),message:S("stores.downloadTargetMissing"),type:"warning"}),!1):this.downloadFile(s.path)},async downloadFile(s){if(!s)return this.dependencies.pushToast({title:S("common.downloadFailed"),message:S("stores.downloadPathInvalid"),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:S("common.downloadFailed"),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)}}}),JC="agents_sandbox_setup_never",x1="agents_sandbox_setup_snoozed",Yee=1e3,Jee=12*60*60*1e3;function Zee(){try{const s=sessionStorage.getItem(x1);if(!s)return!1;const e=Number(s);return!Number.isFinite(e)||Date.now()-e>Jee?(sessionStorage.removeItem(x1),!1):!0}catch{return!1}}const ete=hn("sandboxSetup",{state:()=>({status:null,checking:!1,dialogVisible:!1,progress:null,starting:!1,snoozed:Zee(),pollTimer:null}),getters:{neverAsk(){try{return localStorage.getItem(JC)==="1"}catch{return!1}},missing(){const s=this.status;return!s||!s.applicable?!1:s.state==="wsl_missing"||s.state==="distro_missing"||s.state==="bwrap_missing"},shouldAutoPrompt(){var s;return this.dialogVisible||this.snoozed||this.neverAsk?!1:(s=this.progress)!=null&&s.active?!0:this.missing},setupFinished(){const s=this.progress;return!!s&&!s.active&&s.phase!=="idle"}},actions:{async fetchStatus(s=!1){if(!this.checking){this.checking=!0;try{const e=await fetch(`/api/sandbox/status${s?"?force=1":""}`,{credentials:"same-origin"}),t=await e.json().catch(()=>({}));e.ok&&(t!=null&&t.success)&&(this.status=t.data)}catch{}finally{this.checking=!1}}},async autoCheck(){var s;if(await this.fetchStatus(),(s=this.status)!=null&&s.setup_running){this.dialogVisible=!0,this.startPolling();return}this.shouldAutoPrompt&&(this.dialogVisible=!0)},async recheck(){await this.fetchStatus(!0)},openWizard(){var s;this.dialogVisible=!0,(s=this.progress)!=null&&s.active&&this.startPolling(),this.status||this.fetchStatus()},snooze(){this.snoozed=!0;try{sessionStorage.setItem(x1,String(Date.now()))}catch{}this.dialogVisible=!1},setNeverAsk(){try{localStorage.setItem(JC,"1")}catch{}},resetNeverAsk(){try{localStorage.removeItem(JC)}catch{}},closeDialog(s){var e;(e=this.progress)!=null&&e.active||(s&&this.setNeverAsk(),this.snooze())},async startSetup(){var s;if(!(this.starting||(s=this.progress)!=null&&s.active)){this.starting=!0;try{const e=await fetch("/api/sandbox/setup",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"same-origin",body:JSON.stringify({enable_wsl_if_needed:!0})}),t=await e.json().catch(()=>({}));e.ok&&(t!=null&&t.success)?(this.progress=t.data,this.startPolling()):this.progress={active:!1,phase:"error",step_index:0,step_total:6,step_title:"",log_tail:[],download_bytes:null,download_total:null,error:(t==null?void 0:t.error)||"start failed",error_kind:"start_failed",updated_at:Date.now()/1e3}}catch{this.progress={active:!1,phase:"error",step_index:0,step_total:6,step_title:"",log_tail:[],download_bytes:null,download_total:null,error:"network error",error_kind:"start_failed",updated_at:Date.now()/1e3}}finally{this.starting=!1}}},startPolling(){this.pollTimer||(this.pollOnce(),this.pollTimer=setInterval(()=>void this.pollOnce(),Yee))},stopPolling(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null)},async pollOnce(){try{const s=await fetch("/api/sandbox/setup/status",{credentials:"same-origin"}),e=await s.json().catch(()=>({}));if(!s.ok||!(e!=null&&e.success))return;this.progress=e.data,this.progress.active||(this.stopPolling(),this.progress.phase==="done"&&this.fetchStatus(!0))}catch{}},async retrySetup(){this.progress=null,await this.startSetup()}}}),S0=new WeakMap;let iw=null;const mI=new WeakMap;let rw=null,ZC=0;const eT=1200,gI=new Map;let tT=0;const sT=160,vI=new Map;function Bw(){if(typeof window>"u")return!1;try{const s=Number(window.__SHOW_TAG_DRAWING_UNTIL__||0);return Date.now()<=s}catch{return!1}}function tte(){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 ste(){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 Fw(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 Zv(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 R1(s){return!!s.querySelector("show_html, show-html, .chat-inline-html, .chat-inline-card--html")}function Gd(s,e={},t=s,n=280){if(!ste()||tT>=sT)return;const i=Date.now(),r=vI.get(t)||0;if(!(n>0&&i-r<n)){if(vI.set(t,i),tT+=1,tT===sT){console.warn("[SHOW_HTML_SCROLL_TRACE]","log-limit-reached",{max:sT});return}console.log("[SHOW_HTML_SCROLL_TRACE]",s,e)}}function Ci(s,e={},t=s,n=120){if(!tte()||ZC>=eT)return;const i=Date.now(),r=gI.get(t)||0;if(!(n>0&&i-r<n)){if(gI.set(t,i),ZC+=1,ZC===eT){console.warn("[SCROLL_DEBUG]","log-limit-reached",{max:eT});return}console.log("[SCROLL_DEBUG]",s,e)}}function I1(s,e){var u,d;const t=(u=s.getMessagesAreaElement)==null?void 0:u.call(s);if(!t){Ci("scrollToBottom:skip:no-area");return}const n=Bw()&&R1(t);if(!(t.scrollHeight>t.clientHeight+2)&&!(e!=null&&e.force)&&!n){Ci("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&&((d=s.chatSetScrollState)==null||d.call(s,{userScrolling:!1}));return}const r=`t${Date.now()}_${Math.random().toString(36).slice(2,7)}`,o=Fw(t);(n||e!=null&&e.force)&&Gd("scrollToBottom:start",{traceId:r,drawingActive:n,force:!!(e!=null&&e.force),...o,lastShowHtml:Zv(t)},"scrollToBottom:start",120);const a=(e==null?void 0:e.behavior)==="smooth"&&typeof t.scrollTo=="function";Ci("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=S0.get(t);c||(c={rafId:null,settleTimer:null},S0.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)){Ci("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)&&Gd("scrollToBottom:after-write",{traceId:r,drawingActive:n,...Fw(t),lastShowHtml:Zv(t)},"scrollToBottom:after-write",120);let h=0,p=-1;const g=Date.now(),v=n?30:12,m=n?3200:1200,y=()=>{h+=1,t.scrollTop=t.scrollHeight+(n?Math.max(24,Math.floor(t.clientHeight*.12)):0);const _=t.scrollHeight,b=_-t.scrollTop-t.clientHeight,k=Math.abs(_-p)<=2,w=Math.abs(b)<=2,T=Date.now()-g,A=!w&&h<v&&T<m;if(Ci("scrollToBottom:settle",{traceId:r,settleCount:h,settleElapsed:T,currentHeight:_,lastHeight:p,remain:b,atBottom:w,heightStable:k,top:t.scrollTop,client:t.clientHeight},"scrollToBottom:settle",80),p=_,A){(n||e!=null&&e.force)&&(h===1||h===4||h===6)&&Gd("scrollToBottom:settle-progress",{traceId:r,settleCount:h,drawingActive:n,currentHeight:_,top:t.scrollTop,client:t.clientHeight,remain:b},"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(b)>2)&&Gd("scrollToBottom:done",{traceId:r,settleCount:h,drawingActive:n,...Fw(t),lastShowHtml:Zv(t)},"scrollToBottom:done",120),Ci("scrollToBottom:done",{traceId:r,settleCount:h,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,Ci("scrollToBottom:raf",{traceId:r},`scrollToBottom:raf:${r}`,0),l(),!c.settleTimer&&typeof s._setScrollingFlag=="function"&&s._setScrollingFlag(!1)})}function yI(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&&Bw()&&R1(t);if(!n&&Bw()&&t&&Gd("conditional:skip-stale-drawing-window",{...Fw(t),lastShowHtml:Zv(t)},"conditional:skip-stale-drawing-window",260),Ci("conditional:start",{active:e,autoScrollEnabled:s.autoScrollEnabled,userScrolling:s.userScrolling,drawingActive:n},"conditional:start",120),s.autoScrollEnabled===!0&&e){if(!t){Ci("conditional:skip:no-area");return}if(rw&&rw!==t){Ci("conditional:area-replaced",{},"conditional:area-replaced",0);const g=S0.get(rw);g&&g.rafId!==null&&(cancelAnimationFrame(g.rafId),g.rafId=null),g&&g.settleTimer&&(clearTimeout(g.settleTimer),g.settleTimer=null)}rw=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}),Ci("conditional:skip:no-overflow",{top:a,height:c,client:l,remain:u},"conditional:skip:no-overflow",120);return}c<=l+2&&n&&Gd("conditional:drawing-no-overflow-but-continue",{top:a,height:c,client:l,remain:u,drawingActive:n},"conditional:drawing-no-overflow-but-continue",200);const d=S0.get(t);if((d==null?void 0:d.rafId)!==null||d!=null&&d.settleTimer){Ci("conditional:skip:pending-task",{hasRaf:(d==null?void 0:d.rafId)!==null,hasSettle:!!(d!=null&&d.settleTimer),top:a,height:c,client:l},"conditional:skip:pending-task",100);return}const h=Date.now(),p=mI.get(t)||0;if(h-p<90){Ci("conditional:skip:too-frequent",{gap:h-p,top:a,height:c,client:l},"conditional:skip:too-frequent",100);return}mI.set(t,h),s.userScrolling===!0&&((o=s.chatSetScrollState)==null||o.call(s,{userScrolling:!1})),iw!==null&&cancelAnimationFrame(iw),iw=requestAnimationFrame(()=>{var _;iw=null;const g=(_=s.getMessagesAreaElement)==null?void 0:_.call(s);if(!g||g!==t){Ci("conditional:skip:area-changed-before-raf",{},"conditional:skip:area-changed-before-raf",0);return}const v=g.scrollHeight,m=g.clientHeight,y=Bw()&&R1(g);if(v<=m+2&&!y){Ci("conditional:skip:no-overflow-before-raf",{top:g.scrollTop,height:v,client:m},"conditional:skip:no-overflow-before-raf",100);return}y&&Gd("conditional:raf-scroll",{top:g.scrollTop,height:v,client:m,remain:v-g.scrollTop-m,lastShowHtml:Zv(g)},"conditional:raf-scroll",140),Ci("conditional:raf-scroll",{top:g.scrollTop,height:v,client:m},"conditional:raf-scroll",80),I1(s,{ignoreUserScrolling:!0,resetUserScrolling:!0,force:y})})}}function nte(s){var e;s.autoScrollEnabled||(e=s.chatSetScrollState)==null||e.call(s,{autoScrollEnabled:!0,userScrolling:!1})}function ite(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 bI(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 rte(s){if(Array.isArray(s))return s}function ote(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 ate(){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 lte(s,e){return rte(s)||ote(s,e)||cte(s,e)||ate()}function cte(s,e){if(s){if(typeof s=="string")return bI(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)?bI(s,e):void 0}}const XD=Object.entries,_I=Object.setPrototypeOf,ute=Object.isFrozen,dte=Object.getPrototypeOf,hte=Object.getOwnPropertyDescriptor;let lr=Object.freeze,Vo=Object.seal,yp=Object.create,YD=typeof Reflect<"u"&&Reflect,P1=YD.apply,L1=YD.construct;lr||(lr=function(e){return e});Vo||(Vo=function(e){return e});P1||(P1=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)});L1||(L1=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 Ed=xn(Array.prototype.forEach),fte=xn(Array.prototype.lastIndexOf),wI=xn(Array.prototype.pop),ip=xn(Array.prototype.push),pte=xn(Array.prototype.splice),Vi=Array.isArray,cv=xn(String.prototype.toLowerCase),nT=xn(String.prototype.toString),SI=xn(String.prototype.match),rp=xn(String.prototype.replace),kI=xn(String.prototype.indexOf),mte=xn(String.prototype.trim),gte=xn(Number.prototype.toString),vte=xn(Boolean.prototype.toString),CI=typeof BigInt>"u"?null:xn(BigInt.prototype.toString),TI=typeof Symbol>"u"?null:xn(Symbol.prototype.toString),sn=xn(Object.prototype.hasOwnProperty),$g=xn(Object.prototype.toString),Jn=xn(RegExp.prototype.test),op=yte(TypeError);function xn(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 P1(s,e,n)}}function yte(s){return function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return L1(s,t)}}function Dt(s,e){let t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:cv;if(_I&&_I(s,null),!Vi(e))return s;let n=e.length;for(;n--;){let i=e[n];if(typeof i=="string"){const r=t(i);r!==i&&(ute(e)||(e[n]=r),i=r)}s[i]=!0}return s}function bte(s){for(let e=0;e<s.length;e++)sn(s,e)||(s[e]=null);return s}function gi(s){const e=yp(null);for(const n of XD(s)){var t=lte(n,2);const i=t[0],r=t[1];sn(s,i)&&(Vi(r)?e[i]=bte(r):r&&typeof r=="object"&&r.constructor===Object?e[i]=gi(r):e[i]=r)}return e}function _te(s){switch(typeof s){case"string":return s;case"number":return gte(s);case"boolean":return vte(s);case"bigint":return CI?CI(s):"0";case"symbol":return TI?TI(s):"Symbol()";case"undefined":return $g(s);case"function":case"object":{if(s===null)return $g(s);const e=s,t=xa(e,"toString");if(typeof t=="function"){const n=t(e);return typeof n=="string"?n:$g(n)}return $g(s)}default:return $g(s)}}function xa(s,e){for(;s!==null;){const n=hte(s,e);if(n){if(n.get)return xn(n.get);if(typeof n.value=="function")return xn(n.value)}s=dte(s)}function t(){return null}return t}function wte(s){try{return Jn(s,""),!0}catch{return!1}}const AI=lr(["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"]),iT=lr(["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"]),rT=lr(["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"]),Ste=lr(["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"]),oT=lr(["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"]),kte=lr(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),EI=lr(["#text"]),MI=lr(["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"]),aT=lr(["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"]),xI=lr(["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"]),ow=lr(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),Cte=Vo(/{{[\w\W]*|^[\w\W]*}}/g),Tte=Vo(/<%[\w\W]*|^[\w\W]*%>/g),Ate=Vo(/\${[\w\W]*/g),Ete=Vo(/^data-[\-\w.\u00B7-\uFFFF]+$/),Mte=Vo(/^aria-[\-\w]+$/),RI=Vo(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),xte=Vo(/^(?:\w+script|data):/i),Rte=Vo(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Ite=Vo(/^html$/i),Pte=Vo(/^[a-z][.\w]*(-[.\w]+)+$/i),Aa={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,progressingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},Lte=function(){return typeof window>"u"?null:window},Ote=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}},II=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function JD(){let s=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Lte();const e=et=>JD(et);if(e.version="3.4.8",e.removed=[],!s||!s.document||s.document.nodeType!==Aa.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,d=s.trustedTypes,h=a.prototype,p=xa(h,"cloneNode"),g=xa(h,"remove"),v=xa(h,"nextSibling"),m=xa(h,"childNodes"),y=xa(h,"parentNode"),_=xa(h,"shadowRoot"),b=xa(h,"attributes"),k=o&&o.prototype?xa(o.prototype,"nodeType"):null,w=o&&o.prototype?xa(o.prototype,"nodeName"):null;if(typeof r=="function"){const et=t.createElement("template");et.content&&et.content.ownerDocument&&(t=et.content.ownerDocument)}let T,A="",C=0;const E=function(ae){if(C>0)throw op('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.');C++;try{return T.createHTML(ae)}finally{C--}},x=t,D=x.implementation,N=x.createNodeIterator,O=x.createDocumentFragment,G=x.getElementsByTagName,Z=n.importNode;let q=II();e.isSupported=typeof XD=="function"&&typeof y=="function"&&D&&D.createHTMLDocument!==void 0;const V=Cte,I=Tte,$=Ate,L=Ete,K=Mte,se=xte,oe=Rte,ve=Pte;let le=RI,ue=null;const P=Dt({},[...AI,...iT,...rT,...oT,...EI]);let X=null;const J=Dt({},[...MI,...aT,...xI,...ow]);let ne=Object.seal(yp(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}})),ce=null,_e=null;const Pe=Object.seal(yp(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let it=!0,at=!0,rt=!1,Oe=!0,xe=!1,pe=!0,he=!1,ye=!1,ke=!1,Le=!1,st=!1,gt=!1,Wt=!0,jt=!1;const ht="user-content-";let Qt=!0,It=!1,ns={},ot=null;const $s=Dt({},["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 Er=null;const In=Dt({},["audio","video","img","source","image","track"]);let Ko=null;const ao=Dt({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),Pn="http://www.w3.org/1998/Math/MathML",qo="http://www.w3.org/2000/svg",Yn="http://www.w3.org/1999/xhtml";let Oi=Yn,Mr=!1,Di=null;const gl=Dt({},[Pn,qo,Yn],nT);let Qo=Dt({},["mi","mo","mn","ms","mtext"]),lo=Dt({},["annotation-xml"]);const fi=Dt({},["title","style","font","a","script"]);let Ni=null;const wa=["application/xhtml+xml","text/html"],vl="text/html";let re=null,we=null;const Ae=t.createElement("form"),bt=function(ae){return ae instanceof RegExp||ae instanceof Function},hs=function(){let ae=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(we&&we===ae)return;(!ae||typeof ae!="object")&&(ae={}),ae=gi(ae),Ni=wa.indexOf(ae.PARSER_MEDIA_TYPE)===-1?vl:ae.PARSER_MEDIA_TYPE,re=Ni==="application/xhtml+xml"?nT:cv,ue=sn(ae,"ALLOWED_TAGS")&&Vi(ae.ALLOWED_TAGS)?Dt({},ae.ALLOWED_TAGS,re):P,X=sn(ae,"ALLOWED_ATTR")&&Vi(ae.ALLOWED_ATTR)?Dt({},ae.ALLOWED_ATTR,re):J,Di=sn(ae,"ALLOWED_NAMESPACES")&&Vi(ae.ALLOWED_NAMESPACES)?Dt({},ae.ALLOWED_NAMESPACES,nT):gl,Ko=sn(ae,"ADD_URI_SAFE_ATTR")&&Vi(ae.ADD_URI_SAFE_ATTR)?Dt(gi(ao),ae.ADD_URI_SAFE_ATTR,re):ao,Er=sn(ae,"ADD_DATA_URI_TAGS")&&Vi(ae.ADD_DATA_URI_TAGS)?Dt(gi(In),ae.ADD_DATA_URI_TAGS,re):In,ot=sn(ae,"FORBID_CONTENTS")&&Vi(ae.FORBID_CONTENTS)?Dt({},ae.FORBID_CONTENTS,re):$s,ce=sn(ae,"FORBID_TAGS")&&Vi(ae.FORBID_TAGS)?Dt({},ae.FORBID_TAGS,re):gi({}),_e=sn(ae,"FORBID_ATTR")&&Vi(ae.FORBID_ATTR)?Dt({},ae.FORBID_ATTR,re):gi({}),ns=sn(ae,"USE_PROFILES")?ae.USE_PROFILES&&typeof ae.USE_PROFILES=="object"?gi(ae.USE_PROFILES):ae.USE_PROFILES:!1,it=ae.ALLOW_ARIA_ATTR!==!1,at=ae.ALLOW_DATA_ATTR!==!1,rt=ae.ALLOW_UNKNOWN_PROTOCOLS||!1,Oe=ae.ALLOW_SELF_CLOSE_IN_ATTR!==!1,xe=ae.SAFE_FOR_TEMPLATES||!1,pe=ae.SAFE_FOR_XML!==!1,he=ae.WHOLE_DOCUMENT||!1,Le=ae.RETURN_DOM||!1,st=ae.RETURN_DOM_FRAGMENT||!1,gt=ae.RETURN_TRUSTED_TYPE||!1,ke=ae.FORCE_BODY||!1,Wt=ae.SANITIZE_DOM!==!1,jt=ae.SANITIZE_NAMED_PROPS||!1,Qt=ae.KEEP_CONTENT!==!1,It=ae.IN_PLACE||!1,le=wte(ae.ALLOWED_URI_REGEXP)?ae.ALLOWED_URI_REGEXP:RI,Oi=typeof ae.NAMESPACE=="string"?ae.NAMESPACE:Yn,Qo=sn(ae,"MATHML_TEXT_INTEGRATION_POINTS")&&ae.MATHML_TEXT_INTEGRATION_POINTS&&typeof ae.MATHML_TEXT_INTEGRATION_POINTS=="object"?gi(ae.MATHML_TEXT_INTEGRATION_POINTS):Dt({},["mi","mo","mn","ms","mtext"]),lo=sn(ae,"HTML_INTEGRATION_POINTS")&&ae.HTML_INTEGRATION_POINTS&&typeof ae.HTML_INTEGRATION_POINTS=="object"?gi(ae.HTML_INTEGRATION_POINTS):Dt({},["annotation-xml"]);const Me=sn(ae,"CUSTOM_ELEMENT_HANDLING")&&ae.CUSTOM_ELEMENT_HANDLING&&typeof ae.CUSTOM_ELEMENT_HANDLING=="object"?gi(ae.CUSTOM_ELEMENT_HANDLING):yp(null);if(ne=yp(null),sn(Me,"tagNameCheck")&&bt(Me.tagNameCheck)&&(ne.tagNameCheck=Me.tagNameCheck),sn(Me,"attributeNameCheck")&&bt(Me.attributeNameCheck)&&(ne.attributeNameCheck=Me.attributeNameCheck),sn(Me,"allowCustomizedBuiltInElements")&&typeof Me.allowCustomizedBuiltInElements=="boolean"&&(ne.allowCustomizedBuiltInElements=Me.allowCustomizedBuiltInElements),xe&&(at=!1),st&&(Le=!0),ns&&(ue=Dt({},EI),X=yp(null),ns.html===!0&&(Dt(ue,AI),Dt(X,MI)),ns.svg===!0&&(Dt(ue,iT),Dt(X,aT),Dt(X,ow)),ns.svgFilters===!0&&(Dt(ue,rT),Dt(X,aT),Dt(X,ow)),ns.mathMl===!0&&(Dt(ue,oT),Dt(X,xI),Dt(X,ow))),Pe.tagCheck=null,Pe.attributeCheck=null,sn(ae,"ADD_TAGS")&&(typeof ae.ADD_TAGS=="function"?Pe.tagCheck=ae.ADD_TAGS:Vi(ae.ADD_TAGS)&&(ue===P&&(ue=gi(ue)),Dt(ue,ae.ADD_TAGS,re))),sn(ae,"ADD_ATTR")&&(typeof ae.ADD_ATTR=="function"?Pe.attributeCheck=ae.ADD_ATTR:Vi(ae.ADD_ATTR)&&(X===J&&(X=gi(X)),Dt(X,ae.ADD_ATTR,re))),sn(ae,"ADD_URI_SAFE_ATTR")&&Vi(ae.ADD_URI_SAFE_ATTR)&&Dt(Ko,ae.ADD_URI_SAFE_ATTR,re),sn(ae,"FORBID_CONTENTS")&&Vi(ae.FORBID_CONTENTS)&&(ot===$s&&(ot=gi(ot)),Dt(ot,ae.FORBID_CONTENTS,re)),sn(ae,"ADD_FORBID_CONTENTS")&&Vi(ae.ADD_FORBID_CONTENTS)&&(ot===$s&&(ot=gi(ot)),Dt(ot,ae.ADD_FORBID_CONTENTS,re)),Qt&&(ue["#text"]=!0),he&&Dt(ue,["html","head","body"]),ue.table&&(Dt(ue,["tbody"]),delete ce.tbody),ae.TRUSTED_TYPES_POLICY){if(typeof ae.TRUSTED_TYPES_POLICY.createHTML!="function")throw op('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof ae.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw op('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');const Ge=T;T=ae.TRUSTED_TYPES_POLICY;try{A=E("")}catch(Bt){throw T=Ge,Bt}}else T===void 0&&ae.TRUSTED_TYPES_POLICY!==null&&(T=Ote(d,i)),T&&typeof A=="string"&&(A=E(""));(q.uponSanitizeElement.length>0||q.uponSanitizeAttribute.length>0)&&ue===P&&(ue=gi(ue)),q.uponSanitizeAttribute.length>0&&X===J&&(X=gi(X)),lr&&lr(ae),we=ae},Ps=Dt({},[...iT,...rT,...Ste]),is=Dt({},[...oT,...kte]),en=function(ae){let Me=y(ae);(!Me||!Me.tagName)&&(Me={namespaceURI:Oi,tagName:"template"});const Ge=cv(ae.tagName),Bt=cv(Me.tagName);return Di[ae.namespaceURI]?ae.namespaceURI===qo?Me.namespaceURI===Yn?Ge==="svg":Me.namespaceURI===Pn?Ge==="svg"&&(Bt==="annotation-xml"||Qo[Bt]):!!Ps[Ge]:ae.namespaceURI===Pn?Me.namespaceURI===Yn?Ge==="math":Me.namespaceURI===qo?Ge==="math"&&lo[Bt]:!!is[Ge]:ae.namespaceURI===Yn?Me.namespaceURI===qo&&!lo[Bt]||Me.namespaceURI===Pn&&!Qo[Bt]?!1:!is[Ge]&&(fi[Ge]||!Ps[Ge]):!!(Ni==="application/xhtml+xml"&&Di[ae.namespaceURI]):!1},ut=function(ae){ip(e.removed,{element:ae});try{y(ae).removeChild(ae)}catch{g(ae)}},pn=function(ae,Me){try{ip(e.removed,{attribute:Me.getAttributeNode(ae),from:Me})}catch{ip(e.removed,{attribute:null,from:Me})}if(Me.removeAttribute(ae),ae==="is")if(Le||st)try{ut(Me)}catch{}else try{Me.setAttribute(ae,"")}catch{}},co=function(ae){let Me=null,Ge=null;if(ke)ae="<remove></remove>"+ae;else{const Zt=SI(ae,/^[\r\n\t ]+/);Ge=Zt&&Zt[0]}Ni==="application/xhtml+xml"&&Oi===Yn&&(ae='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+ae+"</body></html>");const Bt=T?E(ae):ae;if(Oi===Yn)try{Me=new u().parseFromString(Bt,Ni)}catch{}if(!Me||!Me.documentElement){Me=D.createDocument(Oi,"template",null);try{Me.documentElement.innerHTML=Mr?A:Bt}catch{}}const Tt=Me.body||Me.documentElement;return ae&&Ge&&Tt.insertBefore(t.createTextNode(Ge),Tt.childNodes[0]||null),Oi===Yn?G.call(Me,he?"html":"body")[0]:he?Me.documentElement:Tt},$i=function(ae){return N.call(ae.ownerDocument||ae,ae,c.SHOW_ELEMENT|c.SHOW_COMMENT|c.SHOW_TEXT|c.SHOW_PROCESSING_INSTRUCTION|c.SHOW_CDATA_SECTION,null)},Bc=function(ae){var Me,Ge;ae.normalize();const Bt=N.call(ae.ownerDocument||ae,ae,c.SHOW_TEXT|c.SHOW_COMMENT|c.SHOW_CDATA_SECTION|c.SHOW_PROCESSING_INSTRUCTION,null);let Tt=Bt.nextNode();for(;Tt;){let Cs=Tt.data;Ed([V,I,$],pi=>{Cs=rp(Cs,pi," ")}),Tt.data=Cs,Tt=Bt.nextNode()}const Zt=(Me=(Ge=ae.querySelectorAll)===null||Ge===void 0?void 0:Ge.call(ae,"template"))!==null&&Me!==void 0?Me:[];Ed(Array.from(Zt),Cs=>{Bi(Cs.content)&&Bc(Cs.content)})},xr=function(ae){const Me=w?w(ae):null;return typeof Me!="string"||re(Me)!=="form"?!1:typeof ae.nodeName!="string"||typeof ae.textContent!="string"||typeof ae.removeChild!="function"||ae.attributes!==b(ae)||typeof ae.removeAttribute!="function"||typeof ae.setAttribute!="function"||typeof ae.namespaceURI!="string"||typeof ae.insertBefore!="function"||typeof ae.hasChildNodes!="function"||ae.nodeType!==k(ae)||ae.childNodes!==m(ae)},Bi=function(ae){if(!k||typeof ae!="object"||ae===null)return!1;try{return k(ae)===Aa.documentFragment}catch{return!1}},Fc=function(ae){if(!k||typeof ae!="object"||ae===null)return!1;try{return typeof k(ae)=="number"}catch{return!1}};function Fi(et,ae,Me){Ed(et,Ge=>{Ge.call(e,ae,Me,we)})}const mn=function(ae){let Me=null;if(Fi(q.beforeSanitizeElements,ae,null),xr(ae))return ut(ae),!0;const Ge=re(w?w(ae):ae.nodeName);if(Fi(q.uponSanitizeElement,ae,{tagName:Ge,allowedTags:ue}),pe&&ae.hasChildNodes()&&!Fc(ae.firstElementChild)&&Jn(/<[/\w!]/g,ae.innerHTML)&&Jn(/<[/\w!]/g,ae.textContent)||pe&&ae.namespaceURI===Yn&&Ge==="style"&&Fc(ae.firstElementChild)||ae.nodeType===Aa.progressingInstruction||pe&&ae.nodeType===Aa.comment&&Jn(/<[/\w]/g,ae.data))return ut(ae),!0;if(ce[Ge]||!(Pe.tagCheck instanceof Function&&Pe.tagCheck(Ge))&&!ue[Ge]){if(!ce[Ge]&&yl(Ge)&&(ne.tagNameCheck instanceof RegExp&&Jn(ne.tagNameCheck,Ge)||ne.tagNameCheck instanceof Function&&ne.tagNameCheck(Ge)))return!1;if(Qt&&!ot[Ge]){const Tt=y(ae),Zt=m(ae);if(Zt&&Tt){const Cs=Zt.length;for(let pi=Cs-1;pi>=0;--pi){const mi=p(Zt[pi],!0);Tt.insertBefore(mi,v(ae))}}}return ut(ae),!0}return(k?k(ae):ae.nodeType)===Aa.element&&!en(ae)||(Ge==="noscript"||Ge==="noembed"||Ge==="noframes")&&Jn(/<\/no(script|embed|frames)/i,ae.innerHTML)?(ut(ae),!0):(xe&&ae.nodeType===Aa.text&&(Me=ae.textContent,Ed([V,I,$],Tt=>{Me=rp(Me,Tt," ")}),ae.textContent!==Me&&(ip(e.removed,{element:ae.cloneNode()}),ae.textContent=Me)),Fi(q.afterSanitizeElements,ae,null),!1)},Hi=function(ae,Me,Ge){if(_e[Me]||Wt&&(Me==="id"||Me==="name")&&(Ge in t||Ge in Ae))return!1;const Bt=X[Me]||Pe.attributeCheck instanceof Function&&Pe.attributeCheck(Me,ae);if(!(at&&!_e[Me]&&Jn(L,Me))){if(!(it&&Jn(K,Me))){if(!Bt||_e[Me]){if(!(yl(ae)&&(ne.tagNameCheck instanceof RegExp&&Jn(ne.tagNameCheck,ae)||ne.tagNameCheck instanceof Function&&ne.tagNameCheck(ae))&&(ne.attributeNameCheck instanceof RegExp&&Jn(ne.attributeNameCheck,Me)||ne.attributeNameCheck instanceof Function&&ne.attributeNameCheck(Me,ae))||Me==="is"&&ne.allowCustomizedBuiltInElements&&(ne.tagNameCheck instanceof RegExp&&Jn(ne.tagNameCheck,Ge)||ne.tagNameCheck instanceof Function&&ne.tagNameCheck(Ge))))return!1}else if(!Ko[Me]){if(!Jn(le,rp(Ge,oe,""))){if(!((Me==="src"||Me==="xlink:href"||Me==="href")&&ae!=="script"&&kI(Ge,"data:")===0&&Er[ae])){if(!(rt&&!Jn(se,rp(Ge,oe,"")))){if(Ge)return!1}}}}}}return!0},Sa=Dt({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),yl=function(ae){return!Sa[cv(ae)]&&Jn(ve,ae)},Hc=function(ae){Fi(q.beforeSanitizeAttributes,ae,null);const Me=ae.attributes;if(!Me||xr(ae))return;const Ge={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:X,forceKeepAttr:void 0};let Bt=Me.length;for(;Bt--;){const Tt=Me[Bt],Zt=Tt.name,Cs=Tt.namespaceURI,pi=Tt.value,mi=re(Zt),fs=pi;let Es=Zt==="value"?fs:mte(fs);if(Ge.attrName=mi,Ge.attrValue=Es,Ge.keepAttr=!0,Ge.forceKeepAttr=void 0,Fi(q.uponSanitizeAttribute,ae,Ge),Es=Ge.attrValue,jt&&(mi==="id"||mi==="name")&&kI(Es,ht)!==0&&(pn(Zt,ae),Es=ht+Es),pe&&Jn(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,Es)){pn(Zt,ae);continue}if(mi==="attributename"&&SI(Es,"href")){pn(Zt,ae);continue}if(Ge.forceKeepAttr)continue;if(!Ge.keepAttr){pn(Zt,ae);continue}if(!Oe&&Jn(/\/>/i,Es)){pn(Zt,ae);continue}xe&&Ed([V,I,$],Ln=>{Es=rp(Es,Ln," ")});const rs=re(ae.nodeName);if(!Hi(rs,mi,Es)){pn(Zt,ae);continue}if(T&&typeof d=="object"&&typeof d.getAttributeType=="function"&&!Cs)switch(d.getAttributeType(rs,mi)){case"TrustedHTML":{Es=E(Es);break}case"TrustedScriptURL":{Es=T.createScriptURL(Es);break}}if(Es!==fs)try{Cs?ae.setAttributeNS(Cs,Zt,Es):ae.setAttribute(Zt,Es),xr(ae)?ut(ae):wI(e.removed)}catch{pn(Zt,ae)}}Fi(q.afterSanitizeAttributes,ae,null)},Xo=function(ae){let Me=null;const Ge=$i(ae);for(Fi(q.beforeSanitizeShadowDOM,ae,null);Me=Ge.nextNode();)if(Fi(q.uponSanitizeShadowNode,Me,null),mn(Me),Hc(Me),Bi(Me.content)&&Xo(Me.content),(k?k(Me):Me.nodeType)===Aa.element){const Tt=_?_(Me):Me.shadowRoot;Bi(Tt)&&(Yo(Tt),Xo(Tt))}Fi(q.afterSanitizeShadowDOM,ae,null)},Yo=function(ae){const Me=k?k(ae):ae.nodeType;if(Me===Aa.element){const Tt=_?_(ae):ae.shadowRoot;Bi(Tt)&&(Yo(Tt),Xo(Tt))}const Ge=m?m(ae):ae.childNodes;if(!Ge)return;const Bt=[];Ed(Ge,Tt=>{ip(Bt,Tt)});for(const Tt of Bt)Yo(Tt);if(Me===Aa.element){const Tt=w?w(ae):null;if(typeof Tt=="string"&&re(Tt)==="template"){const Zt=ae.content;Bi(Zt)&&Yo(Zt)}}};return e.sanitize=function(et){let ae=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},Me=null,Ge=null,Bt=null,Tt=null;if(Mr=!et,Mr&&(et="<!-->"),typeof et!="string"&&!Fc(et)&&(et=_te(et),typeof et!="string"))throw op("dirty is not a string, aborting");if(!e.isSupported)return et;if(ye||hs(ae),e.removed=[],typeof et=="string"&&(It=!1),It){const pi=w?w(et):et.nodeName;if(typeof pi=="string"){const mi=re(pi);if(!ue[mi]||ce[mi])throw op("root node is forbidden and cannot be sanitized in-place")}if(xr(et))throw op("root node is clobbered and cannot be sanitized in-place");Yo(et)}else if(Fc(et))Me=co("<!---->"),Ge=Me.ownerDocument.importNode(et,!0),Ge.nodeType===Aa.element&&Ge.nodeName==="BODY"||Ge.nodeName==="HTML"?Me=Ge:Me.appendChild(Ge),Yo(Ge);else{if(!Le&&!xe&&!he&&et.indexOf("<")===-1)return T&>?E(et):et;if(Me=co(et),!Me)return Le?null:gt?A:""}Me&&ke&&ut(Me.firstChild);const Zt=$i(It?et:Me);for(;Bt=Zt.nextNode();)mn(Bt),Hc(Bt),Bi(Bt.content)&&Xo(Bt.content);if(It)return xe&&Bc(et),et;if(Le){if(xe&&Bc(Me),st)for(Tt=O.call(Me.ownerDocument);Me.firstChild;)Tt.appendChild(Me.firstChild);else Tt=Me;return(X.shadowroot||X.shadowrootmode)&&(Tt=Z.call(n,Tt,!0)),Tt}let Cs=he?Me.outerHTML:Me.innerHTML;return he&&ue["!doctype"]&&Me.ownerDocument&&Me.ownerDocument.doctype&&Me.ownerDocument.doctype.name&&Jn(Ite,Me.ownerDocument.doctype.name)&&(Cs="<!DOCTYPE "+Me.ownerDocument.doctype.name+`>
|
||
`+Cs),xe&&Ed([V,I,$],pi=>{Cs=rp(Cs,pi," ")}),T&>?E(Cs):Cs},e.setConfig=function(){let et=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};hs(et),ye=!0},e.clearConfig=function(){we=null,ye=!1},e.isValidAttribute=function(et,ae,Me){we||hs({});const Ge=re(et),Bt=re(ae);return Hi(Ge,Bt,Me)},e.addHook=function(et,ae){typeof ae=="function"&&ip(q[et],ae)},e.removeHook=function(et,ae){if(ae!==void 0){const Me=fte(q[et],ae);return Me===-1?void 0:pte(q[et],Me,1)[0]}return wI(q[et])},e.removeHooks=function(et){q[et]=[]},e.removeAllHooks=function(){q=II()},e}var Dte=JD();(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],d=t.tokenStack[u],h=typeof l=="string"?l:l.content,p=e(n,u),g=h.indexOf(p);if(g>-1){++i;var v=h.substring(0,g),m=new s.Token(n,s.tokenize(d,t.grammar),"language-"+n,d),y=h.substring(g+p.length),_=[];v&&_.push.apply(_,o([v])),_.push(m),y&&_.push.apply(_,o([y])),typeof l=="string"?a.splice.apply(a,[c,1].concat(_)):l.content=_}}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($,L){return $.replace(/<<(\d+)>>/g,function(K,se){return"(?:"+L[+se]+")"})}function t($,L,K){return RegExp(e($,L),"")}function n($,L){for(var K=0;K<L;K++)$=$.replace(/<<self>>/g,function(){return"(?:"+$+")"});return $.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($){return"\\b(?:"+$.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),d=n(/\((?:[^()]|<<self>>)*\)/.source,2),h=/@?\b[A-Za-z_]\w*\b/.source,p=e(/<<0>>(?:\s*<<1>>)?/.source,[h,u]),g=e(/(?!<<0>>)<<1>>(?:\s*\.\s*<<1>>)*/.source,[c,p]),v=/\[\s*(?:,\s*)*\]/.source,m=e(/<<0>>(?:\s*(?:\?\s*)?<<1>>)*(?:\s*\?)?/.source,[g,v]),y=e(/[^,()<>[\];=+\-*/%&|^]|<<0>>|<<1>>|<<2>>/.source,[u,d,v]),_=e(/\(<<0>>+(?:,<<0>>+)+\)/.source,[y]),b=e(/(?:<<0>>|<<1>>)(?:\s*(?:\?\s*)?<<2>>)*(?:\s*\?)?/.source,[_,g,v]),k={keyword:a,punctuation:/[<>()?,.:[\]]/},w=/'(?:[^\r\n'\\]|\\.|\\[Uux][\da-fA-F]{1,8})'/.source,T=/"(?:\\.|[^\\"\r\n])*"/.source,A=/@"(?:""|\\[\s\S]|[^\\"])*"(?!")/.source;s.languages.csharp=s.languages.extend("clike",{string:[{pattern:t(/(^|[^$\\])<<0>>/.source,[A]),lookbehind:!0,greedy:!0},{pattern:t(/(^|[^@$\\])<<0>>/.source,[T]),lookbehind:!0,greedy:!0}],"class-name":[{pattern:t(/(\busing\s+static\s+)<<0>>(?=\s*;)/.source,[g]),lookbehind:!0,inside:k},{pattern:t(/(\busing\s+<<0>>\s*=\s*)<<1>>(?=\s*;)/.source,[h,b]),lookbehind:!0,inside:k},{pattern:t(/(\busing\s+)<<0>>(?=\s*=)/.source,[h]),lookbehind:!0},{pattern:t(/(\b<<0>>\s+)<<1>>/.source,[o,p]),lookbehind:!0,inside:k},{pattern:t(/(\bcatch\s*\(\s*)<<0>>/.source,[g]),lookbehind:!0,inside:k},{pattern:t(/(\bwhere\s+)<<0>>/.source,[h]),lookbehind:!0},{pattern:t(/(\b(?:is(?:\s+not)?|as)\s+)<<0>>/.source,[m]),lookbehind:!0,inside:k},{pattern:t(/\b<<0>>(?=\s+(?!<<1>>|with\s*\{)<<2>>(?:\s*[=,;:{)\]]|\s+(?:in|when)\b))/.source,[b,l,h]),inside:k}],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,[h]),lookbehind:!0,alias:"punctuation"}}),s.languages.insertBefore("csharp","class-name",{namespace:{pattern:t(/(\b(?:namespace|using)\s+)<<0>>(?:\s*\.\s*<<0>>)*(?=\s*[;{])/.source,[h]),lookbehind:!0,inside:{punctuation:/\./}},"type-expression":{pattern:t(/(\b(?:default|sizeof|typeof)\s*\(\s*(?!\s))(?:[^()\s]|\s(?!\s)|<<0>>)*(?=\s*\))/.source,[d]),lookbehind:!0,alias:"class-name",inside:k},"return-type":{pattern:t(/<<0>>(?=\s+(?:<<1>>\s*(?:=>|[({]|\.\s*this\s*\[)|this\s*\[))/.source,[b,g]),inside:k,alias:"class-name"},"constructor-invocation":{pattern:t(/(\bnew\s+)<<0>>(?=\s*[[({])/.source,[b]),lookbehind:!0,inside:k,alias:"class-name"},"generic-method":{pattern:t(/<<0>>\s*<<1>>(?=\s*\()/.source,[h,u]),inside:{function:t(/^<<0>>/.source,[h]),generic:{pattern:RegExp(u),alias:"class-name",inside:k}}},"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,h,b,a.source,d,/\bnew\s*\(\s*\)/.source]),lookbehind:!0,inside:{"record-arguments":{pattern:t(/(^(?!new\s*\()<<0>>\s*)<<1>>/.source,[p,d]),lookbehind:!0,greedy:!0,inside:s.languages.csharp},keyword:a,"class-name":{pattern:RegExp(b),greedy:!0,inside:k},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 C=T+"|"+w,E=e(/\/(?![*/])|\/\/[^\r\n]*[\r\n]|\/\*(?:[^*]|\*(?!\/))*\*\/|<<0>>/.source,[C]),x=n(e(/[^"'/()]|<<0>>|\(<<self>>*\)/.source,[E]),2),D=/\b(?:assembly|event|field|method|module|param|property|return|type)\b/.source,N=e(/<<0>>(?:\s*\(<<1>>*\))?/.source,[g,x]);s.languages.insertBefore("csharp","class-name",{attribute:{pattern:t(/((?:^|[^\s\w>)?])\s*\[\s*)(?:<<0>>\s*:\s*)?<<1>>(?:\s*,\s*<<1>>)*(?=\s*\])/.source,[D,N]),lookbehind:!0,greedy:!0,inside:{target:{pattern:t(/^<<0>>(?=\s*:)/.source,[D]),alias:"keyword"},"attribute-arguments":{pattern:t(/\(<<0>>*\)/.source,[x]),inside:s.languages.csharp},"class-name":{pattern:RegExp(g),inside:{punctuation:/\./}},punctuation:/[:,]/}}});var O=/:[^}\r\n]+/.source,G=n(e(/[^"'/()]|<<0>>|\(<<self>>*\)/.source,[E]),2),Z=e(/\{(?!\{)(?:(?![}:])<<0>>)*<<1>>?\}/.source,[G,O]),q=n(e(/[^"'/()]|\/(?!\*)|\/\*(?:[^*]|\*(?!\/))*\*\/|<<0>>|\(<<self>>*\)/.source,[C]),2),V=e(/\{(?!\{)(?:(?![}:])<<0>>)*<<1>>?\}/.source,[q,O]);function I($,L){return{interpolation:{pattern:t(/((?:^|[^{])(?:\{\{)*)<<0>>/.source,[$]),lookbehind:!0,inside:{"format-string":{pattern:t(/(^\{(?:(?![}:])<<0>>)*)<<1>>(?=\}$)/.source,[L,O]),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,[Z]),lookbehind:!0,greedy:!0,inside:I(Z,G)},{pattern:t(/(^|[^@\\])\$"(?:\\.|\{\{|<<0>>|[^\\"{])*"/.source,[V]),lookbehind:!0,greedy:!0,inside:I(V,q)}],char:{pattern:RegExp(w),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://,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 d=c[u],h=!1;if(typeof d!="string"&&(d.type==="tag"&&d.content[0]&&d.content[0].type==="tag"?d.content[0].content[0].content==="</"?l.length>0&&l[l.length-1].tagName===o(d.content[0].content[1])&&l.pop():d.content[d.content.length-1].content==="/>"||l.push({tagName:o(d.content[0].content[1]),openedBraces:0}):l.length>0&&d.type==="punctuation"&&d.content==="{"?l[l.length-1].openedBraces++:l.length>0&&l[l.length-1].openedBraces>0&&d.type==="punctuation"&&d.content==="}"?l[l.length-1].openedBraces--:h=!0),(h||typeof d=="string")&&l.length>0&&l[l.length-1].openedBraces===0){var p=o(d);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)}d.content&&typeof d.content!="string"&&a(d.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(d){u!==d&&(s.languages.markdown[u].inside.content.inside[d]=s.languages.markdown[d])})}),s.hooks.add("after-tokenize",function(u){if(u.language!=="markdown"&&u.language!=="md")return;function d(h){if(!(!h||typeof h=="string"))for(var p=0,g=h.length;p<g;p++){var v=h[p];if(v.type!=="code"){d(v.content);continue}var m=v.content[1],y=v.content[3];if(m&&y&&m.type==="code-language"&&y.type==="code-block"&&typeof m.content=="string"){var _=m.content.replace(/\b#/g,"sharp").replace(/\b\+\+/g,"pp");_=(/[a-z][\w-]*/i.exec(_)||[""])[0].toLowerCase();var b="language-"+_;y.alias?typeof y.alias=="string"?y.alias=[y.alias,b]:y.alias.push(b):y.alias=[b]}}}d(u.tokens)}),s.hooks.add("wrap",function(u){if(u.type==="code-block"){for(var d="",h=0,p=u.classes.length;h<p;h++){var g=u.classes[h],v=/language-(.+)/.exec(g);if(v){d=v[1];break}}var m=s.languages[d];if(m)u.content=s.highlight(l(u.content),m,d);else if(d&&d!=="none"&&s.plugins.autoloader){var y="md-"+new Date().valueOf()+"-"+Math.floor(Math.random()*1e16);u.attributes.id=y,s.plugins.autoloader.loadLanguages(d,function(){var _=document.getElementById(y);_&&(_.innerHTML=s.highlight(_.textContent,s.languages[d],d))})}}});var o=RegExp(s.languages.markup.tag.pattern.source,"gi"),a={amp:"&",lt:"<",gt:">",quot:'"'},c=String.fromCodePoint||String.fromCharCode;function l(u){var d=u.replace(o,"");return d=d.replace(/&(\w{1,8}|#x?[\da-f]{1,8});/gi,function(h,p){if(p=p.toLowerCase(),p[0]==="#"){var g;return p[1]==="x"?g=parseInt(p.slice(2),16):g=Number(p.slice(1)),c(g)}else{var v=a[p];return v||h}}),d}s.languages.md=s.languages.markdown})(Prism);const Nte={".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 ZD(s){const e=s.split("/").pop()||"",t=e.lastIndexOf(".");if(t<0)return null;const n=e.slice(t).toLowerCase();return Nte[n]||null}function $te(s){return s.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function O1(s,e){if(e){const t=PS.languages[e];if(t)try{return PS.highlight(s,t,e)}catch{}}return $te(s)}const Bte=["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("; "),Fte=`(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) {
|
||
// Remove the id first so the hash update does not trigger the browser's default anchor scroll
|
||
target.removeAttribute('id');
|
||
try { window.location.hash = id; } catch (err) { /* ignore under 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) { /* skip cross-origin child frames */ }
|
||
}
|
||
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 eN(){return`<meta http-equiv="Content-Security-Policy" content="${Bte}" /><script>${Fte}<\/script>`}function Hte(s){const e=eN(),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 kM='<!doctype html><html><head><meta charset="utf-8"></head><body></body></html>';function D1(s){const e=(s||"").trim();return e?/<html[\s>]/i.test(e)?Hte(e):`<!doctype html>
|
||
<html>
|
||
<head>
|
||
<meta charset="utf-8" />
|
||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||
${eN()}
|
||
<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>`:kM}const lT=500;let cT=0;function Ute(){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 CM(s,e={}){if(Ute()&&!(cT>=lT)){if(cT+=1,cT===lT){console.warn("[SHOW_HTML_DEBUG]","log-limit-reached",{max:lT});return}console.log("[SHOW_HTML_DEBUG]",s,e)}}let Zr=null,PI=!1;function tN(){return!!(Zr!=null&&Zr.root.classList.contains("is-open"))}function Wte(){PI||typeof document>"u"||(PI=!0,document.addEventListener("keydown",s=>{s.key!=="Escape"||!tN()||(s.stopPropagation(),TM())}))}function zte(){if(Zr)return Zr;Wte();const s=document.createElement("div");s.className="show-html-fullscreen",s.setAttribute("role","dialog"),s.setAttribute("aria-modal","true"),s.setAttribute("aria-label",S("utils.fullscreenPreview"));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=S("utils.fullscreenPreview");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=S("utils.refresh"),o.setAttribute("aria-label",S("utils.refresh")),o.textContent="↻";const a=document.createElement("button");a.type="button",a.className="show-html-fullscreen__btn show-html-fullscreen__btn--close",a.title=S("utils.closeEsc"),a.setAttribute("aria-label",S("utils.closeFullscreenPreview")),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 d=Zr;if(!(d!=null&&d.payload))return;const h=d.payload.srcdoc;d.iframe.srcdoc=kM,requestAnimationFrame(()=>{Zr!=null&&Zr.payload&&(Zr.iframe.srcdoc=h)}),CM("fullscreen:refresh",{srcdocLength:h.length})},a.onclick=u=>{u.preventDefault(),u.stopPropagation(),TM()},document.body.appendChild(s),Zr={root:s,iframe:l,titleEl:n,noticeEl:i,payload:null},Zr}function sN(s){if(typeof document>"u")return;const e=zte();e.payload=s,e.titleEl.textContent=s.title||S("utils.fullscreenPreview");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"),CM("fullscreen:open",{allowScripts:s.allowScripts,srcdocLength:s.srcdoc.length,hasNotice:!!t})}function TM(){const s=Zr;!s||!tN()||(s.root.classList.remove("is-open"),document.documentElement.classList.remove("show-html-fullscreen-open"),s.payload=null,s.iframe.srcdoc=kM,CM("fullscreen:close",{}))}var jte={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),d=n.structuredClone,h=n.ArrayBuffer,p=n.DataView,g=Math.max,v=Math.min,m=h.prototype,y=p.prototype,_=i(m.slice),b=r(m,"resizable","get"),k=r(m,"maxByteLength","get"),w=i(y.getInt8),T=i(y.setInt8);s.exports=(u||l)&&function(A,C,E){var x=c(A),D=C===void 0?x:o(C),N=!b||!b(A),O;if(a(A),u&&(A=d(A,{transfer:[A]}),x===D&&(E||N)))return A;if(x>=D&&(!E||N))O=_(A,0,D);else{var G=E&&!N&&k?{maxByteLength:g(D,k(A))}:void 0;O=new h(D,G);for(var Z=new p(A),q=new p(O),V=v(D,x),I=0;I<V;I++)T(q,I,w(Z,I))}return u||l(A),O}},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),d=t(6699),h=t(6840),p=t(2106),g=t(1625),v=t(2787),m=t(2967),y=t(8227),_=t(3392),b=t(1181),k=b.enforce,w=b.get,T=r.Int8Array,A=T&&T.prototype,C=r.Uint8ClampedArray,E=C&&C.prototype,x=T&&v(T),D=A&&v(A),N=Object.prototype,O=r.TypeError,G=y("toStringTag"),Z=_("TYPED_ARRAY_TAG"),q="TypedArrayConstructor",V=n&&!!m&&l(r.opera)!=="Opera",I=!1,$,L,K,se={Int8Array:1,Uint8Array:1,Uint8ClampedArray:1,Int16Array:2,Uint16Array:2,Int32Array:4,Uint32Array:4,Float32Array:4,Float64Array:8},oe={BigInt64Array:8,BigUint64Array:8},ve=function(_e){if(!a(_e))return!1;var Pe=l(_e);return Pe==="DataView"||c(se,Pe)||c(oe,Pe)},le=function(ce){var _e=v(ce);if(a(_e)){var Pe=w(_e);return Pe&&c(Pe,q)?Pe[q]:le(_e)}},ue=function(ce){if(!a(ce))return!1;var _e=l(ce);return c(se,_e)||c(oe,_e)},P=function(ce){if(ue(ce))return ce;throw new O("Target is not a typed array")},X=function(ce){if(o(ce)&&(!m||g(x,ce)))return ce;throw new O(u(ce)+" is not a typed array constructor")},J=function(ce,_e,Pe,it){if(i){if(Pe)for(var at in se){var rt=r[at];if(rt&&c(rt.prototype,ce))try{delete rt.prototype[ce]}catch{try{rt.prototype[ce]=_e}catch{}}}(!D[ce]||Pe)&&h(D,ce,Pe?_e:V&&A[ce]||_e,it)}},ne=function(ce,_e,Pe){var it,at;if(i){if(m){if(Pe){for(it in se)if(at=r[it],at&&c(at,ce))try{delete at[ce]}catch{}}if(!x[ce]||Pe)try{return h(x,ce,Pe?_e:V&&x[ce]||_e)}catch{}else return}for(it in se)at=r[it],at&&(!at[ce]||Pe)&&h(at,ce,_e)}};for($ in se)L=r[$],K=L&&L.prototype,K?k(K)[q]=L:V=!1;for($ in oe)L=r[$],K=L&&L.prototype,K&&(k(K)[q]=L);if((!V||!o(x)||x===Function.prototype)&&(x=function(){throw new O("Incorrect invocation")},V))for($ in se)r[$]&&m(r[$],x);if((!V||!D||D===N)&&(D=x.prototype,V))for($ in se)r[$]&&m(r[$].prototype,D);if(V&&v(E)!==D&&m(E,D),i&&!c(D,G)){I=!0,p(D,G,{configurable:!0,get:function(){return a(this)?this[Z]:void 0}});for($ in se)r[$]&&d(r[$].prototype,Z,$)}s.exports={NATIVE_ARRAY_BUFFER_VIEWS:V,TYPED_ARRAY_TAG:I&&Z,aTypedArray:P,aTypedArrayConstructor:X,exportTypedArrayMethod:J,exportTypedArrayStaticMethod:ne,getTypedArrayConstructor:le,isView:ve,isTypedArray:ue,TypedArray:x,TypedArrayPrototype:D}},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 d=n(c),h=r(d);if(h===0)return!a&&-1;var p=i(u,h),g;if(a&&l!==l){for(;h>p;)if(g=d[p++],g!==g)return!0}else for(;h>p;p++)if((a||p in d)&&d[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(d,h){try{return d[h]}catch{}};s.exports=n?r:function(d){var h,p,g;return d===void 0?"Undefined":d===null?"Null":typeof(p=u(h=c(d),a))=="string"?p:l?r(h):(g=r(h))==="Object"&&i(h.callee)?"Arguments":g}},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),d=o.f,h=r.f,p=0;p<u.length;p++){var g=u[p];!n(a,g)&&!(l&&n(l,g))&&d(a,g,h(c,g))}}},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 d=u.enumerable,h=u.name!==void 0?u.name:c;if(n(l)&&r(l,h,u),u.global)d?a[c]=l:o(c,l);else{try{u.unsafe?a[c]&&(d=!0):delete a[c]}catch{}d?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,d,h,p;if(r)l=function(g){o(g,{transfer:[g]})};else if(a)try{c||(u=i("worker_threads"),u&&(c=u.MessageChannel)),c&&(d=new c,h=new a(2),p=function(g){d.port1.postMessage(null,[g])},h.byteLength===2&&(p(h),h.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,d){var h=u.target,p=u.global,g=u.stat,v,m,y,_,b,k;if(p?m=n:g?m=n[h]||a(h,{}):m=n[h]&&n[h].prototype,m)for(y in d){if(b=d[y],u.dontCallGetSet?(k=i(m,y),_=k&&k.value):_=m[y],v=l(p?y:h+(g?".":"#")+y,u.forced),!v&&_!==void 0){if(typeof b==typeof _)continue;c(b,_)}(u.sham||_&&_.sham)&&r(b,"sham",!0),o(m,y,b,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 d=arguments.length<2?a(l):u;if(i(d))return r(n(d,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,d=Math.max,h=function(p,g){this.set=p,this.size=d(g,0),this.has=n(p.has),this.keys=n(p.keys)};h.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 g=+p.size;if(g!==g)throw new u(c);var v=o(g);if(v<0)throw new l(c);return new h(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),d="Object already initialized",h=i.TypeError,p=i.WeakMap,g,v,m,y=function(w){return m(w)?v(w):g(w,{})},_=function(w){return function(T){var A;if(!r(T)||(A=v(T)).type!==w)throw new h("Incompatible receiver, "+w+" required");return A}};if(n||c.state){var b=c.state||(c.state=new p);b.get=b.get,b.has=b.has,b.set=b.set,g=function(w,T){if(b.has(w))throw new h(d);return T.facade=w,b.set(w,T),T},v=function(w){return b.get(w)||{}},m=function(w){return b.has(w)}}else{var k=l("state");u[k]=!0,g=function(w,T){if(a(w,k))throw new h(d);return T.facade=w,o(w,k,T),T},v=function(w){return a(w,k)?w[k]:{}},m=function(w){return a(w,k)}}s.exports={set:g,get:v,has:m,enforce:y,getterFor:_}},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(d,h){var p=c[a(d)];return p===u?!0:p===l?!1:i(h)?n(h):!!h},a=o.normalize=function(d){return String(d).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),d=t(851),h=t(9539),p=TypeError,g=function(m,y){this.stopped=m,this.result=y},v=g.prototype;s.exports=function(m,y,_){var b=_&&_.that,k=!!(_&&_.AS_ENTRIES),w=!!(_&&_.IS_RECORD),T=!!(_&&_.IS_ITERATOR),A=!!(_&&_.INTERRUPTED),C=n(y,b),E,x,D,N,O,G,Z,q=function($){var L=E;return E=void 0,L&&h(L,"normal"),new g(!0,$)},V=function($){return k?(r($),A?C($[0],$[1],q):C($[0],$[1])):A?C($,q):C($)};if(w)E=m.iterator;else if(T)E=m;else{if(x=d(m),!x)throw new p(o(m)+" is not iterable");if(a(x)){for(D=0,N=c(m);N>D;D++)if(O=V(m[D]),O&&l(v,O))return O;return new g(!1)}E=u(m,x)}for(G=w?m.next:E.next;!(Z=i(G,E)).done;){var I=Z.value;try{O=V(I)}catch($){if(E)h(E,"throw",$);else throw $}if(typeof O=="object"&&O&&l(v,O))return O}return new g(!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(d){u=!0,l=d}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,d=t(2529),h=t(9539),p=t(1385),g=a("toStringTag"),v="IteratorHelper",m="WrapForValidIterator",y="normal",_="throw",b=c.set,k=function(A){var C=c.getterFor(A?m:v);return o(i(u),{next:function(){var x=C(this);if(A)return x.nextHandler();if(x.done)return d(void 0,!0);try{var D=x.nextHandler();return x.returnHandlerResult?D:d(D,x.done)}catch(N){throw x.done=!0,N}},return:function(){var E=C(this),x=E.iterator,D=E.done;if(E.done=!0,A){var N=l(x,"return");return N?n(N,x):d(void 0,!0)}if(D)return d(void 0,!0);if(E.inner)try{h(E.inner.iterator,y)}catch(O){return h(x,_,O)}if(E.openIters)try{p(E.openIters,y)}catch(O){if(x)return h(x,_,O);throw O}return x&&h(x,y),d(void 0,!0)}})},w=k(!0),T=k(!1);r(T,g,"Iterator Helper"),s.exports=function(A,C,E){var x=function(N,O){O?(O.iterator=N.iterator,O.next=N.next):O=N,O.type=C?m:v,O.returnHandlerResult=!!E,O.nextHandler=A,O.counter=0,O.done=!1,b(this,O)};return x.prototype=C?w:T,x}},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),d=l("iterator"),h=!1,p,g,v;[].keys&&(v=[].keys(),"next"in v?(g=a(a(v)),g!==Object.prototype&&(p=g)):h=!0);var m=!r(p)||n(function(){var y={};return p[d].call(y)!==y});m?p={}:u&&(p=o(p)),i(p[d])||c(p,d,function(){return this}),s.exports={IteratorPrototype:p,BUGGY_SAFARI_ITERATORS:h}},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),d=u.enforce,h=u.get,p=String,g=Object.defineProperty,v=n("".slice),m=n("".replace),y=n([].join),_=a&&!i(function(){return g(function(){},"length",{value:8}).length!==8}),b=String(String).split("String"),k=s.exports=function(w,T,A){v(p(T),0,7)==="Symbol("&&(T="["+m(p(T),/^Symbol\(([^)]*)\).*$/,"$1")+"]"),A&&A.getter&&(T="get "+T),A&&A.setter&&(T="set "+T),(!o(w,"name")||c&&w.name!==T)&&(a?g(w,"name",{value:T,configurable:!0}):w.name=T),_&&A&&o(A,"arity")&&w.length!==A.arity&&g(w,"length",{value:A.arity});try{A&&o(A,"constructor")&&A.constructor?a&&g(w,"prototype",{writable:!1}):w.prototype&&(w.prototype=void 0)}catch{}var C=d(w);return o(C,"source")||(C.source=y(b,typeof T=="string"?T:"")),w};Function.prototype.toString=k(function(){return r(this)&&h(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=">",d="<",h="prototype",p="script",g=l("IE_PROTO"),v=function(){},m=function(w){return d+p+u+w+d+"/"+p+u},y=function(w){w.write(m("")),w.close();var T=w.parentWindow.Object;return w=null,T},_=function(){var w=c("iframe"),T="java"+p+":",A;return w.style.display="none",a.appendChild(w),w.src=String(T),A=w.contentWindow.document,A.open(),A.write(m("document.F=Object")),A.close(),A.F},b,k=function(){try{b=new ActiveXObject("htmlfile")}catch{}k=typeof document<"u"?document.domain&&b?y(b):_():y(b);for(var w=r.length;w--;)delete k[h][r[w]];return k()};o[g]=!0,s.exports=Object.create||function(T,A){var C;return T!==null?(v[h]=n(T),C=new v,v[h]=null,C[g]=T):C=k(),A===void 0?C:i.f(C,A)}},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,d){o(u);for(var h=a(d),p=c(d),g=p.length,v=0,m;g>v;)r.f(u,m=p[v++],h[m]);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,d="enumerable",h="configurable",p="writable";e.f=n?r?function(v,m,y){if(o(v),m=a(m),o(y),typeof v=="function"&&m==="prototype"&&"value"in y&&p in y&&!y[p]){var _=u(v,m);_&&_[p]&&(v[m]=y.value,y={configurable:h in y?y[h]:_[h],enumerable:d in y?y[d]:_[d],writable:!1})}return l(v,m,y)}:l:function(v,m,y){if(o(v),m=a(m),o(y),i)try{return l(v,m,y)}catch{}if("get"in y||"set"in y)throw new c("Accessors not supported");return"value"in y&&(v[m]=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),d=Object.getOwnPropertyDescriptor;e.f=n?d:function(p,g){if(p=a(p),g=c(g),u)try{return d(p,g)}catch{}if(l(p,g))return o(!i(r.f,p,g),p[g])}},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(d){var h=r(d);if(n(h,c))return h[c];var p=h.constructor;return i(p)&&h instanceof p?p.prototype:h 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 d=r(l),h=0,p=[],g;for(g in d)!i(a,g)&&i(d,g)&&c(p,g);for(;u.length>h;)i(d,g=u[h++])&&(~o(p,g)||c(p,g));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(d,h){return r(d),o(h),i(d)&&(a?l(d,h):d.__proto__=h),d}}():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 d=r.f(a(u)),h=o.f;return h?c(d,h(u)):d}},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),d={'\\"':'"',"\\\\":"\\","\\/":"/","\\b":"\b","\\f":"\f","\\n":`
|
||
`,"\\r":"\r","\\t":" "},h=/^[\da-f]{4}$/i,p=/^[\u0000-\u001F]$/;s.exports=function(g,v){for(var m=!0,y="";v<g.length;){var _=c(g,v);if(_==="\\"){var b=l(g,v,v+2);if(i(d,b))y+=d[b],v+=2;else if(b==="\\u"){v+=2;var k=l(g,v,v+4);if(!u(h,k))throw new r("Bad Unicode escape at: "+v);y+=a(o(k,16)),v+=4}else throw new r('Unknown escape sequence: "'+b+'"')}else if(_==='"'){m=!1,v++;break}else{if(u(p,_))throw new r("Bad control character in string literal at: "+v);y+=_,v++}}if(m)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,d=i.remove;s.exports=function(p){var g=n(this),v=a(p),m=r(g);return o(m)<=v.size?c(m,function(y){v.includes(y)&&d(m,y)}):l(v.getIterator(),function(y){u(m,y)&&d(m,y)}),m}},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,d=i.has;s.exports=function(p){var g=n(this),v=o(p),m=new l;return r(g)>v.size?c(v.getIterator(),function(y){d(g,y)&&u(m,y)}):a(g,function(y){v.includes(y)&&u(m,y)}),m}},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(d){var h=n(this),p=o(d);if(r(h)<=p.size)return a(h,function(v){if(p.includes(v))return!1},!0)!==!1;var g=p.getIterator();return c(g,function(v){if(i(h,v))return l(g.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(d){if(!u.includes(d))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 d=n(this),h=o(u);if(r(d)<h.size)return!1;var p=h.getIterator();return a(p,function(g){if(!i(d,g))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(d,h,p){return p?i({iterator:l(d),next:u},h):c(d,h)}},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(h){var p=n(this),g=o(h).getIterator(),v=r(p);return a(g,function(m){l(p,m)?u(v,m):c(v,m)}),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),d=o(l).getIterator(),h=r(u);return a(d,function(p){i(h,p)}),h}},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:"© 2013–2025 Denis Pushkarev (zloirock.ru), 2025–2026 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(d,h){if(!i(d)||r(d))return d;var p=o(d,u),g;if(p){if(h===void 0&&(h="default"),g=n(p,d,h),!i(g)||r(g))return g;throw new l("Can't convert object to primitive value")}return h===void 0&&(h="number"),a(d,h)}},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),d=c.c2i,h=c.c2iUrl,p=n.SyntaxError,g=n.TypeError,v=i("".charAt),m=function(b,k){for(var w=b.length;k<w;k++){var T=v(b,k);if(T!==" "&&T!==" "&&T!==`
|
||
`&&T!=="\f"&&T!=="\r")break}return k},y=function(b,k,w){var T=b.length;T<4&&(b+=T===2?"AA":"A");var A=(k[v(b,0)]<<18)+(k[v(b,1)]<<12)+(k[v(b,2)]<<6)+k[v(b,3)],C=[A>>16&255,A>>8&255,A&255];if(T===2){if(w&&C[1]!==0)throw new p("Extra bits");return[C[0]]}if(T===3){if(w&&C[2]!==0)throw new p("Extra bits");return[C[0],C[1]]}return C},_=function(b,k,w){for(var T=k.length,A=0;A<T;A++)b[w+A]=k[A];return w+T};s.exports=function(b,k,w,T){o(b),r(k);var A=l(k)==="base64"?d:h,C=k?k.lastChunkHandling:void 0;if(C===void 0&&(C="loose"),C!=="loose"&&C!=="strict"&&C!=="stop-before-partial")throw new g("Incorrect `lastChunkHandling` option");w&&u(w.buffer);var E=b.length,x=w||[],D=0,N=0,O="",G=0;if(T)for(;;){if(G=m(b,G),G===E){if(O.length>0){if(C==="stop-before-partial")break;if(C==="loose"){if(O.length===1)throw new p("Malformed padding: exactly one additional character");D=_(x,y(O,A,!1),D)}else throw new p("Missing padding")}N=E;break}var Z=v(b,G);if(++G,Z==="="){if(O.length<2)throw new p("Padding is too early");if(G=m(b,G),O.length===2){if(G===E){if(C==="stop-before-partial")break;throw new p("Malformed padding: only one =")}v(b,G)==="="&&(++G,G=m(b,G))}if(G<E)throw new p("Unexpected character after padding");D=_(x,y(O,A,C==="strict"),D),N=E;break}if(!a(A,Z))throw new p("Unexpected character");var q=T-D;if(q===1&&O.length===2||q===2&&O.length===3||(O+=Z,O.length===4&&(D=_(x,y(O,A,!1),D),O="",N=G,D===T)))break}return{bytes:x,read:N,written:D}}},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 d=l.length;if(d%2!==0)throw new o("String should be an even number of characters");for(var h=u?a(u.length,d/2):d/2,p=u||new r(h),g=c(l,/.{2}/g),v=0;v<h;v++){var m=+("0x"+g[v]+"0");if(m!==m)throw new o("String should only contain hex characters");p[v]=m>>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"),d="";return c.pathname="c%20d",l.forEach(function(h,p){l.delete("b"),d+=p+h}),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"||d!=="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"),d=c?l.for||l:l&&l.withoutSetter||o;s.exports=function(h){return r(u,h)||(u[h]=a&&r(l,h)?l[h]:d("Symbol."+h)),u[h]}},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(h){return h instanceof TypeError}},d=l||!u();n({target:"Array",proto:!0,arity:1,forced:d},{push:function(p){var g=i(this),v=r(g),m=arguments.length;a(v+m);for(var y=0;y<m;y++)g[v]=arguments[y],v++;return o(g,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),d=t(9039),h=t(9297),p=t(8227),g=t(7657).IteratorPrototype,v=t(3724),m=t(6395),y="constructor",_="Iterator",b=p("toStringTag"),k=TypeError,w=i[_],T=m||!a(w)||w.prototype!==g||!d(function(){w({})}),A=function(){if(r(this,g),c(this)===g)throw new k("Abstract class Iterator not directly constructable")},C=function(E,x){v?l(g,E,{configurable:!0,get:function(){return x},set:function(D){if(o(this),this===g)throw new k("You can't redefine this property");h(this,E)?this[E]=D:u(this,E,D)}}):g[E]=x};h(g,b)||C(b,_),(T||!h(g,y)||g[y]===Object)&&C(y,A),A.prototype=g,n({global:!0,constructor:!0,forced:T},{Iterator:A})},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),d=t(684),h=t(4549),p=t(6395),g=!p&&!d("drop",0),v=!p&&!g&&h("drop",RangeError),m=p||g||v,y=u(function(){for(var _=this.iterator,b=this.next,k,w;this.remaining;)if(this.remaining--,k=r(i(b,_)),w=this.done=!!k.done,w)return;if(k=r(i(b,_)),w=this.done=!!k.done,!w)return k.value});n({target:"Iterator",proto:!0,real:!0,forced:m},{drop:function(b){r(this);var k;try{k=c(a(+b))}catch(w){l(this,"throw",w)}return v?i(v,this,k):new y(o(this),{remaining:k})}})},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),d=u("every",TypeError);n({target:"Iterator",proto:!0,real:!0,forced:d},{every:function(p){a(this);try{o(p)}catch(m){l(this,"throw",m)}if(d)return i(d,this,p);var g=c(this),v=0;return!r(g,function(m,y){if(!p(m,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),d=t(9539),h=t(684),p=t(4549),g=!u&&!h("filter",function(){}),v=!u&&!g&&p("filter",TypeError),m=u||g||v,y=c(function(){for(var _=this.iterator,b=this.predicate,k=this.next,w,T,A;;){if(w=o(i(k,_)),T=this.done=!!w.done,T)return;if(A=w.value,l(_,b,[A,this.counter++],!0))return A}});n({target:"Iterator",proto:!0,real:!0,forced:m},{filter:function(b){o(this);try{r(b)}catch(k){d(this,"throw",k)}return v?i(v,this,b):new y(a(this),{predicate:b})}})},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),d=u("find",TypeError);n({target:"Iterator",proto:!0,real:!0,forced:d},{find:function(p){a(this);try{o(p)}catch(m){l(this,"throw",m)}if(d)return i(d,this,p);var g=c(this),v=0;return r(g,function(m,y){if(p(m,v++))return y(m)},{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),d=t(6395),h=t(684),p=t(4549);function g(){try{var b=Iterator.prototype.flatMap.call(new Map([[4,5]]).entries(),function(k){return k});b.next(),b.return()}catch{return!0}}var v=!d&&!h("flatMap",function(){}),m=!d&&!v&&p("flatMap",TypeError),y=d||v||m||g(),_=l(function(){for(var b=this.iterator,k=this.mapper,w,T;;){if(T=this.inner)try{if(w=o(i(T.next,T.iterator)),!w.done)return w.value;this.inner=null}catch(A){u(b,"throw",A)}if(w=o(i(this.next,b)),this.done=!!w.done)return;try{this.inner=c(k(w.value,this.counter++),!1)}catch(A){u(b,"throw",A)}}});n({target:"Iterator",proto:!0,real:!0,forced:y},{flatMap:function(k){o(this);try{r(k)}catch(w){u(this,"throw",w)}return m?i(m,this,k):new _(a(this),{mapper:k,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),d=u("forEach",TypeError);n({target:"Iterator",proto:!0,real:!0,forced:d},{forEach:function(p){a(this);try{o(p)}catch(m){l(this,"throw",m)}if(d)return i(d,this,p);var g=c(this),v=0;r(g,function(m){p(m,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),d=t(684),h=t(4549),p=t(6395),g=!p&&!d("map",function(){}),v=!p&&!g&&h("map",TypeError),m=p||g||v,y=c(function(){var _=this.iterator,b=o(i(this.next,_)),k=this.done=!!b.done;if(!k)return l(_,this.mapper,[b.value,this.counter++],!0)});n({target:"Iterator",proto:!0,real:!0,forced:m},{map:function(b){o(this);try{r(b)}catch(k){u(this,"throw",k)}return v?i(v,this,b):new y(a(this),{mapper:b})}})},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),d=u("some",TypeError);n({target:"Iterator",proto:!0,real:!0,forced:d},{some:function(p){a(this);try{o(p)}catch(m){l(this,"throw",m)}if(d)return i(d,this,p);var g=c(this),v=0;return r(g,function(m,y){if(p(m,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),d=t(684),h=t(4549),p=t(6395),g=!p&&!d("take",1),v=!p&&!g&&h("take",RangeError),m=p||g||v,y=l(function(){var _=this.iterator;if(!this.remaining--)return this.done=!0,u(_,"normal",void 0);var b=r(i(this.next,_)),k=this.done=!!b.done;if(!k)return b.value});n({target:"Iterator",proto:!0,real:!0,forced:m},{take:function(b){r(this);var k;try{k=c(a(+b))}catch(w){u(this,"throw",w)}return v?i(v,this,k):new y(o(this),{remaining:k})}})},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),d=t(4376),h=t(9297),p=t(655),g=t(6198),v=t(4659),m=t(9039),y=t(8235),_=t(4495),b=r.JSON,k=r.Number,w=r.SyntaxError,T=b&&b.parse,A=o("Object","keys"),C=Object.getOwnPropertyDescriptor,E=a("".charAt),x=a("".slice),D=a(/./.exec),N=a([].push),O=/^\d$/,G=/^[1-9]$/,Z=/^[\d-]$/,q=/^[\t\n\r ]$/,V=0,I=1,$=function(ue,P){ue=p(ue);var X=new oe(ue,0),J=X.parse(),ne=J.value,ce=X.skip(q,J.end);if(ce<ue.length)throw new w('Unexpected extra character: "'+E(ue,ce)+'" after the parsed data at: '+ce);return l(P)?L({"":ne},"",P,J):ne},L=function(ue,P,X,J){var ne=ue[P],ce=J&&ne===J.value,_e=ce&&typeof J.source=="string"?{source:J.source}:{},Pe,it,at,rt,Oe;if(u(ne)){var xe=d(ne),pe=ce?J.nodes:xe?[]:{};if(xe)for(Pe=pe.length,at=g(ne),rt=0;rt<at;rt++)K(ne,rt,L(ne,""+rt,X,rt<Pe?pe[rt]:void 0));else for(it=A(ne),at=g(it),rt=0;rt<at;rt++)Oe=it[rt],K(ne,Oe,L(ne,Oe,X,h(pe,Oe)?pe[Oe]:void 0))}return c(X,ue,P,ne,_e)},K=function(ue,P,X){if(i){var J=C(ue,P);if(J&&!J.configurable)return}X===void 0?delete ue[P]:v(ue,P,X)},se=function(ue,P,X,J){this.value=ue,this.end=P,this.source=X,this.nodes=J},oe=function(ue,P){this.source=ue,this.index=P};oe.prototype={fork:function(ue){return new oe(this.source,ue)},parse:function(){var ue=this.source,P=this.skip(q,this.index),X=this.fork(P),J=E(ue,P);if(D(Z,J))return X.number();switch(J){case"{":return X.object();case"[":return X.array();case'"':return X.string();case"t":return X.keyword(!0);case"f":return X.keyword(!1);case"n":return X.keyword(null)}throw new w('Unexpected character: "'+J+'" at: '+P)},node:function(ue,P,X,J,ne){return new se(P,J,ue?null:x(this.source,X,J),ne)},object:function(){for(var ue=this.source,P=this.index+1,X=!1,J={},ne={},ce=!1;P<ue.length;){if(P=this.until(['"',"}"],P),E(ue,P)==="}"&&!X){P++,ce=!0;break}var _e=this.fork(P).string(),Pe=_e.value;P=_e.end,P=this.until([":"],P)+1,P=this.skip(q,P),_e=this.fork(P).parse(),v(ne,Pe,_e),v(J,Pe,_e.value),P=this.until([",","}"],_e.end);var it=E(ue,P);if(it===",")X=!0,P++;else if(it==="}"){P++,ce=!0;break}}if(!ce)throw new w("Unterminated object at: "+P);return this.node(I,J,this.index,P,ne)},array:function(){for(var ue=this.source,P=this.index+1,X=!1,J=[],ne=[],ce=!1;P<ue.length;){if(P=this.skip(q,P),E(ue,P)==="]"&&!X){P++,ce=!0;break}var _e=this.fork(P).parse();if(N(ne,_e),N(J,_e.value),P=this.until([",","]"],_e.end),E(ue,P)===",")X=!0,P++;else if(E(ue,P)==="]"){P++,ce=!0;break}}if(!ce)throw new w("Unterminated array at: "+P);return this.node(I,J,this.index,P,ne)},string:function(){var ue=this.index,P=y(this.source,this.index+1);return this.node(V,P.value,ue,P.end)},number:function(){var ue=this.source,P=this.index,X=P;if(E(ue,X)==="-"&&X++,E(ue,X)==="0")X++;else if(D(G,E(ue,X)))X=this.skip(O,X+1);else throw new w("Failed to parse number at: "+X);if(E(ue,X)==="."){var J=X+1;if(X=this.skip(O,J),J===X)throw new w("Failed to parse number's fraction at: "+X)}if(E(ue,X)==="e"||E(ue,X)==="E"){X++,(E(ue,X)==="+"||E(ue,X)==="-")&&X++;var ne=X;if(X=this.skip(O,X),ne===X)throw new w("Failed to parse number's exponent value at: "+X)}return this.node(V,k(x(ue,P,X)),P,X)},keyword:function(ue){var P=""+ue,X=this.index,J=X+P.length;if(x(this.source,X,J)!==P)throw new w("Failed to parse value at: "+X);return this.node(V,ue,X,J)},skip:function(ue,P){for(var X=this.source;P<X.length&&D(ue,E(X,P));P++);return P},until:function(ue,P){P=this.skip(q,P);for(var X=E(this.source,P),J=0;J<ue.length;J++)if(ue[J]===X)return P;throw new w('Unexpected character: "'+X+'" at: '+P)}};var ve=m(function(){var ue="9007199254740993",P;return T(ue,function(X,J,ne){P=ne.source}),P!==ue}),le=_&&!m(function(){return 1/T("-0 ")!==-1/0});n({target:"JSON",stat:!0,forced:ve},{parse:function(P,X){return le&&!l(X)?T(P):$(P,X)}})},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),d=t(5810),h=t(757),p=t(2195),g=t(655),v=t(7680),m=t(8235),y=t(3392),_=t(4495),b=t(7819),k=String,w=i("JSON","stringify"),T=a(/./.exec),A=a("".charAt),C=a("".charCodeAt),E=a("".replace),x=a("".slice),D=a([].push),N=a(1.1.toString),O=/[\uD800-\uDFFF]/g,G=/^[\uD800-\uDBFF]$/,Z=/^[\uDC00-\uDFFF]$/,q=y(),V=q.length,I=!_||c(function(){var oe=i("Symbol")("stringify detection");return w([oe])!=="[null]"||w({a:oe})!=="{}"||w(Object(oe))!=="{}"}),$=c(function(){return w("\uDF06\uD834")!=='"\\udf06\\ud834"'||w("\uDEAD")!=='"\\udead"'}),L=I?function(oe,ve){var le=v(arguments),ue=se(ve);if(!(!u(ue)&&(oe===void 0||h(oe))))return le[1]=function(P,X){if(u(ue)&&(X=o(ue,this,k(P),X)),!h(X))return X},r(w,null,le)}:w,K=function(oe,ve,le){var ue=A(le,ve-1),P=A(le,ve+1);return T(G,oe)&&!T(Z,P)||T(Z,oe)&&!T(G,ue)?"\\u"+N(C(oe,0),16):oe},se=function(oe){if(u(oe))return oe;if(l(oe)){for(var ve=oe.length,le=[],ue=0;ue<ve;ue++){var P=oe[ue];typeof P=="string"?D(le,P):(typeof P=="number"||p(P)==="Number"||p(P)==="String")&&D(le,g(P))}var X=le.length,J=!0;return function(ne,ce){if(J)return J=!1,ce;if(l(this))return ce;for(var _e=0;_e<X;_e++)if(le[_e]===ne)return ce}}};w&&n({target:"JSON",stat:!0,arity:3,forced:I||$||!b},{stringify:function(ve,le,ue){var P=se(le),X=[],J=L(ve,function(rt,Oe){var xe=u(P)?o(P,this,k(rt),Oe):Oe;return!b&&d(xe)?q+(D(X,xe.rawJSON)-1):xe},ue);if(typeof J!="string"||($&&(J=E(J,O,K)),b))return J;for(var ne="",ce=J.length,_e=0;_e<ce;_e++){var Pe=A(J,_e);if(Pe==='"'){var it=m(J,++_e).end-1,at=x(J,_e,it);ne+=x(at,0,V)===q?X[x(at,V)]:'"'+at+'"',_e=it}else ne+=Pe}return ne}})},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(d,h){var p=c(this,d);if(i(h),p)return a(this,d);d===0&&1/d===-1/0&&(d=0);var g=h(d);return l(this,d,g),g}})},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,d){return a(this,u)?o(this,u):(c(this,u,d),d)}})},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,d=Math.pow,h=i([].push),p=d(2,1023),g=d(2,53)-1,v=Number.MAX_VALUE,m=d(2,971),y={},_={},b={},k={},w={},T=function(A,C){var E=A+C,x=C-(E-A);return{hi:E,lo:x}};n({target:"Math",stat:!0},{sumPrecise:function(C){var E=[],x=0,D=k;switch(r(C,function(ue){if(++x>g)throw new o("Maximum allowed index exceeded");if(typeof ue!="number")throw new a("Value is not a number");D!==y&&(ue!==ue?D=y:ue===c?D=D===_?y:b:ue===-c?D=D===b?y:_:(ue!==0||1/ue===c)&&(D===k||D===w)&&(D=w,h(E,ue)))}),D){case y:return l;case _:return-c;case b:return c;case k:return-0}for(var N=[],O=0,G,Z,q,V,I,$,L=0;L<E.length;L++){G=E[L];for(var K=0,se=0;se<N.length;se++){if(Z=N[se],u(G)<u(Z)&&($=G,G=Z,Z=$),q=T(G,Z),V=q.hi,I=q.lo,u(V)===c){var oe=V===c?1:-1;O+=oe,G=G-oe*p-oe*p,u(G)<u(Z)&&($=G,G=Z,Z=$),q=T(G,Z),V=q.hi,I=q.lo}I!==0&&(N[K++]=I),G=V}N.length=K,G!==0&&h(N,G)}var ve=N.length-1;if(V=0,I=0,O!==0){var le=ve>=0?N[ve]:0;if(ve--,u(O)>1||O>0&&le>0||O<0&&le<0)return O>0?c:-c;if(q=T(O*p,le/2),V=q.hi,I=q.lo,I*=2,u(2*V)===c)return V>0?V===p&&I===-(m/2)&&ve>=0&&N[ve]<0?v:c:V===-p&&I===m/2&&ve>=0&&N[ve]>0?-v:-c;I!==0&&(N[++ve]=I,I=0),V*=2}for(;ve>=0&&(q=T(V,N[ve--]),V=q.hi,I=q.lo,I===0););return ve>=0&&(I<0&&N[ve]<0||I>0&&N[ve]>0)&&(Z=I*2,G=V+Z,Z===G-V&&(V=G)),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,d=!1,h=!u||!u.try||l(function(){u.try(function(p){d=p===8},8)}).error||!d;n({target:"Promise",stat:!0,forced:h},{try:function(p){var g=arguments.length>1?o(arguments,1):[],v=a.f(this),m=l(function(){return r(c(p),void 0,g)});return(m.error?v.reject:v.resolve)(m.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 d=0;return{next:function(){var h=d++>1;return u.has(1)&&u.clear(),{done:h,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,d=RangeError,h=function(){try{new Int8Array(1).with(2,{valueOf:function(){throw 8}})}catch(g){return g===8}}(),p=h&&function(){try{new Int8Array(1).with(-.5,1)}catch{return!0}}();u("with",function(g,v){var m=c(this),y=r(m),_=o(g),b=_<0?y+_:_,k=i(m)?a(v):+v;if(b>=y||b<0)throw new d("Incorrect index");for(var w=new(l(m))(y),T=0;T<y;T++)w[T]=T===b?k:m[T];return w},!h||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 d=o(u,arguments.length>1?arguments[1]:void 0,null,9007199254740991);return r(a,d.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 d=r(u,arguments.length>1?arguments[1]:void 0,this,this.length);return{read:d.read,written:d.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(d){o(this),r(d),a(this.buffer);var h=c(d,this).read;return{read:h,written:h/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),d=l.i2c,h=l.i2cUrl,p=r("".charAt),g=i.Uint8Array,v=!g||!g.prototype.toBase64||!function(){try{var m=new g;m.toBase64(null)}catch{return!0}}();g&&n({target:"Uint8Array",proto:!0,forced:v},{toBase64:function(){var y=a(this),_=arguments.length?o(arguments[0]):void 0,b=u(_)==="base64"?d:h,k=!!_&&!!_.omitPadding;c(this.buffer);for(var w="",T=0,A=y.length,C,E=function(x){return p(b,C>>6*x&63)};T+2<A;T+=3)C=(y[T]<<16)+(y[T+1]<<8)+y[T+2],w+=E(3)+E(2)+E(1)+E(0);return T+2===A?(C=(y[T]<<16)+(y[T+1]<<8),w+=E(3)+E(2)+E(1)+(k?"":"=")):T+1===A&&(C=y[T]<<16,w+=E(3)+E(2)+(k?"":"==")),w}})},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,d=i.Uint8Array,h=!d||!d.prototype.toHex||!function(){try{var p=new d([255,255,255,255,255,255,255,255]);return p.toHex()==="ffffffffffffffff"}catch{return!1}}();d&&n({target:"Uint8Array",proto:!0,forced:h},{toHex:function(){o(this),a(this.buffer);for(var g=u(this.length),v=0,m=this.length;v<m;v++){var y=c(this[v],16);g[v]=y.length===1?"0"+y:y}return l(g,"")}})},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,d=a.set,h=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:h},{getOrInsertComputed:function(g,v){if(c||r(this),o(g),i(v),u(this,g))return l(this,g);var m=v(g);return d(this,g,m),m}})},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,d){return a(this,u)?o(this,u):(c(this,u,d),d)}})},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),d=t(2603),h=t(5002),p=t(8574),g=t(3724),v=t(6395),m="DOMException",y=r("Error"),_=r(m),b=function(){l(this,k);var q=arguments.length,V=d(q<1?void 0:arguments[0]),I=d(q<2?void 0:arguments[1],"Error"),$=new _(V,I),L=new y(V);return L.name=m,a($,"stack",o(1,p(L.stack,1))),u($,this,b),$},k=b.prototype=_.prototype,w="stack"in new y(m),T="stack"in new _(1,2),A=_&&g&&Object.getOwnPropertyDescriptor(i,m),C=!!A&&!(A.writable&&A.configurable),E=w&&!C&&!T;n({global:!0,constructor:!0,forced:v||E},{DOMException:E?b:_});var x=r(m),D=x.prototype;if(D.constructor!==x){v||a(D,"constructor",o(1,x));for(var N in h)if(c(h,N)){var O=h[N],G=O.s;c(x,G)||a(x,G,o(6,O.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),d=i(c.forEach),h=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(g){var v=arguments.length,m=v<2?void 0:arguments[1];if(v&&m===void 0)return u(this,g);var y=[];d(this,function(A,C){h(y,{key:C,value:A})}),o(v,1);for(var _=r(g),b=r(m),k=0,w=y.length,T;k<w;)T=y[k],u(this,T.key),k++;for(k=0;k<w;)T=y[k++],T.key===_&&T.value===b||l(this,T.key,T.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),d=new a("a=1");(d.has("a",2)||!d.has("a",void 0))&&n(c,"has",function(p){var g=arguments.length,v=g<2?void 0:arguments[1];if(g&&v===void 0)return u(this,p);var m=l(this,p);o(g,1);for(var y=r(v),_=0;_<m.length;)if(m[_++]===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 d=r(arguments.length,1),h=o(u),p=d<2||arguments[1]===void 0?void 0:o(arguments[1]);try{return new c(h,p)}catch{return null}}})}},LI={};function Ct(s){var e=LI[s];if(e!==void 0)return e.exports;var t=LI[s]={exports:{}};return jte[s].call(t.exports,t,t.exports,Ct),t.exports}Ct.d=(s,e)=>{for(var t in e)Ct.o(e,t)&&!Ct.o(s,t)&&Object.defineProperty(s,t,{enumerable:!0,get:e[t]})};Ct.o=(s,e)=>Object.prototype.hasOwnProperty.call(s,e);Ct(4423);Ct(4114);Ct(6573);Ct(8100);Ct(7936);Ct(8111);Ct(2489);Ct(5367);Ct(2731);Ct(9577);Ct(6632);Ct(4226);Ct(9486);Ct(456);Ct(5781);const to=typeof process=="object"&&process+""=="[object process]"&&!process.versions.nw&&!(process.versions.electron&&process.type&&process.type!=="browser"),Sc=[1/0,1/0,-1/0,-1/0],Kd=new Float32Array(Sc),N1=[.001,0,0,.001,0,0],uT=1.35,Dr="http://www.w3.org/2000/svg",eo={ANY:1,DISPLAY:2,PRINT:4,ANNOTATIONS_FORMS:16,ANNOTATIONS_STORAGE:32,ANNOTATIONS_DISABLE:64,IS_EDITING:128,OPLIST:256},iu={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},Ap="pdfjs_internal_id_",Sy="pdfjs_internal_editor_",Et={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15,POPUP:16,SIGNATURE:101,COMMENT:102},Rt={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},Vte={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},On={FILL:0,STROKE:1,FILL_STROKE:2,INVISIBLE:3,FILL_STROKE_MASK:3,ADD_TO_PATH_FLAG:4},Hw={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},Sn={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},bp={SOLID:1,DASHED:2,BEVELED:3,INSET:4,UNDERLINE:5},Tk={ERRORS:0,WARNINGS:1,INFOS:5},$l={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},Bg={moveTo:0,lineTo:1,curveTo:2,quadraticCurveTo:3,closePath:4},Gte={NEED_PASSWORD:1,INCORRECT_PASSWORD:2};let Ak=Tk.WARNINGS;function Kte(s){Number.isInteger(s)&&(Ak=s)}function qte(){return Ak}function Ek(s){Ak>=Tk.INFOS&&console.info(`Info: ${s}`)}function At(s){Ak>=Tk.WARNINGS&&console.warn(`Warning: ${s}`)}function ss(s){throw new Error(s)}function Ys(s,e){s||ss(e)}function Qte(s){switch(s==null?void 0:s.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}function nN(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=Jte(s)}catch{}}const n=e?URL.parse(s,e):URL.parse(s);return Qte(n)?n:null}function iN(s,e,t=!1){const n=URL.parse(s);return n?(n.hash=e,n.href):t&&nN(s,"http://example.com")?s.split("#",1)[0]+`${e?`#${e}`:""}`:""}function $1(s){return s.substring(s.lastIndexOf("/")+1)}function Mt(s,e,t,n=!1){return Object.defineProperty(s,e,{value:t,enumerable:!n,configurable:!0,writable:!1}),t}const Wf=function(){function e(t,n){this.message=t,this.name=n}return e.prototype=new Error,e.constructor=e,e}();class OI extends Wf{constructor(e,t){super(e,"PasswordException"),this.code=t}}class dT extends Wf{constructor(e,t){super(e,"UnknownErrorException"),this.details=t}}class B1 extends Wf{constructor(e){super(e,"InvalidPDFException")}}class k0 extends Wf{constructor(e,t,n){super(e,"ResponseException"),this.status=t,this.missing=n}}class Xte extends Wf{constructor(e){super(e,"FormatError")}}class pd extends Wf{constructor(e){super(e,"AbortException")}}function Yte(s){(typeof s!="object"||(s==null?void 0:s.length)===void 0)&&ss("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 Mk(s){typeof s!="string"&&ss("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 Rs{static get isLittleEndian(){const e=new Uint8Array(4);e[0]=1;const t=new Uint32Array(e.buffer,0,1);return Mt(this,"isLittleEndian",t[0]===1)}static get isOffscreenCanvasSupported(){return Mt(this,"isOffscreenCanvasSupported",typeof OffscreenCanvas<"u")}static get isImageDecoderSupported(){return Mt(this,"isImageDecoderSupported",typeof ImageDecoder<"u")}static get isFloat16ArraySupported(){return Mt(this,"isFloat16ArraySupported",typeof Float16Array<"u")}static get isSanitizerSupported(){return Mt(this,"isSanitizerSupported",typeof Sanitizer<"u")}static get platform(){const{platform:e,userAgent:t}=navigator;return Mt(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")),Mt(this,"isCanvasFilterSupported",(e==null?void 0:e.filter)!==void 0)}static get isAlphaColorInputSupported(){if(typeof document>"u")return Mt(this,"isAlphaColorInputSupported",!1);const e=document.createElement("input");return e.type="color",e.setAttribute("alpha",""),e.value="#ff000080",Mt(this,"isAlphaColorInputSupported",e.value!=="#ff0000")}}var xc,Uw,F1;class Fe{static get hexNums(){return Mt(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 d=e[n+u],h=e[n+u+1];e[n+u]=d*i+h*o+c,e[n+u+1]=d*r+h*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],d=e[1],h=e[2],p=e[3];let g=i*u+c,v=g,m=i*h+c,y=m,_=a*d+l,b=_,k=a*p+l,w=k;if(r!==0||o!==0){const T=r*u,A=r*h,C=o*d,E=o*p;g+=C,y+=C,m+=E,v+=E,_+=T,w+=T,k+=A,b+=A}n[0]=Math.min(n[0],g,m,v,y),n[1]=Math.min(n[1],_,k,b,w),n[2]=Math.max(n[2],g,m,v,y),n[3]=Math.max(n[3],_,k,b,w)}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,d=Math.sqrt(u**2-(a*l-c**2));t[0]=Math.sqrt(u+d||1),t[1]=Math.sqrt(u-d||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),H(this,xc,F1).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),H(this,xc,F1).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)}}xc=new WeakSet,Uw=function(e,t,n,i,r,o,a,c,l,u){if(l<=0||l>=1)return;const d=1-l,h=l*l,p=h*l,g=d*(d*(d*e+3*l*t)+3*h*n)+p*i,v=d*(d*(d*r+3*l*o)+3*h*a)+p*c;u[0]=Math.min(u[0],g),u[1]=Math.min(u[1],v),u[2]=Math.max(u[2],g),u[3]=Math.max(u[3],v)},F1=function(e,t,n,i,r,o,a,c,l,u,d,h){if(Math.abs(l)<1e-12){Math.abs(u)>=1e-12&&H(this,xc,Uw).call(this,e,t,n,i,r,o,a,c,-d/u,h);return}const p=u**2-4*d*l;if(p<0)return;const g=Math.sqrt(p),v=2*l;H(this,xc,Uw).call(this,e,t,n,i,r,o,a,c,(-u+g)/v,h),H(this,xc,Uw).call(this,e,t,n,i,r,o,a,c,(-u-g)/v,h)},B(Fe,xc);function Jte(s){return decodeURIComponent(escape(s))}let hT=null,DI=null;function Zte(s){return hT||(hT=/([\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,DI=new Map([["ſt","ſt"]])),s.replaceAll(hT,(e,t,n)=>t?t.normalize("NFKC"):DI.get(n))}function rN(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();const s=new Uint8Array(32);return crypto.getRandomValues(s),Yte(s)}function ese(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=()=>[],EM=()=>new Map,H1=()=>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())});Ct(1701);Ct(4603);Ct(7566);Ct(8721);function zs(s,e,t){return Math.min(Math.max(s,e),t)}class y_{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,d,h,p;switch(i%=360,i<0&&(i+=360),i){case 180:u=-1,d=0,h=0,p=1;break;case 90:u=0,d=1,h=1,p=0;break;case 270:u=0,d=-1,h=-1,p=0;break;case 0:u=1,d=0,h=0,p=-1;break;default:throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.")}a&&(h=-h,p=-p);let g,v,m,y;u===0?(g=Math.abs(l-e[1])*n+r,v=Math.abs(c-e[0])*n+o,m=(e[3]-e[1])*n,y=(e[2]-e[0])*n):(g=Math.abs(c-e[0])*n+r,v=Math.abs(l-e[1])*n+o,m=(e[2]-e[0])*n,y=(e[3]-e[1])*n),this.transform=[u*n,d*n,h*n,p*n,g-u*n*c-h*n*l,v-d*n*c-p*n*l],this.width=m,this.height=y}get rawDims(){const e=this.viewBox;return Mt(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 y_({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 Fe.applyTransform(n,this.transform),n}convertToViewportRectangle(e){const t=[e[0],e[1]];Fe.applyTransform(t,this.transform);const n=[e[2],e[3]];return Fe.applyTransform(n,this.transform),[t[0],t[1],n[0],n[1]]}convertToPdfPoint(e,t){const n=[e,t];return Fe.applyInverseTransform(n,this.transform),n}}class ky{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(ky.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 oN{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 d,h;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&&ky.shouldBuildText(i.name)&&l.push(p)}return{textDivs:l}}const u=[[i,-1,o]];for(;u.length>0;){const[p,g,v]=u.at(-1);if(g+1===p.children.length){u.pop();continue}const m=p.children[++u.at(-1)[1]];if(m===null)continue;const{name:y}=m;if(y==="#text"){const b=document.createTextNode(m.value);l.push(b),v.append(b);continue}const _=(d=m==null?void 0:m.attributes)!=null&&d.xmlns?document.createElementNS(m.attributes.xmlns,y):document.createElement(y);if(v.append(_),m.attributes&&this.setAttributes({html:_,element:m,storage:t,intent:r,linkService:n}),((h=m.children)==null?void 0:h.length)>0)u.push([m,-1,_]);else if(m.value){const b=document.createTextNode(m.value);a&&ky.shouldBuildText(y)&&l.push(b),_.append(b)}}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 y_({viewBox:[0,0,parseInt(i,10),parseInt(r,10)],userUnit:1,scale:t,rotation:n})}}const Nd=class Nd{};Se(Nd,"CSS",96),Se(Nd,"PDF",72),Se(Nd,"PDF_TO_CSS_UNITS",Nd.CSS/Nd.PDF);let md=Nd;async function MM(s,e="text"){if(ey(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 xM extends Wf{constructor(e,t=0){super(e,"RenderingCancelledException"),this.extraDelay=t}}function xk(s){const e=s.length;let t=0;for(;t<e&&s[t].trim()==="";)t++;return s.substring(t,t+5).toLowerCase()==="data:"}function RM(s){return typeof s=="string"&&/\.pdf$/i.test(s)}function tse(s){return[s]=s.split(/[#?]/,1),$1(s)}function sse(s,e="document.pdf"){if(typeof s!="string")return e;if(xk(s))return At('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=$1(c),c.length===4&&r.test(c))?a:c}catch{return a}},r=/\.pdf$/i,o=$1(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 ru;class NI{constructor(){B(this,ru,new Map);Se(this,"times",[])}time(e){f(this,ru).has(e)&&At(`Timer is already running for ${e}`),f(this,ru).set(e,Date.now())}timeEnd(e){f(this,ru).has(e)||At(`Timer has not been started for ${e}`),this.times.push({name:e,start:f(this,ru).get(e),end:Date.now()}),f(this,ru).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("")}}ru=new WeakMap;function ey(s,e){const t=e?URL.parse(s,e):URL.parse(s);return/https?:/.test((t==null?void 0:t.protocol)??"")}function Go(s){s.preventDefault()}function Xs(s){s.preventDefault(),s.stopPropagation()}var xy;class C0{static toDateObject(e){if(e instanceof Date)return e;if(!e||typeof e!="string")return null;f(this,xy)||R(this,xy,new RegExp("^D:(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?([Z|+\\-])?(\\d{2})?'?(\\d{2})?'?"));const t=f(this,xy).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 d=parseInt(t[9],10)||0;return d=d>=0&&d<=59?d:0,l==="-"?(o+=u,a+=d):l==="+"&&(o-=u,a-=d),new Date(Date.UTC(n,i,r,o,a,c))}}xy=new WeakMap,B(C0,xy);function b_(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 __(s){const e=b_(s);return e?e.slice(0,3):(At(`Not a valid color format: "${s}"`),[0,0,0])}function nse(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,__(n))}e.remove()}function xs(s){const{a:e,b:t,c:n,d:i,e:r,f:o}=s.getTransform();return[e,t,n,i,r,o]}function Ea(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 $f(s,e,t=!1,n=!0){if(e instanceof y_){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 hl{constructor(){const{pixelRatio:e}=hl;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=hl.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 U1=["image/apng","image/avif","image/bmp","image/gif","image/jpeg","image/png","image/svg+xml","image/webp","image/x-icon"];class ise{static get isDarkMode(){var e;return Mt(this,"isDarkMode",!!((e=window==null?void 0:window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches))}}class rse{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(),Mt(this,"commentForegroundColor",__(n))}}function ose(s,e){e=zs(e??1,0,1);const t=255*(1-e);return s.map(n=>Math.round(n*e+t))}function $I(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 W1(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 BI(s){return s<=.03928?s/12.92:((s+.055)/1.055)**2.4}function FI(s,e,t){W1(s,t),t.map(BI);const n=.2126*t[0]+.7152*t[1]+.0722*t[2];W1(e,t),t.map(BI);const i=.2126*t[0]+.7152*t[1]+.0722*t[2];return n>i?(n+.05)/(i+.05):(i+.05)/(n+.05)}const HI=new Map;function ase(s,e){const t=s[0]+s[1]*256+s[2]*65536+e[0]*16777216+e[1]*4294967296+e[2]*1099511627776;let n=HI.get(t);if(n)return n;const i=new Float32Array(9),r=i.subarray(0,3),o=i.subarray(3,6);$I(s,o);const a=i.subarray(6,9);$I(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]),FI(o,a,r)<l){let u,d;c?(u=o[2],d=1):(u=0,d=o[2]);const h=.005;for(;d-u>h;){const p=o[2]=(u+d)/2;c===FI(o,a,r)<l?u=p:d=p}o[2]=c?d:u}return W1(o,r),n=Fe.makeHexColor(Math.round(r[0]*255),Math.round(r[1]*255),Math.round(r[2]*255)),HI.set(t,n),n}function aN({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 oN.render({xfaHtml:s,div:i,intent:"richText"});i.firstElementChild.classList.add("richText",t),n.append(i)}function lN(s){const e=new Path2D;if(!s)return e;for(let t=0,n=s.length;t<n;)switch(s[t++]){case Bg.moveTo:e.moveTo(s[t++],s[t++]);break;case Bg.lineTo:e.lineTo(s[t++],s[t++]);break;case Bg.curveTo:e.bezierCurveTo(s[t++],s[t++],s[t++],s[t++],s[t++],s[t++]);break;case Bg.quadraticCurveTo:e.quadraticCurveTo(s[t++],s[t++],s[t++],s[t++]);break;case Bg.closePath:e.closePath();break;default:At(`Unrecognized drawing path operator: ${s[t-1]}`);break}return e}Ct(4972);Ct(4628);Ct(7642);Ct(8004);Ct(3853);Ct(5876);Ct(2475);Ct(5024);Ct(1698);Ct(8454);Ct(9452);Ct(4979);Ct(3579);Ct(3110);Ct(9314);Ct(1148);Ct(9112);var ou,au,wo,So,Ry,lu,Lp,Op,Iy,D0,cN,di,uN,dN,_p,uv;const Ol=class Ol{constructor(e){B(this,di);B(this,ou,null);B(this,au,null);B(this,wo);B(this,So,null);B(this,Ry,null);B(this,lu,null);B(this,Lp,null);B(this,Op,null);R(this,wo,e),f(Ol,Iy)||R(Ol,Iy,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=R(this,ou,document.createElement("div"));e.classList.add("editToolbar","hidden"),e.setAttribute("role","toolbar");const t=f(this,wo)._uiManager._signal;t instanceof AbortSignal&&!t.aborted&&(e.addEventListener("contextmenu",Go,{signal:t}),e.addEventListener("pointerdown",H(Ol,D0,cN),{signal:t}));const n=R(this,So,document.createElement("div"));n.className="buttons",e.append(n);const i=f(this,wo).toolbarPosition;if(i){const{style:r}=e,o=f(this,wo)._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,ou)}hide(){var e;f(this,ou).classList.add("hidden"),(e=f(this,au))==null||e.hideDropdown()}show(){var e,t;f(this,ou).classList.remove("hidden"),(e=f(this,Ry))==null||e.shown(),(t=f(this,lu))==null||t.shown()}addDeleteButton(){const{editorType:e,_uiManager:t}=f(this,wo),n=document.createElement("button");n.classList.add("basic","deleteButton"),n.tabIndex=0,n.setAttribute("data-l10n-id",f(Ol,Iy)[e]),H(this,di,_p).call(this,n)&&n.addEventListener("click",i=>{t.delete()},{signal:t._signal}),f(this,So).append(n)}async addAltText(e){const t=await e.render();H(this,di,_p).call(this,t),f(this,So).append(t,f(this,di,uv)),R(this,Ry,e)}addComment(e,t=null){if(f(this,lu))return;const n=e.renderForToolbar();if(!n)return;H(this,di,_p).call(this,n);const i=R(this,Lp,f(this,di,uv));t?(f(this,So).insertBefore(n,t),f(this,So).insertBefore(i,t)):f(this,So).append(n,i),R(this,lu,e),e.toolbar=this}addColorPicker(e){if(f(this,au))return;R(this,au,e);const t=e.renderButton();H(this,di,_p).call(this,t),f(this,So).append(t,f(this,di,uv))}async addEditSignatureButton(e){const t=R(this,Op,await e.renderEditButton(f(this,wo)));H(this,di,_p).call(this,t),f(this,So).append(t,f(this,di,uv))}removeButton(e){var t,n;switch(e){case"comment":(t=f(this,lu))==null||t.removeToolbarCommentButton(),R(this,lu,null),(n=f(this,Lp))==null||n.remove(),R(this,Lp,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,So).querySelector(n);i&&e==="comment"&&this.addComment(t,i)}updateEditSignatureButton(e){f(this,Op)&&(f(this,Op).title=e)}remove(){var e;f(this,ou).remove(),(e=f(this,au))==null||e.destroy(),R(this,au,null)}};ou=new WeakMap,au=new WeakMap,wo=new WeakMap,So=new WeakMap,Ry=new WeakMap,lu=new WeakMap,Lp=new WeakMap,Op=new WeakMap,Iy=new WeakMap,D0=new WeakSet,cN=function(e){e.stopPropagation()},di=new WeakSet,uN=function(e){f(this,wo)._focusEventsAllowed=!1,Xs(e)},dN=function(e){f(this,wo)._focusEventsAllowed=!0,Xs(e)},_p=function(e){const t=f(this,wo)._uiManager._signal;return!(t instanceof AbortSignal)||t.aborted?!1:(e.addEventListener("focusin",H(this,di,uN).bind(this),{capture:!0,signal:t}),e.addEventListener("focusout",H(this,di,dN).bind(this),{capture:!0,signal:t}),e.addEventListener("contextmenu",Go,{signal:t}),!0)},uv=function(){const e=document.createElement("div");return e.className="divider",e},B(Ol,D0),B(Ol,Iy,null);let z1=Ol;var Py,Xd,Fl,Oc,hN,fN,j1;class lse{constructor(e){B(this,Oc);B(this,Py,null);B(this,Xd,null);B(this,Fl);R(this,Fl,e)}show(e,t,n){const[i,r]=H(this,Oc,fN).call(this,t,n),{style:o}=f(this,Xd)||R(this,Xd,H(this,Oc,hN).call(this));e.append(f(this,Xd)),o.insetInlineEnd=`${100*i}%`,o.top=`calc(${100*r}% + var(--editor-toolbar-vert-offset))`}hide(){f(this,Xd).remove()}}Py=new WeakMap,Xd=new WeakMap,Fl=new WeakMap,Oc=new WeakSet,hN=function(){const e=R(this,Xd,document.createElement("div"));e.className="editToolbar",e.setAttribute("role","toolbar");const t=f(this,Fl)._signal;t instanceof AbortSignal&&!t.aborted&&e.addEventListener("contextmenu",Go,{signal:t});const n=R(this,Py,document.createElement("div"));return n.className="buttons",e.append(n),f(this,Fl).hasCommentManager()&&H(this,Oc,j1).call(this,"commentButton","pdfjs-comment-floating-button","pdfjs-comment-floating-button-label",()=>{f(this,Fl).commentSelection("floating_button")}),H(this,Oc,j1).call(this,"highlightButton","pdfjs-highlight-floating-button1","pdfjs-highlight-floating-button-label",()=>{f(this,Fl).highlightSelection("floating_button")}),e},fN=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]},j1=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,Fl)._signal;a instanceof AbortSignal&&!a.aborted&&(r.addEventListener("contextmenu",Go,{signal:a}),r.addEventListener("click",i,{signal:a})),f(this,Py).append(r)};const cse="9556e50a-f4f8-4f57-9831-f9ddff0176eb",use=Object.freeze({internal:cse});function pN(s,e,t){for(const n of t)e.addEventListener(n,s[n].bind(s))}var Yd,Jd,Dp,Zd;const ys=class ys{static initializeAndAddPointerId(e){(f(ys,Jd)||R(ys,Jd,new Set)).add(e)}static setPointer(e,t){f(ys,Yd)||R(ys,Yd,t),f(ys,Zd)??R(ys,Zd,e)}static setTimeStamp(e){R(ys,Dp,e)}static isSamePointerId(e){return f(ys,Yd)===e}static isSamePointerIdOrRemove(e){var t;return f(ys,Yd)===e?!0:((t=f(ys,Jd))==null||t.delete(e),!1)}static isSamePointerType(e){return f(ys,Zd)===e}static isInitializedAndDifferentPointerType(e){return f(ys,Zd)!==null&&!ys.isSamePointerType(e)}static isSameTimeStamp(e){return f(ys,Dp)===e}static isUsingMultiplePointers(){var e;return((e=f(ys,Jd))==null?void 0:e.size)>=1}static clearPointerType(){R(ys,Zd,null)}static clearPointerIds(){R(ys,Yd,NaN),R(ys,Jd,null)}static clearTimeStamp(){R(ys,Dp,NaN)}};Yd=new WeakMap,Jd=new WeakMap,Dp=new WeakMap,Zd=new WeakMap,B(ys,Yd,NaN),B(ys,Jd,null),B(ys,Dp,NaN),B(ys,Zd,null);let bi=ys;var N0;class dse{constructor(){B(this,N0,0)}get id(){return`${Sy}${Ls(this,N0)._++}`}}N0=new WeakMap;var Np,Ly,_i,$p,Ww;const UM=class UM{constructor(){B(this,$p);B(this,Np,rN());B(this,Ly,0);B(this,_i,null)}static get _isSVGFittingCanvas(){const e=`data:image/svg+xml;charset=UTF-8,<svg viewBox="0 0 1 1" width="1" height="1" xmlns="${Dr}"><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 Mt(this,"_isSVGFittingCanvas",r)}async getFromFile(e){const{lastModified:t,name:n,size:i,type:r}=e;return H(this,$p,Ww).call(this,`${t}_${n}_${i}_${r}`,e)}async getFromUrl(e){return H(this,$p,Ww).call(this,e,e)}async getFromBlob(e,t){const n=await t;return H(this,$p,Ww).call(this,e,n)}async getFromId(e){f(this,_i)||R(this,_i,new Map);const t=f(this,_i).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,_i)||R(this,_i,new Map);let n=f(this,_i).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,Np)}_${Ls(this,Ly)._++}`,refCounter:1,isSvg:!1},f(this,_i).set(e,n),f(this,_i).set(n.id,n),n}getSvgUrl(e){const t=f(this,_i).get(e);return t!=null&&t.isSvg?t.svgUrl:null}deleteId(e){var i;f(this,_i)||R(this,_i,new Map);const t=f(this,_i).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,Np)}_`)}};Np=new WeakMap,Ly=new WeakMap,_i=new WeakMap,$p=new WeakSet,Ww=async function(e,t){f(this,_i)||R(this,_i,new Map);let n=f(this,_i).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,Np)}_${Ls(this,Ly)._++}`,refCounter:0,isSvg:!1});let i;if(typeof t=="string"?(n.url=t,i=await MM(t,"blob")):t instanceof File?i=n.file=t:t instanceof Blob&&(i=t),i.type==="image/svg+xml"){const r=UM._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 d=n.svgUrl=o.result;a.src=await r?`${d}#svgView(preserveAspectRatio(none))`:d},a.onerror=o.onerror=u});o.readAsDataURL(i),await c}else n.bitmap=await createImageBitmap(i);n.refCounter=1}catch(i){At(i),n=null}return f(this,_i).set(e,n),n&&f(this,_i).set(n.id,n),n};let V1=UM;var gn,cu,Oy,qs;class hse{constructor(e=128){B(this,gn,[]);B(this,cu,!1);B(this,Oy);B(this,qs,-1);R(this,Oy,e)}add({cmd:e,undo:t,post:n,mustExec:i,type:r=NaN,overwriteIfSameType:o=!1,keepUndo:a=!1}){if(i&&e(),f(this,cu))return;const c={cmd:e,undo:t,post:n,type:r};if(f(this,qs)===-1){f(this,gn).length>0&&(f(this,gn).length=0),R(this,qs,0),f(this,gn).push(c);return}if(o&&f(this,gn)[f(this,qs)].type===r){a&&(c.undo=f(this,gn)[f(this,qs)].undo),f(this,gn)[f(this,qs)]=c;return}const l=f(this,qs)+1;l===f(this,Oy)?f(this,gn).splice(0,1):(R(this,qs,l),l<f(this,gn).length&&f(this,gn).splice(l)),f(this,gn).push(c)}undo(){if(f(this,qs)===-1)return;R(this,cu,!0);const{undo:e,post:t}=f(this,gn)[f(this,qs)];e(),t==null||t(),R(this,cu,!1),R(this,qs,f(this,qs)-1)}redo(){if(f(this,qs)<f(this,gn).length-1){R(this,qs,f(this,qs)+1),R(this,cu,!0);const{cmd:e,post:t}=f(this,gn)[f(this,qs)];e(),t==null||t(),R(this,cu,!1)}}hasSomethingToUndo(){return f(this,qs)!==-1}hasSomethingToRedo(){return f(this,qs)<f(this,gn).length-1}cleanType(e){if(f(this,qs)!==-1){for(let t=f(this,qs);t>=0;t--)if(f(this,gn)[t].type!==e){f(this,gn).splice(t+1,f(this,qs)-t),R(this,qs,t);return}f(this,gn).length=0,R(this,qs,-1)}}destroy(){R(this,gn,null)}}gn=new WeakMap,cu=new WeakMap,Oy=new WeakMap,qs=new WeakMap;var $0,mN;class w_{constructor(e){B(this,$0);this.buffer=[],this.callbacks=new Map,this.allKeys=new Set;const{isMac:t}=Rs.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(H(this,$0,mN).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||Xs(t))}}$0=new WeakSet,mN=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 B0=class B0{get _colors(){const e=new Map([["CanvasText",null],["Canvas",null]]);return nse(e),Mt(this,"_colors",e)}convert(e){const t=__(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 B0._colorsMapping.get(n);return t}getHexCode(e){const t=this._colors.get(e);return t?Fe.makeHexColor(...t):e}};Se(B0,"_colorsMapping",new Map([["CanvasText",[0,0,0]],["Canvas",[255,255,255]]]));let G1=B0;var Bp,Nr,Fp,rn,Qs,Hp,Up,Ki,Wp,ko,Fn,uu,du,hu,fu,Na,Co,eh,Dy,Ny,zp,$y,$a,pu,jp,mu,Ba,F0,Hl,Vp,By,gu,th,Gp,vu,Fy,kn,ps,Ul,yu,bu,Hy,Kp,Uy,_u,Fa,Wl,Wy,zy,To,je,zw,K1,gN,vN,yN,dv,bN,_N,wN,q1,SN,kN,CN,TN,ji,Il,AN,EN,Q1,MN,hv,X1;const Ep=class Ep{constructor(e,t,n,i,r,o,a,c,l,u,d,h,p,g,v,m){B(this,je);B(this,Bp,new AbortController);B(this,Nr,null);B(this,Fp,null);B(this,rn,new Map);B(this,Qs,new Map);B(this,Hp,null);B(this,Up,null);B(this,Ki,null);B(this,Wp,null);B(this,ko,new hse);B(this,Fn,null);B(this,uu,null);B(this,du,null);B(this,hu,0);B(this,fu,new Set);B(this,Na,null);B(this,Co,null);B(this,eh,new Set);Se(this,"_editorUndoBar",null);B(this,Dy,!1);B(this,Ny,!1);B(this,zp,!1);B(this,$y,null);B(this,$a,null);B(this,pu,null);B(this,jp,null);B(this,mu,!1);B(this,Ba,null);B(this,F0,new dse);B(this,Hl,!1);B(this,Vp,!1);B(this,By,!1);B(this,gu,null);B(this,th,null);B(this,Gp,null);B(this,vu,null);B(this,Fy,null);B(this,kn,Et.NONE);B(this,ps,new Set);B(this,Ul,null);B(this,yu,null);B(this,bu,null);B(this,Hy,null);B(this,Kp,null);B(this,Uy,{isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1});B(this,_u,[0,0]);B(this,Fa,null);B(this,Wl,null);B(this,Wy,null);B(this,zy,null);B(this,To,null);const y=this._signal=f(this,Bp).signal;R(this,Wl,e),R(this,Wy,t),R(this,zy,n),R(this,Up,i),R(this,Fn,r),R(this,yu,o),R(this,Kp,c),this._eventBus=a;const _={signal:y,...use};a.on("editingaction",this.onEditingAction.bind(this),_),a.on("pagechanging",this.onPageChanging.bind(this),_),a.on("scalechanging",this.onScaleChanging.bind(this),_),a.on("rotationchanging",this.onRotationChanging.bind(this),_),a.on("setpreference",this.onSetPreference.bind(this),_),a.on("switchannotationeditorparams",b=>this.updateParams(b.type,b.value),_),window.addEventListener("pointerdown",()=>{R(this,Vp,!0)},{capture:!0,signal:y}),window.addEventListener("pointerup",()=>{R(this,Vp,!1)},{capture:!0,signal:y}),window.addEventListener("beforeunload",H(this,je,gN).bind(this),{capture:!0,signal:y}),H(this,je,bN).call(this),H(this,je,TN).call(this),H(this,je,q1).call(this),R(this,Ki,c.annotationStorage),R(this,$y,c.filterFactory),R(this,bu,l),R(this,jp,u||null),R(this,Dy,d),R(this,Ny,h),R(this,zp,p),R(this,Fy,g||null),this.viewParameters={realScale:md.PDF_TO_CSS_UNITS,rotation:0},this.isShiftKeyDown=!1,this._editorUndoBar=v||null,this._supportsPinchToZoom=m!==!1,r==null||r.setSidebarUiManager(this)}static get _keyboardManager(){const e=Ep.prototype,t=o=>f(o,Wl).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 Mt(this,"_keyboardManager",new w_([[["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,Wl).contains(a)&&!o.isEnterHandled}],[[" ","mac+ "],e.addNewEditorFromKeyboard,{checker:(o,{target:a})=>!(a instanceof HTMLButtonElement)&&f(o,Wl).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,To))==null||e.resolve(),R(this,To,null),(t=f(this,Bp))==null||t.abort(),R(this,Bp,null),this._signal=null;for(const u of f(this,Qs).values())u.destroy();f(this,Qs).clear(),f(this,rn).clear(),f(this,eh).clear(),(n=f(this,vu))==null||n.clear(),R(this,Nr,null),f(this,ps).clear(),f(this,ko).destroy(),(i=f(this,Up))==null||i.destroy(),(r=f(this,Fn))==null||r.destroy(),(o=f(this,yu))==null||o.destroy(),(a=f(this,Ba))==null||a.hide(),R(this,Ba,null),(c=f(this,Gp))==null||c.destroy(),R(this,Gp,null),R(this,Fp,null),f(this,$a)&&(clearTimeout(f(this,$a)),R(this,$a,null)),f(this,Fa)&&(clearTimeout(f(this,Fa)),R(this,Fa,null)),(l=this._editorUndoBar)==null||l.destroy(),R(this,Kp,null)}combinedSignal(e){return AbortSignal.any([this._signal,e.signal])}get mlManager(){return f(this,Fy)}get useNewAltTextFlow(){return f(this,Ny)}get useNewAltTextWhenAddingImage(){return f(this,zp)}get hcmFilter(){return Mt(this,"hcmFilter",f(this,bu)?f(this,$y).addHCMFilter(f(this,bu).foreground,f(this,bu).background):"none")}get direction(){return Mt(this,"direction",getComputedStyle(f(this,Wl)).direction)}get _highlightColors(){return Mt(this,"_highlightColors",f(this,jp)?new Map(f(this,jp).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 Mt(this,"highlightColors",null);const t=new Map,n=!!f(this,bu);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 Mt(this,"highlightColors",t)}get highlightColorNames(){return Mt(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),R(this,du,e)}setMainHighlightColorPicker(e){R(this,Gp,e)}editAltText(e,t=!1){var n;(n=f(this,Up))==null||n.editAltText(this,e,t)}hasCommentManager(){return!!f(this,Fn)}editComment(e,t,n,i){var r;(r=f(this,Fn))==null||r.showDialog(this,e,t,n,i)}selectComment(e,t){const n=f(this,Qs).get(e),i=n==null?void 0:n.getEditorByUID(t);i==null||i.toggleComment(!0,!0)}updateComment(e){var t;(t=f(this,Fn))==null||t.updateComment(e.getData())}updatePopupColor(e){var t;(t=f(this,Fn))==null||t.updatePopupColor(e)}removeComment(e){var t;(t=f(this,Fn))==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,Fn))==null||i.toggleCommentPopup(e,t,n)}makeCommentColor(e,t){var n;return e&&((n=f(this,Fn))==null?void 0:n.makeCommentColor(e,t))||null}getCommentDialogElement(){var e;return((e=f(this,Fn))==null?void 0:e.dialogElement)||null}async waitForEditorsRendered(e){if(f(this,Qs).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,yu))==null||t.getSignature({uiManager:this,editor:e})}get signatureManager(){return f(this,yu)}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":R(this,zp,t);break}}onPageChanging({pageNumber:e}){R(this,hu,e-1)}deletePage(e){for(const t of this.getEditors(e))t.remove();f(this,Qs).delete(e),f(this,hu)===e&&R(this,hu,0)}focusMainContainer(){f(this,Wl).focus()}findParent(e,t){for(const n of f(this,Qs).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,Wy).classList.toggle("noUserSelect",e)}addShouldRescale(e){f(this,eh).add(e)}removeShouldRescale(e){f(this,eh).delete(e)}onScaleChanging({scale:e}){var t;this.commitOrRemove(),this.viewParameters.realScale=e*md.PDF_TO_CSS_UNITS;for(const n of f(this,eh))n.onScaleChanging();(t=f(this,du))==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=H(this,je,zw).call(this,n).closest(".textLayer"),d=this.getSelectionBoxes(u);if(!d)return;n.empty();const h=H(this,je,K1).call(this,u),p=f(this,kn)===Et.NONE,g=()=>{const v=h==null?void 0:h.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:e,boxes:d,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(Et.HIGHLIGHT,g);return}g()}commentSelection(e=""){this.highlightSelection(e,!0)}getAndRemoveDataFromAnnotationStorage(e){if(!f(this,Ki))return null;const t=`${Sy}${e}`,n=f(this,Ki).getRawValue(t);return n&&f(this,Ki).remove(t),n}addToAnnotationStorage(e){!e.isEmpty()&&f(this,Ki)&&!f(this,Ki).has(e.id)&&f(this,Ki).setValue(e.id,e)}a11yAlert(e,t=null){const n=f(this,zy);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,mu)&&(R(this,mu,!1),H(this,je,dv).call(this,"main_toolbar")),!this.hasSelection)return;const{activeElement:e}=document;for(const t of f(this,ps))if(t.div.contains(e)){R(this,th,[t,e]),t._focusEventsAllowed=!1;break}}focus(){if(!f(this,th))return;const[e,t]=f(this,th);R(this,th,null),t.addEventListener("focusin",()=>{e._focusEventsAllowed=!0},{once:!0,signal:this._signal}),t.focus()}addEditListeners(){H(this,je,q1).call(this),this.setEditingState(!0)}removeEditListeners(){H(this,je,SN).call(this),this.setEditingState(!1)}dragOver(e){for(const{type:t}of e.dataTransfer.items)for(const n of f(this,Co))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,Co))if(n.isHandlingMimeForPasting(t.type)){n.paste(t,this.currentLayer),e.preventDefault();return}}copy(e){var n;if(e.preventDefault(),(n=f(this,Nr))==null||n.commitOrRemove(),!this.hasSelection)return;const t=[];for(const i of f(this,ps)){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,Co))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){At(`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)H(this,je,Q1).call(this,c);H(this,je,X1).call(this,r)},a=()=>{for(const c of r)c.remove()};this.addCommands({cmd:o,undo:a,mustExec:!0})}catch(r){At(`paste: "${r.message}".`)}}keydown(e){!this.isShiftKeyDown&&e.key==="Shift"&&(this.isShiftKeyDown=!0),f(this,kn)!==Et.NONE&&!this.isEditorHandlingKeyboard&&Ep._keyboardManager.exec(this,e)}keyup(e){this.isShiftKeyDown&&e.key==="Shift"&&(this.isShiftKeyDown=!1,f(this,mu)&&(R(this,mu,!1),H(this,je,dv).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,Hp).get(e);n&&(n.pageIndex=t,f(this,Qs).set(t,n),f(this,Hl)?n.enable():n.disable())}startUpdatePages(){R(this,Hp,new Map(f(this,Qs))),f(this,Qs).clear()}endUpdatePages(){R(this,Hp,null)}clonePage(e,t){for(const n of this.getEditors(e)){const i=n.serialize(n.mode!==Et.HIGHLIGHT);i&&(i.pageIndex=t,i.id=this.getId(),i.isClone=!0,delete i.popupRef,f(this,Ki).setValue(i.id,i))}}findClonesForPage(e){const t=[],{pageIndex:n}=e;for(const[i,r]of f(this,Ki))r.pageIndex===n&&r.isClone&&(f(this,Ki).remove(i),t.push(e.deserialize(r).then(o=>{o&&(o.isClone=!0,e.addOrRebuild(o))})));return Promise.all(t)}setEditingState(e){e?(H(this,je,_N).call(this),H(this,je,kN).call(this),H(this,je,ji).call(this,{isEditing:f(this,kn)!==Et.NONE,isEmpty:H(this,je,hv).call(this),hasSomethingToUndo:f(this,ko).hasSomethingToUndo(),hasSomethingToRedo:f(this,ko).hasSomethingToRedo(),hasSelectedEditor:!1})):(H(this,je,wN).call(this),H(this,je,CN).call(this),H(this,je,ji).call(this,{isEditing:!1}),this.disableUserSelect(!1))}registerEditorTypes(e){if(!f(this,Co)){R(this,Co,e);for(const t of f(this,Co))H(this,je,Il).call(this,t.defaultPropertiesToUpdate)}}getId(){return f(this,F0).id}get currentLayer(){return f(this,Qs).get(f(this,hu))}getLayer(e){return f(this,Qs).get(e)}get currentPageIndex(){return f(this,hu)}addLayer(e){f(this,Qs).set(e.pageIndex,e),f(this,Hl)?e.enable():e.disable()}removeLayer(e){f(this,Qs).delete(e.pageIndex)}async updateMode(e,t=null,n=!1,i=!1,r=!1,o=!1){var a,c,l,u,d,h;if(f(this,kn)!==e&&!(f(this,To)&&(await f(this,To).promise,!f(this,To)))){if(R(this,To,Promise.withResolvers()),(a=f(this,du))==null||a.commitOrRemove(),f(this,kn)===Et.POPUP&&((c=f(this,Fn))==null||c.hideSidebar()),(l=f(this,Fn))==null||l.destroyPopup(),R(this,kn,e),e===Et.NONE){this.setEditingState(!1),H(this,je,EN).call(this);for(const p of f(this,rn).values())p.hideStandaloneCommentButton();(u=this._editorUndoBar)==null||u.hide(),this.toggleComment(null),f(this,To).resolve();return}for(const p of f(this,rn).values())p.addStandaloneCommentButton();e===Et.SIGNATURE&&await((d=f(this,yu))==null?void 0:d.loadSignatures()),n&&bi.clearPointerType(),this.setEditingState(!0),await H(this,je,AN).call(this),this.unselectAll();for(const p of f(this,Qs).values())p.updateMode(e);if(e===Et.POPUP){f(this,Fp)||R(this,Fp,await f(this,Kp).getAnnotationsByType(new Set(f(this,Co).map(v=>v._editorType))));const p=new Set,g=[];for(const v of f(this,rn).values()){const{annotationElementId:m,hasComment:y,deleted:_}=v;m&&p.add(m),y&&!_&&g.push(v.getData())}for(const v of f(this,Fp)){const{id:m,popupRef:y,contentsObj:_}=v;y&&(_!=null&&_.str)&&!p.has(m)&&!f(this,fu).has(m)&&g.push(v)}(h=f(this,Fn))==null||h.showSidebar(g)}if(!t){i&&this.addNewEditorFromKeyboard(),f(this,To).resolve();return}for(const p of f(this,rn).values())p.uid===t?(this.setSelected(p),o?p.editComment():r?p.enterInEditMode():p.focus()):p.unselect();f(this,To).resolve()}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(e){e.mode!==f(this,kn)&&this._eventBus.dispatch("switchannotationeditormode",{source:this,...e})}updateParams(e,t){if(f(this,Co)){switch(e){case Rt.CREATE:this.currentLayer.addNewEditor(t);return;case Rt.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}}),(f(this,Hy)||R(this,Hy,new Map)).set(e,t),this.showAllEditors("highlight",t);break}if(this.hasSelection)for(const n of f(this,ps))n.updateParams(e,t);else for(const n of f(this,Co))n.updateDefaultParams(e,t)}}showAllEditors(e,t,n=!1){var r;for(const o of f(this,rn).values())o.editorType===e&&o.show(t);(((r=f(this,Hy))==null?void 0:r.get(Rt.HIGHLIGHT_SHOW_ALL))??!0)!==t&&H(this,je,Il).call(this,[[Rt.HIGHLIGHT_SHOW_ALL,t]])}enableWaiting(e=!1){if(f(this,By)!==e){R(this,By,e);for(const t of f(this,Qs).values())e?t.disableClick():t.enableClick(),t.div.classList.toggle("waiting",e)}}*getEditors(e){for(const t of f(this,rn).values())t.pageIndex===e&&(yield t)}getEditor(e){return f(this,rn).get(e)}addEditor(e){f(this,rn).set(e.id,e)}removeEditor(e){var t,n;e.div.contains(document.activeElement)&&(f(this,$a)&&clearTimeout(f(this,$a)),R(this,$a,setTimeout(()=>{this.focusMainContainer(),R(this,$a,null)},0))),f(this,rn).delete(e.id),e.annotationElementId&&((t=f(this,vu))==null||t.delete(e.annotationElementId)),this.unselect(e),(!e.annotationElementId||!f(this,fu).has(e.annotationElementId))&&((n=f(this,Ki))==null||n.remove(e.id))}addDeletedAnnotationElement(e){f(this,fu).add(e.annotationElementId),this.addChangedExistingAnnotation(e),e.deleted=!0}isDeletedAnnotationElement(e){return f(this,fu).has(e)}removeDeletedAnnotationElement(e){f(this,fu).delete(e.annotationElementId),this.removeChangedExistingAnnotation(e),e.deleted=!1}setActiveEditor(e){f(this,Nr)!==e&&(R(this,Nr,e),e&&H(this,je,Il).call(this,e.propertiesToUpdate))}updateUI(e){f(this,je,MN)===e&&H(this,je,Il).call(this,e.propertiesToUpdate)}updateUIForDefaultProperties(e){H(this,je,Il).call(this,e.defaultPropertiesToUpdate)}toggleSelected(e){if(f(this,ps).has(e)){f(this,ps).delete(e),e.unselect(),H(this,je,ji).call(this,{hasSelectedEditor:this.hasSelection});return}f(this,ps).add(e),e.select(),H(this,je,Il).call(this,e.propertiesToUpdate),H(this,je,ji).call(this,{hasSelectedEditor:!0})}setSelected(e){var t,n;this.updateToolbar({mode:e.mode,editId:e.uid}),(t=f(this,du))==null||t.commitOrRemove();for(const i of f(this,ps))i!==e&&i.unselect();(n=f(this,Fn))==null||n.destroyPopup(),f(this,ps).clear(),f(this,ps).add(e),e.select(),H(this,je,Il).call(this,e.propertiesToUpdate),H(this,je,ji).call(this,{hasSelectedEditor:!0})}isSelected(e){return f(this,ps).has(e)}get firstSelectedEditor(){return f(this,ps).values().next().value}unselect(e){e.unselect(),f(this,ps).delete(e),H(this,je,ji).call(this,{hasSelectedEditor:this.hasSelection})}get hasSelection(){return f(this,ps).size!==0}get isEnterHandled(){return f(this,ps).size===1&&this.firstSelectedEditor.isEnterHandled}undo(){var e;f(this,ko).undo(),H(this,je,ji).call(this,{hasSomethingToUndo:f(this,ko).hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:H(this,je,hv).call(this)}),(e=this._editorUndoBar)==null||e.hide()}redo(){f(this,ko).redo(),H(this,je,ji).call(this,{hasSomethingToUndo:!0,hasSomethingToRedo:f(this,ko).hasSomethingToRedo(),isEmpty:H(this,je,hv).call(this)})}addCommands(e){f(this,ko).add(e),H(this,je,ji).call(this,{hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:H(this,je,hv).call(this)})}cleanUndoStack(e){f(this,ko).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,ps)],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)H(this,je,Q1).call(this,o)};this.addCommands({cmd:n,undo:i,mustExec:!0})}commitOrRemove(){var e;(e=f(this,Nr))==null||e.commitOrRemove()}hasSomethingToControl(){return f(this,Nr)||this.hasSelection}selectAll(){for(const e of f(this,ps))e.commit();H(this,je,X1).call(this,f(this,rn).values())}unselectAll(){var e,t;if(!(f(this,Nr)&&(f(this,Nr).commitOrRemove(),f(this,kn)!==Et.NONE))&&!((e=f(this,du))!=null&&e.commitOrRemove())&&((t=f(this,Fn))==null||t.destroyPopup(),!!this.hasSelection)){for(const n of f(this,ps))n.unselect();f(this,ps).clear(),H(this,je,ji).call(this,{hasSelectedEditor:!1})}}translateSelectedEditors(e,t,n=!1){if(n||this.commitOrRemove(),!this.hasSelection)return;f(this,_u)[0]+=e,f(this,_u)[1]+=t;const[i,r]=f(this,_u),o=[...f(this,ps)],a=1e3;f(this,Fa)&&clearTimeout(f(this,Fa)),R(this,Fa,setTimeout(()=>{R(this,Fa,null),f(this,_u)[0]=f(this,_u)[1]=0,this.addCommands({cmd:()=>{for(const c of o)f(this,rn).has(c.id)&&(c.translateInPage(i,r),c.translationDone())},undo:()=>{for(const c of o)f(this,rn).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),R(this,Na,new Map);for(const e of f(this,ps))f(this,Na).set(e,{savedX:e.x,savedY:e.y,savedPageIndex:e.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!f(this,Na))return!1;this.disableUserSelect(!1);const e=f(this,Na);R(this,Na,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,rn).has(i.id)){const c=f(this,Qs).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,Na))for(const n of f(this,Na).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,ps).size===1&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(e){return f(this,Nr)===e}getActive(){return f(this,Nr)}getMode(){return f(this,kn)}isEditingMode(){return f(this,kn)!==Et.NONE}get imageManager(){return Mt(this,"imageManager",new V1)}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,d,h)=>({x:(u-i)/o,y:1-(l+d-n)/r,width:h/o,height:d/r});break;case"180":a=(l,u,d,h)=>({x:1-(l+d-n)/r,y:1-(u+h-i)/o,width:d/r,height:h/o});break;case"270":a=(l,u,d,h)=>({x:1-(u+h-i)/o,y:(l-n)/r,width:h/o,height:d/r});break;default:a=(l,u,d,h)=>({x:(l-n)/r,y:(u-i)/o,width:d/r,height:h/o});break}const c=[];for(let l=0,u=t.rangeCount;l<u;l++){const d=t.getRangeAt(l);if(!d.collapsed)for(const{x:h,y:p,width:g,height:v}of d.getClientRects())g===0||v===0||c.push(a(h,p,g,v))}return c.length===0?null:c}addChangedExistingAnnotation({annotationElementId:e,id:t}){(f(this,Wp)||R(this,Wp,new Map)).set(e,t)}removeChangedExistingAnnotation({annotationElementId:e}){var t;(t=f(this,Wp))==null||t.delete(e)}renderAnnotationElement(e){var i;const t=(i=f(this,Wp))==null?void 0:i.get(e.data.id);if(!t)return;const n=f(this,Ki).getRawValue(t);n&&(f(this,kn)===Et.NONE&&!n.hasBeenModified||n.renderAnnotationElement(e))}setMissingCanvas(e,t,n){var r;const i=(r=f(this,vu))==null?void 0:r.get(e);i&&(i.setCanvas(t,n),f(this,vu).delete(e))}addMissingCanvas(e,t){(f(this,vu)||R(this,vu,new Map)).set(e,t)}};Bp=new WeakMap,Nr=new WeakMap,Fp=new WeakMap,rn=new WeakMap,Qs=new WeakMap,Hp=new WeakMap,Up=new WeakMap,Ki=new WeakMap,Wp=new WeakMap,ko=new WeakMap,Fn=new WeakMap,uu=new WeakMap,du=new WeakMap,hu=new WeakMap,fu=new WeakMap,Na=new WeakMap,Co=new WeakMap,eh=new WeakMap,Dy=new WeakMap,Ny=new WeakMap,zp=new WeakMap,$y=new WeakMap,$a=new WeakMap,pu=new WeakMap,jp=new WeakMap,mu=new WeakMap,Ba=new WeakMap,F0=new WeakMap,Hl=new WeakMap,Vp=new WeakMap,By=new WeakMap,gu=new WeakMap,th=new WeakMap,Gp=new WeakMap,vu=new WeakMap,Fy=new WeakMap,kn=new WeakMap,ps=new WeakMap,Ul=new WeakMap,yu=new WeakMap,bu=new WeakMap,Hy=new WeakMap,Kp=new WeakMap,Uy=new WeakMap,_u=new WeakMap,Fa=new WeakMap,Wl=new WeakMap,Wy=new WeakMap,zy=new WeakMap,To=new WeakMap,je=new WeakSet,zw=function({anchorNode:e}){return e.nodeType===Node.TEXT_NODE?e.parentElement:e},K1=function(e){const{currentLayer:t}=this;if(t.hasTextLayer(e))return t;for(const n of f(this,Qs).values())if(n.hasTextLayer(e))return n;return null},gN=function(e){var t;this.commitOrRemove(),(t=this.currentLayer)==null||t.endDrawingSession(!1)},vN=function(){const e=document.getSelection();if(!e||e.isCollapsed)return;const n=H(this,je,zw).call(this,e).closest(".textLayer"),i=this.getSelectionBoxes(n);i&&(f(this,Ba)||R(this,Ba,new lse(this)),f(this,Ba).show(n,i,this.direction==="ltr"))},yN=function(){var r,o,a;const e=document.getSelection();if(!e||e.isCollapsed){f(this,Ul)&&((r=f(this,Ba))==null||r.hide(),R(this,Ul,null),H(this,je,ji).call(this,{hasSelectedText:!1}));return}const{anchorNode:t}=e;if(t===f(this,Ul))return;const i=H(this,je,zw).call(this,e).closest(".textLayer");if(!i){f(this,Ul)&&((o=f(this,Ba))==null||o.hide(),R(this,Ul,null),H(this,je,ji).call(this,{hasSelectedText:!1}));return}if((a=f(this,Ba))==null||a.hide(),R(this,Ul,t),H(this,je,ji).call(this,{hasSelectedText:!0}),!(f(this,kn)!==Et.HIGHLIGHT&&f(this,kn)!==Et.NONE)&&(f(this,kn)===Et.HIGHLIGHT&&this.showAllEditors("highlight",!0,!0),R(this,mu,this.isShiftKeyDown),!this.isShiftKeyDown)){const c=f(this,kn)===Et.HIGHLIGHT?H(this,je,K1).call(this,i):null;if(c==null||c.toggleDrawing(),f(this,Vp)){const l=new AbortController,u=this.combinedSignal(l),d=h=>{h.type==="pointerup"&&h.button!==0||(l.abort(),c==null||c.toggleDrawing(!0),h.type==="pointerup"&&H(this,je,dv).call(this,"main_toolbar"))};window.addEventListener("pointerup",d,{signal:u}),window.addEventListener("blur",d,{signal:u})}else c==null||c.toggleDrawing(!0),H(this,je,dv).call(this,"main_toolbar")}},dv=function(e=""){f(this,kn)===Et.HIGHLIGHT?this.highlightSelection(e):f(this,Dy)&&H(this,je,vN).call(this)},bN=function(){document.addEventListener("selectionchange",H(this,je,yN).bind(this),{signal:this._signal})},_N=function(){if(f(this,pu))return;R(this,pu,new AbortController);const e=this.combinedSignal(f(this,pu));window.addEventListener("focus",this.focus.bind(this),{signal:e}),window.addEventListener("blur",this.blur.bind(this),{signal:e})},wN=function(){var e;(e=f(this,pu))==null||e.abort(),R(this,pu,null)},q1=function(){if(f(this,gu))return;R(this,gu,new AbortController);const e=this.combinedSignal(f(this,gu));window.addEventListener("keydown",this.keydown.bind(this),{signal:e}),window.addEventListener("keyup",this.keyup.bind(this),{signal:e})},SN=function(){var e;(e=f(this,gu))==null||e.abort(),R(this,gu,null)},kN=function(){if(f(this,uu))return;R(this,uu,new AbortController);const e=this.combinedSignal(f(this,uu));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})},CN=function(){var e;(e=f(this,uu))==null||e.abort(),R(this,uu,null)},TN=function(){const e=this._signal;document.addEventListener("dragover",this.dragOver.bind(this),{signal:e}),document.addEventListener("drop",this.drop.bind(this),{signal:e})},ji=function(e){Object.entries(e).some(([n,i])=>f(this,Uy)[n]!==i)&&(this._eventBus.dispatch("editingstateschanged",{source:this,details:Object.assign(f(this,Uy),e)}),f(this,kn)===Et.HIGHLIGHT&&e.hasSelectedEditor===!1&&H(this,je,Il).call(this,[[Rt.HIGHLIGHT_FREE,!0]]))},Il=function(e){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:e})},AN=async function(){if(!f(this,Hl)){R(this,Hl,!0);const e=[];for(const t of f(this,Qs).values())e.push(t.enable());await Promise.all(e);for(const t of f(this,rn).values())t.enable()}},EN=function(){if(this.unselectAll(),f(this,Hl)){R(this,Hl,!1);for(const e of f(this,Qs).values())e.disable();for(const e of f(this,rn).values())e.disable()}},Q1=function(e){const t=f(this,Qs).get(e.pageIndex);t?t.addOrRebuild(e):(this.addEditor(e),this.addToAnnotationStorage(e))},MN=function(){let e=null;for(e of f(this,ps));return e},hv=function(){if(f(this,rn).size===0)return!0;if(f(this,rn).size===1)for(const e of f(this,rn).values())return e.isEmpty();return!1},X1=function(e){for(const t of f(this,ps))t.unselect();f(this,ps).clear();for(const t of e)t.isEmpty()||(f(this,ps).add(t),t.select());H(this,je,ji).call(this,{hasSelectedEditor:this.hasSelection})},Se(Ep,"TRANSLATE_SMALL",1),Se(Ep,"TRANSLATE_BIG",10);let Bf=Ep;var Hn,Ha,ia,qp,Ua,$r,Qp,Wa,pr,zl,sh,za,wu,ba,fv,jw;const Gi=class Gi{constructor(e){B(this,ba);B(this,Hn,null);B(this,Ha,!1);B(this,ia,null);B(this,qp,null);B(this,Ua,null);B(this,$r,null);B(this,Qp,!1);B(this,Wa,null);B(this,pr,null);B(this,zl,null);B(this,sh,null);B(this,za,!1);R(this,pr,e),R(this,za,e._uiManager.useNewAltTextFlow),f(Gi,wu)||R(Gi,wu,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){Gi._l10n??(Gi._l10n=e)}async render(){const e=R(this,ia,document.createElement("button"));e.className="altText",e.tabIndex="0";const t=R(this,qp,document.createElement("span"));e.append(t),f(this,za)?(e.classList.add("new"),e.setAttribute("data-l10n-id",f(Gi,wu).missing),t.setAttribute("data-l10n-id",f(Gi,wu)["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,pr)._uiManager._signal;e.addEventListener("contextmenu",Go,{signal:n}),e.addEventListener("pointerdown",r=>r.stopPropagation(),{signal:n});const i=r=>{r.preventDefault(),f(this,pr)._uiManager.editAltText(f(this,pr)),f(this,za)&&f(this,pr)._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_clicked",data:{label:f(this,ba,fv)}})};return e.addEventListener("click",i,{capture:!0,signal:n}),e.addEventListener("keydown",r=>{r.target===e&&r.key==="Enter"&&(R(this,Qp,!0),i(r))},{signal:n}),await H(this,ba,jw).call(this),e}finish(){f(this,ia)&&(f(this,ia).focus({focusVisible:f(this,Qp)}),R(this,Qp,!1))}isEmpty(){return f(this,za)?f(this,Hn)===null:!f(this,Hn)&&!f(this,Ha)}hasData(){return f(this,za)?f(this,Hn)!==null||!!f(this,zl):this.isEmpty()}get guessedText(){return f(this,zl)}async setGuessedText(e){f(this,Hn)===null&&(R(this,zl,e),R(this,sh,await Gi._l10n.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer",{generatedAltText:e})),H(this,ba,jw).call(this))}toggleAltTextBadge(e=!1){var t;if(!f(this,za)||f(this,Hn)){(t=f(this,Wa))==null||t.remove(),R(this,Wa,null);return}if(!f(this,Wa)){const n=R(this,Wa,document.createElement("div"));n.className="noAltTextBadge",f(this,pr).div.append(n)}f(this,Wa).classList.toggle("hidden",!e)}serialize(e){let t=f(this,Hn);return!e&&f(this,zl)===t&&(t=f(this,sh)),{altText:t,decorative:f(this,Ha),guessedText:f(this,zl),textWithDisclaimer:f(this,sh)}}get data(){return{altText:f(this,Hn),decorative:f(this,Ha)}}set data({altText:e,decorative:t,guessedText:n,textWithDisclaimer:i,cancel:r=!1}){n&&(R(this,zl,n),R(this,sh,i)),!(f(this,Hn)===e&&f(this,Ha)===t)&&(r||(R(this,Hn,e),R(this,Ha,t)),H(this,ba,jw).call(this))}toggle(e=!1){f(this,ia)&&(!e&&f(this,$r)&&(clearTimeout(f(this,$r)),R(this,$r,null)),f(this,ia).disabled=!e)}shown(){f(this,pr)._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_displayed",data:{label:f(this,ba,fv)}})}destroy(){var e,t;(e=f(this,ia))==null||e.remove(),R(this,ia,null),R(this,qp,null),R(this,Ua,null),(t=f(this,Wa))==null||t.remove(),R(this,Wa,null)}};Hn=new WeakMap,Ha=new WeakMap,ia=new WeakMap,qp=new WeakMap,Ua=new WeakMap,$r=new WeakMap,Qp=new WeakMap,Wa=new WeakMap,pr=new WeakMap,zl=new WeakMap,sh=new WeakMap,za=new WeakMap,wu=new WeakMap,ba=new WeakSet,fv=function(){return f(this,Hn)&&"added"||f(this,Hn)===null&&this.guessedText&&"review"||"missing"},jw=async function(){var i,r,o;const e=f(this,ia);if(!e)return;if(f(this,za)){if(e.classList.toggle("done",!!f(this,Hn)),e.setAttribute("data-l10n-id",f(Gi,wu)[f(this,ba,fv)]),(i=f(this,qp))==null||i.setAttribute("data-l10n-id",f(Gi,wu)[`${f(this,ba,fv)}-label`]),!f(this,Hn)){(r=f(this,Ua))==null||r.remove();return}}else{if(!f(this,Hn)&&!f(this,Ha)){e.classList.remove("done"),(o=f(this,Ua))==null||o.remove();return}e.classList.add("done"),e.setAttribute("data-l10n-id","pdfjs-editor-alt-text-edit-button")}let t=f(this,Ua);if(!t){R(this,Ua,t=document.createElement("span")),t.className="tooltip",t.setAttribute("role","tooltip"),t.id=`alt-text-tooltip-${f(this,pr).id}`;const a=100,c=f(this,pr)._uiManager._signal;c.addEventListener("abort",()=>{clearTimeout(f(this,$r)),R(this,$r,null)},{once:!0}),e.addEventListener("mouseenter",()=>{R(this,$r,setTimeout(()=>{R(this,$r,null),f(this,Ua).classList.add("show"),f(this,pr)._reportTelemetry({action:"alt_text_tooltip"})},a))},{signal:c}),e.addEventListener("mouseleave",()=>{var l;f(this,$r)&&(clearTimeout(f(this,$r)),R(this,$r,null)),(l=f(this,Ua))==null||l.classList.remove("show")},{signal:c})}f(this,Ha)?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,pr).getElementForAltText();n==null||n.setAttribute("aria-describedby",t.id)},B(Gi,wu,null),Se(Gi,"_l10n",null);let T0=Gi;var ei,Ao,nh,Ms,jy,Su,Eo,ku,Cu,ih,Vy,Y1;class aw{constructor(e){B(this,Vy);B(this,ei,null);B(this,Ao,null);B(this,nh,!1);B(this,Ms,null);B(this,jy,null);B(this,Su,null);B(this,Eo,null);B(this,ku,null);B(this,Cu,!1);B(this,ih,null);R(this,Ms,e)}renderForToolbar(){const e=R(this,Ao,document.createElement("button"));return e.className="comment",H(this,Vy,Y1).call(this,e,!1)}renderForStandalone(){const e=R(this,ei,document.createElement("button"));e.className="annotationCommentButton";const t=f(this,Ms).commentButtonPosition;if(t){const{style:n}=e;n.insetInlineEnd=`calc(${100*(f(this,Ms)._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,Ms).commentButtonColor;i&&(n.backgroundColor=i)}return H(this,Vy,Y1).call(this,e,!0)}focusButton(){setTimeout(()=>{var e;(e=f(this,ei)??f(this,Ao))==null||e.focus()},0)}onUpdatedColor(){if(!f(this,ei))return;const e=f(this,Ms).commentButtonColor;e&&(f(this,ei).style.backgroundColor=e),f(this,Ms)._uiManager.updatePopupColor(f(this,Ms))}get commentButtonWidth(){var e;return(((e=f(this,ei))==null?void 0:e.getBoundingClientRect().width)??0)/f(this,Ms).parent.boundingClientRect.width}get commentPopupPositionInLayer(){if(f(this,ih))return f(this,ih);if(!f(this,ei))return null;const{x:e,y:t,height:n}=f(this,ei).getBoundingClientRect(),{x:i,y:r,width:o,height:a}=f(this,Ms).parent.boundingClientRect;return[(e-i)/o,(t+n-r)/a]}set commentPopupPositionInLayer(e){R(this,ih,e)}hasDefaultPopupPosition(){return f(this,ih)===null}removeStandaloneCommentButton(){var e;(e=f(this,ei))==null||e.remove(),R(this,ei,null)}removeToolbarCommentButton(){var e;(e=f(this,Ao))==null||e.remove(),R(this,Ao,null)}setCommentButtonStates({selected:e,hasPopup:t}){f(this,ei)&&(f(this,ei).classList.toggle("selected",e),f(this,ei).ariaExpanded=t)}edit(e){const t=this.commentPopupPositionInLayer;let n,i;if(t)[n,i]=t;else{[n,i]=f(this,Ms).commentButtonPosition;const{width:u,height:d,x:h,y:p}=f(this,Ms);n=h+n*u,i=p+i*d}const r=f(this,Ms).parent.boundingClientRect,{x:o,y:a,width:c,height:l}=r;f(this,Ms)._uiManager.editComment(f(this,Ms),o+n*c,a+i*l,{...e,parentDimensions:r})}finish(){f(this,Ao)&&(f(this,Ao).focus({focusVisible:f(this,nh)}),R(this,nh,!1))}isDeleted(){return f(this,Cu)||f(this,Eo)===""}isEmpty(){return f(this,Eo)===null}hasBeenEdited(){return this.isDeleted()||f(this,Eo)!==f(this,jy)}serialize(){return this.data}get data(){return{text:f(this,Eo),richText:f(this,Su),date:f(this,ku),deleted:this.isDeleted()}}set data(e){if(e!==f(this,Eo)&&R(this,Su,null),e===null){R(this,Eo,""),R(this,Cu,!0);return}R(this,Eo,e),R(this,ku,new Date),R(this,Cu,!1)}restoreData({text:e,richText:t,date:n}){R(this,Eo,e),R(this,Su,t),R(this,ku,n),R(this,Cu,!1)}setInitialText(e,t=null){R(this,jy,e),this.data=e,R(this,ku,null),R(this,Su,t)}shown(){}destroy(){var e,t;(e=f(this,Ao))==null||e.remove(),R(this,Ao,null),(t=f(this,ei))==null||t.remove(),R(this,ei,null),R(this,Eo,""),R(this,Su,null),R(this,ku,null),R(this,Ms,null),R(this,nh,!1),R(this,Cu,!1)}}ei=new WeakMap,Ao=new WeakMap,nh=new WeakMap,Ms=new WeakMap,jy=new WeakMap,Su=new WeakMap,Eo=new WeakMap,ku=new WeakMap,Cu=new WeakMap,ih=new WeakMap,Vy=new WeakSet,Y1=function(e,t){if(!f(this,Ms)._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,Ms)._uiManager.getCommentDialogElement()],e.setAttribute("data-l10n-id","pdfjs-editor-add-comment-button"));const n=f(this,Ms)._uiManager._signal;if(!(n instanceof AbortSignal)||n.aborted)return e;e.addEventListener("contextmenu",Go,{signal:n}),t&&(e.addEventListener("focusin",r=>{f(this,Ms)._focusEventsAllowed=!1,Xs(r)},{capture:!0,signal:n}),e.addEventListener("focusout",r=>{f(this,Ms)._focusEventsAllowed=!0,Xs(r)},{capture:!0,signal:n})),e.addEventListener("pointerdown",r=>r.stopPropagation(),{signal:n});const i=r=>{r.preventDefault(),e===f(this,Ao)?this.edit():f(this,Ms).toggleComment(!0)};return e.addEventListener("click",i,{capture:!0,signal:n}),e.addEventListener("keydown",r=>{r.target===e&&r.key==="Enter"&&(R(this,nh,!0),i(r))},{signal:n}),e.addEventListener("pointerenter",()=>{f(this,Ms).toggleComment(!1,!0)},{signal:n}),e.addEventListener("pointerleave",()=>{f(this,Ms).toggleComment(!1,!1)},{signal:n}),e};var Xp,rh,Gy,Ky,qy,Qy,Xy,jl,oh,Vl,ah,Gl,gd,xN,RN,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}){B(this,gd);B(this,Xp);B(this,rh,!1);B(this,Gy,null);B(this,Ky);B(this,qy);B(this,Qy);B(this,Xy);B(this,jl,null);B(this,oh);B(this,Vl,null);B(this,ah);B(this,Gl,null);R(this,Xp,e),R(this,Gy,n),R(this,Ky,t),R(this,qy,i),R(this,Qy,r),R(this,Xy,o),R(this,ah,new AbortController),R(this,oh,AbortSignal.any([a,f(this,ah).signal])),e.addEventListener("touchstart",H(this,gd,xN).bind(this),{passive:!1,signal:f(this,oh)})}get MIN_TOUCH_DISTANCE_TO_PINCH(){return 35/hl.pixelRatio}destroy(){var e,t;(e=f(this,ah))==null||e.abort(),R(this,ah,null),(t=f(this,jl))==null||t.abort(),R(this,jl,null)}};Xp=new WeakMap,rh=new WeakMap,Gy=new WeakMap,Ky=new WeakMap,qy=new WeakMap,Qy=new WeakMap,Xy=new WeakMap,jl=new WeakMap,oh=new WeakMap,Vl=new WeakMap,ah=new WeakMap,Gl=new WeakMap,gd=new WeakSet,xN=function(e){var i,r,o;if((i=f(this,Ky))!=null&&i.call(this))return;if(e.touches.length===1){if(f(this,jl))return;const a=R(this,jl,new AbortController),c=AbortSignal.any([f(this,oh),a.signal]),l=f(this,Xp),u={capture:!0,signal:c,passive:!1},d=h=>{var p;h.pointerType==="touch"&&((p=f(this,jl))==null||p.abort(),R(this,jl,null))};l.addEventListener("pointerdown",h=>{h.pointerType==="touch"&&(Xs(h),d(h))},u),l.addEventListener("pointerup",d,u),l.addEventListener("pointercancel",d,u);return}if(!f(this,Gl)){R(this,Gl,new AbortController);const a=AbortSignal.any([f(this,oh),f(this,Gl).signal]),c=f(this,Xp),l={signal:a,capture:!1,passive:!1};c.addEventListener("touchmove",H(this,gd,RN).bind(this),l);const u=H(this,gd,IN).bind(this);c.addEventListener("touchend",u,l),c.addEventListener("touchcancel",u,l),l.capture=!0,c.addEventListener("pointerdown",Xs,l),c.addEventListener("pointermove",Xs,l),c.addEventListener("pointercancel",Xs,l),c.addEventListener("pointerup",Xs,l),(r=f(this,qy))==null||r.call(this)}if(Xs(e),e.touches.length!==2||(o=f(this,Gy))!=null&&o.call(this)){R(this,Vl,null);return}let[t,n]=e.touches;t.identifier>n.identifier&&([t,n]=[n,t]),R(this,Vl,{touch0X:t.screenX,touch0Y:t.screenY,touch1X:n.screenX,touch1Y:n.screenY})},RN=function(e){var k;if(!f(this,Vl)||e.touches.length!==2)return;Xs(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,Vl),{touch0X:l,touch0Y:u,touch1X:d,touch1Y:h}=c,p=d-l,g=h-u,v=o-i,m=a-r,y=Math.hypot(v,m)||1,_=Math.hypot(p,g)||1;if(!f(this,rh)&&Math.abs(_-y)<=WM.MIN_TOUCH_DISTANCE_TO_PINCH)return;if(c.touch0X=i,c.touch0Y=r,c.touch1X=o,c.touch1Y=a,!f(this,rh)){R(this,rh,!0);return}const b=[(i+o)/2,(r+a)/2];(k=f(this,Qy))==null||k.call(this,b,_,y)},IN=function(e){var t;e.touches.length>=2||(f(this,Gl)&&(f(this,Gl).abort(),R(this,Gl,null),(t=f(this,Xy))==null||t.call(this)),f(this,Vl)&&(Xs(e),R(this,Vl,null),R(this,rh,!1)))};let A0=WM;var lh,ra,Us,ms,Kl,Yp,Tu,Yy,ti,ch,ql,Mo,Au,Jy,uh,Br,Zy,dh,Ql,ja,Jp,Zp,xo,hh,eb,H0,yt,J1,tb,Z1,Vw,PN,LN,eA,Gw,tA,ON,DN,NN,sA,$N,nA,BN,FN,HN,iA,pv;const wt=class wt{constructor(e){B(this,yt);B(this,lh,null);B(this,ra,null);B(this,Us,null);B(this,ms,null);B(this,Kl,null);B(this,Yp,!1);B(this,Tu,null);B(this,Yy,"");B(this,ti,null);B(this,ch,null);B(this,ql,null);B(this,Mo,null);B(this,Au,null);B(this,Jy,"");B(this,uh,!1);B(this,Br,null);B(this,Zy,!1);B(this,dh,!1);B(this,Ql,!1);B(this,ja,null);B(this,Jp,0);B(this,Zp,0);B(this,xo,null);B(this,hh,null);Se(this,"isSelected",!1);Se(this,"_isCopy",!1);Se(this,"_editToolbar",null);Se(this,"_initialOptions",Object.create(null));Se(this,"_initialData",null);Se(this,"_isVisible",!0);Se(this,"_uiManager",null);Se(this,"_focusEventsAllowed",!0);B(this,eb,!1);B(this,H0,wt._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=wt.prototype._resizeWithKeyboard,t=Bf.TRANSLATE_SMALL,n=Bf.TRANSLATE_BIG;return Mt(this,"_resizerKeyboardManager",new w_([[["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"],wt.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 Mt(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(e){const t=new fse({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(wt._l10n??(wt._l10n=e),wt._l10nAlert??(wt._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"})),wt._l10nResizer??(wt._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"})),wt._borderLineWidth!==-1)return;const n=getComputedStyle(document.documentElement);wt._borderLineWidth=parseFloat(n.getPropertyValue("--outline-width"))||0}static updateDefaultParams(e,t){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(e){return!1}static paste(e,t){ss("Not implemented")}get propertiesToUpdate(){return[]}get _isDraggable(){return f(this,eb)}set _isDraggable(e){var t;R(this,eb,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,H0)}setParent(e){var t;e!==null?(this.pageIndex=e.pageIndex,this.pageDimensions=e.pageDimensions):(H(this,yt,pv).call(this),(t=f(this,Mo))==null||t.remove(),R(this,Mo,null)),this.parent=e}focusin(e){this._focusEventsAllowed&&(f(this,uh)?R(this,uh,!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){H(this,yt,J1).call(this,this.parentDimensions,e,t)}translateInPage(e,t){f(this,Br)||R(this,Br,[this.x,this.y,this.width,this.height]),H(this,yt,J1).call(this,this.pageDimensions,e,t),this.div.scrollIntoView({block:"nearest"})}translationDone(){this._onTranslated(this.x,this.y)}drag(e,t){f(this,Br)||R(this,Br,[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:d,y:h}=this.div.getBoundingClientRect();this.parent.findNewParent(this,d,h)&&(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,Br)&&(f(this,Br)[0]!==this.x||f(this,Br)[1]!==this.y)}get _hasBeenResized(){return!!f(this,Br)&&(f(this,Br)[2]!==this.width||f(this,Br)[3]!==this.height)}getBaseTranslation(){const[e,t]=this.parentDimensions,{_borderLineWidth:n}=wt,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=zs(r,0,n-a),o=zs(o,0,i-c);break;case 90:r=zs(r,0,n-c),o=zs(o,a,i);break;case 180:r=zs(r,a,n),o=zs(o,c,i);break;case 270:r=zs(r,c,n),o=zs(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 H(n=wt,tb,Z1).call(n,e,t,this.parentRotation)}pageTranslationToScreen(e,t){var n;return H(n=wt,tb,Z1).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,Us))==null||e.finish()}get toolbarButtons(){return null}async addEditToolbar(){if(this._editToolbar||f(this,dh))return this._editToolbar;this._editToolbar=new z1(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,Us))==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,Us)||(T0.initialize(wt._l10n),R(this,Us,new T0(this)),f(this,lh)&&(f(this,Us).data=f(this,lh),R(this,lh,null))),f(this,Us)}get altTextData(){var e;return(e=f(this,Us))==null?void 0:e.data}set altTextData(e){f(this,Us)&&(f(this,Us).data=e)}get guessedAltText(){var e;return(e=f(this,Us))==null?void 0:e.guessedText}async setGuessedAltText(e){var t;await((t=f(this,Us))==null?void 0:t.setGuessedText(e))}serializeAltText(e){var t;return(t=f(this,Us))==null?void 0:t.serialize(e)}hasAltText(){return!!f(this,Us)&&!f(this,Us).isEmpty()}hasAltTextData(){var e;return((e=f(this,Us))==null?void 0:e.hasData())??!1}focusCommentButton(){var e;(e=f(this,ms))==null||e.focusButton()}addCommentButton(){return this.canAddComment?f(this,ms)||R(this,ms,new aw(this)):null}addStandaloneCommentButton(){if(this._uiManager.hasCommentManager()){if(f(this,Kl)){this._uiManager.isEditingMode()&&f(this,Kl).classList.remove("hidden");return}this.hasComment&&(R(this,Kl,f(this,ms).renderForStandalone()),this.div.append(f(this,Kl)))}}removeStandaloneCommentButton(){f(this,ms).removeStandaloneCommentButton(),R(this,Kl,null)}hideStandaloneCommentButton(){var e;(e=f(this,Kl))==null||e.classList.add("hidden")}get comment(){if(!f(this,ms))return null;const{data:{richText:e,text:t,date:n,deleted:i}}=f(this,ms);return{text:t,richText:e,date:n,deleted:i,color:this.getNonHCMColor(),opacity:this.opacity??1}}set comment(e){f(this,ms)||R(this,ms,new aw(this)),typeof e=="object"&&e!==null?f(this,ms).restoreData(e):f(this,ms).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,ms)||R(this,ms,new aw(this)),f(this,ms).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,ms))==null?void 0:e.hasBeenEdited()}get hasDeletedComment(){var e;return(e=f(this,ms))==null?void 0:e.isDeleted()}get hasComment(){return!!f(this,ms)&&!f(this,ms).isEmpty()&&!f(this,ms).isDeleted()}async editComment(e){f(this,ms)||R(this,ms,new aw(this)),f(this,ms).edit(e)}toggleComment(e,t=void 0){this.hasComment&&this._uiManager.toggleComment(this,e,t)}setSelectedCommentButton(e){f(this,ms).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,ms).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,Yp)?-1:0,e.setAttribute("role","application"),this.defaultL10nId&&e.setAttribute("data-l10n-id",this.defaultL10nId),this._isVisible||e.classList.add("hidden"),this.setInForeground(),H(this,yt,nA).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),pN(this,e,["keydown","pointerdown","dblclick"]),this.isResizable&&this._uiManager._supportsPinchToZoom&&(f(this,hh)||R(this,hh,new A0({container:e,isPinchingDisabled:()=>!this.isSelected,onPinchStart:H(this,yt,ON).bind(this),onPinching:H(this,yt,DN).bind(this),onPinchEnd:H(this,yt,NN).bind(this),signal:this._uiManager._signal}))),this.addStandaloneCommentButton(),(o=this._uiManager._editorUndoBar)==null||o.hide(),e}pointerdown(e){const{isMac:t}=Rs.platform;if(e.button!==0||e.ctrlKey&&t){e.preventDefault();return}if(R(this,uh,!0),this._isDraggable){H(this,yt,$N).call(this,e);return}H(this,yt,sA).call(this,e)}_onStartDragging(){}_onStopDragging(){}moveInDOM(){f(this,ja)&&clearTimeout(f(this,ja)),R(this,ja,setTimeout(()=>{var e;R(this,ja,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,d=this.x*r,h=this.y*o,p=this.width*r,g=this.height*o;switch(n){case 0:return[d+l+a,o-h-u-g+c,d+l+p+a,o-h-u+c];case 90:return[d+u+a,o-h+l+c,d+u+g+a,o-h+l+p+c];case 180:return[d-l-p+a,o-h+u+c,d-l+a,o-h+u+g+c];case 270:return[d-u-g+a,o-h-l-p+c,d-u+a,o-h-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&&wt._colorManager.convert(this._uiManager.getNonHCMColor(this.color))}onUpdatedColor(){var e;(e=f(this,ms))==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),R(this,dh,!0),!0)}disableEditMode(){return this.isInEditMode()?(this.parent.setEditingState(!0),R(this,dh,!1),!0):!1}isInEditMode(){return f(this,dh)}shouldGetKeyboardEvents(){return f(this,Ql)}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(){H(this,yt,nA).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,R(i,lh,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,Au))==null||e.abort(),R(this,Au,null),this.isEmpty()||this.commit(),this.parent?this.parent.remove(this):this._uiManager.removeEditor(this),this.hideCommentPopup(),f(this,ja)&&(clearTimeout(f(this,ja)),R(this,ja,null)),H(this,yt,pv).call(this),this.removeEditToolbar(),f(this,xo)){for(const i of f(this,xo).values())clearTimeout(i);R(this,xo,null)}this.parent=null,(t=f(this,hh))==null||t.destroy(),R(this,hh,null),(n=f(this,Mo))==null||n.remove(),R(this,Mo,null)}get isResizable(){return!1}makeResizable(){this.isResizable&&(H(this,yt,PN).call(this),f(this,ti).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[wt._round(n+(r-n)*e),wt._round(i+(o-i)*(1-t))]}get commentButtonColor(){return this._uiManager.makeCommentColor(this.getNonHCMColor(),this.opacity)}get commentPopupPosition(){return f(this,ms).commentPopupPositionInLayer}set commentPopupPosition(e){f(this,ms).commentPopupPositionInLayer=e}hasDefaultPopupPosition(){return f(this,ms).hasDefaultPopupPosition()}get commentButtonWidth(){return f(this,ms).commentButtonWidth}get elementBeforePopup(){return this.div}setCommentButtonStates(e){var t;(t=f(this,ms))==null||t.setCommentButtonStates(e)}keydown(e){if(!this.isResizable||e.target!==this.div||e.key!=="Enter")return;this._uiManager.setSelected(this),R(this,ql,{savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height});const t=f(this,ti).children;if(!f(this,ra)){R(this,ra,Array.from(t));const o=H(this,yt,BN).bind(this),a=H(this,yt,FN).bind(this),c=this._uiManager._signal;for(const l of f(this,ra)){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",H(this,yt,HN).bind(this,u),{signal:c}),l.setAttribute("data-l10n-id",wt._l10nResizer[u])}}const n=f(this,ra)[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,ra).length/4);if(r!==i){if(r<i)for(let a=0;a<i-r;a++)f(this,ti).append(f(this,ti).firstElementChild);else if(r>i)for(let a=0;a<r-i;a++)f(this,ti).firstElementChild.before(f(this,ti).lastElementChild);let o=0;for(const a of t){const l=f(this,ra)[o++].getAttribute("data-resizer-name");a.setAttribute("data-l10n-id",wt._l10nResizer[l])}}H(this,yt,iA).call(this,0),R(this,Ql,!0),f(this,ti).firstElementChild.focus({focusVisible:!0}),e.preventDefault(),e.stopImmediatePropagation()}_resizeWithKeyboard(e,t){f(this,Ql)&&H(this,yt,tA).call(this,f(this,Jy),{deltaX:e,deltaY:t,fromKeyboard:!0})}_stopResizingWithKeyboard(){H(this,yt,pv).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,Us))==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,ti))==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,Us))==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,Zy)}set isEditing(e){R(this,Zy,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,xo)||R(this,xo,new Map);const{action:n}=e;let i=f(this,xo).get(n);i&&clearTimeout(i),i=setTimeout(()=>{this._reportTelemetry(e),f(this,xo).delete(n),f(this,xo).size===0&&R(this,xo,null)},wt._telemetryTimeout),f(this,xo).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),R(this,Yp,!1)}disable(){this.div&&(this.div.tabIndex=-1),R(this,Yp,!0)}updateFakeAnnotationElement(e){if(!f(this,Mo)&&!this.deleted){R(this,Mo,e.addFakeAnnotation(this));return}if(this.deleted){f(this,Mo).remove(),R(this,Mo,null);return}(this.hasEditedComment||this._hasBeenMoved||this._hasBeenResized)&&f(this,Mo).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()}};lh=new WeakMap,ra=new WeakMap,Us=new WeakMap,ms=new WeakMap,Kl=new WeakMap,Yp=new WeakMap,Tu=new WeakMap,Yy=new WeakMap,ti=new WeakMap,ch=new WeakMap,ql=new WeakMap,Mo=new WeakMap,Au=new WeakMap,Jy=new WeakMap,uh=new WeakMap,Br=new WeakMap,Zy=new WeakMap,dh=new WeakMap,Ql=new WeakMap,ja=new WeakMap,Jp=new WeakMap,Zp=new WeakMap,xo=new WeakMap,hh=new WeakMap,eb=new WeakMap,H0=new WeakMap,yt=new WeakSet,J1=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()},tb=new WeakSet,Z1=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]}},Vw=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]}},PN=function(){if(f(this,ti))return;R(this,ti,document.createElement("div")),f(this,ti).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,ti).append(i),i.classList.add("resizer",n),i.setAttribute("data-resizer-name",n),i.addEventListener("pointerdown",H(this,yt,LN).bind(this,n),{signal:t}),i.addEventListener("contextmenu",Go,{signal:t}),i.tabIndex=-1}this.div.prepend(f(this,ti))},LN=function(e,t){var u;t.preventDefault();const{isMac:n}=Rs.platform;if(t.button!==0||t.ctrlKey&&n)return;(u=f(this,Us))==null||u.toggle(!1);const i=this._isDraggable;this._isDraggable=!1,R(this,ch,[t.screenX,t.screenY]);const r=new AbortController,o=this._uiManager.combinedSignal(r);this.parent.togglePointerEvents(!1),window.addEventListener("pointermove",H(this,yt,tA).bind(this,e),{passive:!0,capture:!0,signal:o}),window.addEventListener("touchmove",Xs,{passive:!1,signal:o}),window.addEventListener("contextmenu",Go,{signal:o}),R(this,ql,{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 d;r.abort(),this.parent.togglePointerEvents(!0),(d=f(this,Us))==null||d.toggle(!0),this._isDraggable=i,this.parent.div.style.cursor=a,this.div.style.cursor=c,H(this,yt,Gw).call(this)};window.addEventListener("pointerup",l,{signal:o}),window.addEventListener("blur",l,{signal:o})},eA=function(e,t,n,i){this.width=n,this.height=i,this.x=e,this.y=t,this.setDims(),this.fixAndSetPosition(),this._onResized()},Gw=function(){if(!f(this,ql))return;const{savedX:e,savedY:t,savedWidth:n,savedHeight:i}=f(this,ql);R(this,ql,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:H(this,yt,eA).bind(this,r,o,a,c),undo:H(this,yt,eA).bind(this,e,t,n,i),mustExec:!0})},tA=function(e,t){const[n,i]=this.parentDimensions,r=this.x,o=this.y,a=this.width,c=this.height,l=wt.MIN_SIZE/n,u=wt.MIN_SIZE/i,d=H(this,yt,Vw).call(this,this.rotation),h=(q,V)=>[d[0]*q+d[2]*V,d[1]*q+d[3]*V],p=H(this,yt,Vw).call(this,360-this.rotation),g=(q,V)=>[p[0]*q+p[2]*V,p[1]*q+p[3]*V];let v,m,y=!1,_=!1;switch(e){case"topLeft":y=!0,v=(q,V)=>[0,0],m=(q,V)=>[q,V];break;case"topMiddle":v=(q,V)=>[q/2,0],m=(q,V)=>[q/2,V];break;case"topRight":y=!0,v=(q,V)=>[q,0],m=(q,V)=>[0,V];break;case"middleRight":_=!0,v=(q,V)=>[q,V/2],m=(q,V)=>[0,V/2];break;case"bottomRight":y=!0,v=(q,V)=>[q,V],m=(q,V)=>[0,0];break;case"bottomMiddle":v=(q,V)=>[q/2,V],m=(q,V)=>[q/2,0];break;case"bottomLeft":y=!0,v=(q,V)=>[0,V],m=(q,V)=>[q,0];break;case"middleLeft":_=!0,v=(q,V)=>[0,V/2],m=(q,V)=>[q,V/2];break}const b=v(a,c),k=m(a,c);let w=h(...k);const T=wt._round(r+w[0]),A=wt._round(o+w[1]);let C=1,E=1,x,D;if(t.fromKeyboard)({deltaX:x,deltaY:D}=t);else{const{screenX:q,screenY:V}=t,[I,$]=f(this,ch);[x,D]=this.screenToPageTranslation(q-I,V-$),f(this,ch)[0]=q,f(this,ch)[1]=V}if([x,D]=g(x/n,D/i),y){const q=Math.hypot(a,c);C=E=Math.max(Math.min(Math.hypot(k[0]-b[0]-x,k[1]-b[1]-D)/q,1/a,1/c),l/a,u/c)}else _?C=zs(Math.abs(k[0]-b[0]-x),l,1)/a:E=zs(Math.abs(k[1]-b[1]-D),u,1)/c;const N=wt._round(a*C),O=wt._round(c*E);w=h(...m(N,O));const G=T-w[0],Z=A-w[1];f(this,Br)||R(this,Br,[this.x,this.y,this.width,this.height]),this.width=N,this.height=O,this.x=G,this.y=Z,this.setDims(),this.fixAndSetPosition(),this._onResizing()},ON=function(){var e;R(this,ql,{savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height}),(e=f(this,Us))==null||e.toggle(!1),this.parent.togglePointerEvents(!1)},DN=function(e,t,n){let r=.7*(n/t)+1-.7;if(r===1)return;const o=H(this,yt,Vw).call(this,this.rotation),a=(T,A)=>[o[0]*T+o[2]*A,o[1]*T+o[3]*A],[c,l]=this.parentDimensions,u=this.x,d=this.y,h=this.width,p=this.height,g=wt.MIN_SIZE/c,v=wt.MIN_SIZE/l;r=Math.max(Math.min(r,1/h,1/p),g/h,v/p);const m=wt._round(h*r),y=wt._round(p*r);if(m===h&&y===p)return;f(this,Br)||R(this,Br,[u,d,h,p]);const _=a(h/2,p/2),b=wt._round(u+_[0]),k=wt._round(d+_[1]),w=a(m/2,y/2);this.x=b-w[0],this.y=k-w[1],this.width=m,this.height=y,this.setDims(),this.fixAndSetPosition(),this._onResizing()},NN=function(){var e;(e=f(this,Us))==null||e.toggle(!0),this.parent.togglePointerEvents(!0),H(this,yt,Gw).call(this)},sA=function(e){const{isMac:t}=Rs.platform;e.ctrlKey&&!t||e.shiftKey||e.metaKey&&t?this.parent.toggleSelected(this):this.parent.setSelected(this)},$N=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(),R(this,Tu,null),R(this,uh,!1),this._uiManager.endDragSession()||H(this,yt,sA).call(this,l),n&&this._onStopDragging()};t&&(R(this,Jp,e.clientX),R(this,Zp,e.clientY),R(this,Tu,e.pointerId),R(this,Yy,e.pointerType),window.addEventListener("pointermove",l=>{n||(n=!0,this._uiManager.toggleComment(this,!0,!1),this._onStartDragging());const{clientX:u,clientY:d,pointerId:h}=l;if(h!==f(this,Tu)){Xs(l);return}const[p,g]=this.screenToPageTranslation(u-f(this,Jp),d-f(this,Zp));R(this,Jp,u),R(this,Zp,d),this._uiManager.dragSelectedEditors(p,g)},o),window.addEventListener("touchmove",Xs,o),window.addEventListener("pointerdown",l=>{l.pointerType===f(this,Yy)&&(f(this,hh)||l.isPrimary)&&a(l),Xs(l)},o));const c=l=>{if(!f(this,Tu)||f(this,Tu)===l.pointerId){a(l);return}Xs(l)};window.addEventListener("pointerup",c,{signal:r}),window.addEventListener("blur",c,{signal:r})},nA=function(){if(f(this,Au)||!this.div)return;R(this,Au,new AbortController);const e=this._uiManager.combinedSignal(f(this,Au));this.div.addEventListener("focusin",this.focusin.bind(this),{signal:e}),this.div.addEventListener("focusout",this.focusout.bind(this),{signal:e})},BN=function(e){wt._resizerKeyboardManager.exec(this,e)},FN=function(e){var t;f(this,Ql)&&((t=e.relatedTarget)==null?void 0:t.parentNode)!==f(this,ti)&&H(this,yt,pv).call(this)},HN=function(e){R(this,Jy,f(this,Ql)?e:"")},iA=function(e){if(f(this,ra))for(const t of f(this,ra))t.tabIndex=e},pv=function(){R(this,Ql,!1),H(this,yt,iA).call(this,-1),H(this,yt,Gw).call(this)},B(wt,tb),Se(wt,"_l10n",null),Se(wt,"_l10nAlert",null),Se(wt,"_l10nResizer",null),Se(wt,"_borderLineWidth",-1),Se(wt,"_colorManager",new G1),Se(wt,"_zIndex",1),Se(wt,"_telemetryTimeout",1e3);let cs=wt;class fse extends cs{constructor(e){super(e),this.annotationElementId=e.annotationElementId,this.deleted=!0}serialize(){return this.serializeDeleted()}}const UI=3285377520,vo=4294901760,Ma=65535;class rA{constructor(e){this.h1=e?e&4294967295:UI,this.h2=e?e&4294967295:UI}update(e){let t,n;if(typeof e=="string"){t=new Uint8Array(e.length*2),n=0;for(let v=0,m=e.length;v<m;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 d=3432918353,h=461845907,p=d&Ma,g=h&Ma;for(let v=0;v<i;v++)v&1?(a=o[v],a=a*d&vo|a*p&Ma,a=a<<15|a>>>17,a=a*h&vo|a*g&Ma,l^=a,l=l<<13|l>>>19,l=l*5+3864292196):(c=o[v],c=c*d&vo|c*p&Ma,c=c<<15|c>>>17,c=c*h&vo|c*g&Ma,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*d&vo|a*p&Ma,a=a<<15|a>>>17,a=a*h&vo|a*g&Ma,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&vo|e*36045&Ma,t=t*4283543511&vo|((t<<16|e>>>16)*2950163797&vo)>>>16,e^=t>>>1,e=e*444984403&vo|e*60499&Ma,t=t*3301882366&vo|((t<<16|e>>>16)*3120437893&vo)>>>16,e^=t>>>1,(e>>>0).toString(16).padStart(8,"0")+(t>>>0).toString(16).padStart(8,"0")}}const Cy=Object.freeze({map:null,hash:"",transfer:void 0});var fh,ph,Xl,si,U0,UN;class IM{constructor(){B(this,U0);B(this,fh,!1);B(this,ph,null);B(this,Xl,null);B(this,si,new Map);Se(this,"onSetModified",null);Se(this,"onResetModified",null);Se(this,"onAnnotationEditor",null)}getValue(e,t){const n=f(this,si).get(e);return n===void 0?t:Object.assign(t,n)}getRawValue(e){return f(this,si).get(e)}remove(e){var n;const t=f(this,si).get(e);t!==void 0&&(t instanceof cs&&f(this,Xl).delete(t.annotationElementId),f(this,si).delete(e),f(this,si).size===0&&this.resetModified(),!f(this,si).values().some(i=>i instanceof cs)&&((n=this.onAnnotationEditor)==null||n.call(this,null)))}setValue(e,t){var r;const n=f(this,si).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,si).set(e,t);i&&H(this,U0,UN).call(this),t instanceof cs&&((f(this,Xl)||R(this,Xl,new Map)).set(t.annotationElementId,t),(r=this.onAnnotationEditor)==null||r.call(this,t.constructor._type))}has(e){return f(this,si).has(e)}get size(){return f(this,si).size}resetModified(){var e;f(this,fh)&&(R(this,fh,!1),(e=this.onResetModified)==null||e.call(this))}get print(){return new WN(this)}get serializable(){if(f(this,si).size===0)return Cy;const e=new Map,t=new rA,n=[],i=Object.create(null);let r=!1;for(const[o,a]of f(this,si)){const c=a instanceof cs?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}:Cy}get editorStats(){let e=null;const t=new Map;let n=0,i=0;for(const r of f(this,si).values()){if(!(r instanceof cs)){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 d=c.getOrInsertComputed(l,EM);d.set(u,(d.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(){R(this,ph,null)}updateEditor(e,t){var i;const n=(i=f(this,Xl))==null?void 0:i.get(e);return n?(n.updateFromAnnotationLayer(t),!0):!1}getEditor(e){var t;return((t=f(this,Xl))==null?void 0:t.get(e))||null}get modifiedIds(){if(f(this,ph))return f(this,ph);const e=[];if(f(this,Xl))for(const n of f(this,Xl).values())n.serialize()&&e.push(n.annotationElementId);let t="";if(e.length){const n=new rA;n.update(e.join(",")),t=n.hexdigest()}return R(this,ph,{ids:new Set(e),hash:t})}[Symbol.iterator](){return f(this,si).entries()}}fh=new WeakMap,ph=new WeakMap,Xl=new WeakMap,si=new WeakMap,U0=new WeakSet,UN=function(){var e;f(this,fh)||(R(this,fh,!0),(e=this.onSetModified)==null||e.call(this))};var sb;class WN extends IM{constructor(t){super();B(this,sb,Cy);const{serializable:n}=t;if(n===Cy)return;const{map:i,hash:r,transfer:o}=n,a=structuredClone(i,o?{transfer:o}:null);R(this,sb,{map:a,hash:r,transfer:[]})}get print(){ss("Should not call PrintAnnotationStorage.print")}get serializable(){return f(this,sb)}get modifiedIds(){return Mt(this,"modifiedIds",{ids:new Set,hash:""})}}sb=new WeakMap;Ct(7588);const ap="__forcedDependency",{floor:WI,ceil:zI}=Math;function jI(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 pse(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 oA=new Uint32Array(new Uint8Array([255,255,0,0]).buffer)[0];var em,Eu;class mse{constructor(e,t){B(this,em);B(this,Eu);R(this,em,e),R(this,Eu,t)}get length(){return f(this,em).length}isEmpty(e){return f(this,em)[e]===oA}minX(e){return f(this,Eu)[e*4+0]/256}minY(e){return f(this,Eu)[e*4+1]/256}maxX(e){return(f(this,Eu)[e*4+2]+1)/256}maxY(e){return(f(this,Eu)[e*4+3]+1)/256}}em=new WeakMap,Eu=new WeakMap;const VI=(s,e)=>s==null?void 0:s.getOrInsertComputed(e,()=>({dependencies:new Set,isRenderingOperation:!1}));var Yl,as,Ds,mh,gh,vh,wi,nb,aA;class gse{constructor(e,t){B(this,nb);B(this,Yl,[[1,0,0,1,0,0]]);B(this,as,[-1/0,-1/0,1/0,1/0]);B(this,Ds,new Float64Array(Sc));Se(this,"_pendingBBoxIdx",-1);B(this,mh);B(this,gh);B(this,vh);B(this,wi);Se(this,"_savesStack",[]);Se(this,"_markedContentStack",[]);R(this,mh,e.width),R(this,gh,e.height),H(this,nb,aA).call(this,t)}growOperationsCount(e){e>=f(this,wi).length&&H(this,nb,aA).call(this,e,f(this,wi))}get clipBox(){return f(this,as)}save(e){return R(this,as,{__proto__:f(this,as)}),this._savesStack.push(e),this}restore(e,t){const n=Object.getPrototypeOf(f(this,as));if(n===null)return this;R(this,as,n);const i=this._savesStack.pop();return i!==void 0&&(t==null||t(i,e),f(this,wi)[e]=f(this,wi)[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,wi)[e]=f(this,wi)[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,wi)[e]=f(this,wi)[n]),this}pushBaseTransform(e){return f(this,Yl).push(Fe.multiplyByDOMMatrix(f(this,Yl).at(-1),e.getTransform())),this}popBaseTransform(){return f(this,Yl).length>1&&f(this,Yl).pop(),this}resetBBox(e){return this._pendingBBoxIdx!==e&&(this._pendingBBoxIdx=e,f(this,Ds).set(Sc,0)),this}recordClipBox(e,t,n,i,r,o){const a=Fe.multiplyByDOMMatrix(f(this,Yl).at(-1),t.getTransform()),c=Sc.slice();Fe.axialAlignedBoundingBox([n,r,i,o],a,c);const l=Fe.intersect(f(this,as),c);return l?(f(this,as)[0]=l[0],f(this,as)[1]=l[1],f(this,as)[2]=l[2],f(this,as)[3]=l[3]):(f(this,as)[0]=f(this,as)[1]=1/0,f(this,as)[2]=f(this,as)[3]=-1/0),this}recordBBox(e,t,n,i,r,o){const a=f(this,as);if(a[0]===1/0)return this;const c=Fe.multiplyByDOMMatrix(f(this,Yl).at(-1),t.getTransform());if(a[0]===-1/0)return Fe.axialAlignedBoundingBox([n,r,i,o],c,f(this,Ds)),this;const l=Sc.slice();return Fe.axialAlignedBoundingBox([n,r,i,o],c,l),f(this,Ds)[0]=zs(l[0],a[0],f(this,Ds)[0]),f(this,Ds)[1]=zs(l[1],a[1],f(this,Ds)[1]),f(this,Ds)[2]=zs(l[2],f(this,Ds)[2],a[2]),f(this,Ds)[3]=zs(l[3],f(this,Ds)[3],a[3]),this}recordFullPageBBox(e){return f(this,Ds)[0]=Math.max(0,f(this,as)[0]),f(this,Ds)[1]=Math.max(0,f(this,as)[1]),f(this,Ds)[2]=Math.min(f(this,mh),f(this,as)[2]),f(this,Ds)[3]=Math.min(f(this,gh),f(this,as)[3]),this}recordOperation(e,t=!1,n){if(this._pendingBBoxIdx!==e)return this;const i=WI(f(this,Ds)[0]*256/f(this,mh)),r=WI(f(this,Ds)[1]*256/f(this,gh)),o=zI(f(this,Ds)[2]*256/f(this,mh)),a=zI(f(this,Ds)[3]*256/f(this,gh));if(jI(f(this,vh),e,i,r,o,a),n)for(const c of n)for(const l of c)l!==e&&jI(f(this,vh),l,i,r,o,a);return t||(this._pendingBBoxIdx=-1),this}bboxToClipBoxDropOperation(e){return this._pendingBBoxIdx===e&&(this._pendingBBoxIdx=-1,f(this,as)[0]=Math.max(f(this,as)[0],f(this,Ds)[0]),f(this,as)[1]=Math.max(f(this,as)[1],f(this,Ds)[1]),f(this,as)[2]=Math.min(f(this,as)[2],f(this,Ds)[2]),f(this,as)[3]=Math.min(f(this,as)[3],f(this,Ds)[3])),this}take(){return new mse(f(this,wi),f(this,vh))}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}}Yl=new WeakMap,as=new WeakMap,Ds=new WeakMap,mh=new WeakMap,gh=new WeakMap,vh=new WeakMap,wi=new WeakMap,nb=new WeakSet,aA=function(e,t){const n=new ArrayBuffer(e*4);R(this,vh,new Uint8ClampedArray(n)),R(this,wi,new Uint32Array(n)),t&&t.length>0?(f(this,wi).set(t),f(this,wi).fill(oA,t.length)):f(this,wi).fill(oA)};var mr,gr,yh,oa,tm,Mu,xu,bs;class vse{constructor(e,t=!1){B(this,mr,{__proto__:null});B(this,gr,{__proto__:null,transform:[],moveText:[],sameLineText:[],[ap]:[]});B(this,yh,new Map);B(this,oa,new Set);B(this,tm,new Map);B(this,Mu);B(this,xu);B(this,bs);R(this,bs,e),t&&(R(this,Mu,new Map),R(this,xu,(n,i)=>{VI(f(this,Mu),i).dependencies.add(n)}))}get clipBox(){return f(this,bs).clipBox}growOperationsCount(e){f(this,bs).growOperationsCount(e)}save(e){return R(this,mr,{__proto__:f(this,mr)}),R(this,gr,{__proto__:f(this,gr),transform:{__proto__:f(this,gr).transform},moveText:{__proto__:f(this,gr).moveText},sameLineText:{__proto__:f(this,gr).sameLineText},[ap]:{__proto__:f(this,gr)[ap]}}),f(this,bs).save(e),this}restore(e){f(this,bs).restore(e,f(this,xu));const t=Object.getPrototypeOf(f(this,mr));return t===null?this:(R(this,mr,t),R(this,gr,Object.getPrototypeOf(f(this,gr))),this)}recordOpenMarker(e){return f(this,bs).recordOpenMarker(e,f(this,xu)),this}getOpenMarker(){return f(this,bs).getOpenMarker()}recordCloseMarker(e){return f(this,bs).recordCloseMarker(e,f(this,xu)),this}beginMarkedContent(e){return f(this,bs).beginMarkedContent(e),this}endMarkedContent(e){return f(this,bs).endMarkedContent(e,f(this,xu)),this}pushBaseTransform(e){return f(this,bs).pushBaseTransform(e),this}popBaseTransform(){return f(this,bs).popBaseTransform(),this}recordSimpleData(e,t){return f(this,mr)[e]=t,this}recordIncrementalData(e,t){return f(this,gr)[e].push(t),this}resetIncrementalData(e,t){return f(this,gr)[e].length=0,this}recordNamedData(e,t){return f(this,yh).set(e,t),this}recordSimpleDataFromNamed(e,t,n){f(this,mr)[e]=f(this,yh).get(t)??n}recordFutureForcedDependency(e,t){return this.recordIncrementalData(ap,t),this}inheritSimpleDataAsFutureForcedDependencies(e){for(const t of e)t in f(this,mr)&&this.recordFutureForcedDependency(t,f(this,mr)[t]);return this}inheritPendingDependenciesAsFutureForcedDependencies(){for(const e of f(this,oa))this.recordFutureForcedDependency(ap,e);return this}resetBBox(e){return f(this,bs).resetBBox(e),this}recordClipBox(e,t,n,i,r,o){return f(this,bs).recordClipBox(e,t,n,i,r,o),this}recordBBox(e,t,n,i,r,o){return f(this,bs).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,tm).get(n),l!==!1&&(u=[0,0,0,0],Fe.axialAlignedBoundingBox(c,n.fontMatrix,u),(i!==1||r!==0||o!==0)&&pse(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 d=a();return c&&u&&l===void 0&&(l=u[0]<=r-d.actualBoundingBoxLeft&&u[2]>=r+d.actualBoundingBoxRight&&u[1]<=o-d.actualBoundingBoxAscent&&u[3]>=o+d.actualBoundingBoxDescent,f(this,tm).set(n,l),l)?this.recordBBox(e,t,u[0],u[2],u[1],u[3]):this.recordBBox(e,t,r-d.actualBoundingBoxLeft,r+d.actualBoundingBoxRight,o-d.actualBoundingBoxAscent,o+d.actualBoundingBoxDescent)}recordFullPageBBox(e){return f(this,bs).recordFullPageBBox(e),this}getSimpleIndex(e){return f(this,mr)[e]}recordDependencies(e,t){const n=f(this,oa),i=f(this,mr),r=f(this,gr);for(const o of t)o in f(this,mr)?n.add(i[o]):o in r&&r[o].forEach(n.add,n);return this}recordNamedDependency(e,t){return f(this,yh).has(t)&&f(this,oa).add(f(this,yh).get(t)),this}recordOperation(e,t=!1){if(this.recordDependencies(e,[ap]),f(this,Mu)){const i=VI(f(this,Mu),e),{dependencies:r}=i;f(this,oa).forEach(r.add,r),f(this,bs)._savesStack.forEach(r.add,r),f(this,bs)._markedContentStack.forEach(r.add,r),r.delete(e),i.isRenderingOperation=!0}const n=!t&&e===f(this,bs)._pendingBBoxIdx;return f(this,bs).recordOperation(e,t,[f(this,oa),f(this,bs)._savesStack,f(this,bs)._markedContentStack]),n&&f(this,oa).clear(),this}recordShowTextOperation(e,t=!1){const n=Array.from(f(this,oa));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,bs)._pendingBBoxIdx;return f(this,bs).bboxToClipBoxDropOperation(e),n&&f(this,oa).clear(),this}take(){return f(this,tm).clear(),f(this,bs).take()}takeDebugMetadata(){return f(this,Mu)}}mr=new WeakMap,gr=new WeakMap,yh=new WeakMap,oa=new WeakMap,tm=new WeakMap,Mu=new WeakMap,xu=new WeakMap,bs=new WeakMap;var _s,on,aa,sm,nm;const zM=class zM{constructor(e,t,n){B(this,_s);B(this,on);B(this,aa);B(this,sm,0);B(this,nm,0);if(e instanceof zM&&f(e,aa)===!!n)return e;R(this,_s,e),R(this,on,t),R(this,aa,!!n)}get clipBox(){return f(this,_s).clipBox}growOperationsCount(){throw new Error("Unreachable")}save(e){return Ls(this,nm)._++,f(this,_s).save(f(this,on)),this}restore(e){return f(this,nm)>0&&(f(this,_s).restore(f(this,on)),Ls(this,nm)._--),this}recordOpenMarker(e){return Ls(this,sm)._++,this}getOpenMarker(){return f(this,sm)>0?f(this,on):f(this,_s).getOpenMarker()}recordCloseMarker(e){return Ls(this,sm)._--,this}beginMarkedContent(e){return this}endMarkedContent(e){return this}pushBaseTransform(e){return f(this,_s).pushBaseTransform(e),this}popBaseTransform(){return f(this,_s).popBaseTransform(),this}recordSimpleData(e,t){return f(this,_s).recordSimpleData(e,f(this,on)),this}recordIncrementalData(e,t){return f(this,_s).recordIncrementalData(e,f(this,on)),this}resetIncrementalData(e,t){return f(this,_s).resetIncrementalData(e,f(this,on)),this}recordNamedData(e,t){return this}recordSimpleDataFromNamed(e,t,n){return f(this,_s).recordSimpleDataFromNamed(e,t,f(this,on)),this}recordFutureForcedDependency(e,t){return f(this,_s).recordFutureForcedDependency(e,f(this,on)),this}inheritSimpleDataAsFutureForcedDependencies(e){return f(this,_s).inheritSimpleDataAsFutureForcedDependencies(e),this}inheritPendingDependenciesAsFutureForcedDependencies(){return f(this,_s).inheritPendingDependenciesAsFutureForcedDependencies(),this}resetBBox(e){return f(this,aa)||f(this,_s).resetBBox(f(this,on)),this}recordClipBox(e,t,n,i,r,o){return f(this,aa)||f(this,_s).recordClipBox(f(this,on),t,n,i,r,o),this}recordBBox(e,t,n,i,r,o){return f(this,aa)||f(this,_s).recordBBox(f(this,on),t,n,i,r,o),this}recordCharacterBBox(e,t,n,i,r,o,a){return f(this,aa)||f(this,_s).recordCharacterBBox(f(this,on),t,n,i,r,o,a),this}recordFullPageBBox(e){return f(this,aa)||f(this,_s).recordFullPageBBox(f(this,on)),this}getSimpleIndex(e){return f(this,_s).getSimpleIndex(e)}recordDependencies(e,t){return f(this,_s).recordDependencies(f(this,on),t),this}recordNamedDependency(e,t){return f(this,_s).recordNamedDependency(f(this,on),t),this}recordOperation(e){return f(this,_s).recordOperation(f(this,on),!0),this}recordShowTextOperation(e){return f(this,_s).recordShowTextOperation(f(this,on),!0),this}bboxToClipBoxDropOperation(e){return f(this,aa)||f(this,_s).bboxToClipBoxDropOperation(f(this,on),!0),this}take(){throw new Error("Unreachable")}takeDebugMetadata(){throw new Error("Unreachable")}};_s=new WeakMap,on=new WeakMap,aa=new WeakMap,sm=new WeakMap,nm=new WeakMap;let Ty=zM;const yo={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 bh,_h,wh,Sh,kh,ib;const ny=class ny{constructor(e){B(this,bh);B(this,_h);B(this,wh,4);B(this,Sh,0);B(this,kh,new(f(ny,ib))(f(this,wh)*6));R(this,bh,e.width),R(this,_h,e.height)}record(e,t,n,i){if(f(this,Sh)===f(this,wh)){R(this,wh,f(this,wh)*2);const a=new(f(ny,ib))(f(this,wh)*6);a.set(f(this,kh)),R(this,kh,a)}const r=xs(e);let o;if(i[0]!==1/0){const a=Sc.slice();Fe.axialAlignedBoundingBox([0,-n,t,0],r,a);const c=Fe.intersect(i,a);if(!c)return;const[l,u,d,h]=c;if(l!==a[0]||u!==a[1]||d!==a[2]||h!==a[3]){const p=Math.atan2(r[1],r[0]),g=Math.abs(Math.sin(p)),v=Math.abs(Math.cos(p));if(g<1e-6||v<1e-6||Math.abs(g-v)<1e-6)o=[l,u,l,h,d,u];else{const m=d-l,y=h-u,_=g*g,b=v*v,k=v*g,w=b-_,T=(y*b-m*k)/w,A=(y*k-m*_)/w;o=[l+A,u,l,u+T,d,h-T]}}}o||(o=[0,-n,0,0,t,-n],Fe.applyTransform(o,r,0),Fe.applyTransform(o,r,2),Fe.applyTransform(o,r,4)),o[0]/=f(this,bh),o[1]/=f(this,_h),o[2]/=f(this,bh),o[3]/=f(this,_h),o[4]/=f(this,bh),o[5]/=f(this,_h),f(this,kh).set(o,f(this,Sh)*6),Ls(this,Sh)._++}take(){return f(this,kh).subarray(0,f(this,Sh)*6)}};bh=new WeakMap,_h=new WeakMap,wh=new WeakMap,Sh=new WeakMap,kh=new WeakMap,ib=new WeakMap,B(ny,ib,Rs.isFloat16ArraySupported?Float16Array:Float32Array);let lA=ny;var im;class yse{constructor({ownerDocument:e=globalThis.document,styleElement:t=null}){B(this,im,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,im).clear(),this.styleElement&&(this.styleElement.remove(),this.styleElement=null)}async loadSystemFont({systemFontInfo:e,disableFontFace:t,_inspectFont:n}){if(!(!e||f(this,im).has(e.loadedName))){if(Ys(!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,im).add(i),n==null||n(e)}catch{At(`Cannot load system font: ${e.baseFontName}, installing it could help to improve PDF rendering.`),this.removeNativeFontFace(a)}return}ss("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 At(`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 Mt(this,"isFontLoadingAPISupported",e)}get isSyncFontLoadingSupported(){return Mt(this,"isSyncFontLoadingSupported",to||Rs.platform.isFirefox)}_queueLoadingCallback(e){function t(){for(Ys(!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 Mt(this,"_loadTestFont",e)}_prepareFontLoadEvent(e,t){function n(w,T){return w.charCodeAt(T)<<24|w.charCodeAt(T+1)<<16|w.charCodeAt(T+2)<<8|w.charCodeAt(T+3)&255}function i(w){return String.fromCharCode(w>>24&255,w>>16&255,w>>8&255,w&255)}function r(w,T,A,C){const E=w.substring(0,T),x=w.substring(T+A);return E+C+x}let o,a;const c=this._document.createElement("canvas");c.width=1,c.height=1;const l=c.getContext("2d");let u=0;function d(w,T){if(++u>30){At("Load test font never loaded."),T();return}if(l.font="30px "+w,l.fillText(".",0,20),l.getImageData(0,0,1,1).data[3]>0){T();return}setTimeout(d.bind(null,w,T))}const h=`lt${Date.now()}${this.loadTestFontId++}`;let p=this._loadTestFont;p=r(p,976,h.length,h);const v=16,m=1482184792;let y=n(p,v);for(o=0,a=h.length-3;o<a;o+=4)y=y-m+n(h,o)|0;o<h.length&&(y=y-m+n(h+"XXX",o)|0),p=r(p,v,4,i(y));const _=`url(data:font/opentype;base64,${btoa(p)});`,b=`@font-face {font-family:"${h}";src:${_}}`;this.insertRule(b);const k=this._document.createElement("div");k.style.visibility="hidden",k.style.width=k.style.height="10px",k.style.position="absolute",k.style.top=k.style.left="0px";for(const w of[e.loadedName,h]){const T=this._document.createElement("span");T.textContent="Hi",T.style.fontFamily=w,k.append(T)}this._document.body.append(k),d(h,()=>{k.remove(),t.complete()})}}im=new WeakMap;var ws;class bse{constructor(e,t=null,n,i){Se(this,"compiledGlyphs",Object.create(null));B(this,ws);R(this,ws,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){At(`getPathGenerator - ignoring character: "${o}".`)}const r=lN(i==null?void 0:i.path);return this.fontExtraProperties||e.delete(n),this.compiledGlyphs[t]=r}get black(){return f(this,ws).black}get bold(){return f(this,ws).bold}get disableFontFace(){return f(this,ws).disableFontFace}set disableFontFace(e){Mt(this,"disableFontFace",!!e)}get fontExtraProperties(){return f(this,ws).fontExtraProperties}get isInvalidPDFjsFont(){return f(this,ws).isInvalidPDFjsFont}get isType3Font(){return f(this,ws).isType3Font}get italic(){return f(this,ws).italic}get missingFile(){return f(this,ws).missingFile}get remeasure(){return f(this,ws).remeasure}get vertical(){return f(this,ws).vertical}get ascent(){return f(this,ws).ascent}get defaultWidth(){return f(this,ws).defaultWidth}get descent(){return f(this,ws).descent}get bbox(){return f(this,ws).bbox}get fontMatrix(){return f(this,ws).fontMatrix}get fallbackName(){return f(this,ws).fallbackName}get loadedName(){return f(this,ws).loadedName}get mimetype(){return f(this,ws).mimetype}get name(){return f(this,ws).name}get data(){return f(this,ws).data}clearData(){f(this,ws).clearData()}get cssFontInfo(){return f(this,ws).cssFontInfo}get systemFontInfo(){return f(this,ws).systemFontInfo}get defaultVMetrics(){return f(this,ws).defaultVMetrics}}ws=new WeakMap;class zN{}Se(zN,"strings",["fontFamily","fontWeight","italicAngle"]);class jN{}Se(jN,"strings",["css","loadedName","baseFontName","src"]);const yi=class yi{};Se(yi,"bools",["black","bold","disableFontFace","fontExtraProperties","isInvalidPDFjsFont","isType3Font","italic","missingFile","remeasure","vertical"]),Se(yi,"numbers",["ascent","defaultWidth","descent"]),Se(yi,"strings",["fallbackName","loadedName","mimetype","name"]),Se(yi,"OFFSET_NUMBERS",Math.ceil(yi.bools.length*2/8)),Se(yi,"OFFSET_BBOX",yi.OFFSET_NUMBERS+yi.numbers.length*8),Se(yi,"OFFSET_FONT_MATRIX",yi.OFFSET_BBOX+1+2*4),Se(yi,"OFFSET_DEFAULT_VMETRICS",yi.OFFSET_FONT_MATRIX+1+8*6),Se(yi,"OFFSET_STRINGS",yi.OFFSET_DEFAULT_VMETRICS+1+2*3);let Lr=yi;class Zi{}Se(Zi,"KIND",0),Se(Zi,"HAS_BBOX",1),Se(Zi,"HAS_BACKGROUND",2),Se(Zi,"SHADING_TYPE",3),Se(Zi,"N_COORD",4),Se(Zi,"N_COLOR",8),Se(Zi,"N_STOP",12),Se(Zi,"N_FIGURES",16);var rb,W0,rm,om,Kw;class _se{constructor(e){B(this,om);B(this,rb);B(this,W0,new TextDecoder);B(this,rm);R(this,rb,e),R(this,rm,new DataView(e))}get fontFamily(){return H(this,om,Kw).call(this,0)}get fontWeight(){return H(this,om,Kw).call(this,1)}get italicAngle(){return H(this,om,Kw).call(this,2)}}rb=new WeakMap,W0=new WeakMap,rm=new WeakMap,om=new WeakSet,Kw=function(e){Ys(e<zN.strings.length,"Invalid string index");let t=0;for(let i=0;i<e;i++)t+=f(this,rm).getUint32(t)+4;const n=f(this,rm).getUint32(t);return f(this,W0).decode(new Uint8Array(f(this,rb),t+4,n))};var Ch,am,Va,Th,mv;class wse{constructor(e){B(this,Th);B(this,Ch);B(this,am,new TextDecoder);B(this,Va);R(this,Ch,e),R(this,Va,new DataView(e))}get guessFallback(){return f(this,Va).getUint8(0)!==0}get css(){return H(this,Th,mv).call(this,0)}get loadedName(){return H(this,Th,mv).call(this,1)}get baseFontName(){return H(this,Th,mv).call(this,2)}get src(){return H(this,Th,mv).call(this,3)}get style(){let e=1;e+=4+f(this,Va).getUint32(e);const t=f(this,Va).getUint32(e),n=f(this,am).decode(new Uint8Array(f(this,Ch),e+4,t));e+=4+t;const i=f(this,Va).getUint32(e),r=f(this,am).decode(new Uint8Array(f(this,Ch),e+4,i));return{style:n,weight:r}}}Ch=new WeakMap,am=new WeakMap,Va=new WeakMap,Th=new WeakSet,mv=function(e){Ys(e<jN.strings.length,"Invalid string index");let t=5;for(let i=0;i<e;i++)t+=f(this,Va).getUint32(t)+4;const n=f(this,Va).getUint32(t);return f(this,am).decode(new Uint8Array(f(this,Ch),t+4,n))};var la,z0,vn,vs,ta,qw,Qw,gv,cA;class Sse{constructor({buffer:e,extra:t}){B(this,vs);B(this,la);B(this,z0,new TextDecoder);B(this,vn);R(this,la,e),R(this,vn,new DataView(e)),t&&Object.assign(this,t)}get black(){return H(this,vs,ta).call(this,0)}get bold(){return H(this,vs,ta).call(this,1)}get disableFontFace(){return H(this,vs,ta).call(this,2)}get fontExtraProperties(){return H(this,vs,ta).call(this,3)}get isInvalidPDFjsFont(){return H(this,vs,ta).call(this,4)}get isType3Font(){return H(this,vs,ta).call(this,5)}get italic(){return H(this,vs,ta).call(this,6)}get missingFile(){return H(this,vs,ta).call(this,7)}get remeasure(){return H(this,vs,ta).call(this,8)}get vertical(){return H(this,vs,ta).call(this,9)}get ascent(){return H(this,vs,qw).call(this,0)}get defaultWidth(){return H(this,vs,qw).call(this,1)}get descent(){return H(this,vs,qw).call(this,2)}get bbox(){return H(this,vs,Qw).call(this,Lr.OFFSET_BBOX,4,"getInt16",2)}get fontMatrix(){return H(this,vs,Qw).call(this,Lr.OFFSET_FONT_MATRIX,6,"getFloat64",8)}get defaultVMetrics(){return H(this,vs,Qw).call(this,Lr.OFFSET_DEFAULT_VMETRICS,3,"getInt16",2)}get fallbackName(){return H(this,vs,gv).call(this,0)}get loadedName(){return H(this,vs,gv).call(this,1)}get mimetype(){return H(this,vs,gv).call(this,2)}get name(){return H(this,vs,gv).call(this,3)}get data(){const{offset:e,length:t}=H(this,vs,cA).call(this);return t===0?void 0:new Uint8Array(f(this,la),e+4,t)}clearData(){const{offset:e,length:t}=H(this,vs,cA).call(this);t!==0&&(f(this,vn).setUint32(e,0),R(this,la,new Uint8Array(f(this,la),0,e+4).slice().buffer),R(this,vn,new DataView(f(this,la))))}get cssFontInfo(){let e=Lr.OFFSET_STRINGS;const t=f(this,vn).getUint32(e);e+=4+t;const n=f(this,vn).getUint32(e);e+=4+n;const i=f(this,vn).getUint32(e);if(i===0)return null;const r=new Uint8Array(i);return r.set(new Uint8Array(f(this,la),e+4,i)),new _se(r.buffer)}get systemFontInfo(){let e=Lr.OFFSET_STRINGS;const t=f(this,vn).getUint32(e);e+=4+t;const n=f(this,vn).getUint32(e);if(n===0)return null;const i=new Uint8Array(n);return i.set(new Uint8Array(f(this,la),e+4,n)),new wse(i.buffer)}}la=new WeakMap,z0=new WeakMap,vn=new WeakMap,vs=new WeakSet,ta=function(e){Ys(e<Lr.bools.length,"Invalid boolean index");const t=Math.floor(e/4),n=e*2%8,i=f(this,vn).getUint8(t)>>n&3;return i===0?void 0:i===2},qw=function(e){return Ys(e<Lr.numbers.length,"Invalid number index"),f(this,vn).getFloat64(Lr.OFFSET_NUMBERS+e*8)},Qw=function(e,t,n,i){const r=f(this,vn).getUint8(e);if(r===0)return;Ys(r===t,"Invalid array length."),e+=1;const o=new Array(r);for(let a=0;a<r;a++)o[a]=f(this,vn)[n](e,!0),e+=i;return o},gv=function(e){Ys(e<Lr.strings.length,"Invalid string index");let t=Lr.OFFSET_STRINGS+4;for(let i=0;i<e;i++)t+=f(this,vn).getUint32(t)+4;const n=f(this,vn).getUint32(t);return f(this,z0).decode(new Uint8Array(f(this,la),t+4,n))},cA=function(){let e=Lr.OFFSET_STRINGS;const t=f(this,vn).getUint32(e);e+=4+t;const n=f(this,vn).getUint32(e);e+=4+n;const i=f(this,vn).getUint32(e);e+=4+i;const r=f(this,vn).getUint32(e);return{offset:e,length:r}};class kse{constructor(e){this.buffer=e,this.view=new DataView(e),this.data=new Uint8Array(e)}getIR(){const e=this.view,t=this.data[Zi.KIND],n=!!this.data[Zi.HAS_BBOX],i=!!this.data[Zi.HAS_BACKGROUND],r=e.getUint32(Zi.N_COORD,!0),o=e.getUint32(Zi.N_COLOR,!0),a=e.getUint32(Zi.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 d=[];for(let g=0;g<a;++g){const v=e.getFloat32(c,!0);c+=4;const m=e.getUint32(c,!0);c+=4,d.push([v,`#${m.toString(16).padStart(6,"0")}`])}let h=null;if(n){h=[];for(let g=0;g<4;++g)h.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",h,d,Array.from(l.slice(0,2)),Array.from(l.slice(2,4)),null,null];if(t===2)return["RadialAxial","radial",h,d,[l[0],l[1]],[l[3],l[4]],l[2],l[5]];if(t===3){const g=this.data[Zi.SHADING_TYPE];let v=null;if(l.length>0){v=Sc.slice();for(let m=0,y=l.length;m<y;m+=2)Fe.pointBoundingBox(l[m],l[m+1],v)}return["Mesh",g,l,u,r,v,h,p]}throw new Error(`Unsupported pattern kind: ${t}`)}}var lm;class Cse{constructor(e){B(this,lm);R(this,lm,e)}get path(){return Rs.isFloat16ArraySupported?new Float16Array(f(this,lm)):new Float32Array(f(this,lm))}}lm=new WeakMap;function Tse(s){if(s instanceof URL)return s;if(typeof s=="string"){if(to){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 Ase(s){if(to&&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 Mk(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 lw(s){if(typeof s!="string")return null;if(s.endsWith("/"))return s;throw new Error(`Invalid factory url: "${s}" must include trailing slash.`)}const uA=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,Ese=s=>typeof s=="object"&&typeof(s==null?void 0:s.name)=="string",Mse=ese.bind(null,uA,Ese);var Jl,j0;class xse{constructor(){B(this,Jl,new Map);B(this,j0,Promise.resolve())}postMessage(e,t){const n={data:structuredClone(e,t?{transfer:t}:null)};f(this,j0).then(()=>{for(const[i]of f(this,Jl))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){At("LoopbackPort - cannot use an `aborted` signal.");return}const o=()=>this.removeEventListener(e,t);i=()=>r.removeEventListener("abort",o),r.addEventListener("abort",o)}f(this,Jl).set(t,i)}removeEventListener(e,t){const n=f(this,Jl).get(t);n==null||n(),f(this,Jl).delete(t)}terminate(){for(const[,e]of f(this,Jl))e==null||e();f(this,Jl).clear()}}Jl=new WeakMap,j0=new WeakMap;Ct(1689);const cw={DATA:1,ERROR:2},wn={CANCEL:1,CANCEL_COMPLETE:2,CLOSE:3,ENQUEUE:4,ERROR:5,PULL:6,PULL_COMPLETE:7,START_COMPLETE:8};function GI(){}function hr(s){if(s instanceof pd||s instanceof B1||s instanceof OI||s instanceof k0||s instanceof dT)return s;switch(s instanceof Error||typeof s=="object"&&s!==null||ss('wrapReason: Expected "reason" to be a (possibly cloned) Error.'),s.name){case"AbortException":return new pd(s.message);case"InvalidPDFException":return new B1(s.message);case"PasswordException":return new OI(s.message,s.code);case"ResponseException":return new k0(s.message,s.status,s.missing);case"UnknownErrorException":return new dT(s.message,s.details)}return new dT(s.message,s.toString())}var cm,Wo,VN,GN,KN,Xw;class vv{constructor(e,t,n){B(this,Wo);B(this,cm,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",H(this,Wo,VN).bind(this),{signal:f(this,cm).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:wn.PULL,streamId:r,desiredSize:l.desiredSize}),u.promise},cancel:l=>{Ys(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:wn.CANCEL,streamId:r,reason:hr(l)}),u.promise}},n)}destroy(){var e;(e=f(this,cm))==null||e.abort(),R(this,cm,null)}}cm=new WeakMap,Wo=new WeakSet,VN=function({data:e}){if(e.targetName!==this.sourceName)return;if(e.stream){H(this,Wo,KN).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===cw.DATA)i.resolve(e.data);else if(e.callback===cw.ERROR)i.reject(hr(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:cw.DATA,callbackId:e.callbackId,data:o})},function(o){r.postMessage({sourceName:n,targetName:i,callback:cw.ERROR,callbackId:e.callbackId,reason:hr(o)})});return}if(e.streamId){H(this,Wo,GN).call(this,e);return}t(e.data)},GN=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,d){if(this.isCancelled)return;const h=this.desiredSize;this.desiredSize-=u,h>0&&this.desiredSize<=0&&(this.sinkCapability=Promise.withResolvers(),this.ready=this.sinkCapability.promise),r.postMessage({sourceName:n,targetName:i,stream:wn.ENQUEUE,streamId:t,chunk:l},d)},close(){this.isCancelled||(this.isCancelled=!0,r.postMessage({sourceName:n,targetName:i,stream:wn.CLOSE,streamId:t}),delete o.streamSinks[t])},error(l){Ys(l instanceof Error,"error must have a valid reason"),!this.isCancelled&&(this.isCancelled=!0,r.postMessage({sourceName:n,targetName:i,stream:wn.ERROR,streamId:t,reason:hr(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:wn.START_COMPLETE,streamId:t,success:!0})},function(l){r.postMessage({sourceName:n,targetName:i,stream:wn.START_COMPLETE,streamId:t,reason:hr(l)})})},KN=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 wn.START_COMPLETE:e.success?o.startCall.resolve():o.startCall.reject(hr(e.reason));break;case wn.PULL_COMPLETE:e.success?o.pullCall.resolve():o.pullCall.reject(hr(e.reason));break;case wn.PULL:if(!a){r.postMessage({sourceName:n,targetName:i,stream:wn.PULL_COMPLETE,streamId:t,success:!0});break}a.desiredSize<=0&&e.desiredSize>0&&a.sinkCapability.resolve(),a.desiredSize=e.desiredSize,Promise.try(a.onPull||GI).then(function(){r.postMessage({sourceName:n,targetName:i,stream:wn.PULL_COMPLETE,streamId:t,success:!0})},function(l){r.postMessage({sourceName:n,targetName:i,stream:wn.PULL_COMPLETE,streamId:t,reason:hr(l)})});break;case wn.ENQUEUE:if(Ys(o,"enqueue should have stream controller"),o.isClosed)break;o.controller.enqueue(e.chunk);break;case wn.CLOSE:if(Ys(o,"close should have stream controller"),o.isClosed)break;o.isClosed=!0,o.controller.close(),H(this,Wo,Xw).call(this,o,t);break;case wn.ERROR:Ys(o,"error should have stream controller"),o.controller.error(hr(e.reason)),H(this,Wo,Xw).call(this,o,t);break;case wn.CANCEL_COMPLETE:e.success?o.cancelCall.resolve():o.cancelCall.reject(hr(e.reason)),H(this,Wo,Xw).call(this,o,t);break;case wn.CANCEL:if(!a)break;const c=hr(e.reason);Promise.try(a.onCancel||GI,c).then(function(){r.postMessage({sourceName:n,targetName:i,stream:wn.CANCEL_COMPLETE,streamId:t,success:!0})},function(l){r.postMessage({sourceName:n,targetName:i,stream:wn.CANCEL_COMPLETE,streamId:t,reason:hr(l)})}),a.sinkCapability.reject(c),a.isCancelled=!0,delete this.streamSinks[t];break;default:throw new Error("Unexpected stream case")}},Xw=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 V0;class qN{constructor({cMapUrl:e=null,standardFontDataUrl:t=null,wasmUrl:n=null}){B(this,V0,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:ss(`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,V0)[e]} data at: ${i}`)})}async _fetch(e,t){ss("Abstract method `_fetch` called.")}}V0=new WeakMap;class KI extends qN{async _fetch(e,t){const n=t==="cMapUrl"&&!e.endsWith(".bcmap")?"text":"bytes",i=await MM(e,n);return i instanceof Uint8Array?i:Mk(i)}}var ob;class QN{constructor({enableHWA:e=!1}){B(this,ob,!1);R(this,ob,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,ob)})}}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){ss("Abstract method `_createCanvas` called.")}}ob=new WeakMap;class Rse extends QN{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 XN{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 Ah,um,Zl,Ga,Un,Eh,Ru,ze,Bn,yv,Jc,Yw,Rd,YN,dA,Id,bv,_v,hA,wv,JN,ZN;class Ise extends XN{constructor({docId:t,ownerDocument:n=globalThis.document}){super();B(this,ze);B(this,Ah);B(this,um);B(this,Zl);B(this,Ga);B(this,Un);B(this,Eh);B(this,Ru,0);R(this,Ga,t),R(this,Un,n)}addFilter(t){if(!t)return"none";let n=f(this,ze,Bn).get(t);if(n)return n;const[i,r,o]=H(this,ze,Yw).call(this,t),a=t.length===1?i:`${i}${r}${o}`;if(n=f(this,ze,Bn).get(a),n)return f(this,ze,Bn).set(t,n),n;const c=`g_${f(this,Ga)}_transfer_map_${Ls(this,Ru)._++}`,l=H(this,ze,Rd).call(this,c);f(this,ze,Bn).set(t,l),f(this,ze,Bn).set(a,l);const u=H(this,ze,Id).call(this,c);return H(this,ze,_v).call(this,i,r,o,u),l}addHCMFilter(t,n){var g;const i=`${t}-${n}`,r="base";let o=f(this,ze,yv).get(r);if((o==null?void 0:o.key)===i||(o?((g=o.filter)==null||g.remove(),o.key=i,o.url="none",o.filter=null):(o={key:i,url:"none",filter:null},f(this,ze,yv).set(r,o)),!t||!n))return o.url;const a=H(this,ze,wv).call(this,t);t=Fe.makeHexColor(...a);const c=H(this,ze,wv).call(this,n);if(n=Fe.makeHexColor(...c),f(this,ze,Jc).style.color="",t==="#000000"&&n==="#ffffff"||t===n)return o.url;const l=new Array(256);for(let v=0;v<=255;v++){const m=v/255;l[v]=m<=.03928?m/12.92:((m+.055)/1.055)**2.4}const u=l.join(","),d=`g_${f(this,Ga)}_hcm_filter`,h=o.filter=H(this,ze,Id).call(this,d);H(this,ze,_v).call(this,u,u,u,h),H(this,ze,dA).call(this,h);const p=(v,m)=>{const y=a[v]/255,_=c[v]/255,b=new Array(m+1);for(let k=0;k<=m;k++)b[k]=y+k/m*(_-y);return b.join(",")};return H(this,ze,_v).call(this,p(0,5),p(1,5),p(2,5),h),o.url=H(this,ze,Rd).call(this,d),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"||!Rs.platform.isFirefox?null:{"backdrop-filter":n,"background-color":"transparent"}}addAlphaFilter(t){let n=f(this,ze,Bn).get(t);if(n)return n;const[i]=H(this,ze,Yw).call(this,[t]),r=`alpha_${i}`;if(n=f(this,ze,Bn).get(r),n)return f(this,ze,Bn).set(t,n),n;const o=`g_${f(this,Ga)}_alpha_map_${Ls(this,Ru)._++}`,a=H(this,ze,Rd).call(this,o);f(this,ze,Bn).set(t,a),f(this,ze,Bn).set(r,a);const c=H(this,ze,Id).call(this,o);return H(this,ze,hA).call(this,i,c),a}addLuminosityFilter(t){let n=f(this,ze,Bn).get(t||"luminosity");if(n)return n;let i,r;if(t?([i]=H(this,ze,Yw).call(this,[t]),r=`luminosity_${i}`):r="luminosity",n=f(this,ze,Bn).get(r),n)return f(this,ze,Bn).set(t,n),n;const o=`g_${f(this,Ga)}_luminosity_map_${Ls(this,Ru)._++}`,a=H(this,ze,Rd).call(this,o);f(this,ze,Bn).set(t,a),f(this,ze,Bn).set(r,a);const c=H(this,ze,Id).call(this,o);return H(this,ze,YN).call(this,c),t&&H(this,ze,hA).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,Bn).get(i);if(r)return r;const o=`g_${f(this,Ga)}_knockout_filter_${Ls(this,Ru)._++}`,a=H(this,ze,Rd).call(this,o);f(this,ze,Bn).set(i,a);const c=H(this,ze,Id).call(this,o),l=f(this,Un).createElementNS(Dr,"feComponentTransfer");c.append(l);const u=f(this,Un).createElementNS(Dr,"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 _;const a=`${n}-${i}-${r}-${o}`;let c=f(this,ze,yv).get(t);if((c==null?void 0:c.key)===a||(c?((_=c.filter)==null||_.remove(),c.key=a,c.url="none",c.filter=null):(c={key:a,url:"none",filter:null},f(this,ze,yv).set(t,c)),!n||!i))return c.url;const[l,u]=[n,i].map(H(this,ze,wv).bind(this));let d=Math.round(.2126*l[0]+.7152*l[1]+.0722*l[2]),h=Math.round(.2126*u[0]+.7152*u[1]+.0722*u[2]),[p,g]=[r,o].map(H(this,ze,ZN).bind(this));h<d&&([d,h,p,g]=[h,d,g,p]),f(this,ze,Jc).style.color="";const v=(b,k,w)=>{const T=new Array(256),A=(h-d)/w,C=b/255,E=(k-b)/(255*w);let x=0;for(let D=0;D<=w;D++){const N=Math.round(d+D*A),O=C+D*E;for(let G=x;G<=N;G++)T[G]=O;x=N+1}for(let D=x;D<256;D++)T[D]=T[x-1];return T.join(",")},m=`g_${f(this,Ga)}_hcm_${t}_filter`,y=c.filter=H(this,ze,Id).call(this,m);return H(this,ze,dA).call(this,y),H(this,ze,_v).call(this,v(p[0],g[0],5),v(p[1],g[1],5),v(p[2],g[2],5),y),c.url=H(this,ze,Rd).call(this,m),c.url}destroy(t=!1){var n,i,r,o;t&&((n=f(this,Eh))!=null&&n.size)||((i=f(this,Zl))==null||i.parentNode.parentNode.remove(),R(this,Zl,null),(r=f(this,um))==null||r.clear(),R(this,um,null),(o=f(this,Eh))==null||o.clear(),R(this,Eh,null),R(this,Ru,0))}}Ah=new WeakMap,um=new WeakMap,Zl=new WeakMap,Ga=new WeakMap,Un=new WeakMap,Eh=new WeakMap,Ru=new WeakMap,ze=new WeakSet,Bn=function(){return f(this,um)||R(this,um,new Map)},yv=function(){return f(this,Eh)||R(this,Eh,new Map)},Jc=function(){if(!f(this,Zl)){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(Dr,"svg");i.setAttribute("width",0),i.setAttribute("height",0),R(this,Zl,f(this,Un).createElementNS(Dr,"defs")),t.append(i),i.append(f(this,Zl)),f(this,Un).body.append(t)}return f(this,Zl)},Yw=function(t){if(t.length===1){const l=t[0],u=new Array(256);for(let h=0;h<256;h++)u[h]=l[h]/255;const d=u.join(",");return[d,d,d]}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(",")]},Rd=function(t){if(f(this,Ah)===void 0){R(this,Ah,"");const n=f(this,Un).URL;n!==f(this,Un).baseURI&&(xk(n)?At('#createUrl: ignore "data:"-URL for performance reasons.'):R(this,Ah,iN(n,"")))}return`url(${f(this,Ah)}#${t})`},YN=function(t){const n=f(this,Un).createElementNS(Dr,"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)},dA=function(t){const n=f(this,Un).createElementNS(Dr,"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)},Id=function(t){const n=f(this,Un).createElementNS(Dr,"filter");return n.setAttribute("color-interpolation-filters","sRGB"),n.setAttribute("id",t),f(this,ze,Jc).append(n),n},bv=function(t,n,i){const r=f(this,Un).createElementNS(Dr,n);r.setAttribute("type","discrete"),r.setAttribute("tableValues",i),t.append(r)},_v=function(t,n,i,r){const o=f(this,Un).createElementNS(Dr,"feComponentTransfer");r.append(o),H(this,ze,bv).call(this,o,"feFuncR",t),H(this,ze,bv).call(this,o,"feFuncG",n),H(this,ze,bv).call(this,o,"feFuncB",i)},hA=function(t,n){const i=f(this,Un).createElementNS(Dr,"feComponentTransfer");n.append(i),H(this,ze,bv).call(this,i,"feFuncA",t)},wv=function(t){return f(this,ze,Jc).style.color=t,__(getComputedStyle(f(this,ze,Jc)).getPropertyValue("color"))},JN=function(t){return f(this,ze,Jc).style.color=t,b_(getComputedStyle(f(this,ze,Jc)).getPropertyValue("color"))},ZN=function(t){const[n,i,r,o]=H(this,ze,JN).call(this,t);if(o===1)return[n,i,r];const[a,c,l]=H(this,ze,wv).call(this,"Canvas");return[fT(n,a,o),fT(i,c,o),fT(r,l,o)]};function fT(s,e,t){return Math.round(t*s+(1-t)*e)}var FP;if(to){let s;try{const e=process.getBuiltinModule("module").createRequire(import.meta.url);try{s=e("@napi-rs/canvas")}catch(t){At(`Cannot load "@napi-rs/canvas" package: "${t}".`)}}catch(e){At(`Cannot access the \`require\` function: "${e}".`)}globalThis.DOMMatrix||(s!=null&&s.DOMMatrix?globalThis.DOMMatrix=s.DOMMatrix:At("Cannot polyfill `DOMMatrix`, rendering may be broken.")),globalThis.ImageData||(s!=null&&s.ImageData?globalThis.ImageData=s.ImageData:At("Cannot polyfill `ImageData`, rendering may be broken.")),globalThis.Path2D||(s!=null&&s.Path2D?globalThis.Path2D=s.Path2D:At("Cannot polyfill `Path2D`, rendering may be broken.")),(FP=globalThis.navigator)!=null&&FP.language||(globalThis.navigator={language:"en-US",platform:"",userAgent:""})}async function Pse(s){const t=await process.getBuiltinModule("fs/promises").readFile(s);return new Uint8Array(t)}class Lse extends XN{}class Ose extends QN{_createCanvas(e,t){return process.getBuiltinModule("module").createRequire(import.meta.url)("@napi-rs/canvas").createCanvas(e,t)}}class Dse extends qN{async _fetch(e,t){return Pse(e)}}const Nse=`
|
||
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 G0,ec,Mh,dm,K0,e$;class $se{constructor(){B(this,K0);B(this,G0,null);B(this,ec,null);B(this,Mh,null);B(this,dm,null)}init(){return f(this,G0)||R(this,G0,H(this,K0,e$).call(this))}get isReady(){return f(this,ec)!==null}loadMeshShader(){if(!f(this,ec)||f(this,Mh))return;const e=f(this,ec).createShaderModule({code:Nse});R(this,Mh,f(this,ec).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,dm)}]},primitive:{topology:"triangle-list"}}))}draw(e,t,n,i,r,o,a,c){this.loadMeshShader();const l=f(this,ec),{offsetX:u,offsetY:d,scaleX:h,scaleY:p}=i,g=l.createBuffer({size:Math.max(e.byteLength,4),usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST});e.byteLength>0&&l.queue.writeBuffer(g,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 m=l.createBuffer({size:8*4,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});l.queue.writeBuffer(m,0,new Float32Array([u,d,h,p,o,a,c,0]));const y=l.createBindGroup({layout:f(this,Mh).getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:m}}]}),_=new OffscreenCanvas(o,a),b=_.getContext("webgpu");b.configure({device:l,format:f(this,dm),alphaMode:r?"opaque":"premultiplied"});const k=r?{r:r[0]/255,g:r[1]/255,b:r[2]/255,a:1}:{r:0,g:0,b:0,a:0},w=l.createCommandEncoder(),T=w.beginRenderPass({colorAttachments:[{view:b.getCurrentTexture().createView(),clearValue:k,loadOp:"clear",storeOp:"store"}]});return n>0&&(T.setPipeline(f(this,Mh)),T.setBindGroup(0,y),T.setVertexBuffer(0,g),T.setVertexBuffer(1,v),T.draw(n)),T.end(),l.queue.submit([w.finish()]),g.destroy(),v.destroy(),m.destroy(),_.transferToImageBitmap()}}G0=new WeakMap,ec=new WeakMap,Mh=new WeakMap,dm=new WeakMap,K0=new WeakSet,e$=async function(){var e;if(!((e=globalThis.navigator)!=null&&e.gpu))return!1;try{const t=await navigator.gpu.requestAdapter();return t?(R(this,dm,navigator.gpu.getPreferredCanvasFormat()),R(this,ec,await t.requestDevice()),!0):!1}catch{return!1}};const Rk=new $se;function Bse(){return Rk.init()}function Fse(){return Rk.isReady}function Hse(){Rk.loadMeshShader()}function Use(s,e,t,n,i,r,o,a){return Rk.draw(s,e,t,n,i,r,o,a)}const ai={FILL:"Fill",STROKE:"Stroke",SHADING:"Shading"};function Jw(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 PM{isModifyingCurrentTransform(){return!1}getPattern(){ss("Abstract method `getPattern` called.")}}class Wse extends PM{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(),Fe.applyTransform(i,t),Fe.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);Fe.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(),Fe.applyTransform(n,t),Fe.applyTransform(i,t));let r=this._r1,o=this._r0;if(t){const l=new Float32Array(2);Fe.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===ai.STROKE||i===ai.FILL){if(this.isOriginBased()){let h=Fe.transform(n,t.baseTransform);this.matrix&&(h=Fe.transform(h,this.matrix));const p=.001,g=Math.hypot(h[0],h[1]),v=Math.hypot(h[2],h[3]),m=(h[0]*h[2]+h[1]*h[3])/(g*v);if(Math.abs(m)<p)if(this.isRadial()){if(Math.abs(g-v)<p)return this._createGradient(e,h)}else return this._createGradient(e,h)}const o=t.current.getClippedPathBoundingBox(i,xs(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=Fe.transform(n,[1,0,0,1,o[0],o[1]]),u.transform(...t.baseTransform),this.matrix&&u.transform(...this.matrix),Jw(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 d=new DOMMatrix(n);r.setTransform(d)}else this.areConic()&&(e.save(),Jw(e,this._bbox),e.fillStyle=this._createReversedGradient(e),e.fillRect(-1e10,-1e10,2e10,2e10),e.restore()),Jw(e,this._bbox),r=this._createGradient(e);return r}}function zse(s,e,t,n,i,r,o,a){const c=e.coords,l=e.colors,u=s.data,d=s.width*4;let h;c[t*2+1]>c[n*2+1]&&(h=t,t=n,n=h,h=r,r=o,o=h),c[n*2+1]>c[i*2+1]&&(h=n,n=i,i=h,h=o,o=a,a=h),c[t*2+1]>c[n*2+1]&&(h=t,t=n,n=h,h=r,r=o,o=h);const p=(c[t*2]+e.offsetX)*e.scaleX,g=(c[t*2+1]+e.offsetY)*e.scaleY,v=(c[n*2]+e.offsetX)*e.scaleX,m=(c[n*2+1]+e.offsetY)*e.scaleY,y=(c[i*2]+e.offsetX)*e.scaleX,_=(c[i*2+1]+e.offsetY)*e.scaleY;if(g>=_)return;const b=l[r*4],k=l[r*4+1],w=l[r*4+2],T=l[o*4],A=l[o*4+1],C=l[o*4+2],E=l[a*4],x=l[a*4+1],D=l[a*4+2],N=Math.round(g),O=Math.round(_);let G,Z,q,V,I,$,L,K;for(let se=N;se<=O;se++){if(se<m){const P=se<g?0:(g-se)/(g-m);G=p-(p-v)*P,Z=b-(b-T)*P,q=k-(k-A)*P,V=w-(w-C)*P}else{let P;se>_?P=1:m===_?P=0:P=(m-se)/(m-_),G=v-(v-y)*P,Z=T-(T-E)*P,q=A-(A-x)*P,V=C-(C-D)*P}let oe;se<g?oe=0:se>_?oe=1:oe=(g-se)/(g-_),I=p-(p-y)*oe,$=b-(b-E)*oe,L=k-(k-x)*oe,K=w-(w-D)*oe;const ve=Math.round(Math.min(G,I)),le=Math.round(Math.max(G,I));let ue=d*se+ve*4;for(let P=ve;P<=le;P++)oe=(G-P)/(G-I),oe<0?oe=0:oe>1&&(oe=1),u[ue++]=Z-(Z-$)*oe|0,u[ue++]=q-(q-L)*oe|0,u[ue++]=V-(V-K)*oe|0,u[ue++]=255}}class jse extends PM{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,Hse()}_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,d=Math.min(Math.ceil(Math.abs(l*e[0]*1.1)),3e3)||1,h=Math.min(Math.ceil(Math.abs(u*e[1]*1.1)),3e3)||1,p=l?l/d:1,g=u?u/h:1,v={coords:this._posData,colors:this._colData,offsetX:-a,offsetY:-c,scaleX:1/p,scaleY:1/g},m=d+2*2,y=h+2*2,_=n.create(m,y);if(Fse()&&this._vertexCount>48)_.context.drawImage(Use(this._posData,this._colData,this._vertexCount,v,t,m,y,2),0,0);else{const b=_.context.createImageData(d,h);if(t){const k=b.data;for(let w=0,T=k.length;w<T;w+=4)k[w]=t[0],k[w+1]=t[1],k[w+2]=t[2],k[w+3]=255}for(let k=0,w=this._vertexCount;k<w;k+=3)zse(b,v,k,k+1,k+2,k,k+1,k+2);_.context.putImageData(b,2,2)}return{canvas:_.canvas,offsetX:a-2*p,offsetY:c-2*g,scaleX:p,scaleY:g}}isModifyingCurrentTransform(){return!0}getPattern(e,t,n,i){Jw(e,this._bbox);const r=new Float32Array(2);if(i===ai.SHADING)Fe.singularValueDecompose2dScale(xs(e),r);else if(this.matrix){Fe.singularValueDecompose2dScale(this.matrix,r);const[c,l]=r;Fe.singularValueDecompose2dScale(t.baseTransform,r),r[0]*=c,r[1]*=l}else Fe.singularValueDecompose2dScale(t.baseTransform,r);const o=this._createMeshCanvas(r,i===ai.SHADING?null:this._background,t.canvasFactory);i!==ai.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 Vse extends PM{getPattern(){return"hotpink"}}function Gse(s){switch(s[0]){case"RadialAxial":return new Wse(s);case"Mesh":return new jse(s);case"Dummy":return new Vse}throw new Error(`Unknown IR type: ${s[0]}`)}const qI={COLORED:1,UNCOLORED:2},q0=class q0{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?Fe.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 d=Math.floor((n-a)/l)+1,h=Math.ceil((n+e-r)/l)-1,p=Math.floor((i-c)/u)+1,g=Math.ceil((i+t-o)/u)-1;return h<=d&&g<=p?[d,p]:null}updatePatternDims(e,t){const n=Fe.inverseTransform(this.patternBaseMatrix),i=[e[0],e[1]],r=[e[2],e[3]];Fe.applyTransform(i,n),Fe.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 h,p;const[r,o,a,c]=this.bbox,l=e.canvasFactory.create(n.size,i.size),u=l.context,d=this.canvasGraphicsFactory.createCanvasGraphics(u,t);return d.groupLevel=e.groupLevel,this.setFillAndStrokeStyleToContext(d,this.paintType,this.color),u.translate(-n.scale*r,-i.scale*o),d.transform(0,n.scale,0,0,i.scale,0,0),u.save(),(h=d.dependencyTracker)==null||h.save(),this.clipBbox(d,r,o,a,c),d.baseTransform=xs(d.ctx),d.executeOperatorList(this.operatorList),d.endDrawing(),(p=d.dependencyTracker)==null||p.restore(),u.restore(),l}_getCombinedScales(){const e=new Float32Array(2);Fe.singularValueDecompose2dScale(this.matrix,e);const[t,n]=e;return Fe.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,d=e.dependencyTracker;if(d&&(e.dependencyTracker=new Ty(d,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 h=l-a,p=u-c,[g,v]=this._getCombinedScales(),m=this.getSizeAndScale(h,this.ctx.canvas.width,g),y=this.getSizeAndScale(p,this.ctx.canvas.height,v),_=this._renderTileCanvas(e,o,m,y);e.ctx.drawImage(_.canvas,a,c,h,p),e.canvasFactory.destroy(_)}else this.setFillAndStrokeStyleToContext(e,this.paintType,this.color),this.clipBbox(e,a,c,l,u),e.baseTransformStack.push(e.baseTransform),e.baseTransform=xs(e.ctx),e.executeOperatorList(this.operatorList),e.baseTransform=e.baseTransformStack.pop();e.restore(),d&&(e.dependencyTracker=d)}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),Ek("TilingType: "+this.tilingType);const[d,h]=this._getCombinedScales();let p=a,g=c,v=!1,m=!1;Math.ceil(l*d)>=Math.ceil(a*d)?p=l:v=!0,Math.ceil(u*h)>=Math.ceil(c*h)?g=u:m=!0;const y=this.getSizeAndScale(p,this.ctx.canvas.width,d),_=this.getSizeAndScale(g,this.ctx.canvas.height,h),b=this._renderTileCanvas(e,t,y,_);if(v||m){const k=b.canvas;v&&(p=l),m&&(g=u);const w=this.getSizeAndScale(p,this.ctx.canvas.width,d),T=this.getSizeAndScale(g,this.ctx.canvas.height,h),A=w.size,C=T.size,E=e.canvasFactory.create(A,C),x=E.context,D=v?Math.floor(a/l):0,N=m?Math.floor(c/u):0;for(let O=0;O<=D;O++)for(let G=0;G<=N;G++)x.drawImage(k,A*O,C*G,A,C,0,0,A,C);return e.canvasFactory.destroy(b),{canvas:E.canvas,canvasEntry:E,scaleX:w.scale,scaleY:T.scale,offsetX:n,offsetY:i}}return{canvas:b.canvas,canvasEntry:b,scaleX:y.scale,scaleY:_.scale,offsetX:n,offsetY:i}}getSizeAndScale(e,t,n){const i=Math.max(q0.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),Fe.axialAlignedBoundingBox([t,n,i,r],xs(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 qI.COLORED:const{fillStyle:o,strokeStyle:a}=this.ctx;i.fillStyle=r.fillColor=o,i.strokeStyle=r.strokeColor=a;break;case qI.UNCOLORED:i.fillStyle=i.strokeStyle=n,r.fillColor=r.strokeColor=n;break;default:throw new Xte(`Unsupported paint type: ${t}`)}}isModifyingCurrentTransform(){return!1}getPattern(e,t,n,i,r){const o=i!==ai.SHADING?Fe.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}};Se(q0,"MAX_PATTERN_SIZE",3e3);let ty=q0;function Kse({src:s,srcPos:e=0,dest:t,width:n,height:i,nonBlackColor:r=4294967295,inverseDecode:o=!1}){const a=Rs.isLittleEndian?4278190080:255,[c,l]=o?[r,a]:[a,r],u=n>>3,d=n&7,h=c^l,p=s.length;t=new Uint32Array(t.buffer);let g=0;for(let v=0;v<i;++v){for(const y=e+u;e<y;++e,g+=8){const _=s[e];t[g]=c^-(_>>7&1)&h,t[g+1]=c^-(_>>6&1)&h,t[g+2]=c^-(_>>5&1)&h,t[g+3]=c^-(_>>4&1)&h,t[g+4]=c^-(_>>3&1)&h,t[g+5]=c^-(_>>2&1)&h,t[g+6]=c^-(_>>1&1)&h,t[g+7]=c^-(_&1)&h}if(d===0)continue;const m=e<p?s[e++]:255;for(let y=0;y<d;++y,++g)t[g]=c^-(m>>7-y&1)&h}return{srcPos:e,destPos:g}}const QI=16,XI=100,qse=15,YI=10,wr=16,pT=new DOMMatrix,so=new Float32Array(2);function JI(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 uw(s,e,t,n,i,r,o,a,c,l){const[u,d,h,p,g,v]=xs(s);if(d===0&&h===0){const _=o*u+g,b=Math.round(_),k=a*p+v,w=Math.round(k),T=(o+c)*u+g,A=Math.abs(Math.round(T)-b)||1,C=(a+l)*p+v,E=Math.abs(Math.round(C)-w)||1;return s.setTransform(Math.sign(u),0,0,Math.sign(p),b,w),s.drawImage(e,t,n,i,r,0,0,A,E),s.setTransform(u,d,h,p,g,v),[A,E]}if(u===0&&p===0){const _=a*h+g,b=Math.round(_),k=o*d+v,w=Math.round(k),T=(a+l)*h+g,A=Math.abs(Math.round(T)-b)||1,C=(o+c)*d+v,E=Math.abs(Math.round(C)-w)||1;return s.setTransform(0,Math.sign(d),Math.sign(h),0,b,w),s.drawImage(e,t,n,i,r,0,0,E,A),s.setTransform(u,d,h,p,g,v),[E,A]}s.drawImage(e,t,n,i,r,o,a,c,l);const m=Math.hypot(u,d),y=Math.hypot(h,p);return[m*c,y*l]}class ZI{constructor(e,t){Se(this,"alphaIsShape",!1);Se(this,"fontSize",0);Se(this,"fontSizeScale",1);Se(this,"textMatrix",null);Se(this,"textMatrixScale",1);Se(this,"fontMatrix",N1);Se(this,"leading",0);Se(this,"x",0);Se(this,"y",0);Se(this,"lineX",0);Se(this,"lineY",0);Se(this,"charSpacing",0);Se(this,"wordSpacing",0);Se(this,"textHScale",1);Se(this,"textRenderingMode",On.FILL);Se(this,"textRise",0);Se(this,"fillColor","#000000");Se(this,"strokeColor","#000000");Se(this,"tilingPatternDims",null);Se(this,"patternFill",!1);Se(this,"patternStroke",!1);Se(this,"fillAlpha",1);Se(this,"strokeAlpha",1);Se(this,"lineWidth",1);Se(this,"activeSMask",null);Se(this,"transferMaps","none");Se(this,"minMax",Kd.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=ai.FILL,t=null){const n=this.minMax.slice();if(e===ai.STROKE){t||ss("Stroke bounding box must include transform."),Fe.singularValueDecompose2dScale(t,so);const i=so[0]*this.lineWidth/2,r=so[1]*this.lineWidth/2;n[0]-=i,n[1]-=r,n[2]+=i,n[3]+=r}return n}updateClipFromPath(){const e=Fe.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(Kd,0)}getClippedPathBoundingBox(e=ai.FILL,t=null){return Fe.intersect(this.clipBox,this.getPathBoundingBox(e,t))}}function eP(s,e){if(e instanceof ImageData){s.putImageData(e,0,0);return}const t=e.height,n=e.width,i=t%wr,r=(t-i)/wr,o=i===0?r:r+1,a=s.createImageData(n,wr);let c=0,l;const u=e.data,d=a.data;let h,p,g,v;if(e.kind===Hw.GRAYSCALE_1BPP){const m=u.byteLength,y=new Uint32Array(d.buffer,0,d.byteLength>>2),_=y.length,b=n+7>>3,k=4294967295,w=Rs.isLittleEndian?4278190080:255;for(h=0;h<o;h++){for(g=h<r?wr:i,l=0,p=0;p<g;p++){const T=m-c;let A=0;const C=T>b?n:T*8-7,E=C&-8;let x=0,D=0;for(;A<E;A+=8)D=u[c++],y[l++]=D&128?k:w,y[l++]=D&64?k:w,y[l++]=D&32?k:w,y[l++]=D&16?k:w,y[l++]=D&8?k:w,y[l++]=D&4?k:w,y[l++]=D&2?k:w,y[l++]=D&1?k:w;for(;A<C;A++)x===0&&(D=u[c++],x=128),y[l++]=D&x?k:w,x>>=1}for(;l<_;)y[l++]=0;s.putImageData(a,0,h*wr)}}else if(e.kind===Hw.RGBA_32BPP){for(p=0,v=n*wr*4,h=0;h<r;h++)d.set(u.subarray(c,c+v)),c+=v,s.putImageData(a,0,p),p+=wr;h<o&&(v=n*i*4,d.set(u.subarray(c,c+v)),s.putImageData(a,0,p))}else if(e.kind===Hw.RGB_24BPP)for(g=wr,v=n*g,h=0;h<o;h++){for(h>=r&&(g=i,v=n*g),l=0,p=v;p--;)d[l++]=u[c++],d[l++]=u[c++],d[l++]=u[c++],d[l++]=255;s.putImageData(a,0,h*wr)}else throw new Error(`bad image kind: ${e.kind}`)}function tP(s,e){if(e.bitmap){s.drawImage(e.bitmap,0,0);return}const t=e.height,n=e.width,i=t%wr,r=(t-i)/wr,o=i===0?r:r+1,a=s.createImageData(n,wr);let c=0;const l=e.data,u=a.data;for(let d=0;d<o;d++){const h=d<r?wr:i;({srcPos:c}=Kse({src:l,srcPos:c,dest:u,width:n,height:h,nonBlackColor:0})),s.putImageData(a,0,d*wr)}}function Md(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 dw(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 sP(s,e){if(e)return!0;Fe.singularValueDecompose2dScale(s,so);const t=Math.fround(hl.pixelRatio*md.PDF_TO_CSS_UNITS);return so[0]<=t&&so[1]<=t}const Qse=["butt","round","square"],Xse=["miter","round","bevel"],Yse={},nP={};var Fr,Iu,xh,Rh,Ih,Ph,Lh,Pu,Oh,Ka,mt,fA,pA,mA,gA,vA,dr,vi,yA,Zw;const jM=class jM{constructor(e,t,n,i,r,{optionalContentConfig:o,markedContentStack:a=null},c,l,u,d){B(this,mt);B(this,Fr,0);B(this,Iu,0);B(this,xh,null);B(this,Rh,null);B(this,Ih,null);B(this,Ph,null);B(this,Lh,1);B(this,Pu);B(this,Oh,null);B(this,Ka,[]);this.ctx=e,this.current=new ZI(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=d??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(...xs(this.compositeCtx))}this.ctx.save(),dw(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=xs(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>YI&&typeof n=="function",d=u?Date.now()+qse:0;let h=0;const p=this.commonObjs,g=this.objs;let v,m;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],m=o[c]??null,v!==$l.dependency)m===null?this[v](c):this[v](c,...m);else for(const _ of m){(y=this.dependencyTracker)==null||y.recordNamedData(_,c);const b=_.startsWith("g_")?p:g;if(!b.has(_))return b.get(_,n),c}if(c++,c===l)return c;if(u&&++h>YI){if(Date.now()>d)return n(),c;h=0}}}endDrawing(){H(this,mt,fA).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,Ka))H(this,mt,Zw).call(this,e);f(this,Ka).length=0,R(this,xh,null),R(this,Rh,null),R(this,Ih,null),R(this,Ph,null),R(this,Lh,1),R(this,Oh,null),R(this,Iu,0),R(this,Fr,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(),H(this,mt,pA).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,d=i;for(;c>2&&u>1||l>2&&d>1;){let y=u,_=d;c>2&&u>1&&(y=Math.ceil(u/2),c/=u/y),l>2&&d>1&&(_=Math.ceil(d/2),l/=d/_),a.push({newWidth:y,newHeight:_}),u=y,d=_}if(a.length===0)return{img:e,paintWidth:n,paintHeight:i,tmpCanvas:null};if(a.length===1){const{newWidth:y,newHeight:_}=a[0],b=this.canvasFactory.create(y,_);return b.context.drawImage(e,0,0,n,i,0,0,y,_),{img:b.canvas,paintWidth:y,paintHeight:_,tmpCanvas:b}}let h=this.canvasFactory.create(1,1),p=this.canvasFactory.create(1,1),g=n,v=i,m=e;for(const{newWidth:y,newHeight:_}of a)this.canvasFactory.reset(p,y,_),p.context.drawImage(m,0,0,g,v,0,0,y,_),[h,p]=[p,h],m=h.canvas,g=y,v=_;return this.canvasFactory.destroy(p),{img:h.canvas,paintWidth:g,paintHeight:v,tmpCanvas:h}}_createMaskCanvas(e,t){var D,N;const n=this.ctx,{width:i,height:r}=t,o=this.current.fillColor,a=this.current.patternFill,c=xs(n);let l,u,d,h;if((t.bitmap||t.data)&&t.count>1){const O=t.bitmap||t.data.buffer;u=JSON.stringify(a?c:[c.slice(0,4),o]),l=this._cachedBitmapsMap.getOrInsertComputed(O,EM);const G=l.get(u);if(G&&!a){const Z=Math.round(Math.min(c[0],c[2])+c[4]),q=Math.round(Math.min(c[1],c[3])+c[5]);return(D=this.dependencyTracker)==null||D.recordDependencies(e,yo.transformAndFill),{canvas:G,offsetX:Z,offsetY:q}}d=G}d||(h=this.canvasFactory.create(i,r),tP(h.context,t));let p=Fe.transform(c,[1/i,0,0,-1/r,0,0]);p=Fe.transform(p,[1,0,0,1,0,-r]);const g=Kd.slice();Fe.axialAlignedBoundingBox([0,0,i,r],p,g);const[v,m,y,_]=g,b=Math.round(y-v)||1,k=Math.round(_-m)||1,w=this.canvasFactory.create(b,k),T=w.context,A=v,C=m;T.translate(-A,-C),T.transform(...p);let E=null;if(!d){const O=this._scaleImage(h.canvas,Ea(T));d=O.img,E=O.tmpCanvas,d!==h.canvas&&(this.canvasFactory.destroy(h),h=null),l&&a&&(l.set(u,d),E=null,h=null)}T.imageSmoothingEnabled=sP(xs(T),t.interpolate),uw(T,d,0,0,d.width,d.height,0,0,i,r),E&&this.canvasFactory.destroy(E),h&&this.canvasFactory.destroy(h),T.globalCompositeOperation="source-in";const x=Fe.transform(Ea(T),[1,0,0,1,-A,-C]);return T.fillStyle=a?o.getPattern(n,this,x,ai.FILL,e):o,T.fillRect(0,0,i,r),l&&!a&&l.set(u,w.canvas),(N=this.dependencyTracker)==null||N.recordDependencies(e,yo.transformAndFill),{canvas:w.canvas,canvasEntry:l&&!a?null:w,offsetX:Math.round(A),offsetY:Math.round(C)}}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=Qse[t]}setLineJoin(e,t){var n;(n=this.dependencyTracker)==null||n.recordSimpleData("lineJoin",e),this.ctx.lineJoin=Xse[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,k]=b_(i),w=Math.round(.3*_+.59*b+.11*k);a=(r==null?void 0:r[w])??w}else a=(r==null?void 0:r[0])??0;const c=4,{width:l,height:u}=this.ctx.canvas,d=t.width*t.height,h=l*u<c*d,p=o?{url:n==="Alpha"?this.filterFactory.addAlphaFilter(r):this.filterFactory.addLuminosityFilter(r),subtype:n,transferMap:r}:null,g=n==="Luminosity"?i:null;let v,m,y;h?(v=this._bakeSMaskCanvas(t,e.offsetX,e.offsetY,l,u,g,p),m=0,y=0):(v=this._bakeSMaskCanvas(t,0,0,t.width,t.height,g,p),m=e.offsetX,y=e.offsetY),this.smaskPreparedEntry=v,this.smaskPreparedFor=e,this.smaskPreparedOffsetX=m,this.smaskPreparedOffsetY=y,this.smaskPreparedOOBAlpha=!h&&a!==0?a:null}_bakeSMaskCanvas(e,t,n,i,r,o,a){!o&&!a&&ss("_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),d=u.context;d.filter=a.url;const h=Rs.isCanvasFilterSupported&&d.filter!=="none"&&d.filter!=="";if(d.drawImage(c.canvas,0,0),Rs.isCanvasFilterSupported&&(d.filter="none"),!h){const p=d.getImageData(0,0,i,r),{data:g}=p,{transferMap:v}=a;if(a.subtype==="Luminosity")for(let m=0,y=g.length;m<y;m+=4){const _=.3*g[m]+.59*g[m+1]+.11*g[m+2]+.5|0;g[m]=g[m+1]=g[m+2]=0,g[m+3]=(v==null?void 0:v[_])??_}else for(let m=3,y=g.length;m<y;m+=4)g[m]=v[g[m]];d.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()),Md(this.suspendedCtx,r),JI(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(),Md(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,Iu)>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,d=o,h=a,p=c;const g=this.smaskPreparedOOBAlpha,v=g!==null;if(v){u=Math.max(r,t.offsetX),d=Math.max(o,t.offsetY);const m=Math.min(r+a,t.offsetX+t.canvas.width),y=Math.min(o+c,t.offsetY+t.canvas.height);h=m-u,p=y-d}if(h>0&&p>0){const m=u-this.smaskPreparedOffsetX,y=d-this.smaskPreparedOffsetY;n.save(),n.globalAlpha=1,n.setTransform(1,0,0,1,0,0);const _=new Path2D;_.rect(u,d,h,p),n.clip(_),n.globalCompositeOperation="destination-in",n.drawImage(l.canvas,m,y,h,p,u,d,h,p),n.restore()}v&&g<255&&this._applySMaskOOBAlpha(n,r,o,a,c,u,d,u+h,d+p,g)}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 d=o<c&&a<l;if(d&&o===t&&a===n&&c===t+i&&l===n+r)return;const h=new Path2D;h.rect(t,n,i,r),d&&h.rect(o,a,c-o,l-a),e.save(),e.globalAlpha=u/255,e.setTransform(1,0,0,1,0,0),e.clip(h,"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&&Md(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&&(Md(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!==$l.stroke&&t!==$l.closeStroke&&(this.current.tilingPatternDims=null),this[t](e,r);return}if(this.dependencyTracker!==null){const a=t===$l.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]=lN(r)),Fe.axialAlignedBoundingBox(i,xs(this.ctx),this.current.minMax);const o=this.current.tilingPatternDims;if(o&&t!==$l.stroke&&t!==$l.closeStroke&&this.current.fillColor instanceof ty){const a=Fe.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&&H(this,mt,dr).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,Ea(r),ai.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,yo.stroke),n&&this.consumePath(e,t,this.current.getClippedPathBoundingBox(ai.STROKE,xs(this.ctx))),r.globalAlpha=this.current.fillAlpha,H(this,mt,vi).call(this,i)}closeStroke(e,t){this.stroke(e,t)}fill(e,t,n=!0){var u,d,h;const i=n&&H(this,mt,dr).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,yo.fill),a){const p=this.current.tilingPatternDims,g=p&&o.canSkipPatternCanvas(p);if(g){o.drawPattern(this,t,this.pendingEOFill,g,e),this.pendingEOFill=!1,n&&this.consumePath(e,t,l),this.current.tilingPatternDims=null,H(this,mt,vi).call(this,i);return}const v=o.isModifyingCurrentTransform()?r.getTransform():null;if((d=this.dependencyTracker)==null||d.save(e),r.save(),r.fillStyle=o.getPattern(r,this,Ea(r),ai.FILL,e),v){const m=new Path2D;m.addPath(t,r.getTransform().invertSelf().multiplySelf(v)),t=m}c=!0}this.contentVisible&&l!==null&&(this.pendingEOFill?(r.fill(t,"evenodd"),this.pendingEOFill=!1):r.fill(t)),c&&(r.restore(),(h=this.dependencyTracker)==null||h.restore(e)),n&&this.consumePath(e,t,l),H(this,mt,vi).call(this,i)}eoFill(e,t){this.pendingEOFill=!0,this.fill(e,t)}fillStroke(e,t){const n=H(this,mt,dr).call(this,Math.min(this.current.fillAlpha,this.current.strokeAlpha));this.fill(e,t,!1),this.stroke(e,t,!1),this.consumePath(e,t),H(this,mt,vi).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=H(this,mt,dr).call(this,this.current.fillAlpha);this.ctx.fill(t),(i=this.dependencyTracker)==null||i.recordDependencies(e,yo.rawFillPath).recordOperation(e),H(this,mt,vi).call(this,n)}clip(e){var t;(t=this.dependencyTracker)==null||t.recordFutureForcedDependency("clipMode",e),this.pendingClip=Yse}eoClip(e){var t;(t=this.dependencyTracker)==null||t.recordFutureForcedDependency("clipMode",e),this.pendingClip=nP}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 d,h;(d=this.dependencyTracker)==null||d.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||N1,(r.fontMatrix[0]===0||r.fontMatrix[3]===0)&&At("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=((h=i.systemFontInfo)==null?void 0:h.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<QI?u=QI:n>XI&&(u=XI),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,k;const a=this.ctx,c=this.current,l=c.font,u=c.textRenderingMode,d=c.fontSize/c.fontSizeScale,h=u&On.FILL_STROKE_MASK,p=!!(u&On.ADD_TO_PATH_FLAG),g=c.patternFill&&!l.missingFile,v=c.patternStroke&&!l.missingFile;let m;if((l.disableFontFace||p||g||v)&&!l.missingFile&&(m=l.getPathGenerator(this.commonObjs,t)),m&&(l.disableFontFace||g||v)){a.save(),a.translate(n,i),a.scale(d,-d),(y=this.dependencyTracker)==null||y.recordCharacterBBox(e,a,l);let w;if(h===On.FILL||h===On.FILL_STROKE)if(r){w=a.getTransform(),a.setTransform(...r);const T=H(this,mt,yA).call(this,m,w,r);a.fill(T)}else a.fill(m);if(h===On.STROKE||h===On.FILL_STROKE)if(o){w||(w=a.getTransform()),a.setTransform(...o);const{a:T,b:A,c:C,d:E}=w,x=Fe.inverseTransform(o),D=Fe.transform([T,A,C,E,0,0],x);Fe.singularValueDecompose2dScale(D,so),a.lineWidth*=Math.max(so[0],so[1])/d,a.stroke(H(this,mt,yA).call(this,m,w,o))}else a.lineWidth/=d,a.stroke(m);a.restore()}else(h===On.FILL||h===On.FILL_STROKE)&&(a.fillText(t,n,i),(_=this.dependencyTracker)==null||_.recordCharacterBBox(e,a,l,d,n,i,()=>a.measureText(t))),(h===On.STROKE||h===On.FILL_STROKE)&&(this.dependencyTracker&&((b=this.dependencyTracker)==null||b.recordCharacterBBox(e,a,l,d,n,i,()=>a.measureText(t)).recordDependencies(e,yo.stroke)),a.strokeText(t,n,i));p&&((this.pendingTextPaths||(this.pendingTextPaths=[])).push({transform:xs(a),x:n,y:i,fontSize:d,path:m}),(k=this.dependencyTracker)==null||k.recordCharacterBBox(e,a,l,d,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 Mt(this,"isFontSubpixelAAEnabled",i)}showText(e,t){var N,O,G,Z;this.dependencyTracker&&(this.dependencyTracker.recordDependencies(e,yo.showText).resetBBox(e),this.current.textRenderingMode&On.ADD_TO_PATH_FLAG&&this.dependencyTracker.recordFutureForcedDependency("textClip",e).inheritPendingDependenciesAsFutureForcedDependencies());const n=this.current,i=n.font;if(i.isType3Font){const q=H(this,mt,dr).call(this,n.fillAlpha);this.showType3Text(e,t),(N=this.dependencyTracker)==null||N.recordShowTextOperation(e),H(this,mt,vi).call(this,q);return}const r=n.fontSize;if(r===0){(O=this.dependencyTracker)==null||O.recordOperation(e);return}const o=H(this,mt,dr).call(this,n.fillAlpha),a=this.ctx,c=n.fontSizeScale,l=n.charSpacing,u=n.wordSpacing,d=n.fontDirection,h=n.textHScale*d,p=t.length,g=i.vertical,v=g?1:-1,m=i.defaultVMetrics,y=r*n.fontMatrix[0],_=n.textRenderingMode===On.FILL&&!i.disableFontFace&&!n.patternFill;a.save(),n.textMatrix&&a.transform(...n.textMatrix),a.translate(n.x,n.y+n.textRise),d>0?a.scale(h,-1):a.scale(h,1);let b,k;const w=n.textRenderingMode&On.FILL_STROKE_MASK,T=w===On.FILL||w===On.FILL_STROKE,A=w===On.STROKE||w===On.FILL_STROKE;let C=n.lineWidth;const E=n.textMatrixScale;if(E===0||C===0?A&&(C=this.getSinglePixelWidth()):C/=E,c!==1&&(a.scale(c,c),C/=c),a.lineWidth=C,T&&n.patternFill){a.save();const q=n.fillColor.getPattern(a,this,Ea(a),ai.FILL,e);b=xs(a),a.restore(),a.fillStyle=q}if(A&&n.patternStroke){a.save();const q=n.strokeColor.getPattern(a,this,Ea(a),ai.STROKE,e);k=xs(a),a.restore(),a.strokeStyle=q}if(i.isInvalidPDFjsFont){const q=[];let V=0;for(const $ of t)q.push($.unicode),V+=$.width;const I=q.join("");if(a.fillText(I,0,0),this.dependencyTracker!==null){const $=a.measureText(I);this.dependencyTracker.recordBBox(e,this.ctx,-$.actualBoundingBoxLeft,$.actualBoundingBoxRight,-$.actualBoundingBoxAscent,$.actualBoundingBoxDescent).recordShowTextOperation(e)}n.x+=V*y*h,a.restore(),this.compose(),H(this,mt,vi).call(this,o);return}let x=0,D;for(D=0;D<p;++D){const q=t[D];if(typeof q=="number"){x+=v*q*r/1e3;continue}let V=!1;const I=(q.isSpace?u:0)+l,$=q.fontChar,L=q.accent;let K,se,oe=q.width;if(g){const ue=q.vmetric||m,P=-(q.vmetric?ue[1]:oe*.5)*y,X=ue[2]*y;oe=ue?-ue[0]:oe,K=P/c,se=(x+X)/c}else K=x/c,se=0;let ve;if(i.remeasure&&oe>0){ve=a.measureText($);const ue=ve.width*1e3/r*c;if(oe<ue&&this.isFontSubpixelAAEnabled){const P=oe/ue;V=!0,a.save(),a.scale(P,1),K/=P}else oe!==ue&&(K+=(oe-ue)/2e3*r/c)}if(this.contentVisible&&(q.isInFont||i.missingFile)){if(_&&!L)a.fillText($,K,se),(G=this.dependencyTracker)==null||G.recordCharacterBBox(e,a,ve?{bbox:null}:i,r/c,K,se,()=>ve??a.measureText($));else if(this.paintChar(e,$,K,se,b,k),L){const ue=K+r*L.offset.x/c,P=se-r*L.offset.y/c;this.paintChar(e,L.fontChar,ue,P,b,k)}}const le=g?oe*y-I*d:oe*y+I*d;x+=le,V&&a.restore()}g?n.y-=x:n.x+=x*h,a.restore(),this.compose(),(Z=this.dependencyTracker)==null||Z.recordShowTextOperation(e),H(this,mt,vi).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,d=i.textHScale*a,h=i.fontMatrix||N1,p=t.length,g=i.textRenderingMode===On.INVISIBLE;let v,m,y,_;if(g||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(d,a);const b=this.dependencyTracker;for(this.dependencyTracker=b?new Ty(b,e):null,v=0;v<p;++v){if(m=t[v],typeof m=="number"){_=c*m*o/1e3,this.ctx.translate(_,0),i.x+=_*d;continue}const k=(m.isSpace?u:0)+l,w=r.charProcOperatorList[m.operatorListId];w?this.contentVisible&&(this.save(),n.scale(o,o),n.transform(...h),this.executeOperatorList(w),this.restore()):At(`Type3 character "${m.operatorListId}" is not available.`);const T=[m.width,0];Fe.applyTransform(T,h),y=T[0]*o+k,n.translate(y,0),i.x+=y*d}n.restore(),b&&(this.dependencyTracker=b)}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||xs(this.ctx),r={createCanvasGraphics:(o,a)=>new jM(o,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack},void 0,void 0,this.dependencyTracker?new Ty(this.dependencyTracker,a,!0):null)};n=new ty(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 ty?[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=Gse(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=H(this,mt,dr).call(this,this.current.fillAlpha),i=this.ctx;this.save(e);const r=this._getPattern(e,t);i.fillStyle=r.getPattern(i,this,Ea(i),ai.SHADING,e);const o=Ea(i);if(o){const{width:c,height:l}=i.canvas,u=Kd.slice();Fe.axialAlignedBoundingBox([0,0,c,l],o,u);const[d,h,p,g]=u;this.ctx.fillRect(d,h,p-d,g-h)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);(a=this.dependencyTracker)==null||a.resetBBox(e).recordFullPageBBox(e).recordDependencies(e,yo.transform).recordDependencies(e,yo.fill).recordOperation(e),this.compose(this.current.getClippedPathBoundingBox()),this.restore(e),H(this,mt,vi).call(this,n)}beginInlineImage(){ss("Should not call beginInlineImage")}beginImageData(){ss("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=xs(this.ctx),n)){Fe.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 _;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,Fr)===0&&Ek("TODO: Fully support non-isolated non-knockout groups."),!t.needsIsolation&&!t.knockout&&f(this,Fr)===0&&i.globalAlpha===1&&i.globalCompositeOperation==="source-over"&&!n){if(t.bbox){let b=new Path2D;const[k,w,T,A]=t.bbox;if(b.rect(k,w,T-k,A-w),t.matrix){const C=new Path2D;C.addPath(b,new DOMMatrix(t.matrix)),b=C}i.clip(b)}this.groupStack.push(null),f(this,Ka).push(null),this.groupLevel++;return}const r=xs(i);t.matrix&&i.transform(...t.matrix);const o=[0,0,i.canvas.width,i.canvas.height];let a;t.bbox?(a=Kd.slice(),Fe.axialAlignedBoundingBox(t.bbox,xs(i),a),a=Fe.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),d=Math.max(Math.ceil(a[3])-l,1);this.current.startNewPathAndClipBox([0,0,u,d]);const h=this.canvasFactory.create(u,d);t.smask&&this.smaskGroupCanvases.push(h);const p=h.context,g=t.knockout&&!t.isolated?i:null,v=!t.isolated&&!t.knockout&&!t.smask&&t.needsIsolation&&f(this,Fr)>0,m=t.knockout?this.canvasFactory.create(u,d):null,y=f(this,Fr);if(t.knockout?Ls(this,Fr)._++:R(this,Fr,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 b=new Path2D;const[k,w,T,A]=t.bbox;if(b.rect(k,w,T-k,A-w),t.matrix){const C=new Path2D;C.addPath(b,new DOMMatrix(t.matrix)),b=C}p.clip(b)}t.smask&&this.smaskStack.push({canvas:h.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()),Md(i,p),this.ctx=p,(_=this.dependencyTracker)==null||_.inheritSimpleDataAsFutureForcedDependencies(["fillAlpha","strokeAlpha","globalCompositeOperation"]).pushBaseTransform(i),this.setGState(e,[["BM","source-over"],["ca",1],["CA",1],["TR",null]]),this.groupStack.push(i),f(this,Ka).push({backdropCtx:g,savedKnockoutLevel:y,offsetX:c,offsetY:l,hasInnerBackdrop:v,knockoutMaskEntry:m,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,Ka).pop();if(r&&R(this,Fr,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())),H(this,mt,Zw).call(this,r);else{this.ctx.restore();const a=xs(this.ctx);this.restore(e),this.ctx.save(),this.ctx.setTransform(...a);const c=Kd.slice();Fe.axialAlignedBoundingBox([0,0,n.canvas.width,n.canvas.height],a,c);const l=f(this,Ka).at(-1);if(f(this,Fr)>0)if(r.hasInnerBackdrop){const{width:u,height:d}=n.canvas,h=this.canvasFactory.create(u,d),p=h.context;p.drawImage(i.canvas,r.offsetX,r.offsetY,u,d,0,0,u,d),p.globalCompositeOperation="source-over",p.drawImage(n.canvas,0,0);const g=H(this,mt,mA).call(this,n.canvas);p.globalCompositeOperation="destination-in",p.drawImage(g.canvas,0,0);const v=this.ctx.globalCompositeOperation,m=this.ctx.globalAlpha,y=this.ctx.filter;this.ctx.save(),this.ctx.setTransform(...a),this.ctx.globalAlpha=1,Rs.isCanvasFilterSupported&&(this.ctx.filter="none"),this.ctx.globalCompositeOperation="destination-out",this.ctx.drawImage(g.canvas,0,0),this.ctx.globalCompositeOperation=v,this.ctx.globalAlpha=m,Rs.isCanvasFilterSupported&&(this.ctx.filter=y??"none"),this.ctx.drawImage(h.canvas,0,0),this.ctx.restore(),this.canvasFactory.destroy(g),this.canvasFactory.destroy(h)}else{const u=(l==null?void 0:l.backdropCtx)??null;H(this,mt,vA).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}),H(this,mt,Zw).call(this,r),this.compose(c)}}beginAnnotation(e,t,n,i,r,o){if(H(this,mt,fA).call(this),dw(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,Fe.singularValueDecompose2dScale(xs(this.ctx),so);const{viewportScale:l}=this,u=Math.ceil(a*this.outputScaleX*l),d=Math.ceil(c*this.outputScaleY*l);this.annotationCanvas=this.canvasFactory.create(u,d);const{canvas:h,context:p}=this.annotationCanvas;this.annotationCanvasMap.set(t,h),this.annotationCanvas.savedCtx=this.ctx,this.ctx=p,this.ctx.save(),this.ctx.setTransform(so[0],0,0,-so[1],0,c*so[1]),dw(this.ctx)}else{dw(this.ctx),this.endPath(e);const l=new Path2D;l.rect(n[0],n[1],a,c),this.ctx.clip(l)}}this.current=new ZI(this.ctx.canvas.width,this.ctx.canvas.height),this.baseTransformStack.push(this.baseTransform),this.transform(e,...i),this.transform(e,...r),this.baseTransform=xs(this.ctx)}endAnnotation(e){this.annotationCanvas&&(this.ctx.restore(),H(this,mt,pA).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=H(this,mt,dr).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(),H(this,mt,vi).call(this,i)}paintImageMaskXObjectRepeat(e,t,n,i=0,r=0,o,a){var h,p,g;if(!this.contentVisible)return;t=this.getObject(e,t.data,t);const c=H(this,mt,dr).call(this,this.current.fillAlpha),l=this.ctx;l.save();const u=xs(l);l.transform(n,i,r,o,0,0);const d=this._createMaskCanvas(e,t);l.setTransform(1,0,0,1,d.offsetX-u[4],d.offsetY-u[5]),(h=this.dependencyTracker)==null||h.resetBBox(e);for(let v=0,m=a.length;v<m;v+=2){const y=Fe.transform(u,[n,i,r,o,a[v],a[v+1]]);l.drawImage(d.canvas,y[4],y[5]),(p=this.dependencyTracker)==null||p.recordBBox(e,this.ctx,y[4],y[4]+d.canvas.width,y[5],y[5]+d.canvas.height)}l.restore(),d.canvasEntry&&this.canvasFactory.destroy(d.canvasEntry),this.compose(),(g=this.dependencyTracker)==null||g.recordOperation(e),H(this,mt,vi).call(this,c)}paintImageMaskXObjectGroup(e,t){var a,c,l;if(!this.contentVisible)return;const n=H(this,mt,dr).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,yo.transformAndFill);for(const u of t){const{data:d,width:h,height:p,transform:g}=u,v=this.canvasFactory.create(h,p),m=v.context;m.save();const y=this.getObject(e,d,u);tP(m,y),m.globalCompositeOperation="source-in",m.fillStyle=o?r.getPattern(m,this,Ea(i),ai.FILL,e):r,m.fillRect(0,0,h,p),m.restore(),i.save(),i.transform(...g),i.scale(1,-1),uw(i,v.canvas,0,0,h,p,0,-1,1,1),this.canvasFactory.destroy(v),(c=this.dependencyTracker)==null||c.recordBBox(e,i,0,h,0,p),i.restore()}this.compose(),(l=this.dependencyTracker)==null||l.recordOperation(e),H(this,mt,vi).call(this,n)}paintImageXObject(e,t){if(!this.contentVisible)return;const n=this.getObject(e,t);if(!n){At("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){At("Dependent image isn't ready yet");return}const a=o.width,c=o.height,l=[];for(let u=0,d=r.length;u<d;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 d;if(!this.contentVisible)return;const n=t.width,i=t.height,r=H(this,mt,dr).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 h=this.applyTransferMapsToBitmap(t);c=h.img,l=h.canvasEntry}else if(typeof HTMLElement=="function"&&t instanceof HTMLElement||!t.data)c=t;else{const h=this.canvasFactory.create(n,i);eP(h.context,t),c=this.applyTransferMapsToCanvas(h.context),l=h}const u=this._scaleImage(c,Ea(o));o.imageSmoothingEnabled=sP(xs(o),t.interpolate),this.dependencyTracker&&(this.dependencyTracker.resetBBox(e).recordBBox(e,o,0,n,-i,0).recordDependencies(e,yo.imageXObject).recordOperation(e),(d=this.imagesTracker)==null||d.record(o,n,i,this.dependencyTracker.clipBox)),uw(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),H(this,mt,vi).call(this,r)}paintInlineImageXObjectGroup(e,t,n){var c,l,u;if(!this.contentVisible)return;const i=H(this,mt,dr).call(this,this.current.fillAlpha),r=this.ctx;let o,a=null;if(t.bitmap)o=t.bitmap;else{const d=t.width,h=t.height,p=this.canvasFactory.create(d,h);eP(p.context,t),o=this.applyTransferMapsToCanvas(p.context),a=p}(c=this.dependencyTracker)==null||c.resetBBox(e);for(const d of n)r.save(),r.transform(...d.transform),r.scale(1,-1),uw(r,o,d.x,d.y,d.w,d.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(),H(this,mt,vi).call(this,i)}paintSolidColorImageMask(e){var n;if(!this.contentVisible)return;const t=H(this,mt,dr).call(this,this.current.fillAlpha);(n=this.dependencyTracker)==null||n.resetBBox(e).recordBBox(e,this.ctx,0,1,0,1).recordDependencies(e,yo.fill).recordOperation(e),this.ctx.fillRect(0,0,1,1),this.compose(),H(this,mt,vi).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===nP?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=xs(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,d=l*e;o=u<1?1/u:1,a=d<1?1/d: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 d=e*c;o=u>d?u/d:1,a=l>d?l/d: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),pT.a=1/r,pT.d=1/o;const c=new Path2D;if(c.addPath(e,pT),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}};Fr=new WeakMap,Iu=new WeakMap,xh=new WeakMap,Rh=new WeakMap,Ih=new WeakMap,Ph=new WeakMap,Lh=new WeakMap,Pu=new WeakMap,Oh=new WeakMap,Ka=new WeakMap,mt=new WeakSet,fA=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)},pA=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}}},mA=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,Pu)===void 0&&R(this,Pu,Rs.isCanvasFilterSupported?new Map:"none");let l="none";if(c&&f(this,Pu)instanceof Map&&(l=f(this,Pu).get(n),l||(l=this.filterFactory.addKnockoutFilter(n),f(this,Pu).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),d=a.createImageData(i,r),h=u.data,p=d.data,g=n>0?1/n:1e6;for(let v=3,m=h.length;v<m;v+=4)p[v]=Math.min(Math.round(h[v]*g),255);return a.putImageData(d,0,0),o},gA=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},vA=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:d=1}=n,{width:h,height:p}=t,g=H(this,mt,mA).call(this,t,a,d),v=e.globalCompositeOperation;if(e.save(),e.setTransform(...r),e.globalAlpha=1,Rs.isCanvasFilterSupported&&(e.filter="none"),e.globalCompositeOperation="destination-out",e.drawImage(g.canvas,0,0),i){const[m,y]=o,_=H(this,mt,gA).call(this,c,"knockoutBackdropEntry",h,p),b=_.context;b.drawImage(i,m,y,h,p,0,0,h,p),b.globalCompositeOperation="destination-in",b.drawImage(g.canvas,0,0),b.globalCompositeOperation="source-over",e.globalCompositeOperation="destination-over",e.drawImage(_.canvas,0,0),c||this.canvasFactory.destroy(_)}e.globalCompositeOperation=v,e.globalAlpha=l,Rs.isCanvasFilterSupported&&(e.filter=u??"none"),e.drawImage(t,0,0),e.restore(),a||this.canvasFactory.destroy(g)},dr=function(e=1){if(f(this,Fr)===0||f(this,Iu)>0||!this.contentVisible)return!1;Ls(this,Iu)._++,R(this,Lh,e);const t=f(this,Ka).at(-1),{canvas:n}=this.ctx,i=H(this,mt,gA).call(this,t,"knockoutTempEntry",n.width,n.height);R(this,xh,i);const r=i.context;return r.save(),r.setTransform(this.ctx.getTransform()),Md(this.ctx,r),R(this,Ph,r.globalCompositeOperation),r.globalCompositeOperation="source-over",JI(r,this.ctx),R(this,Oh,t),R(this,Rh,this.ctx),R(this,Ih,this.suspendedCtx),this.ctx=r,this.inSMaskMode&&(this.suspendedCtx=r),!0},vi=function(e){var c;if(!e)return;const t=f(this,xh),n=f(this,Rh),i=f(this,Ih),r=t.context;R(this,xh,null),R(this,Rh,null),R(this,Ih,null),this.inSMaskMode&&this.suspendedCtx===r&&this.ctx!==r&&this.endSMaskMode(),this.inSMaskMode&&(this.suspendedCtx=i),this.ctx._removeMirroring(),this.ctx.globalCompositeOperation=f(this,Ph),R(this,Ph,null),Md(this.ctx,n),this.ctx=n;const o=f(this,Oh);R(this,Oh,null);const a=f(this,Lh);R(this,Lh,1);try{H(this,mt,vA).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(),Ls(this,Iu)._--,o||this.canvasFactory.destroy(t)}},yA=function(e,t,n){const i=new Path2D;return i.addPath(e,new DOMMatrix(n).invertSelf().multiplySelf(t)),i},Zw=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 Rp=jM;for(const s in $l)Rp.prototype[s]!==void 0&&(Rp.prototype[$l[s]]=Rp.prototype[s]);var ab,lb;class Ik{constructor(e,t,n){B(this,ab,null);B(this,lb,null);Se(this,"_fullReader",null);Se(this,"_rangeReaders",new Set);Se(this,"_source",null);this._source=e,R(this,ab,t),R(this,lb,n)}get _progressiveDataLength(){var e;return((e=this._fullReader)==null?void 0:e._loaded)??0}getFullReader(){return Ys(!this._fullReader,"BasePDFStream.getFullReader can only be called once."),this._fullReader=new(f(this,ab))(this)}getRangeReader(e,t){if(t<=this._progressiveDataLength)return null;const n=new(f(this,lb))(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)}}ab=new WeakMap,lb=new WeakMap;class Pk{constructor(e){Se(this,"onProgress",null);Se(this,"_contentLength",0);Se(this,"_filename",null);Se(this,"_headersCapability",Promise.withResolvers());Se(this,"_isRangeSupported",!1);Se(this,"_isStreamingSupported",!1);Se(this,"_loaded",0);Se(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(){ss("Abstract method `read` called")}cancel(e){ss("Abstract method `cancel` called")}}class Lk{constructor(e,t,n){Se(this,"_stream",null);this._stream=e}async read(){ss("Abstract method `read` called")}cancel(e){ss("Abstract method `cancel` called")}}function Jse(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,d){return new RegExp("(?:^|;)\\s*"+u+'\\s*=\\s*([^";\\s][^;\\s]*|"(?:[^"\\\\]|\\\\"?)+"?)',d)}function i(u,d){if(u){if(!/^[\x00-\xFF]+$/.test(d))return d;try{const h=new TextDecoder(u,{fatal:!0}),p=Mk(d);d=h.decode(p),e=!1}catch{}}return d}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 d=[];let h;const p=n("filename\\*((?!0\\d)\\d+)(\\*?)","ig");for(;(h=p.exec(u))!==null;){let[,v,m,y]=h;if(v=parseInt(v,10),v in d){if(v===0)break;continue}d[v]=[m,y]}const g=[];for(let v=0;v<d.length&&v in d;++v){let[m,y]=d[v];y=a(y),m&&(y=unescape(y),v===0&&(y=c(y))),g.push(y)}return g.join("")}function a(u){if(u.startsWith('"')){const d=u.slice(1).split('\\"');for(let h=0;h<d.length;++h){const p=d[h].indexOf('"');p!==-1&&(d[h]=d[h].slice(0,p),d.length=h+1),d[h]=d[h].replaceAll(/\\(.)/g,"$1")}u=d.join('"')}return u}function c(u){const d=u.indexOf("'");if(d===-1)return u;const h=u.slice(0,d),g=u.slice(d+1).replace(/^[^']*'/,"");return i(h,g)}function l(u){return!u.startsWith("=?")||/[\x00-\x19\x80-\xff]/.test(u)?u:u.replaceAll(/=\?([\w-]*)\?([QB])\?((?:[^?]|\?(?!=))*)\?=/gi,function(d,h,p,g){if(p==="q"||p==="Q")return g=g.replaceAll("_"," "),g=g.replaceAll(/=([0-9a-f]{2})/gi,function(v,m){return String.fromCharCode(parseInt(m,16))}),i(h,g);try{g=atob(g)}catch{}return i(h,g)})}return""}function t$(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 Ok(s){var e;return((e=URL.parse(s))==null?void 0:e.origin)??null}function s$({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 n$(s){const e=s.get("Content-Disposition");if(e){let t=Jse(e);if(t.includes("%"))try{t=decodeURIComponent(t)}catch{}if(RM(t))return t}return null}function Dk(s,e){return new k0(`Unexpected server response (${s}) while retrieving PDF "${e.href}".`,s,s===404||s===0&&e.protocol==="file:")}function i$(s,e){if(s!==e)throw new Error(`Expected range response-origin "${s}" to match "${e}".`)}function r$(s,e,t,n){return fetch(s,{method:"GET",headers:e,signal:n.signal,mode:"cors",credentials:t?"include":"same-origin",redirect:"follow"})}function o$(s,e){if(s!==200&&s!==206)throw Dk(s,e)}function Nk(s){if(s instanceof Uint8Array)return s.buffer;if(s instanceof ArrayBuffer)return s;throw new Error(`getArrayBuffer - unexpected data: ${s}`)}class Zse extends Ik{constructor(t){super(t,ene,tne);Se(this,"_responseOrigin",null);const{httpHeaders:n,url:i}=t;Ys(/https?:/.test(i.protocol),"PDFFetchStream only supports http(s):// URLs."),this.headers=t$(!0,n)}}class ene extends Pk{constructor(t){super(t);Se(this,"_abortController",new AbortController);Se(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);r$(o,c,a,this._abortController).then(l=>{t._responseOrigin=Ok(l.url),o$(l.status,o),this._reader=l.body.getReader();const u=l.headers,{contentLength:d,isRangeSupported:h}=s$({responseHeaders:u,isHttp:!0,rangeChunkSize:r,disableRange:n});this._contentLength=d,this._isRangeSupported=h,this._filename=n$(u),!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new pd("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:Nk(t),done:!1})}cancel(t){var n;(n=this._reader)==null||n.cancel(t),this._abortController.abort()}}class tne extends Lk{constructor(t,n,i){super(t,n,i);Se(this,"_abortController",new AbortController);Se(this,"_readCapability",Promise.withResolvers());Se(this,"_reader",null);const{url:r,withCredentials:o}=t._source,a=new Headers(t.headers);a.append("Range",`bytes=${n}-${i-1}`),r$(r,a,o,this._abortController).then(c=>{const l=Ok(c.url);i$(l,t._responseOrigin),o$(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:Nk(t),done:!1}}cancel(t){var n;(n=this._reader)==null||n.cancel(t),this._abortController.abort()}}Ct(116);function iP(s){return s instanceof Uint8Array&&s.byteLength===s.buffer.byteLength?s.buffer:new Uint8Array(s).buffer}function $k(){for(const s of this._requests)s.resolve({value:void 0,done:!0});this._requests.length=0}var Q0,a$;class sne extends Ik{constructor(t){super(t,nne,ine);B(this,Q0);Se(this,"_progressiveDone",!1);Se(this,"_queuedChunks",[]);const{pdfDataRangeTransport:n}=t,{initialData:i,progressiveDone:r}=n;if((i==null?void 0:i.length)>0){const a=iP(i);this._queuedChunks.push(a)}this._progressiveDone=r;const o=a=>{var c;switch(a.type){case"range":case"progressiveRead":H(this,Q0,a$).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()}}Q0=new WeakSet,a$=function(t,n){const i=iP(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);Ys(r,"#onReceiveData - no `PDFDataTransportStreamRangeReader` instance found."),r._enqueue(i)}};var cb;class nne extends Pk{constructor(t){super(t);B(this,cb,$k.bind(this));Se(this,"_done",!1);Se(this,"_queuedChunks",null);Se(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,RM(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,cb).call(this)}progressiveDone(){this._done||(this._done=!0),this._queuedChunks.length===0&&f(this,cb).call(this)}}cb=new WeakMap;var ub;class ine extends Lk{constructor(t,n,i){super(t,n,i);B(this,ub,$k.bind(this));Se(this,"onDone",null);Se(this,"_begin",-1);Se(this,"_done",!1);Se(this,"_queuedChunk",null);Se(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,ub).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,ub).call(this),(n=this.onDone)==null||n.call(this)}}ub=new WeakMap;const mT=200,rP=206;function rne(s){return typeof s!="string"?s:Mk(s).buffer}var qa,gg,l$,c$;class one extends Ik{constructor(t){super(t,ane,lne);B(this,gg);B(this,qa,new WeakMap);Se(this,"_responseOrigin",null);const{httpHeaders:n,url:i}=t;this.url=i,this.isHttp=/https?:/.test(i.protocol),this.headers=t$(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,qa).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===rP||r===mT):i.validateStatus=r=>r===mT,n.responseType="arraybuffer",Ys(t.onError,"Expected `onError` callback to be provided."),n.onerror=()=>t.onError(n.status),n.onreadystatechange=H(this,gg,c$).bind(this,n),n.onprogress=H(this,gg,l$).bind(this,n),n.send(null),n}_abortRequest(t){f(this,qa).has(t)&&(f(this,qa).delete(t),t.abort())}getRangeReader(t,n){const i=super.getRangeReader(t,n);return i&&(i.onClosed=()=>this._rangeReaders.delete(i)),i}}qa=new WeakMap,gg=new WeakSet,l$=function(t,n){var r;const i=f(this,qa).get(t);(r=i==null?void 0:i.onProgress)==null||r.call(i,n)},c$=function(t,n){const i=f(this,qa).get(t);if(!i||(t.readyState>=2&&i.onHeadersReceived&&(i.onHeadersReceived(),delete i.onHeadersReceived),t.readyState!==4)||!f(this,qa).has(t))return;if(f(this,qa).delete(t),t.status===0&&this.isHttp){i.onError(t.status);return}const r=t.status||mT;if(!i.validateStatus(r)){i.onError(t.status);return}const o=rne(t.response);if(r===rP){const a=t.getResponseHeader("Content-Range");/bytes \d+-\d+\/\d+/.test(a)?i.onDone(o):(At('Missing or invalid "Content-Range" header.'),i.onError(0))}else o?i.onDone(o):i.onError(t.status)};var db,fl,u$,d$,h$,f$;class ane extends Pk{constructor(t){super(t);B(this,fl);B(this,db,$k.bind(this));Se(this,"_cachedChunks",[]);Se(this,"_done",!1);Se(this,"_requests",[]);Se(this,"_storedError",null);this._fullRequestXhr=t._request({onHeadersReceived:H(this,fl,u$).bind(this),onDone:H(this,fl,d$).bind(this),onError:H(this,fl,h$).bind(this),onProgress:H(this,fl,f$).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,db).call(this),this._stream._abortRequest(this._fullRequestXhr),this._fullRequestXhr=null}}db=new WeakMap,fl=new WeakSet,u$=function(){const t=this._stream,{disableRange:n,rangeChunkSize:i}=t._source,r=this._fullRequestXhr;t._responseOrigin=Ok(r.responseURL);const o=r.getAllResponseHeaders(),a=new Headers(o?o.trimStart().replace(/[^\S ]+$/,"").split(/[\r\n]+/).map(u=>{const[d,...h]=u.split(": ");return[d,h.join(": ")]}):[]),{contentLength:c,isRangeSupported:l}=s$({responseHeaders:a,isHttp:t.isHttp,rangeChunkSize:i,disableRange:n});this._contentLength=c,this._isRangeSupported=l,this._filename=n$(a),this._isRangeSupported&&t._abortRequest(r),this._headersCapability.resolve()},d$=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,db).call(this)},h$=function(t){this._storedError=Dk(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},f$=function(t){var n;(n=this.onProgress)==null||n.call(this,{loaded:t.loaded,total:t.lengthComputable?t.total:this._contentLength})};var hb,Dc,p$,m$,bA;class lne extends Lk{constructor(t,n,i){super(t,n,i);B(this,Dc);B(this,hb,$k.bind(this));Se(this,"onClosed",null);Se(this,"_done",!1);Se(this,"_queuedChunk",null);Se(this,"_requests",[]);Se(this,"_storedError",null);this._requestXhr=t._request({begin:n,end:i,onHeadersReceived:H(this,Dc,p$).bind(this),onDone:H(this,Dc,m$).bind(this),onError:H(this,Dc,bA).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,hb).call(this),this._stream._abortRequest(this._requestXhr),(n=this.onClosed)==null||n.call(this)}}hb=new WeakMap,Dc=new WeakSet,p$=function(){var n;const t=Ok((n=this._requestXhr)==null?void 0:n.responseURL);try{i$(t,this._stream._responseOrigin)}catch(i){this._storedError=i,H(this,Dc,bA).call(this,0)}},m$=function(t){var n;this._requests.length>0?this._requests.shift().resolve({value:t,done:!1}):this._queuedChunk=t,this._done=!0,f(this,hb).call(this),(n=this.onClosed)==null||n.call(this)},bA=function(t){this._storedError??(this._storedError=Dk(t,this._stream.url));for(const n of this._requests)n.reject(this._storedError);this._requests.length=0,this._queuedChunk=null};function g$(s,e=null){const t=process.getBuiltinModule("fs"),{Readable:n}=process.getBuiltinModule("stream"),i=t.createReadStream(s,e);return n.toWeb(i)}class cne extends Ik{constructor(e){super(e,une,dne);const{url:t}=e;Ys(t.protocol==="file:","PDFNodeStream only supports file:// URLs.")}}class une extends Pk{constructor(t){super(t);Se(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=g$(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 pd("Streaming is disabled.")),this._headersCapability.resolve()}).catch(c=>{c.code==="ENOENT"&&(c=Dk(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:Nk(t),done:!1})}cancel(t){var n;(n=this._reader)==null||n.cancel(t)}}class dne extends Lk{constructor(t,n,i){super(t,n,i);Se(this,"_readCapability",Promise.withResolvers());Se(this,"_reader",null);const{url:r}=t._source;try{const o=g$(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:Nk(t),done:!1}}cancel(t){var n;(n=this._reader)==null||n.cancel(t)}}function hne(s){return ey(s)?Zse:to?cne:one}var fb,pb;class ol{static get workerPort(){return f(this,fb)}static set workerPort(e){if(!(typeof Worker<"u"&&e instanceof Worker)&&e!==null)throw new Error("Invalid `workerPort` type.");R(this,fb,e)}static get workerSrc(){return f(this,pb)}static set workerSrc(e){if(typeof e!="string")throw new Error("Invalid `workerSrc` type.");R(this,pb,e)}}fb=new WeakMap,pb=new WeakMap,B(ol,fb,null),B(ol,pb,"");var hm,mb;class fne{constructor({parsedData:e,rawData:t}){B(this,hm);B(this,mb);R(this,hm,e),R(this,mb,t)}getRaw(){return f(this,mb)}get(e){return f(this,hm).get(e)??null}[Symbol.iterator](){return f(this,hm).entries()}}hm=new WeakMap,mb=new WeakMap;const wp=Symbol("INTERNAL");var gb,vb,yb,fm;class pne{constructor(e,{name:t,intent:n,usage:i,rbGroups:r}){B(this,gb,!1);B(this,vb,!1);B(this,yb,!1);B(this,fm,!0);R(this,gb,!!(e&eo.DISPLAY)),R(this,vb,!!(e&eo.PRINT)),this.name=t,this.intent=n,this.usage=i,this.rbGroups=r}get visible(){if(f(this,yb))return f(this,fm);if(!f(this,fm))return!1;const{print:e,view:t}=this.usage;return f(this,gb)?(t==null?void 0:t.viewState)!=="OFF":f(this,vb)?(e==null?void 0:e.printState)!=="OFF":!0}_setVisible(e,t,n=!1){e!==wp&&ss("Internal method `_setVisible` called."),R(this,yb,n),R(this,fm,t)}}gb=new WeakMap,vb=new WeakMap,yb=new WeakMap,fm=new WeakMap;var Lu,Ss,pm,mm,bb,_A;class mne{constructor(e,t=eo.DISPLAY){B(this,bb);B(this,Lu,null);B(this,Ss,new Map);B(this,pm,null);B(this,mm,null);if(this.renderingIntent=t,this.name=null,this.creator=null,e!==null){this.name=e.name,this.creator=e.creator,R(this,mm,e.order);for(const n of e.groups)f(this,Ss).set(n.id,new pne(t,n));if(e.baseState==="OFF")for(const n of f(this,Ss).values())n._setVisible(wp,!1);for(const n of e.on)f(this,Ss).get(n)._setVisible(wp,!0);for(const n of e.off)f(this,Ss).get(n)._setVisible(wp,!1);R(this,pm,this.getHash())}}isVisible(e){if(f(this,Ss).size===0)return!0;if(!e)return Ek("Optional content group not defined."),!0;if(e.type==="OCG")return f(this,Ss).has(e.id)?f(this,Ss).get(e.id).visible:(At(`Optional content group not found: ${e.id}`),!0);if(e.type==="OCMD"){if(e.expression)return H(this,bb,_A).call(this,e.expression);if(!e.policy||e.policy==="AnyOn"){for(const t of e.ids){if(!f(this,Ss).has(t))return At(`Optional content group not found: ${t}`),!0;if(f(this,Ss).get(t).visible)return!0}return!1}else if(e.policy==="AllOn"){for(const t of e.ids){if(!f(this,Ss).has(t))return At(`Optional content group not found: ${t}`),!0;if(!f(this,Ss).get(t).visible)return!1}return!0}else if(e.policy==="AnyOff"){for(const t of e.ids){if(!f(this,Ss).has(t))return At(`Optional content group not found: ${t}`),!0;if(!f(this,Ss).get(t).visible)return!0}return!1}else if(e.policy==="AllOff"){for(const t of e.ids){if(!f(this,Ss).has(t))return At(`Optional content group not found: ${t}`),!0;if(f(this,Ss).get(t).visible)return!1}return!0}return At(`Unknown optional content policy ${e.policy}.`),!0}return At(`Unknown group type ${e.type}.`),!0}setVisibility(e,t=!0,n=!0){var r;const i=f(this,Ss).get(e);if(!i){At(`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,Ss).get(a))==null||r._setVisible(wp,!1,!0));i._setVisible(wp,!!t,!0),R(this,Lu,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,Ss).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}}R(this,Lu,null)}get hasInitialVisibility(){return f(this,pm)===null||this.getHash()===f(this,pm)}getOrder(){return f(this,Ss).size?f(this,mm)?f(this,mm).slice():[...f(this,Ss).keys()]:null}getGroup(e){return f(this,Ss).get(e)||null}getHash(){if(f(this,Lu)!==null)return f(this,Lu);const e=new rA;for(const[t,n]of f(this,Ss))e.update(`${t}:${n.visible}`);return R(this,Lu,e.hexdigest())}[Symbol.iterator](){return f(this,Ss).entries()}}Lu=new WeakMap,Ss=new WeakMap,pm=new WeakMap,mm=new WeakMap,bb=new WeakSet,_A=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=H(this,bb,_A).call(this,r);else if(f(this,Ss).has(r))o=f(this,Ss).get(r).visible;else return At(`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 yn,ca,ni,Dh,Qa,Ei,Sv,kv,eS;class gne{constructor(){B(this,Ei);B(this,yn,null);B(this,ca,null);B(this,ni,0);B(this,Dh,null);B(this,Qa,null)}get pagesNumber(){return f(this,ni)}set pagesNumber(e){f(this,ni)!==e&&(R(this,ni,e),R(this,yn,null),R(this,ca,null))}movePages(e,t,n){H(this,Ei,Sv).call(this);const i=f(this,yn),r=H(this,Ei,kv).call(this),o=t.length,a=new Uint32Array(o);let c=0;for(let h=0;h<o;h++){const p=t[h]-1;a[h]=i[p],p<n&&c++}const l=f(this,ni),u=l-o,d=zs(n-c,0,u);for(let h=0,p=0;h<l;h++)e.has(h+1)||(i[p++]=i[h]);i.copyWithin(d+o,d,u),i.set(a,d),H(this,Ei,eS).call(this,r),i.every((h,p)=>h===p+1)&&R(this,yn,null)}deletePages(e){H(this,Ei,Sv).call(this);const t=f(this,yn),n=H(this,Ei,kv).call(this);R(this,Qa,{pageNumberToId:t.slice(),pagesNumber:f(this,ni),prevPageNumbers:f(this,ca).slice()});const i=f(this,ni)-e.length;R(this,ni,i);const r=R(this,yn,new Uint32Array(i));R(this,ca,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),H(this,Ei,eS).call(this,n,new Set(e))}cancelDelete(){f(this,Qa)&&(R(this,yn,f(this,Qa).pageNumberToId),R(this,ni,f(this,Qa).pagesNumber),R(this,ca,f(this,Qa).prevPageNumbers),R(this,Qa,null))}cleanSavedData(){R(this,Qa,null)}copyPages(e){H(this,Ei,Sv).call(this),R(this,Dh,{pageNumbers:e,pageIds:e.map(t=>f(this,yn)[t-1])})}cancelCopy(){R(this,Dh,null)}pastePages(e){H(this,Ei,Sv).call(this);const t=f(this,yn),n=H(this,Ei,kv).call(this),{pageNumbers:i,pageIds:r}=f(this,Dh),o=f(this,ni)+i.length;R(this,ni,o);const a=R(this,yn,new Uint32Array(o));R(this,ca,new Int32Array(o)),a.set(t.subarray(0,e),0),a.set(r,e),a.set(t.subarray(e),e+i.length),H(this,Ei,eS).call(this,n,null,e,i),R(this,Dh,null)}hasBeenAltered(){return f(this,yn)!==null}getPageMappingForSaving(e=null){e??(e=H(this,Ei,kv).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,ca))==null?void 0:t[e-1])??0}getPageNumber(e){if(!f(this,yn))return e;const t=f(this,yn);for(let n=0,i=f(this,ni);n<i;n++)if(t[n]===e)return n+1;return 0}getPageId(e){var t;return((t=f(this,yn))==null?void 0:t[e-1])??e}getMapping(){var e;return(e=f(this,yn))==null?void 0:e.subarray(0,this.pagesNumber)}}yn=new WeakMap,ca=new WeakMap,ni=new WeakMap,Dh=new WeakMap,Qa=new WeakMap,Ei=new WeakSet,Sv=function(){if(f(this,yn))return;const e=f(this,ni),t=R(this,yn,new Uint32Array(e));for(let n=0;n<e;n++)t[n]=n+1;R(this,ca,new Int32Array(t))},kv=function(){const e=new Map,t=f(this,yn);for(let n=0,i=f(this,ni);n<i;n++){const r=t[n],o=e.get(r);o?o.push(n+1):e.set(r,[n+1])}return e},eS=function(e,t=null,n=-1,i=null){const r=f(this,ca),o=f(this,yn),a=n+((i==null?void 0:i.length)??0),c=new Map;for(let l=0,u=f(this,ni);l<u;l++){if(l>=n&&l<a){r[l]=-i[l-n];continue}const d=o[l],h=e.get(d);let p=c.get(d)||0;if(t&&h)for(;p<h.length&&t.has(h[p]);)p++;r[l]=h==null?void 0:h[p],c.set(d,p+1)}};const Sp=Symbol("INITIAL_DATA"),oP=()=>({...Promise.withResolvers(),data:Sp});var Ro;class v${constructor(){B(this,Ro,new Map)}get(e,t=null){if(t){const i=f(this,Ro).getOrInsertComputed(e,oP);return i.promise.then(()=>t(i.data)),null}const n=f(this,Ro).get(e);if(!n||n.data===Sp)throw new Error(`Requesting object that isn't resolved yet ${e}.`);return n.data}has(e){const t=f(this,Ro).get(e);return!!t&&t.data!==Sp}delete(e){const t=f(this,Ro).get(e);return!t||t.data===Sp?!1:(f(this,Ro).delete(e),!0)}resolve(e,t=null){const n=f(this,Ro).getOrInsertComputed(e,oP);if(n.data!==Sp)throw new Error(`Object already resolved ${e}.`);n.data=t,n.resolve()}clear(){var e;for(const{data:t}of f(this,Ro).values())(e=t==null?void 0:t.bitmap)==null||e.close();f(this,Ro).clear()}*[Symbol.iterator](){for(const[e,{data:t}]of f(this,Ro))t!==Sp&&(yield[e,t])}}Ro=new WeakMap;const vne=1e5,aP=30;var HP,Ou,qi,_b,wb,gm,Nh,tc,Sb,kb,$h,Cb,vm,Du,ym,Tb,bm,Bh,Ab,Eb,_m,Fh,Mb,wm,Sm,Nc,y$,b$,wA,ro,tS,SA,_$,w$;const Zn=class Zn{constructor({textContentSource:e,images:t,container:n,viewport:i}){B(this,Nc);B(this,Ou,Promise.withResolvers());B(this,qi,null);B(this,_b,!1);B(this,wb,!!((HP=globalThis.FontInspector)!=null&&HP.enabled));B(this,gm,null);B(this,Nh,null);B(this,tc,null);B(this,Sb,0);B(this,kb,0);B(this,$h,null);B(this,Cb,null);B(this,vm,0);B(this,Du,0);B(this,ym,Object.create(null));B(this,Tb,[]);B(this,bm,null);B(this,Bh,[]);B(this,Ab,new WeakMap);B(this,Eb,null);var l;if(e instanceof ReadableStream)R(this,bm,e);else if(typeof e=="object")R(this,bm,new ReadableStream({start(u){u.enqueue(e),u.close()}}));else throw new Error('No "textContentSource" parameter specified.');R(this,qi,R(this,Cb,n)),R(this,gm,t),R(this,Du,i.scale*hl.pixelRatio),R(this,vm,i.rotation),R(this,tc,{div:null,properties:null,ctx:null});const{pageWidth:r,pageHeight:o,pageX:a,pageY:c}=i.rawDims;R(this,Eb,[1,0,0,-1,-a,c+o]),R(this,kb,r),R(this,Sb,o),H(l=Zn,ro,_$).call(l),n.style.setProperty("--min-font-size",f(Zn,wm)),$f(n,i),f(this,Ou).promise.finally(()=>{f(Zn,Sm).delete(this),R(this,tc,null),R(this,ym,null)}).catch(()=>{})}static get fontFamilyMap(){const{isWindows:e,isFirefox:t}=Rs.platform;return Mt(this,"fontFamilyMap",new Map([["sans-serif",`${e&&t?"Calibri, ":""}sans-serif`],["monospace",`${e&&t?"Lucida Console, ":""}monospace`]]))}render(){f(this,gm)&&f(this,qi).append(f(this,gm).render());const e=()=>{f(this,$h).read().then(({value:t,done:n})=>{if(n){f(this,Ou).resolve();return}f(this,Nh)??R(this,Nh,t.lang),Object.assign(f(this,ym),t.styles),H(this,Nc,y$).call(this,t.items),e()},f(this,Ou).reject)};return R(this,$h,f(this,bm).getReader()),f(Zn,Sm).add(this),e(),f(this,Ou).promise}update({viewport:e,onBefore:t=null}){var r;const n=e.scale*hl.pixelRatio,i=e.rotation;if(i!==f(this,vm)&&(t==null||t(),R(this,vm,i),$f(f(this,Cb),{rotation:i})),n!==f(this,Du)){t==null||t(),R(this,Du,n);const o={div:null,properties:null,ctx:H(r=Zn,ro,tS).call(r,f(this,Nh))};for(const a of f(this,Bh))o.properties=f(this,Ab).get(a),o.div=a,H(this,Nc,wA).call(this,o)}}cancel(){var t;const e=new pd("TextLayer task cancelled.");(t=f(this,$h))==null||t.cancel(e).catch(()=>{}),R(this,$h,null),f(this,Ou).reject(e)}get textDivs(){return f(this,Bh)}get textContentItemsStr(){return f(this,Tb)}static cleanup(){if(!(f(this,Sm).size>0)){f(this,_m).clear();for(const{canvas:e}of f(this,Fh).values())e.remove();f(this,Fh).clear()}}};Ou=new WeakMap,qi=new WeakMap,_b=new WeakMap,wb=new WeakMap,gm=new WeakMap,Nh=new WeakMap,tc=new WeakMap,Sb=new WeakMap,kb=new WeakMap,$h=new WeakMap,Cb=new WeakMap,vm=new WeakMap,Du=new WeakMap,ym=new WeakMap,Tb=new WeakMap,bm=new WeakMap,Bh=new WeakMap,Ab=new WeakMap,Eb=new WeakMap,_m=new WeakMap,Fh=new WeakMap,Mb=new WeakMap,wm=new WeakMap,Sm=new WeakMap,Nc=new WeakSet,y$=function(e){var i,r;if(f(this,_b))return;(r=f(this,tc)).ctx??(r.ctx=H(i=Zn,ro,tS).call(i,f(this,Nh)));const t=f(this,Bh),n=f(this,Tb);for(const o of e){if(t.length>vne){At("Ignoring additional textDivs for performance reasons."),R(this,_b,!0);return}if(o.str===void 0){if(o.type==="beginMarkedContentProps"||o.type==="beginMarkedContent"){const a=f(this,qi);R(this,qi,document.createElement("span")),f(this,qi).classList.add("markedContent"),o.id&&f(this,qi).setAttribute("id",`${o.id}`),o.tag==="Artifact"&&(f(this,qi).ariaHidden=!0),a.append(f(this,qi))}else o.type==="endMarkedContent"&&R(this,qi,f(this,qi).parentNode);continue}n.push(o.str),H(this,Nc,b$).call(this,o)}},b$=function(e){var g;const t=document.createElement("span"),n={angle:0,canvasWidth:0,hasText:e.str!=="",hasEOL:e.hasEOL,fontSize:0};f(this,Bh).push(t);const i=Fe.transform(f(this,Eb),e.transform);let r=Math.atan2(i[1],i[0]);const o=f(this,ym)[e.fontName];o.vertical&&(r+=Math.PI/2);let a=f(this,wb)&&o.fontSubstitution||o.fontFamily;a=Zn.fontFamilyMap.get(a)||a;const c=Math.hypot(i[2],i[3]),l=c*H(g=Zn,ro,w$).call(g,a,o,f(this,Nh));let u,d;r===0?(u=i[4],d=i[5]-l):(u=i[4]+l*Math.sin(r),d=i[5]-l*Math.cos(r));const h=t.style;h.left=`${(100*u/f(this,kb)).toFixed(2)}%`,h.top=`${(100*d/f(this,Sb)).toFixed(2)}%`,h.setProperty("--font-height",`${c.toFixed(2)}px`),h.fontFamily=a,n.fontSize=c,t.setAttribute("role","presentation"),t.textContent=e.str,t.dir=e.dir,f(this,wb)&&(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]),m=Math.abs(e.transform[3]);v!==m&&Math.max(v,m)/Math.min(v,m)>1.5&&(p=!0)}if(p&&(n.canvasWidth=o.vertical?e.height:e.width),f(this,Ab).set(t,n),f(this,tc).div=t,f(this,tc).properties=n,H(this,Nc,wA).call(this,f(this,tc)),n.hasText&&f(this,qi).append(t),n.hasEOL){const v=document.createElement("br");v.setAttribute("role","presentation"),f(this,qi).append(v)}},wA=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;H(o=Zn,ro,SA).call(o,i,l*f(this,Du),a);const{width:u}=i.measureText(t.textContent);u>0&&r.setProperty("--scale-x",c*f(this,Du)/u)}n.angle!==0&&r.setProperty("--rotate",`${n.angle}deg`)},ro=new WeakSet,tS=function(e=null){let t=f(this,Fh).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,Fh).set(e,t),f(this,Mb).set(t,{size:0,family:""})}return t},SA=function(e,t,n){const i=f(this,Mb).get(e);t===i.size&&n===i.family||(e.font=`${t}px ${n}`,i.size=t,i.family=n)},_$=function(){if(f(this,wm)!==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),R(this,wm,e.getBoundingClientRect().height),e.remove()},w$=function(e,t,n){const i=f(this,_m).get(e);if(i)return i;const r=H(this,ro,tS).call(this,n);r.canvas.width=r.canvas.height=aP,H(this,ro,SA).call(this,r,aP,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):(Rs.platform.isFirefox&&At("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,_m).set(e,l),l},B(Zn,ro),B(Zn,_m,new Map),B(Zn,Fh,new Map),B(Zn,Mb,new WeakMap),B(Zn,wm,null),B(Zn,Sm,new Set);let Ay=Zn;const yne=100;function S$(s={}){const e=new kA,{docId:t}=e,n=s.url?Tse(s.url):null,i=s.data?Ase(s.data):null,r=s.httpHeaders||null,o=s.withCredentials===!0,a=s.password??null,c=s.range instanceof k$?s.range:null,l=Number.isInteger(s.rangeChunkSize)&&s.rangeChunkSize>0?s.rangeChunkSize:2**16;let u=s.worker instanceof Ey?s.worker:null;const d=s.verbosity,h=typeof s.docBaseUrl=="string"&&!xk(s.docBaseUrl)?s.docBaseUrl:null,p=lw(s.cMapUrl),g=s.cMapPacked!==!1,v=lw(s.iccUrl),m=lw(s.standardFontDataUrl),y=lw(s.wasmUrl),_=s.stopAtErrors!==!0,b=Number.isInteger(s.maxImageSize)&&s.maxImageSize>-1?s.maxImageSize:-1,k=typeof s.isOffscreenCanvasSupported=="boolean"?s.isOffscreenCanvasSupported:!to,w=typeof s.isImageDecoderSupported=="boolean"?s.isImageDecoderSupported:!to,T=Number.isInteger(s.canvasMaxAreaInBytes)?s.canvasMaxAreaInBytes:-1,A=typeof s.disableFontFace=="boolean"?s.disableFontFace:to,C=s.fontExtraProperties===!0,E=s.enableXfa===!0,x=s.ownerDocument||globalThis.document,D=s.disableRange===!0,N=s.disableStream===!0,O=s.disableAutoFetch===!0,G=s.pdfBug===!0,Z=s.CanvasFactory||(to?Ose:Rse),q=s.FilterFactory||(to?Lse:Ise),V=s.BinaryDataFactory||(to?Dse:KI),I=s.enableHWA===!0,L=s.enableWebGPU===!0?Bse():Promise.resolve(!1),K=s.useWasm!==!1,se=s.pagesMapper||new gne,oe=typeof s.useSystemFonts=="boolean"?s.useSystemFonts:!to&&!A,ve=typeof s.useWorkerFetch=="boolean"?s.useWorkerFetch:!!(V===KI&&p&&g&&m&&y&&ey(p,document.baseURI)&&ey(m,document.baseURI)&&ey(y,document.baseURI)),le=null;Kte(d);const ue={canvasFactory:new Z({ownerDocument:x,enableHWA:I}),filterFactory:new q({docId:t,ownerDocument:x}),binaryDataFactory:ve?null:new V({cMapUrl:p,standardFontDataUrl:m,wasmUrl:y})};u||(u=Ey.create({verbosity:d,port:ol.workerPort}),e._worker=u);const P={docId:t,apiVersion:"6.0.227",data:i,password:a,disableAutoFetch:O,rangeChunkSize:l,docBaseUrl:h,enableXfa:E,evaluatorOptions:{maxImageSize:b,disableFontFace:A,ignoreErrors:_,isOffscreenCanvasSupported:k,isImageDecoderSupported:w,canvasMaxAreaInBytes:T,fontExtraProperties:C,useSystemFonts:oe,useWasm:K,useWorkerFetch:ve,cMapUrl:p,cMapPacked:g,iccUrl:v,standardFontDataUrl:m,wasmUrl:y,hasGPU:!1}},X={ownerDocument:x,pdfBug:G,styleElement:le,enableHWA:I,loadingParams:{disableAutoFetch:O,enableXfa:E}};return Promise.all([u.promise,L]).then(function([,J]){if(u.destroyed)throw new Error("Worker was destroyed");P.evaluatorOptions.hasGPU=J;const ne=u.messageHandler.sendWithPromise("GetDocRequest",P,i?[i.buffer]:null);let ce;if(!i)if(c)ce=new sne({pdfDataRangeTransport:c,disableRange:D,disableStream:N});else if(n){const _e=hne(n);ce=new _e({url:n,httpHeaders:r,withCredentials:o,rangeChunkSize:l,disableRange:D,disableStream:N})}else throw new Error("getDocument - expected either `data`, `range`, or `url` parameter.");return ne.then(_e=>{if(u.destroyed)throw new Error("Worker was destroyed");const Pe=new vv(t,_e,u.port),it=new _ne(Pe,e,ce,X,ue,se);if(e._transport=it,e.destroyed)throw new Error("Loading aborted");Pe.send("Ready",null)})}).catch(e._capability.reject).finally(e._setupCapability.resolve),e}var X0;const Y0=class Y0{constructor(){Se(this,"_capability",Promise.withResolvers());Se(this,"_setupCapability",Promise.withResolvers());Se(this,"_transport",null);Se(this,"_worker",null);Se(this,"docId",`d${Ls(Y0,X0)._++}`);Se(this,"destroyed",!1);Se(this,"onPassword",null);Se(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()}};X0=new WeakMap,B(Y0,X0,0);let kA=Y0;var km,Hh;class k${constructor(e,t,n=!1,i=null){B(this,km,Promise.withResolvers());B(this,Hh,null);this.length=e,this.initialData=t,this.progressiveDone=n,this.contentDispositionFilename=i}onDataRange(e,t){f(this,Hh).call(this,{type:"range",begin:e,chunk:t})}onDataProgressiveRead(e){f(this,km).promise.then(()=>{f(this,Hh).call(this,{type:"progressiveRead",chunk:e})})}onDataProgressiveDone(){f(this,km).promise.then(()=>{f(this,Hh).call(this,{type:"progressiveDone"})})}transportReady(e){R(this,Hh,e),f(this,km).resolve()}requestDataRange(e,t){ss("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}km=new WeakMap,Hh=new WeakMap;class bne{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 Mt(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 sc,Uh,Wh,Cv;const VM=class VM{constructor(e,t,n,i,r=!1){B(this,Wh);B(this,sc,!1);B(this,Uh,null);this._pageIndex=e,this._pageInfo=t,this._transport=n,this._stats=r?new NI:null,this._pdfBug=r,this.commonObjs=n.commonObjs,this.objs=new v$,this._intentStates=new Map,this.destroyed=!1,this.recordedBBoxes=null,R(this,Uh,i),this.imageCoordinates=null}clone(e){const t=new VM(e,this._pageInfo,this._transport,f(this,Uh),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 y_({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 Mt(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=iu.ENABLE,transform:o=null,background:a=null,optionalContentConfigPromise:c=null,annotationCanvasMap:l=null,pageColors:u=null,printAnnotationStorage:d=null,isEditing:h=!1,recordImages:p=!1,recordOperations:g=!1,operationsFilter:v=null}){var O,G,Z;(O=this._stats)==null||O.time("Overall");const m=this._transport.getRenderingIntent(i,r,d,h),{renderingIntent:y,cacheKey:_}=m;R(this,sc,!1),c||(c=this._transport.getOptionalContentConfig(y));const b=this._intentStates.getOrInsertComputed(_,H1);b.streamReaderCancelTimeout&&(clearTimeout(b.streamReaderCancelTimeout),b.streamReaderCancelTimeout=null);const k=!!(y&eo.PRINT);b.displayReadyCapability||(b.displayReadyCapability=Promise.withResolvers(),b.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},(G=this._stats)==null||G.time("Page Request"),this._pumpOperatorList(m));const w=!!(this._pdfBug&&((Z=globalThis.StepperManager)!=null&&Z.enabled)),T=!!t&&!this.recordedBBoxes&&(g||w),A=!!t&&!this.imageCoordinates&&p,C=q=>{var V,I,$,L;if(b.renderTasks.delete(D),T){const K=(V=D.gfx)==null?void 0:V.dependencyTracker.take();K&&((I=D.stepper)==null||I.setOperatorBBoxes(K,D.gfx.dependencyTracker.takeDebugMetadata()),g&&(this.recordedBBoxes=K))}A&&!q&&(this.imageCoordinates=($=D.gfx)==null?void 0:$.imagesTracker.take()),k&&R(this,sc,!0),H(this,Wh,Cv).call(this),q?(D.capability.reject(q),this._abortOperatorList({intentState:b,reason:q instanceof Error?q:new Error(q)})):D.capability.resolve(),this._stats&&(this._stats.timeEnd("Rendering"),this._stats.timeEnd("Overall"),(L=globalThis.Stats)!=null&&L.enabled&&globalThis.Stats.add(this.pageNumber,this._stats))};let E=null,x=null;(T||A)&&(x=new gse(t,b.operatorList.length)),T&&(E=new vse(x,w));const D=new TA({callback:C,params:{canvas:t,canvasContext:e,dependencyTracker:E??x,imagesTracker:A?new lA(t):null,viewport:n,transform:o,background:a},objs:this.objs,commonObjs:this.commonObjs,annotationCanvasMap:l,operatorList:b.operatorList,pageIndex:this._pageIndex,canvasFactory:this._transport.canvasFactory,filterFactory:this._transport.filterFactory,useRequestAnimationFrame:!k,pdfBug:this._pdfBug,pageColors:u,enableHWA:this._transport.enableHWA,operationsFilter:v});(b.renderTasks||(b.renderTasks=new Set)).add(D);const N=D.task;return Promise.all([b.displayReadyCapability.promise,c]).then(([q,V])=>{var I;if(this.destroyed){C();return}if((I=this._stats)==null||I.time("Rendering"),!(V.renderingIntent&y))throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");D.initializeGraphics({transparency:q,optionalContentConfig:V}),D.operatorListChanged()}).catch(C),N}getOperatorList({intent:e="display",annotationMode:t=iu.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,H1);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,Uh).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=>ky.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(),R(this,sc,!1),Promise.all(e)}cleanup(e=!1){R(this,sc,!0);const t=H(this,Wh,Cv).call(this);return e&&t&&this._stats&&(this._stats=new NI),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&&H(this,Wh,Cv).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,Uh).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:d,done:h})=>{if(h){l.streamReader=null;return}this._transport.destroyed||(this._renderPageChunk(d,l),u())},d=>{if(l.streamReader=null,!this._transport.destroyed){if(l.operatorList){l.operatorList.lastChunk=!0;for(const h of l.renderTasks)h.operatorListChanged();H(this,Wh,Cv).call(this)}if(l.displayReadyCapability)l.displayReadyCapability.reject(d);else if(l.opListReadCapability)l.opListReadCapability.reject(d);else throw d}})};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 xM){let i=yne;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 pd(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}};sc=new WeakMap,Uh=new WeakMap,Wh=new WeakSet,Cv=function(){if(!f(this,sc)||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(),R(this,sc,!1),!0};let CA=VM;var Nu,ua,nc,zh,J0,jh,Vh,nr,sS,C$,T$,Tv,Cm,nS;const nn=class nn{constructor({name:e=null,port:t=null,verbosity:n=qte()}={}){B(this,nr);B(this,Nu,Promise.withResolvers());B(this,ua,null);B(this,nc,null);B(this,zh,null);if(this.name=e,this.destroyed=!1,this.verbosity=n,t){if(f(nn,Vh).has(t))throw new Error("Cannot use more than one PDFWorker per port.");f(nn,Vh).set(t,this),H(this,nr,C$).call(this,t)}else H(this,nr,T$).call(this)}get promise(){return f(this,Nu).promise}get port(){return f(this,nc)}get messageHandler(){return f(this,ua)}destroy(){var e,t;this.destroyed=!0,(e=f(this,zh))==null||e.terminate(),R(this,zh,null),f(nn,Vh).delete(f(this,nc)),R(this,nc,null),(t=f(this,ua))==null||t.destroy(),R(this,ua,null)}static create(e){const t=f(this,Vh).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 nn(e)}static get workerSrc(){if(ol.workerSrc)return ol.workerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get _setupFakeWorkerGlobal(){return Mt(this,"_setupFakeWorkerGlobal",(async()=>f(this,Cm,nS)?f(this,Cm,nS):(await import(this.workerSrc)).WorkerMessageHandler)())}};Nu=new WeakMap,ua=new WeakMap,nc=new WeakMap,zh=new WeakMap,J0=new WeakMap,jh=new WeakMap,Vh=new WeakMap,nr=new WeakSet,sS=function(){f(this,Nu).resolve(),f(this,ua).send("configure",{verbosity:this.verbosity})},C$=function(e){R(this,nc,e),R(this,ua,new vv("main","worker",e)),f(this,ua).on("ready",()=>{}),H(this,nr,sS).call(this)},T$=function(){if(f(nn,jh)||f(nn,Cm,nS)){H(this,nr,Tv).call(this);return}let{workerSrc:e}=nn;try{nn._isSameOrigin(window.location,e)||(e=nn._createCDNWrapper(new URL(e,window.location).href));const t=new Worker(e,{type:"module"}),n=new vv("main","worker",t),i=()=>{r.abort(),n.destroy(),t.terminate(),this.destroyed?f(this,Nu).reject(new Error("Worker was destroyed")):H(this,nr,Tv).call(this)},r=new AbortController;t.addEventListener("error",()=>{f(this,zh)||i()},{signal:r.signal}),n.on("test",a=>{if(r.abort(),this.destroyed||!a){i();return}R(this,ua,n),R(this,nc,t),R(this,zh,t),H(this,nr,sS).call(this)}),n.on("ready",a=>{if(r.abort(),this.destroyed){i();return}try{o()}catch{H(this,nr,Tv).call(this)}});const o=()=>{const a=new Uint8Array;n.send("test",a,[a.buffer])};o();return}catch{Ek("The worker has been disabled.")}H(this,nr,Tv).call(this)},Tv=function(){f(nn,jh)||(At("Setting up fake worker."),R(nn,jh,!0)),nn._setupFakeWorkerGlobal.then(e=>{if(this.destroyed){f(this,Nu).reject(new Error("Worker was destroyed"));return}const t=new xse;R(this,nc,t);const n=`fake${Ls(nn,J0)._++}`,i=new vv(n+"_worker",n,t);e.setup(i,t),R(this,ua,new vv(n,n+"_worker",t)),H(this,nr,sS).call(this)}).catch(e=>{f(this,Nu).reject(new Error(`Setting up fake worker failed: "${e.message}".`))})},Cm=new WeakSet,nS=function(){var e;try{return((e=globalThis.pdfjsWorker)==null?void 0:e.WorkerMessageHandler)||null}catch{return null}},B(nn,Cm),B(nn,J0,0),B(nn,jh,!1),B(nn,Vh,new WeakMap),to&&(R(nn,jh,!0),ol.workerSrc||(ol.workerSrc="./pdf.worker.mjs")),nn._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},nn._createCDNWrapper=e=>{const t=`await import("${e}");`;return URL.createObjectURL(new Blob([t],{type:"text/javascript"}))};let Ey=nn;var Hr,Gh,ic,da,Kh,Tm,rc,_a,Av,iS;class _ne{constructor(e,t,n,i,r,o){B(this,_a);Se(this,"downloadInfoCapability",Promise.withResolvers());B(this,Hr,null);B(this,Gh,new Map);B(this,ic,null);B(this,da,new Map);B(this,Kh,new Map);B(this,Tm,new Map);B(this,rc,null);this.messageHandler=e,this.loadingTask=t,R(this,ic,n),this.commonObjs=new v$,this.fontLoader=new yse({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,da).set(t,e),f(this,Kh).set(t,Promise.resolve(e))}get annotationStorage(){return Mt(this,"annotationStorage",new IM)}getRenderingIntent(e,t=iu.ENABLE,n=null,i=!1,r=!1){let o=eo.DISPLAY,a=Cy;switch(e){case"any":o=eo.ANY;break;case"display":break;case"print":o=eo.PRINT;break;default:At(`getRenderingIntent - invalid intent: ${e}`)}const c=o&eo.PRINT&&n instanceof WN?n:this.annotationStorage;switch(t){case iu.DISABLE:o+=eo.ANNOTATIONS_DISABLE;break;case iu.ENABLE:break;case iu.ENABLE_FORMS:o+=eo.ANNOTATIONS_FORMS;break;case iu.ENABLE_STORAGE:o+=eo.ANNOTATIONS_STORAGE,a=c.serializable;break;default:At(`getRenderingIntent - invalid annotationMode: ${t}`)}i&&(o+=eo.IS_EDITING),r&&(o+=eo.OPLIST);const{ids:l,hash:u}=c.modifiedIds,d=[o,a.hash,u];return{renderingIntent:o,cacheKey:d.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,rc))==null||n.reject(new Error("Worker was destroyed during onPassword callback"));const e=[];for(const i of f(this,da).values())e.push(i._destroy());f(this,da).clear(),f(this,Kh).clear(),f(this,Tm).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,Gh).clear(),this.filterFactory.destroy(),Ay.cleanup(),(i=f(this,ic))==null||i.cancelAllRequests(new pd("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)=>{Ys(f(this,ic),"GetReader - no `BasePDFStream` instance available."),R(this,Hr,f(this,ic).getFullReader()),f(this,Hr).onProgress=r=>H(this,_a,iS).call(this,r),i.onPull=()=>{f(this,Hr).read().then(function({value:r,done:o}){if(o){i.close();return}Ys(r instanceof ArrayBuffer,"GetReader - expected an ArrayBuffer."),i.enqueue(new Uint8Array(r),1,[r])}).catch(r=>{i.error(r)})},i.onCancel=r=>{f(this,Hr).cancel(r),i.ready.catch(o=>{if(!this.destroyed)throw o})}}),e.on("ReaderHeadersReady",async n=>{await f(this,Hr).headersReady;const{isStreamingSupported:i,isRangeSupported:r,contentLength:o}=f(this,Hr);return i&&r&&(f(this,Hr).onProgress=null),{isStreamingSupported:i,isRangeSupported:r,contentLength:o}}),e.on("GetRangeReader",(n,i)=>{Ys(f(this,ic),"GetRangeReader - no `BasePDFStream` instance available.");const r=f(this,ic).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}Ys(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 bne(n,this))}),e.on("DocException",n=>{t._capability.reject(hr(n))}),e.on("PasswordRequest",n=>{R(this,rc,Promise.withResolvers());try{if(!t.onPassword)throw hr(n);const i=r=>{r instanceof Error?f(this,rc).reject(r):f(this,rc).resolve({password:r})};t.onPassword(i,n.code)}catch(i){f(this,rc).reject(i)}return f(this,rc).promise}),e.on("DataLoaded",n=>{H(this,_a,iS).call(this,{loaded:n.length,total:n.length}),this.downloadInfoCapability.resolve(n)}),e.on("StartRenderPage",n=>{if(this.destroyed)return;f(this,da).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 h=r.error;At(`Error during font loading: ${h}`),this.commonObjs.resolve(n,h);break}const a=new Sse(r),c=this._params.pdfBug&&((o=globalThis.FontInspector)!=null&&o.enabled)?(h,p)=>globalThis.FontInspector.fontAdded(h,p):null,l=new bse(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;Ys(u,"The imageRef must be defined.");for(const h of f(this,da).values())for(const[,p]of h.objs){if((p==null?void 0:p.ref)!==u)continue;if(!p.dataLen)return null;const g=structuredClone(p);return this.commonObjs.resolve(n,g),p.dataLen}break;case"FontPath":this.commonObjs.resolve(n,new Cse(r));break;case"Image":this.commonObjs.resolve(n,r);break;case"Pattern":const d=new kse(r);this.commonObjs.resolve(n,d.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,da).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||H(this,_a,iS).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&&At("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,Hr))==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,d]of a){if((d==null?void 0:d.pageIndex)!==void 0&&d.pageIndex>=0&&d.pageIndex<c.length){const h=c[d.pageIndex]-1;if(h!==d.pageIndex){l.set(u,{...d,pageIndex:h});continue}}l.set(u,d)}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,Kh).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,Tm).set(o.refStr,n);const a=new CA(t,o,this,this.pagesMapper,this._params.pdfBug);return f(this,da).set(t,a),a});return f(this,Kh).set(t,r),r}async getPageIndex(e){if(!uA(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 H(this,_a,Av).call(this,"GetFieldObjects")}hasJSActions(){return H(this,_a,Av).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 H(this,_a,Av).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 H(this,_a,Av).call(this,"GetOptionalContentConfig").then(t=>new mne(t,e))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){const e="GetMetadata";return f(this,Gh).getOrInsertComputed(e,()=>this.messageHandler.sendWithPromise(e,null).then(t=>{var n,i;return{info:t[0],metadata:t[1]?new fne(t[1]):null,contentDispositionFilename:((n=f(this,Hr))==null?void 0:n.filename)??null,contentLength:((i=f(this,Hr))==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,da).values())if(!t.cleanup())throw new Error(`startCleanup: Page ${t.pageNumber} is currently rendering.`);this.commonObjs.clear(),e||this.fontLoader.clear(),f(this,Gh).clear(),this.filterFactory.destroy(!0),Ay.cleanup()}}cachedPageNumber(e){if(!uA(e))return null;const t=e.gen===0?`${e.num}R`:`${e.num}R${e.gen}`,n=f(this,Tm).get(t);if(n>=0){const i=this.pagesMapper.getPageNumber(n+1);if(i!==0)return i}return null}}Hr=new WeakMap,Gh=new WeakMap,ic=new WeakMap,da=new WeakMap,Kh=new WeakMap,Tm=new WeakMap,rc=new WeakMap,_a=new WeakSet,Av=function(e,t=null){return f(this,Gh).getOrInsertComputed(e,()=>this.messageHandler.sendWithPromise(e,t))},iS=function({loaded:e,total:t}){var n,i;(i=(n=this.loadingTask).onProgress)==null||i.call(n,{loaded:e,total:t,percent:t?zs(Math.round(e/t*100),0,100):NaN})};class wne{constructor(e){Se(this,"_internalRenderTask",null);Se(this,"onContinue",null);Se(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 $u,qh;const $d=class $d{constructor({callback:e,params:t,objs:n,commonObjs:i,annotationCanvasMap:r,operatorList:o,pageIndex:a,canvasFactory:c,filterFactory:l,useRequestAnimationFrame:u=!1,pdfBug:d=!1,pageColors:h=null,enableHWA:p=!1,operationsFilter:g=null}){B(this,$u,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=d,this.pageColors=h,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 wne(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=g}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($d,qh).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($d,qh).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 Rp(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,$u)&&(window.cancelAnimationFrame(f(this,$u)),R(this,$u,null)),f($d,qh).delete(this._canvas),e||(e=new xM(`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?R(this,$u,window.requestAnimationFrame(()=>{R(this,$u,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($d,qh).delete(this._canvas),this.callback())))}};$u=new WeakMap,qh=new WeakMap,B($d,qh,new WeakSet);let TA=$d;const Sne="6.0.227",kne="241dbabbf";Ct(3068);var Ur,Qh,Am,Dn,xb,Em,oc,Rb,Bu,ha,Ib,ks,AA,EA,MA,Pd,A$,Zc;const fr=class fr{constructor({editor:e=null,uiManager:t=null}){B(this,ks);B(this,Ur,null);B(this,Qh,null);B(this,Am);B(this,Dn,null);B(this,xb,!1);B(this,Em,!1);B(this,oc,null);B(this,Rb);B(this,Bu,null);B(this,ha,null);var n,i;e?(R(this,Em,!1),R(this,oc,e)):R(this,Em,!0),R(this,ha,(e==null?void 0:e._uiManager)||t),R(this,Rb,f(this,ha)._eventBus),R(this,Am,((n=e==null?void 0:e.color)==null?void 0:n.toUpperCase())||((i=f(this,ha))==null?void 0:i.highlightColors.values().next().value)||"#FFFF98"),f(fr,Ib)||R(fr,Ib,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 Mt(this,"_keyboardManager",new w_([[["Escape","mac+Escape"],fr.prototype._hideDropdownFromKeyboard],[[" ","mac+ "],fr.prototype._colorSelectFromKeyboard],[["ArrowDown","ArrowRight","mac+ArrowDown","mac+ArrowRight"],fr.prototype._moveToNext],[["ArrowUp","ArrowLeft","mac+ArrowUp","mac+ArrowLeft"],fr.prototype._moveToPrevious],[["Home","mac+Home"],fr.prototype._moveToBeginning],[["End","mac+End"],fr.prototype._moveToEnd]]))}renderButton(){const e=R(this,Ur,document.createElement("button"));e.className="colorPicker",e.tabIndex="0",e.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-button"),e.ariaHasPopup="true",f(this,oc)&&(e.ariaControls=`${f(this,oc).id}_colorpicker_dropdown`);const t=f(this,ha)._signal;e.addEventListener("click",H(this,ks,Pd).bind(this),{signal:t}),e.addEventListener("keydown",H(this,ks,MA).bind(this),{signal:t});const n=R(this,Qh,document.createElement("span"));return n.className="swatch",n.ariaHidden="true",n.style.backgroundColor=f(this,Am),e.append(n),e}renderMainDropdown(){const e=R(this,Dn,H(this,ks,AA).call(this));return e.ariaOrientation="horizontal",e.ariaLabelledBy="highlightColorPickerLabel",e}_colorSelectFromKeyboard(e){if(e.target===f(this,Ur)){H(this,ks,Pd).call(this,e);return}const t=e.target.getAttribute("data-color");t&&H(this,ks,EA).call(this,t,e)}_moveToNext(e){var t,n;if(!f(this,ks,Zc)){H(this,ks,Pd).call(this,e);return}if(e.target===f(this,Ur)){(t=f(this,Dn).firstElementChild)==null||t.focus();return}(n=e.target.nextSibling)==null||n.focus()}_moveToPrevious(e){var t,n;if(e.target===((t=f(this,Dn))==null?void 0:t.firstElementChild)||e.target===f(this,Ur)){f(this,ks,Zc)&&this._hideDropdownFromKeyboard();return}f(this,ks,Zc)||H(this,ks,Pd).call(this,e),(n=e.target.previousSibling)==null||n.focus()}_moveToBeginning(e){var t;if(!f(this,ks,Zc)){H(this,ks,Pd).call(this,e);return}(t=f(this,Dn).firstElementChild)==null||t.focus()}_moveToEnd(e){var t;if(!f(this,ks,Zc)){H(this,ks,Pd).call(this,e);return}(t=f(this,Dn).lastElementChild)==null||t.focus()}hideDropdown(){var e,t;(e=f(this,Dn))==null||e.classList.add("hidden"),f(this,Ur).ariaExpanded="false",(t=f(this,Bu))==null||t.abort(),R(this,Bu,null)}_hideDropdownFromKeyboard(){var e;if(!f(this,Em)){if(!f(this,ks,Zc)){(e=f(this,oc))==null||e.unselect();return}this.hideDropdown(),f(this,Ur).focus({preventScroll:!0,focusVisible:f(this,xb)})}}updateColor(e){if(f(this,Qh)&&(f(this,Qh).style.backgroundColor=e),!f(this,Dn))return;const t=f(this,ha).highlightColors.values();for(const n of f(this,Dn).children)n.ariaSelected=t.next().value===e.toUpperCase()}destroy(){var e,t;(e=f(this,Ur))==null||e.remove(),R(this,Ur,null),R(this,Qh,null),(t=f(this,Dn))==null||t.remove(),R(this,Dn,null)}};Ur=new WeakMap,Qh=new WeakMap,Am=new WeakMap,Dn=new WeakMap,xb=new WeakMap,Em=new WeakMap,oc=new WeakMap,Rb=new WeakMap,Bu=new WeakMap,ha=new WeakMap,Ib=new WeakMap,ks=new WeakSet,AA=function(){const e=document.createElement("div"),t=f(this,ha)._signal;e.addEventListener("contextmenu",Go,{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,oc)&&(e.id=`${f(this,oc).id}_colorpicker_dropdown`);for(const[n,i]of f(this,ha).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(fr,Ib)[n]);const o=document.createElement("span");r.append(o),o.className="swatch",o.style.backgroundColor=i,r.ariaSelected=i===f(this,Am),r.addEventListener("click",H(this,ks,EA).bind(this,i),{signal:t}),e.append(r)}return e.addEventListener("keydown",H(this,ks,MA).bind(this),{signal:t}),e},EA=function(e,t){t.stopPropagation(),f(this,Rb).dispatch("switchannotationeditorparams",{source:this,type:Rt.HIGHLIGHT_COLOR,value:e}),this.updateColor(e)},MA=function(e){fr._keyboardManager.exec(this,e)},Pd=function(e){if(f(this,ks,Zc)){this.hideDropdown();return}if(R(this,xb,e.detail===0),f(this,Bu)||(R(this,Bu,new AbortController),window.addEventListener("pointerdown",H(this,ks,A$).bind(this),{signal:f(this,ha).combinedSignal(f(this,Bu))})),f(this,Ur).ariaExpanded="true",f(this,Dn)){f(this,Dn).classList.remove("hidden");return}const t=R(this,Dn,H(this,ks,AA).call(this));f(this,Ur).append(t)},A$=function(e){var t;(t=f(this,Dn))!=null&&t.contains(e.target)||this.hideDropdown()},Zc=function(){return f(this,Dn)&&!f(this,Dn).classList.contains("hidden")},B(fr,Ib,null);let E0=fr;var Wr,Mm,Xh,ac,Pb;const Bd=class Bd{constructor(e){B(this,Wr,null);B(this,Mm,!1);B(this,Xh,null);B(this,ac,null);R(this,Xh,e),R(this,ac,e._uiManager),f(Bd,Pb)||R(Bd,Pb,Object.freeze({freetext:"pdfjs-editor-color-picker-free-text-input",ink:"pdfjs-editor-color-picker-ink-input"}))}renderButton(){if(f(this,Wr))return f(this,Wr);const{editorType:e,colorType:t,colorAndOpacityType:n,opacityType:i,color:r,opacity:o}=f(this,Xh),a=R(this,Mm,Rs.isAlphaColorInputSupported&&i!==void 0),c=R(this,Wr,document.createElement("input"));if(c.type="color",a){c.setAttribute("alpha","");const l=Fe.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(Bd,Pb)[e]),c.addEventListener("input",()=>{if(a){const l=b_(c.value);if(!l)return;const[u,d,h,p]=l,g=Fe.makeHexColor(u,d,h);n!==void 0?f(this,ac).updateParams(n,{color:g,opacity:p}):(f(this,ac).updateParams(t,g),f(this,ac).updateParams(i,p))}else f(this,ac).updateParams(t,c.value)},{signal:f(this,ac)._signal}),c}update(e){if(f(this,Wr))if(f(this,Mm)){const t=Fe.hexNums[Math.round(f(this,Xh).opacity*255)];f(this,Wr).value=e+t}else f(this,Wr).value=e}updateOpacity(e){if(!f(this,Wr)||!f(this,Mm))return;const t=Fe.hexNums[Math.round(e*255)];f(this,Wr).value=f(this,Xh).color+t}destroy(){var e;(e=f(this,Wr))==null||e.remove(),R(this,Wr,null)}hideDropdown(){}};Wr=new WeakMap,Mm=new WeakMap,Xh=new WeakMap,ac=new WeakMap,Pb=new WeakMap,B(Bd,Pb,null);let M0=Bd;Ct(531);function lP(s){return Math.floor(zs(s,0,1)*255).toString(16).padStart(2,"0")}function Fg(s){return zs(s,0,1)*255}class cP{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=Fg(e),[e,e,e]}static G_HTML([e]){const t=lP(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(Fg)}static RGB_HTML(e){return`#${e.map(lP).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[Fg(1-Math.min(1,e+i)),Fg(1-Math.min(1,n+i)),Fg(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 Cne{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){ss("Abstract method `_createSVG` called.")}}class x0 extends Cne{_createSVG(e){return document.createElementNS(Dr,e)}}const Tne=9,Ff=new WeakSet,Ane=new Date().getTimezoneOffset()*60*1e3;class gT{static create(e){switch(e.data.annotationType){case Sn.LINK:return new LM(e);case Sn.TEXT:return new Mne(e);case Sn.WIDGET:switch(e.data.fieldType){case"Tx":return new xne(e);case"Btn":return e.data.radioButton?new x$(e):e.data.checkBox?new Ine(e):new Pne(e);case"Ch":return new Lne(e);case"Sig":return new Rne(e)}return new zf(e);case Sn.POPUP:return new RA(e);case Sn.FREETEXT:return new O$(e);case Sn.LINE:return new Dne(e);case Sn.SQUARE:return new Nne(e);case Sn.CIRCLE:return new $ne(e);case Sn.POLYLINE:return new D$(e);case Sn.CARET:return new Fne(e);case Sn.INK:return new OM(e);case Sn.POLYGON:return new Bne(e);case Sn.HIGHLIGHT:return new N$(e);case Sn.UNDERLINE:return new Hne(e);case Sn.SQUIGGLY:return new Une(e);case Sn.STRIKEOUT:return new Wne(e);case Sn.STAMP:return new $$(e);case Sn.FILEATTACHMENT:return new zne(e);default:return new Zs(e)}}}var Yh,xm,Io,Lb,xA;const GM=class GM{constructor(e,{isRenderable:t=!1,ignoreBorder:n=!1,createQuadrilaterals:i=!1}={}){B(this,Lb);B(this,Yh,null);B(this,xm,!1);B(this,Io,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 GM._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(`${Sy}${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(`${Sy}${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,Io))==null?void 0:e.popup)||this.popup)==null||t.remove(),R(this,Io,this.popup=null)}updateEdited(e){var r;if(!this.container)return;e.rect&&(f(this,Yh)||R(this,Yh,{rect:this.data.rect.slice(0)}));const{rect:t,popup:n}=e;t&&H(this,Lb,xA).call(this,t);let i=((r=f(this,Io))==null?void 0:r.popup)||this.popup;!i&&(n!=null&&n.text)&&(this._createPopup(n),i=f(this,Io).popup),i&&(i.updateEdited(e),n!=null&&n.deleted&&(i.remove(),R(this,Io,null),this.popup=null))}resetEdited(){var e;f(this,Yh)&&(H(this,Lb,xA).call(this,f(this,Yh).rect),(e=f(this,Io))==null||e.popup.resetEdited(),R(this,Yh,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 zf)&&!(this instanceof LM)&&(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 RA){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,m=t.borderStyle.verticalCornerRadius;if(v>0||m>0){const _=`calc(${v}px * var(--total-scale-factor)) / calc(${m}px * var(--total-scale-factor))`;o.borderRadius=_}else if(this instanceof x$){const _=`calc(${a}px * var(--total-scale-factor)) / calc(${c}px * var(--total-scale-factor))`;o.borderRadius=_}switch(t.borderStyle.style){case bp.SOLID:o.borderStyle="solid";break;case bp.DASHED:o.borderStyle="dashed";break;case bp.BEVELED:At("Unimplemented border style: beveled");break;case bp.INSET:At("Unimplemented border style: inset");break;case bp.UNDERLINE:o.borderBottomStyle="solid";break}const y=t.borderColor||null;y?(R(this,xm,!0),o.borderColor=Fe.makeHexColor(...y)):o.borderWidth=0}const l=Fe.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:d,pageX:h,pageY:p}=i.rawDims;o.left=`${100*(l[0]-h)/u}%`,o.top=`${100*(l[1]-p)/d}%`;const{rotation:g}=t;return t.hasOwnCanvas||g===0?(o.width=`${100*a/u}%`,o.height=`${100*c/d}%`):this.setRotation(g,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]=cP[`${o}_HTML`](a),this.annotationStorage.setValue(this.data.id,{[n]:cP[`${o}_rgb`](a)})};return Mt(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,m,y,_]=e.subarray(2,6);if(i===v&&r===m&&t===y&&n===_)return}const{style:o}=this.container;let a;if(f(this,xm)){const{borderColor:v,borderWidth:m}=o;o.borderWidth=0,a=["url('data:image/svg+xml;utf8,",`<svg xmlns="${Dr}" preserveAspectRatio="none" viewBox="0 0 1 1">`,`<g fill="transparent" stroke="${v}" stroke-width="${m}">`],this.container.classList.add("hasBorder")}const c=i-t,l=r-n,{svgFactory:u}=this,d=u.createElement("svg");d.classList.add("quadrilateralsContainer"),d.setAttribute("width",0),d.setAttribute("height",0),d.role="none";const h=u.createElement("defs");d.append(h);const p=u.createElement("clipPath"),g=`clippath_${this.data.id}`;p.setAttribute("id",g),p.setAttribute("clipPathUnits","objectBoundingBox"),h.append(p);for(let v=2,m=e.length;v<m;v+=8){const y=e[v],_=e[v+1],b=e[v+2],k=e[v+3],w=u.createElement("rect"),T=(b-t)/c,A=(r-_)/l,C=(y-b)/c,E=(_-k)/l;w.setAttribute("x",T),w.setAttribute("y",A),w.setAttribute("width",C),w.setAttribute("height",E),p.append(w),a==null||a.push(`<rect vector-effect="non-scaling-stroke" x="${T}" y="${A}" width="${C}" height="${E}"/>`)}f(this,xm)&&(a.push("</g></svg>')"),o.backgroundImage=a.join("")),this.container.append(d),this.container.style.clipPath=`url(#${g})`}_createPopup(e=null){const{data:t}=this;let n,i;e?(n={str:e.text},i=e.date):(n=t.contentsObj,i=t.modificationDate),R(this,Io,new RA({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,Io)||this.popup||this.data.popupRef)}get extraPopupElement(){return f(this,Io)}render(){ss("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&&!Ff.has(l)){At(`_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&&Ff.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]}};Yh=new WeakMap,xm=new WeakMap,Io=new WeakMap,Lb=new WeakSet,xA=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 Zs=GM;class Ene extends Zs{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 no,Ld,E$,M$;class LM extends Zs{constructor(t,n=null){super(t,{isRenderable:!0,ignoreBorder:!!(n!=null&&n.ignoreBorder),createQuadrilaterals:!0});B(this,no);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?(H(this,no,E$).call(this,i,t.attachment,t.overlaidText,t.attachmentDest),r=!0):t.setOCGState?(H(this,no,M$).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==="")&&H(this,no,Ld).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),H(this,no,Ld).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),H(this,no,Ld).call(this)}_bindResetFormAction(t,n){const i=t.onclick;if(i||(t.href=this.linkService.getAnchorUrl("")),H(this,no,Ld).call(this),!this._fieldObjects){At('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.'),i||(t.onclick=()=>!1);return}t.onclick=()=>{var d;i==null||i();const{fields:r,refs:o,include:a}=n,c=[];if(r.length!==0||o.length!==0){const h=new Set(o);for(const p of r){const g=this._fieldObjects[p]||[];for(const{id:v}of g)h.add(v)}for(const p of Object.values(this._fieldObjects))for(const g of p)h.has(g.id)===a&&c.push(g)}else for(const h of Object.values(this._fieldObjects))c.push(...h);const l=this.annotationStorage,u=[];for(const h of c){const{id:p}=h;switch(u.push(p),h.type){case"text":{const v=h.defaultValue||"";l.setValue(p,{value:v});break}case"checkbox":case"radiobutton":{const v=h.defaultValue===h.exportValues;l.setValue(p,{value:v});break}case"combobox":case"listbox":{const v=h.defaultValue||"";l.setValue(p,{value:v});break}default:continue}const g=document.querySelector(`[data-element-id="${p}"]`);if(g){if(!Ff.has(g)){At(`_bindResetFormAction - element not allowed: ${p}`);continue}}else continue;g.dispatchEvent(new Event("resetform"))}return this.enableScripting&&((d=this.linkService.eventBus)==null||d.dispatch("dispatcheventinsandbox",{source:this,detail:{id:"app",ids:u,name:"ResetForm"}})),!1}}}no=new WeakSet,Ld=function(){this.container.setAttribute("data-internal-link","")},E$=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},H(this,no,Ld).call(this)},M$=function(t,n,i=""){t.href=this.linkService.getAnchorUrl(""),t.onclick=()=>(this.linkService.executeSetOCGState(n),!1),i&&(t.title=i),H(this,no,Ld).call(this)};class Mne extends Zs{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 zf extends Zs{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 Rs.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":Fe.makeHexColor(...t)}_setTextStyle(e){const t=["left","center","right"],{fontColor:n}=this.data.defaultAppearanceData,i=this.data.defaultAppearanceData.fontSize||Tne,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/(uT*i))||1,d=l/u;o=Math.min(i,c(d/uT))}else{const l=Math.abs(this.data.rect[3]-this.data.rect[1]-a);o=Math.min(i,c(l/uT))}r.fontSize=`calc(${o}px * var(--total-scale-factor))`,r.color=Fe.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 xne extends zf{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),Ff.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:d,datetimeType:h,timeStep:p}=this.data,g=!!h&&this.enableScripting;d&&(n.title=d),this._setRequired(n,this.data.required),c&&(n.maxLength=c),n.addEventListener("input",m=>{e.setValue(t,{value:m.target.value}),this.setPropertyOnSiblings(n,"value",m.target.value,"value"),u.formattedValue=null}),n.addEventListener("resetform",m=>{const y=this.data.defaultFieldValue??"";n.value=u.userValue=y,u.formattedValue=null});let v=m=>{const{formattedValue:y}=u;y!=null&&(m.target.value=y),m.target.scrollLeft=0};if(this.enableScripting&&this.hasJSActions){n.addEventListener("focus",y=>{var b;if(u.focused)return;const{target:_}=y;if(g&&(_.type=h,p&&(_.step=p)),u.userValue){const k=u.userValue;if(g)if(h==="time"){const w=new Date(k),T=[w.getHours(),w.getMinutes(),w.getSeconds()];_.value=T.map(A=>A.toString().padStart(2,"0")).join(":")}else _.value=new Date(k-Ane).toISOString().split(h==="date"?"T":".",1)[0];else _.value=k}u.lastCommittedValue=_.value,u.commitKey=1,(b=this.data.actions)!=null&&b.Focus||(u.focused=!0)}),n.addEventListener("updatefromsandbox",y=>{this.showElementAndHideCanvas(y.target);const _={value(b){u.userValue=b.detail.value??"",g||e.setValue(t,{value:u.userValue.toString()}),b.target.value=u.userValue},formattedValue(b){const{formattedValue:k}=b.detail;u.formattedValue=k,k!=null&&b.target!==document.activeElement&&(b.target.value=k);const w={formattedValue:k};g&&(w.value=k),e.setValue(t,w)},selRange(b){b.target.setSelectionRange(...b.detail.selRange)},charLimit:b=>{var A;const{charLimit:k}=b.detail,{target:w}=b;if(k===0){w.removeAttribute("maxLength");return}w.setAttribute("maxLength",k);let T=u.userValue;!T||T.length<=k||(T=T.slice(0,k),w.value=u.userValue=T,e.setValue(t,{value:T}),(A=this.linkService.eventBus)==null||A.dispatch("dispatcheventinsandbox",{source:this,detail:{id:t,name:"Keystroke",value:T,willCommit:!0,commitKey:1,selStart:w.selectionStart,selEnd:w.selectionEnd}}))}};this._dispatchEventFromSandbox(_,y)}),n.addEventListener("keydown",y=>{var k;u.commitKey=1;let _=-1;if(y.key==="Escape"?_=0:y.key==="Enter"&&!this.data.multiLine?_=2:y.key==="Tab"&&(u.commitKey=3),_===-1)return;const{value:b}=y.target;u.lastCommittedValue!==b&&(u.lastCommittedValue=b,u.userValue=b,(k=this.linkService.eventBus)==null||k.dispatch("dispatcheventinsandbox",{source:this,detail:{id:t,name:"Keystroke",value:b,willCommit:!0,commitKey:_,selStart:y.target.selectionStart,selEnd:y.target.selectionEnd}}))});const m=v;v=null,n.addEventListener("blur",y=>{var k,w;if(!u.focused||!y.relatedTarget)return;(k=this.data.actions)!=null&&k.Blur||(u.focused=!1);const{target:_}=y;let{value:b}=_;if(g){if(b&&h==="time"){const T=b.split(":").map(A=>parseInt(A,10));b=new Date(2e3,0,1,T[0],T[1],T[2]||0).valueOf(),_.step=""}else b.includes("T")||(b=`${b}T00:00`),b=new Date(b).valueOf();_.type="text"}u.userValue=b,u.lastCommittedValue!==b&&((w=this.linkService.eventBus)==null||w.dispatch("dispatcheventinsandbox",{source:this,detail:{id:t,name:"Keystroke",value:b,willCommit:!0,commitKey:u.commitKey,selStart:y.target.selectionStart,selEnd:y.target.selectionEnd}})),m(y)}),(r=this.data.actions)!=null&&r.Keystroke&&n.addEventListener("beforeinput",y=>{var E;u.lastCommittedValue=null;const{data:_,target:b}=y,{value:k,selectionStart:w,selectionEnd:T}=b;let A=w,C=T;switch(y.inputType){case"deleteWordBackward":{const x=k.substring(0,w).match(/\w*\W*$/);x&&(A-=x[0].length);break}case"deleteWordForward":{const x=k.substring(w).match(/^\W*\w*/);x&&(C+=x[0].length);break}case"deleteContentBackward":w===T&&(A-=1);break;case"deleteContentForward":w===T&&(C+=1);break}y.preventDefault(),(E=this.linkService.eventBus)==null||E.dispatch("dispatcheventinsandbox",{source:this,detail:{id:t,name:"Keystroke",value:k,change:_||"",willCommit:!1,selStart:A,selEnd:C}})}),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 Rne extends zf{constructor(e){super(e,{isRenderable:!!e.data.hasOwnCanvas})}}class Ine extends zf{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 Ff.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 x$ extends zf{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(Ff.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 d of this._getElementsByName(l.target.name)){const h=u&&d.id===n;d.domElement&&(d.domElement.checked=h),e.setValue(d.id,{value:h})}}};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 Pne extends LM{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 Lne extends zf{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");Ff.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",d=>{const h=this.data.defaultFieldValue;for(const p of i.options)p.selected=p.value===h});const o=(d,h)=>{const p=h.replaceAll(" "," ");d.textContent=p,p!==h&&d.setAttribute("display-value",h)};for(const d of this.data.options){const h=document.createElement("option");o(h,d.displayValue),h.value=d.exportValue,n.value.includes(d.exportValue)&&(h.setAttribute("selected",!0),r=!1),i.append(h)}let a=null;if(r){const d=document.createElement("option");d.value=" ",d.setAttribute("hidden",!0),d.setAttribute("selected",!0),i.prepend(d),a=()=>{d.remove(),i.removeEventListener("input",a),a=null},i.addEventListener("input",a)}const c=d=>{const h=d?"value":"textContent",{options:p,multiple:g}=i;return g?Array.prototype.filter.call(p,v=>v.selected).map(v=>v[h]):p.selectedIndex===-1?null:p[p.selectedIndex][h]};let l=c(!1);const u=d=>{const h=d.target.options;return Array.prototype.map.call(h,p=>({displayValue:p.getAttribute("display-value")||p.textContent,exportValue:p.value}))};return this.enableScripting&&this.hasJSActions?(i.addEventListener("updatefromsandbox",d=>{const h={value(p){a==null||a();const g=p.detail.value,v=new Set(Array.isArray(g)?g:[g]);for(const m of i.options)m.selected=v.has(m.value);e.setValue(t,{value:c(!0)}),l=c(!1)},multipleSelection(p){i.multiple=!0},remove(p){const g=i.options,v=p.detail.remove;g[v].selected=!1,i.remove(v),g.length>0&&Array.prototype.findIndex.call(g,y=>y.selected)===-1&&(g[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:g,displayValue:v,exportValue:m}=p.detail.insert,y=i.children[g],_=document.createElement("option");o(_,v),_.value=m,y?y.before(_):i.append(_),e.setValue(t,{value:c(!0),items:u(p)}),l=c(!1)},items(p){const{items:g}=p.detail;for(;i.length!==0;)i.remove(0);for(const v of g){const{displayValue:m,exportValue:y}=v,_=document.createElement("option");o(_,m),_.value=y,i.append(_)}i.options.length>0&&(i.options[0].selected=!0),e.setValue(t,{value:c(!0),items:u(p)}),l=c(!1)},indices(p){const g=new Set(p.detail.indices);for(const v of p.target.options)v.selected=g.has(v.index);e.setValue(t,{value:c(!0)}),l=c(!1)},editable(p){p.target.disabled=!p.detail.editable}};this._dispatchEventFromSandbox(h,d)}),i.addEventListener("input",d=>{var g;const h=c(!0),p=c(!1);e.setValue(t,{value:h}),d.preventDefault(),(g=this.linkService.eventBus)==null||g.dispatch("dispatcheventinsandbox",{source:this,detail:{id:t,name:"Keystroke",value:l,change:p,changeEx:h,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"]],d=>d.target.value)):i.addEventListener("input",function(d){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 Ob,IA;class RA extends Zs{constructor(t){const{data:n,elements:i,parent:r}=t,o=!!r._commentManager;super(t,{isRenderable:!o&&Zs._hasPopupData(n)});B(this,Ob);if(this.elements=i,o&&Zs._hasPopupData(n)){const a=this.popup=H(this,Ob,IA).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=H(this,Ob,IA).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=>`${Ap}${r}`).join(",")),this.container}}Ob=new WeakSet,IA=function(){return new One({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 zr,Fu,Z0,ek,Rm,Im,an,Xa,Hu,Jh,Pm,Lm,Ya,jr,lc,cc,ln,uc,Uu,Db,dc,Om,Zh,Wu,Wn,zu,$t,rS,PA,LA,OA,oS,DA,R$,I$,P$,L$,aS,lS,NA;class One{constructor({container:e,color:t,elements:n,titleObj:i,modificationDate:r,contentsObj:o,richText:a,parent:c,rect:l,parentRect:u,open:d,commentManager:h=null}){B(this,$t);B(this,zr,null);B(this,Fu,H(this,$t,P$).bind(this));B(this,Z0,H(this,$t,NA).bind(this));B(this,ek,H(this,$t,lS).bind(this));B(this,Rm,H(this,$t,aS).bind(this));B(this,Im,null);B(this,an,null);B(this,Xa,null);B(this,Hu,null);B(this,Jh,null);B(this,Pm,null);B(this,Lm,null);B(this,Ya,!1);B(this,jr,null);B(this,lc,null);B(this,cc,null);B(this,ln,null);B(this,uc,null);B(this,Uu,null);B(this,Db,null);B(this,dc,null);B(this,Om,null);B(this,Zh,null);B(this,Wu,!1);B(this,Wn,null);B(this,zu,null);R(this,an,e),R(this,Om,i),R(this,Xa,o),R(this,dc,a),R(this,Pm,c),R(this,Im,t),R(this,Db,l),R(this,Lm,u),R(this,Jh,n),R(this,zr,h),R(this,Wn,n[0]),R(this,Hu,C0.toDateObject(r)),this.trigger=n.flatMap(p=>p.getElementsToTriggerPopup()),h||(H(this,$t,rS).call(this),f(this,an).hidden=!0,d&&H(this,$t,aS).call(this))}renderCommentButton(){if(f(this,ln)){f(this,ln).parentNode||f(this,Wn).container.after(f(this,ln));return}if(f(this,uc)||H(this,$t,PA).call(this),!f(this,uc))return;const{signal:e}=R(this,lc,new AbortController),t=f(this,Wn).hasOwnCommentButton,n=()=>{f(this,zr).toggleCommentPopup(this,!0,void 0,!t)},i=()=>{f(this,zr).toggleCommentPopup(this,!1,!0,!t)},r=()=>{f(this,zr).toggleCommentPopup(this,!1,!1)};if(t){R(this,ln,f(this,Wn).container);for(const o of this.trigger)o.ariaHasPopup="dialog",o.ariaControls="commentPopup",o.addEventListener("keydown",f(this,Fu),{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=R(this,ln,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"),H(this,$t,OA).call(this),H(this,$t,LA).call(this),o.addEventListener("keydown",f(this,Fu),{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,Pm)._commentManager.makeCommentColor(e,t):null}focusCommentButton(){setTimeout(()=>{var e;(e=f(this,ln))==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,ln)}get comment(){return f(this,zu)||R(this,zu,f(this,Wn).commentText),f(this,zu)}set comment(e){e!==this.comment&&(f(this,Wn).commentText=R(this,zu,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,ln)&&(f(this,ln).classList.toggle("selected",e),f(this,ln).ariaExpanded=t)}setSelectedCommentButton(e){f(this,ln).classList.toggle("selected",e)}get commentPopupPosition(){if(f(this,Uu))return f(this,Uu);const{x:e,y:t,height:n}=f(this,ln).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){R(this,Uu,e)}hasDefaultPopupPosition(){return f(this,Uu)===null}get commentButtonPosition(){return f(this,uc)}get commentButtonWidth(){return f(this,ln).getBoundingClientRect().width/this.parentBoundingClientRect.width}editComment(e){const[t,n]=f(this,Uu)||this.commentButtonPosition.map(l=>l/100),i=this.parentBoundingClientRect,{x:r,y:o,width:a,height:c}=i;f(this,zr).showDialog(null,this,r+t*a,o+n*c,{...e,parentDimensions:i})}render(){var n,i;if(f(this,jr))return;const e=R(this,jr,document.createElement("div"));if(e.className="popup",f(this,Im)){const r=e.style.outlineColor=Fe.makeHexColor(...f(this,Im));e.style.backgroundColor=`color-mix(in srgb, ${r} 30%, white)`}const t=document.createElement("span");if(t.className="header",(n=f(this,Om))!=null&&n.str){const r=document.createElement("span");r.className="title",t.append(r),{dir:r.dir,str:r.textContent}=f(this,Om)}if(e.append(t),f(this,Hu)){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,Hu).valueOf()})),r.dateTime=f(this,Hu).toISOString(),t.append(r)}aN({html:f(this,$t,oS)||f(this,Xa).str,dir:(i=f(this,Xa))==null?void 0:i.dir,className:"popupContent"},e),f(this,an).append(e)}updateEdited({rect:e,popup:t,deleted:n}){var i;if(f(this,zr)){n?(this.remove(),R(this,zu,null)):t&&(t.deleted?this.remove():(H(this,$t,OA).call(this),R(this,zu,t.text))),e&&(R(this,uc,null),H(this,$t,PA).call(this),H(this,$t,LA).call(this));return}if(n||t!=null&&t.deleted){this.remove();return}H(this,$t,rS).call(this),f(this,Zh)||R(this,Zh,{contentsObj:f(this,Xa),richText:f(this,dc)}),e&&R(this,cc,null),t&&t.text&&(R(this,dc,H(this,$t,I$).call(this,t.text)),R(this,Hu,C0.toDateObject(t.date)),R(this,Xa,null)),(i=f(this,jr))==null||i.remove(),R(this,jr,null)}resetEdited(){var e;f(this,Zh)&&({contentsObj:Ls(this,Xa)._,richText:Ls(this,dc)._}=f(this,Zh),R(this,Zh,null),(e=f(this,jr))==null||e.remove(),R(this,jr,null),R(this,cc,null))}remove(){var e,t,n;if((e=f(this,lc))==null||e.abort(),R(this,lc,null),(t=f(this,jr))==null||t.remove(),R(this,jr,null),R(this,Wu,!1),R(this,Ya,!1),(n=f(this,ln))==null||n.remove(),R(this,ln,null),this.trigger)for(const i of this.trigger)i.classList.remove("popupTriggerArea")}forceHide(){R(this,Wu,this.isVisible),f(this,Wu)&&(f(this,an).hidden=!0)}maybeShow(){f(this,zr)||(H(this,$t,rS).call(this),f(this,Wu)&&(f(this,jr)||H(this,$t,lS).call(this),R(this,Wu,!1),f(this,an).hidden=!1))}get isVisible(){return f(this,zr)?!1:f(this,an).hidden===!1}}zr=new WeakMap,Fu=new WeakMap,Z0=new WeakMap,ek=new WeakMap,Rm=new WeakMap,Im=new WeakMap,an=new WeakMap,Xa=new WeakMap,Hu=new WeakMap,Jh=new WeakMap,Pm=new WeakMap,Lm=new WeakMap,Ya=new WeakMap,jr=new WeakMap,lc=new WeakMap,cc=new WeakMap,ln=new WeakMap,uc=new WeakMap,Uu=new WeakMap,Db=new WeakMap,dc=new WeakMap,Om=new WeakMap,Zh=new WeakMap,Wu=new WeakMap,Wn=new WeakMap,zu=new WeakMap,$t=new WeakSet,rS=function(){var t;if(f(this,lc))return;R(this,lc,new AbortController);const{signal:e}=f(this,lc);for(const n of this.trigger)n.addEventListener("click",f(this,Rm),{signal:e}),n.addEventListener("pointerenter",f(this,ek),{signal:e}),n.addEventListener("pointerleave",f(this,Z0),{signal:e}),n.classList.add("popupTriggerArea");for(const n of f(this,Jh))(t=n.container)==null||t.addEventListener("keydown",f(this,Fu),{signal:e})},PA=function(){const e=f(this,Jh).find(t=>t.hasCommentButton);e&&R(this,uc,e._normalizePoint(e.commentButtonPosition))},LA=function(){if(f(this,Wn).extraPopupElement&&!f(this,Wn).editor)return;f(this,ln)||this.renderCommentButton();const[e,t]=f(this,uc),{style:n}=f(this,ln);n.left=`calc(${e}%)`,n.top=`calc(${t}% - var(--comment-button-dim))`},OA=function(){f(this,Wn).extraPopupElement||(f(this,ln)||this.renderCommentButton(),f(this,ln).style.backgroundColor=this.commentButtonColor||"")},oS=function(){const e=f(this,dc),t=f(this,Xa);return e!=null&&e.str&&(!(t!=null&&t.str)||t.str===e.str)&&f(this,dc).html||null},DA=function(){var e,t,n;return((n=(t=(e=f(this,$t,oS))==null?void 0:e.attributes)==null?void 0:t.style)==null?void 0:n.fontSize)||0},R$=function(){var e,t,n;return((n=(t=(e=f(this,$t,oS))==null?void 0:e.attributes)==null?void 0:t.style)==null?void 0:n.color)||null},I$=function(e){const t=[],n={str:e,html:{name:"div",attributes:{dir:"auto"},children:[{name:"p",children:t}]}},i={style:{color:f(this,$t,R$),fontSize:f(this,$t,DA)?`calc(${f(this,$t,DA)}px * var(--total-scale-factor))`:""}};for(const r of e.split(`
|
||
`))t.push({name:"span",value:r,attributes:i});return n},P$=function(e){e.altKey||e.shiftKey||e.ctrlKey||e.metaKey||(e.key==="Enter"||e.key==="Escape"&&f(this,Ya))&&H(this,$t,aS).call(this)},L$=function(){if(f(this,cc)!==null)return;const{page:{view:e},viewport:{rawDims:{pageWidth:t,pageHeight:n,pageX:i,pageY:r}}}=f(this,Pm);let o=!!f(this,Lm),a=o?f(this,Lm):f(this,Db);for(const g of f(this,Jh))if(!a||Fe.intersect(g.data.rect,a)!==null){a=g.data.rect,o=!0;break}const c=Fe.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,d=c[0]+u,h=c[1];R(this,cc,[100*(d-i)/t,100*(h-r)/n]);const{style:p}=f(this,an);p.left=`${f(this,cc)[0]}%`,p.top=`${f(this,cc)[1]}%`},aS=function(){if(f(this,zr)){f(this,zr).toggleCommentPopup(this,!1);return}R(this,Ya,!f(this,Ya)),f(this,Ya)?(H(this,$t,lS).call(this),f(this,an).addEventListener("click",f(this,Rm)),f(this,an).addEventListener("keydown",f(this,Fu))):(H(this,$t,NA).call(this),f(this,an).removeEventListener("click",f(this,Rm)),f(this,an).removeEventListener("keydown",f(this,Fu)))},lS=function(){f(this,jr)||this.render(),this.isVisible?f(this,Ya)&&f(this,an).classList.add("focused"):(H(this,$t,L$).call(this),f(this,an).hidden=!1,f(this,an).style.zIndex=parseInt(f(this,an).style.zIndex,10)+1e3)},NA=function(){f(this,an).classList.remove("focused"),!(f(this,Ya)||!this.isVisible)&&(f(this,an).hidden=!0,f(this,an).style.zIndex=parseInt(f(this,an).style.zIndex,10)-1e3)};class O$ extends Zs{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0}),this.textContent=e.data.textContent,this.textPosition=e.data.textPosition,this.annotationEditorType=Et.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 Nb;class Dne extends Zs{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0});B(this,Nb,null)}render(){this.container.classList.add("lineAnnotation");const{data:t,width:n,height:i}=this,r=this.svgFactory.create(n,i,!0),o=R(this,Nb,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,Nb)}addHighlightArea(){this.container.classList.add("highlightArea")}}Nb=new WeakMap;var $b;class Nne extends Zs{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0});B(this,$b,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=R(this,$b,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,$b)}addHighlightArea(){this.container.classList.add("highlightArea")}}$b=new WeakMap;var Bb;class $ne extends Zs{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0});B(this,Bb,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=R(this,Bb,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,Bb)}addHighlightArea(){this.container.classList.add("highlightArea")}}Bb=new WeakMap;var Fb;class D$ extends Zs{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0});B(this,Fb,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 d=0,h=n.length;d<h;d+=2){const p=n[d]-t[0],g=t[3]-n[d+1];l.push(`${p},${g}`)}l=l.join(" ");const u=R(this,Fb,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,Fb)}addHighlightArea(){this.container.classList.add("highlightArea")}}Fb=new WeakMap;class Bne extends D${constructor(e){super(e),this.containerClassName="polygonAnnotation",this.svgElementName="svg:polygon"}}class Fne extends Zs{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 Hb,ef,Ub,$A;class OM extends Zs{constructor(t){super(t,{isRenderable:!0,ignoreBorder:!0});B(this,Ub);B(this,Hb,null);B(this,ef,[]);this.containerClassName="inkAnnotation",this.svgElementName="svg:polyline",this.annotationEditorType=this.data.it==="InkHighlight"?Et.HIGHLIGHT:Et.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}=H(this,Ub,$A).call(this,n,t),u=this.svgFactory.create(c,l,!0),d=R(this,Hb,this.svgFactory.createElement("svg:g"));u.append(d),d.setAttribute("stroke-width",r.width||1),d.setAttribute("stroke-linecap","round"),d.setAttribute("stroke-linejoin","round"),d.setAttribute("stroke-miterlimit",10),d.setAttribute("stroke","transparent"),d.setAttribute("fill","transparent"),d.setAttribute("transform",a);for(let h=0,p=i.length;h<p;h++){const g=this.svgFactory.createElement(this.svgElementName);f(this,ef).push(g),g.setAttribute("points",i[h].join(",")),d.append(g)}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,Hb);if(n>=0&&o.setAttribute("stroke-width",n||1),i)for(let a=0,c=f(this,ef).length;a<c;a++)f(this,ef)[a].setAttribute("points",i[a].join(","));if(r){const{transform:a,width:c,height:l}=H(this,Ub,$A).call(this,this.data.rotation,r);o.parentElement.setAttribute("viewBox",`0 0 ${c} ${l}`),o.setAttribute("transform",a)}}getElementsToTriggerPopup(){return f(this,ef)}addHighlightArea(){this.container.classList.add("highlightArea")}}Hb=new WeakMap,ef=new WeakMap,Ub=new WeakSet,$A=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 N$ extends Zs{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0,createQuadrilaterals:!0}),this.annotationEditorType=Et.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 Hne extends Zs{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 Une extends Zs{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 Wne extends Zs{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 $$ extends Zs{constructor(e){super(e,{isRenderable:!0,ignoreBorder:!0}),this.annotationEditorType=Et.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 Wb,zb,BA;class zne extends Zs{constructor(t){var i;super(t,{isRenderable:!0});B(this,zb);B(this,Wb,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",H(this,zb,BA).bind(this)),R(this,Wb,i);const{isMac:r}=Rs.platform;return t.addEventListener("keydown",o=>{o.key==="Enter"&&(r?o.metaKey:o.ctrlKey)&&H(this,zb,BA).call(this)}),!n.popupRef&&this.hasPopupData?(this.hasOwnCommentButton=!0,this._createPopup()):i.classList.add("popupTriggerArea"),t.append(i),t}getElementsToTriggerPopup(){return f(this,Wb)}addHighlightArea(){this.container.classList.add("highlightArea")}}Wb=new WeakMap,zb=new WeakSet,BA=function(){var t;(t=this.downloadManager)==null||t.openOrDownloadData(this.content,this.filename)};var tf,sf,Dm,ju,jb,nf,vr,Vb,Rc,cS,HA;const KM=class KM{constructor({div:e,accessibilityManager:t,annotationCanvasMap:n,annotationEditorUIManager:i,page:r,viewport:o,structTreeLayer:a,commentManager:c,linkService:l,annotationStorage:u}){B(this,Rc);B(this,tf,null);B(this,sf,null);B(this,Dm,null);B(this,ju,new Map);B(this,jb,null);B(this,nf,null);B(this,vr,[]);B(this,Vb,!1);Se(this,"zIndex",0);this.div=e,R(this,tf,t),R(this,sf,n),R(this,jb,a||null),R(this,nf,l||null),R(this,Dm,u||new IM),this.page=r,this.viewport=o,this._annotationEditorUIManager=i,this._commentManager=c||null}hasEditableAnnotations(){return f(this,ju).size>0}async render(e){var c;const{annotations:t,optionalContentConfig:n}=e,i=this.div;$f(i,this.viewport);const r=new Map,o=[],a={data:null,layer:i,linkService:f(this,nf),downloadManager:e.downloadManager,imageResourcesPath:e.imageResourcesPath||"",renderForms:e.renderForms!==!1,svgFactory:new x0,annotationStorage:f(this,Dm),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===Sn.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 d=gT.create(a);if(!d.isRenderable)continue;u||(f(this,vr).push(d),l.popupRef&&r.getOrInsertComputed(l.popupRef,AM).push(d));const h=d.render();l.hidden&&(h.style.visibility="hidden"),d.updateOC(n),d._isEditable&&(f(this,ju).set(d.data.id,d),(c=this._annotationEditorUIManager)==null||c.renderAnnotationElement(d))}await H(this,Rc,cS).call(this);for(const l of o){const u=a.elements=r.get(l.id);a.data=l;const d=gT.create(a);if(!d.isRenderable)continue;const h=d.render();d.contentElement.id=`${Ap}${l.id}`,l.hidden&&(h.style.visibility="hidden"),u.at(-1).container.after(h)}H(this,Rc,HA).call(this)}async addLinkAnnotations(e){const t={data:null,layer:this.div,linkService:f(this,nf),svgFactory:new x0,parent:this};for(const n of e){n.borderStyle||(n.borderStyle=KM._defaultBorderStyle),t.data=n;const i=gT.create(t);i.isRenderable&&(i.render(),i.contentElement.id=`${Ap}${n.id}`,f(this,vr).push(i))}await H(this,Rc,cS).call(this)}update({viewport:e,optionalContentConfig:t}){const n=this.div;this.viewport=e,$f(n,{rotation:e.rotation});for(const i of f(this,vr))i.updateOC(t);H(this,Rc,HA).call(this),n.hidden=!1}getEditableAnnotations(){return f(this,ju).values()}getEditableAnnotation(e){return f(this,ju).get(e)}addFakeAnnotation(e){const{div:t}=this,{id:n,rotation:i}=e,r=new Ene({data:{id:n,rect:e.getPDFRect(),rotation:i},editor:e,layer:t,parent:this,enableComment:!!this._commentManager,linkService:f(this,nf),annotationStorage:f(this,Dm)});return r.render(),r.contentElement.id=`${Ap}${n}`,r.createOrUpdatePopup(),f(this,vr).push(r),r}removeAnnotation(e){var i;const t=f(this,vr).findIndex(r=>r.data.id===e);if(t<0)return;const[n]=f(this,vr).splice(t,1);(i=f(this,tf))==null||i.removePointerInTextLayer(n.contentElement)}updateFakeAnnotations(e){if(e.length!==0){for(const t of e)t.updateFakeAnnotationElement(this);H(this,Rc,cS).call(this)}}togglePointerEvents(e=!1){this.div.classList.toggle("disabled",!e)}static get _defaultBorderStyle(){return Mt(this,"_defaultBorderStyle",Object.freeze({width:1,rawWidth:1,style:bp.SOLID,dashArray:[3],horizontalCornerRadius:0,verticalCornerRadius:0}))}};tf=new WeakMap,sf=new WeakMap,Dm=new WeakMap,ju=new WeakMap,jb=new WeakMap,nf=new WeakMap,vr=new WeakMap,Vb=new WeakMap,Rc=new WeakSet,cS=async function(){var n,i,r;if(f(this,vr).length===0)return;this.div.replaceChildren();const e=[];if(!f(this,Vb)){R(this,Vb,!0);for(const{contentElement:o,data:{id:a}}of f(this,vr)){const c=o.id=`${Ap}${a}`;e.push((n=f(this,jb))==null?void 0:n.getAriaAttributes(c).then(l=>{if(l)for(const[u,d]of l)o.setAttribute(u,d)}))}}f(this,vr).sort(({data:{rect:[o,a,c,l]}},{data:{rect:[u,d,h,p]}})=>{if(o===c&&a===l)return 1;if(u===h&&d===p)return-1;const g=l,v=a,m=(a+l)/2,y=p,_=d,b=(d+p)/2;if(m>=y&&b<=v)return-1;if(b>=g&&m<=_)return 1;const k=(o+c)/2,w=(u+h)/2;return k-w});const t=document.createDocumentFragment();for(const o of f(this,vr))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,tf))for(const o of f(this,vr))f(this,tf).addPointerInTextLayer(o.contentElement,!1)},HA=function(){var t;if(!f(this,sf))return;const e=this.div;for(const[n,i]of f(this,sf)){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,ju).get(n);a&&(a._hasNoCanvas?((t=this._annotationEditorUIManager)==null||t.setMissingCanvas(n,r.id,i),a._hasNoCanvas=!1):a.canvas=i)}f(this,sf).clear()};let FA=KM;const hw=/\r\n?|\n/g;var Vr,Gb,rf,Gr,En,B$,F$,H$,uS,Ic,dS,hS,U$,WA,W$;const Os=class Os extends cs{constructor(t){super({...t,name:"freeTextEditor"});B(this,En);B(this,Vr,"");B(this,Gb,`${this.id}-editor`);B(this,rf,null);B(this,Gr);Se(this,"_colorPicker",null);this.color=t.color||Os._defaultColor||cs._defaultLineColor,R(this,Gr,t.fontSize||Os._defaultFontSize),this.annotationElementId||this._uiManager.a11yAlert(cs._l10nAlert.freetext),this.canAddComment=!1}static get _keyboardManager(){const t=Os.prototype,n=o=>o.isEmpty(),i=Bf.TRANSLATE_SMALL,r=Bf.TRANSLATE_BIG;return Mt(this,"_keyboardManager",new w_([[["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){cs.initialize(t,n);const i=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(i.getPropertyValue("--freetext-padding"))}static updateDefaultParams(t,n){switch(t){case Rt.FREETEXT_SIZE:Os._defaultFontSize=n;break;case Rt.FREETEXT_COLOR:Os._defaultColor=n;break}}updateParams(t,n){switch(t){case Rt.FREETEXT_SIZE:H(this,En,B$).call(this,n);break;case Rt.FREETEXT_COLOR:H(this,En,F$).call(this,n);break}}static get defaultPropertiesToUpdate(){return[[Rt.FREETEXT_SIZE,Os._defaultFontSize],[Rt.FREETEXT_COLOR,Os._defaultColor||cs._defaultLineColor]]}get propertiesToUpdate(){return[[Rt.FREETEXT_SIZE,f(this,Gr)],[Rt.FREETEXT_COLOR,this.color]]}get toolbarButtons(){return this._colorPicker||(this._colorPicker=new M0(this)),[["colorPicker",this._colorPicker]]}get colorType(){return Rt.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[-Os._internalPadding*t,-(Os._internalPadding+f(this,Gr))*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"),R(this,rf,new AbortController);const t=this._uiManager.combinedSignal(f(this,rf));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,Gb)),this._isDraggable=!0,(t=f(this,rf))==null||t.abort(),R(this,rf,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,Vr),n=R(this,Vr,H(this,En,H$).call(this).trimEnd());if(t===n)return;const i=r=>{if(R(this,Vr,r),!r){this.remove();return}H(this,En,hS).call(this),this._uiManager.rebuild(this),H(this,En,uS).call(this)};this.addCommands({cmd:()=>{i(n)},undo:()=>{i(t)},mustExec:!1}),H(this,En,uS).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){Os._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,Gb)),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,Gr)}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,d]=this.pageDimensions,[h,p]=this.pageTranslation;let g,v;switch(this.rotation){case 0:g=t+(a[0]-h)/u,v=n+this.height-(a[1]-p)/d;break;case 90:g=t+(a[0]-h)/u,v=n-(a[1]-p)/d,[c,l]=[l,-c];break;case 180:g=t-this.width+(a[0]-h)/u,v=n-(a[1]-p)/d,[c,l]=[-c,-l];break;case 270:g=t+(a[0]-h-this.height*d)/u,v=n+(a[1]-p-this.width*u)/d,[c,l]=[-l,c];break}this.setAt(g*r,v*o,c,l)}else this._moveAfterPaste(t,n);H(this,En,hS).call(this),this._isDraggable=!0,this.editorDiv.contentEditable=!1}else this._isDraggable=!1,this.editorDiv.contentEditable=!0;return this.div}editorDivPaste(t){var g,v,m;const n=t.clipboardData||window.clipboardData,{types:i}=n;if(i.length===1&&i[0]==="text/plain")return;t.preventDefault();const r=H(g=Os,Ic,WA).call(g,n.getData("text")||"").replaceAll(hw,`
|
||
`);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=[],d=[];if(c.nodeType===Node.TEXT_NODE){const y=c.parentElement;if(d.push(c.nodeValue.slice(l).replaceAll(hw,"")),y!==this.editorDiv){let _=u;for(const b of this.editorDiv.childNodes){if(b===y){_=d;continue}_.push(H(v=Os,Ic,dS).call(v,b))}}u.push(c.nodeValue.slice(0,l).replaceAll(hw,""))}else if(c===this.editorDiv){let y=u,_=0;for(const b of this.editorDiv.childNodes)_++===l&&(y=d),y.push(H(m=Os,Ic,dS).call(m,b))}R(this,Vr,`${u.join(`
|
||
`)}${r}${d.join(`
|
||
`)}`),H(this,En,hS).call(this);const h=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 _=y.nodeValue.length;if(p<=_){h.setStart(y,p),h.setEnd(y,p);break}p-=_}o.removeAllRanges(),o.addRange(h)}get contentDiv(){return this.editorDiv}getPDFRect(){const t=Os._internalPadding*this.parentScale;return this.getRect(t,t)}static async deserialize(t,n,i){var a;let r=null;if(t instanceof O$){const{data:{defaultAppearanceData:{fontSize:c,fontColor:l},rect:u,rotation:d,id:h,popupRef:p,richText:g,contentsObj:v,creationDate:m,modificationDate:y},textContent:_,textPosition:b,parent:{page:{pageNumber:k}}}=t;if(!_||_.length===0)return null;r=t={annotationType:Et.FREETEXT,color:Array.from(l),fontSize:c,value:_.join(`
|
||
`),position:b,pageIndex:k-1,rect:u.slice(0),rotation:d,annotationElementId:h,id:h,deleted:!1,popupRef:p,comment:(v==null?void 0:v.str)||null,richText:g,creationDate:m,modificationDate:y}}const o=await super.deserialize(t,n,i);return R(o,Gr,t.fontSize),o.color=Fe.makeHexColor(...t.color),R(o,Vr,H(a=Os,Ic,WA).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=cs._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:this.color),i=Object.assign(super.serialize(t),{color:n,fontSize:f(this,Gr),value:H(this,En,U$).call(this)});return this.addComment(i),t?(i.isCopy=!0,i):this.annotationElementId&&!H(this,En,W$).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,Gr)}px * var(--total-scale-factor))`,i.color=this.color,n.replaceChildren();for(const r of f(this,Vr).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,Vr)}}),n}resetAnnotationElement(t){super.resetAnnotationElement(t),t.resetEdited()}};Vr=new WeakMap,Gb=new WeakMap,rf=new WeakMap,Gr=new WeakMap,En=new WeakSet,B$=function(t){const n=r=>{this.editorDiv.style.fontSize=`calc(${r}px * var(--total-scale-factor))`,this.translate(0,-(r-f(this,Gr))*this.parentScale),R(this,Gr,r),H(this,En,uS).call(this)},i=f(this,Gr);this.addCommands({cmd:n.bind(this,t),undo:n.bind(this,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:Rt.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})},F$=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:Rt.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})},H$=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(H(i=Os,Ic,dS).call(i,r)),n=r);return t.join(`
|
||
`)},uS=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()},Ic=new WeakSet,dS=function(t){return(t.nodeType===Node.TEXT_NODE?t.nodeValue:t.innerText).replaceAll(hw,"")},hS=function(){if(this.editorDiv.replaceChildren(),!!f(this,Vr))for(const t of f(this,Vr).split(`
|
||
`)){const n=document.createElement("div");n.append(t?document.createTextNode(t):document.createElement("br")),this.editorDiv.append(n)}},U$=function(){return f(this,Vr).replaceAll(" "," ")},WA=function(t){return t.replaceAll(" "," ")},W$=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},B(Os,Ic),Se(Os,"_freeTextDefaultContent",""),Se(Os,"_internalPadding",0),Se(Os,"_defaultColor",null),Se(Os,"_defaultFontSize",10),Se(Os,"_type","freetext"),Se(Os,"_editorType",Et.FREETEXT);let UA=Os;class Je{toSVGPath(){ss("Abstract method `toSVGPath` must be implemented.")}get box(){ss("Abstract getter `box` must be implemented.")}serialize(e,t){ss("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]}}Se(Je,"PRECISION",1e-4);var Kr,fa,Nm,$m,Ja,zt,of,af,Kb,qb,Bm,Fm,Vu,Qb,tk,sk,Nn,Ev,z$,j$,V$,G$,K$,q$;const Dl=class Dl{constructor({x:e,y:t},n,i,r,o,a=0){B(this,Nn);B(this,Kr);B(this,fa,[]);B(this,Nm);B(this,$m);B(this,Ja,[]);B(this,zt,new Float32Array(18));B(this,of);B(this,af);B(this,Kb);B(this,qb);B(this,Bm);B(this,Fm);B(this,Vu,[]);R(this,Kr,n),R(this,Fm,r*i),R(this,$m,o),f(this,zt).set([NaN,NaN,NaN,NaN,e,t],6),R(this,Nm,a),R(this,qb,f(Dl,Qb)*i),R(this,Kb,f(Dl,sk)*i),R(this,Bm,i),f(this,Vu).push(e,t)}isEmpty(){return isNaN(f(this,zt)[8])}add({x:e,y:t}){var E;R(this,of,e),R(this,af,t);const[n,i,r,o]=f(this,Kr);let[a,c,l,u]=f(this,zt).subarray(8,12);const d=e-l,h=t-u,p=Math.hypot(d,h);if(p<f(this,Kb))return!1;const g=p-f(this,qb),v=g/p,m=v*d,y=v*h;let _=a,b=c;a=l,c=u,l+=m,u+=y,(E=f(this,Vu))==null||E.push(e,t);const k=-y/g,w=m/g,T=k*f(this,Fm),A=w*f(this,Fm);return f(this,zt).set(f(this,zt).subarray(2,8),0),f(this,zt).set([l+T,u+A],4),f(this,zt).set(f(this,zt).subarray(14,18),12),f(this,zt).set([l-T,u-A],16),isNaN(f(this,zt)[6])?(f(this,Ja).length===0&&(f(this,zt).set([a+T,c+A],2),f(this,Ja).push(NaN,NaN,NaN,NaN,(a+T-n)/r,(c+A-i)/o),f(this,zt).set([a-T,c-A],14),f(this,fa).push(NaN,NaN,NaN,NaN,(a-T-n)/r,(c-A-i)/o)),f(this,zt).set([_,b,a,c,l,u],6),!this.isEmpty()):(f(this,zt).set([_,b,a,c,l,u],6),Math.abs(Math.atan2(b-c,_-a)-Math.atan2(y,m))<Math.PI/2?([a,c,l,u]=f(this,zt).subarray(2,6),f(this,Ja).push(NaN,NaN,NaN,NaN,((a+l)/2-n)/r,((c+u)/2-i)/o),[a,c,_,b]=f(this,zt).subarray(14,18),f(this,fa).push(NaN,NaN,NaN,NaN,((_+a)/2-n)/r,((b+c)/2-i)/o),!0):([_,b,a,c,l,u]=f(this,zt).subarray(0,6),f(this,Ja).push(((_+5*a)/6-n)/r,((b+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,zt).subarray(12,18),f(this,fa).push(((_+5*a)/6-n)/r,((b+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,Ja),t=f(this,fa);if(isNaN(f(this,zt)[6])&&!this.isEmpty())return H(this,Nn,z$).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]}`);H(this,Nn,V$).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 H(this,Nn,j$).call(this,n),n.join(" ")}newFreeDrawOutline(e,t,n,i,r,o){return new Q$(e,t,n,i,r,o)}getOutlines(){var d;const e=f(this,Ja),t=f(this,fa),n=f(this,zt),[i,r,o,a]=f(this,Kr),c=new Float32Array((((d=f(this,Vu))==null?void 0:d.length)??0)+2);for(let h=0,p=c.length-2;h<p;h+=2)c[h]=(f(this,Vu)[h]-i)/o,c[h+1]=(f(this,Vu)[h+1]-r)/a;if(c[c.length-2]=(f(this,of)-i)/o,c[c.length-1]=(f(this,af)-r)/a,isNaN(n[6])&&!this.isEmpty())return H(this,Nn,G$).call(this,c);const l=new Float32Array(f(this,Ja).length+24+f(this,fa).length);let u=e.length;for(let h=0;h<u;h+=2){if(isNaN(e[h])){l[h]=l[h+1]=NaN;continue}l[h]=e[h],l[h+1]=e[h+1]}u=H(this,Nn,q$).call(this,l,u);for(let h=t.length-6;h>=6;h-=6)for(let p=0;p<6;p+=2){if(isNaN(t[h+p])){l[u]=l[u+1]=NaN,u+=2;continue}l[u]=t[h+p],l[u+1]=t[h+p+1],u+=2}return H(this,Nn,K$).call(this,l,u),this.newFreeDrawOutline(l,c,f(this,Kr),f(this,Bm),f(this,Nm),f(this,$m))}};Kr=new WeakMap,fa=new WeakMap,Nm=new WeakMap,$m=new WeakMap,Ja=new WeakMap,zt=new WeakMap,of=new WeakMap,af=new WeakMap,Kb=new WeakMap,qb=new WeakMap,Bm=new WeakMap,Fm=new WeakMap,Vu=new WeakMap,Qb=new WeakMap,tk=new WeakMap,sk=new WeakMap,Nn=new WeakSet,Ev=function(){const e=f(this,zt).subarray(4,6),t=f(this,zt).subarray(16,18),[n,i,r,o]=f(this,Kr);return[(f(this,of)+(e[0]-t[0])/2-n)/r,(f(this,af)+(e[1]-t[1])/2-i)/o,(f(this,of)+(t[0]-e[0])/2-n)/r,(f(this,af)+(t[1]-e[1])/2-i)/o]},z$=function(){const[e,t,n,i]=f(this,Kr),[r,o,a,c]=H(this,Nn,Ev).call(this);return`M${(f(this,zt)[2]-e)/n} ${(f(this,zt)[3]-t)/i} L${(f(this,zt)[4]-e)/n} ${(f(this,zt)[5]-t)/i} L${r} ${o} L${a} ${c} L${(f(this,zt)[16]-e)/n} ${(f(this,zt)[17]-t)/i} L${(f(this,zt)[14]-e)/n} ${(f(this,zt)[15]-t)/i} Z`},j$=function(e){const t=f(this,fa);e.push(`L${t[4]} ${t[5]} Z`)},V$=function(e){const[t,n,i,r]=f(this,Kr),o=f(this,zt).subarray(4,6),a=f(this,zt).subarray(16,18),[c,l,u,d]=H(this,Nn,Ev).call(this);e.push(`L${(o[0]-t)/i} ${(o[1]-n)/r} L${c} ${l} L${u} ${d} L${(a[0]-t)/i} ${(a[1]-n)/r}`)},G$=function(e){const t=f(this,zt),[n,i,r,o]=f(this,Kr),[a,c,l,u]=H(this,Nn,Ev).call(this),d=new Float32Array(36);return d.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(d,e,f(this,Kr),f(this,Bm),f(this,Nm),f(this,$m))},K$=function(e,t){const n=f(this,fa);return e.set([NaN,NaN,NaN,NaN,n[4],n[5]],t),t+=6},q$=function(e,t){const n=f(this,zt).subarray(4,6),i=f(this,zt).subarray(16,18),[r,o,a,c]=f(this,Kr),[l,u,d,h]=H(this,Nn,Ev).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,d,h,NaN,NaN,NaN,NaN,(i[0]-r)/a,(i[1]-o)/c],t),t+=24},B(Dl,Qb,8),B(Dl,tk,2),B(Dl,sk,f(Dl,Qb)+f(Dl,tk));let R0=Dl;var Hm,lf,hc,Xb,qr,Yb,bn,nk,X$;class Q$ extends Je{constructor(t,n,i,r,o,a){super();B(this,nk);B(this,Hm);B(this,lf,new Float32Array(4));B(this,hc);B(this,Xb);B(this,qr);B(this,Yb);B(this,bn);R(this,bn,t),R(this,qr,n),R(this,Hm,i),R(this,Yb,r),R(this,hc,o),R(this,Xb,a),this.firstPoint=[NaN,NaN],this.lastPoint=[NaN,NaN],H(this,nk,X$).call(this,a);const[c,l,u,d]=f(this,lf);for(let h=0,p=t.length;h<p;h+=2)t[h]=(t[h]-c)/u,t[h+1]=(t[h+1]-l)/d;for(let h=0,p=n.length;h<p;h+=2)n[h]=(n[h]-c)/u,n[h+1]=(n[h+1]-l)/d}toSVGPath(){const t=[`M${f(this,bn)[4]} ${f(this,bn)[5]}`];for(let n=6,i=f(this,bn).length;n<i;n+=6){if(isNaN(f(this,bn)[n])){t.push(`L${f(this,bn)[n+4]} ${f(this,bn)[n+5]}`);continue}t.push(`C${f(this,bn)[n]} ${f(this,bn)[n+1]} ${f(this,bn)[n+2]} ${f(this,bn)[n+3]} ${f(this,bn)[n+4]} ${f(this,bn)[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=Je._rescale(f(this,bn),t,r,a,-c),u=Je._rescale(f(this,qr),t,r,a,-c);break;case 90:l=Je._rescaleAndSwap(f(this,bn),t,n,a,c),u=Je._rescaleAndSwap(f(this,qr),t,n,a,c);break;case 180:l=Je._rescale(f(this,bn),i,n,-a,c),u=Je._rescale(f(this,qr),i,n,-a,c);break;case 270:l=Je._rescaleAndSwap(f(this,bn),i,r,-a,-c),u=Je._rescaleAndSwap(f(this,qr),i,r,-a,-c);break}return{outline:Array.from(l),points:[Array.from(u)]}}get box(){return f(this,lf)}newOutliner(t,n,i,r,o,a=0){return new R0(t,n,i,r,o,a)}getNewOutline(t,n){const[i,r,o,a]=f(this,lf),[c,l,u,d]=f(this,Hm),h=o*u,p=a*d,g=i*u+c,v=r*d+l,m=this.newOutliner({x:f(this,qr)[0]*h+g,y:f(this,qr)[1]*p+v},f(this,Hm),f(this,Yb),t,f(this,Xb),n??f(this,hc));for(let y=2;y<f(this,qr).length;y+=2)m.add({x:f(this,qr)[y]*h+g,y:f(this,qr)[y+1]*p+v});return m.getOutlines()}}Hm=new WeakMap,lf=new WeakMap,hc=new WeakMap,Xb=new WeakMap,qr=new WeakMap,Yb=new WeakMap,bn=new WeakMap,nk=new WeakSet,X$=function(t){const n=f(this,bn);let i=n[4],r=n[5];const o=[i,r,i,r];let a=i,c=r,l=i,u=r;const d=t?Math.max:Math.min,h=new Float32Array(4);for(let g=6,v=n.length;g<v;g+=6){const m=n[g+4],y=n[g+5];isNaN(n[g])?(Fe.pointBoundingBox(m,y,o),c>y?(a=m,c=y):c===y&&(a=d(a,m)),u<y?(l=m,u=y):u===y&&(l=d(l,m))):(h.set(Sc,0),Fe.bezierBoundingBox(i,r,...n.slice(g,g+6),h),Fe.rectBoundingBox(...h,o),c>h[1]?(a=h[0],c=h[1]):c===h[1]&&(a=d(a,h[0])),u<h[3]?(l=h[2],u=h[3]):u===h[3]&&(l=d(l,h[2]))),i=m,r=y}const p=f(this,lf);p[0]=o[0]-f(this,hc),p[1]=o[1]-f(this,hc),p[2]=o[2]-o[0]+2*f(this,hc),p[3]=o[3]-o[1]+2*f(this,hc),this.firstPoint=[a,c],this.lastPoint=[l,u]};var Jb,Zb,e_,Gu,pa,ir,Y$,fS,J$,Z$,jA;class zA{constructor(e,t=0,n=0,i=!0){B(this,ir);B(this,Jb);B(this,Zb);B(this,e_);B(this,Gu,[]);B(this,pa,[]);const r=Sc.slice(),o=10**-4;for(const{x:v,y:m,width:y,height:_}of e){const b=Math.floor((v-t)/o)*o,k=Math.ceil((v+y+t)/o)*o,w=Math.floor((m-t)/o)*o,T=Math.ceil((m+_+t)/o)*o,A=[b,w,T,!0],C=[k,w,T,!1];f(this,Gu).push(A,C),Fe.rectBoundingBox(b,w,k,T,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 d=i?-1/0:1/0,h=1/0;const p=f(this,Gu).at(i?-1:-2),g=[p[0],p[2]];for(const v of f(this,Gu)){const[m,y,_,b]=v;!b&&i?y<h?(h=y,d=m):y===h&&(d=Math.max(d,m)):b&&!i&&(y<h?(h=y,d=m):y===h&&(d=Math.min(d,m))),v[0]=(m-l)/a,v[1]=(y-u)/c,v[2]=(_-u)/c}R(this,Jb,new Float32Array([l,u,a,c])),R(this,Zb,[d,h]),R(this,e_,g)}getOutlines(){f(this,Gu).sort((t,n)=>t[0]-n[0]||t[1]-n[1]||t[2]-n[2]);const e=[];for(const t of f(this,Gu))t[3]?(e.push(...H(this,ir,jA).call(this,t)),H(this,ir,J$).call(this,t)):(H(this,ir,Z$).call(this,t),e.push(...H(this,ir,jA).call(this,t)));return H(this,ir,Y$).call(this,e)}}Jb=new WeakMap,Zb=new WeakMap,e_=new WeakMap,Gu=new WeakMap,pa=new WeakMap,ir=new WeakSet,Y$=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,d]=o;n.delete(o);let h=a,p=c;for(r=[a,l],i.push(r);;){let g;if(n.has(u))g=u;else if(n.has(d))g=d;else break;n.delete(g),[a,c,l,u,d]=g,h!==a&&(r.push(h,p,a,p===c?c:l),h=a),p=p===c?l:c}r.push(h,p)}return new jne(i,f(this,Jb),f(this,Zb),f(this,e_))},fS=function(e){const t=f(this,pa);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},J$=function([,e,t]){const n=H(this,ir,fS).call(this,e);f(this,pa).splice(n,0,[e,t])},Z$=function([,e,t]){const n=H(this,ir,fS).call(this,e);for(let i=n;i<f(this,pa).length;i++){const[r,o]=f(this,pa)[i];if(r!==e)break;if(r===e&&o===t){f(this,pa).splice(i,1);return}}for(let i=n-1;i>=0;i--){const[r,o]=f(this,pa)[i];if(r!==e)break;if(r===e&&o===t){f(this,pa).splice(i,1);return}}},jA=function(e){const[t,n,i]=e,r=[[t,n,i]],o=H(this,ir,fS).call(this,i);for(let a=0;a<o;a++){const[c,l]=f(this,pa)[a];for(let u=0,d=r.length;u<d;u++){const[,h,p]=r[u];if(!(l<=h||p<=c)){if(h>=c){if(p>l)r[u][1]=l;else{if(d===1)return[];r.splice(u,1),u--,d--}continue}r[u][2]=c,p>l&&r.push([t,l,p])}}}return r};var t_,Um;class jne extends Je{constructor(t,n,i,r){super();B(this,t_);B(this,Um);R(this,Um,t),R(this,t_,n),this.firstPoint=i,this.lastPoint=r}toSVGPath(){const t=[];for(const n of f(this,Um)){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,Um)){const d=new Array(u.length);for(let h=0;h<u.length;h+=2)d[h]=t+u[h]*c,d[h+1]=r-u[h+1]*l;a.push(d)}return a}get box(){return f(this,t_)}get classNamesForOutlining(){return["highlightOutline"]}}t_=new WeakMap,Um=new WeakMap;class VA extends R0{newFreeDrawOutline(e,t,n,i,r,o){return new Vne(e,t,n,i,r,o)}}class Vne extends Q${newOutliner(e,t,n,i,r,o=0){return new VA(e,t,n,i,r,o)}}var Wm,s_,fc,cf,n_,yr,i_,r_,uf,Qr,Xr,ii,zm,jm,Si,Vm,Po,o_,Nt,GA,pS,eB,tB,sB,KA,Od,Fo,kp,nB,mS,gS,iB,rB,oB,aB,lB;const es=class es extends cs{constructor(t){super({...t,name:"highlightEditor"});B(this,Nt);B(this,Wm,null);B(this,s_,0);B(this,fc);B(this,cf,null);B(this,n_,null);B(this,yr,null);B(this,i_,null);B(this,r_,0);B(this,uf,null);B(this,Qr,null);B(this,Xr,null);B(this,ii,!1);B(this,zm,null);B(this,jm,null);B(this,Si,null);B(this,Vm,"");B(this,Po);B(this,o_,"");this.color=t.color||es._defaultColor,R(this,Po,t.thickness||es._defaultThickness),this.opacity=t.opacity||es._defaultOpacity,R(this,fc,t.boxes||null),R(this,o_,t.methodOfCreation||""),R(this,Vm,t.text||""),this._isDraggable=!1,this.defaultL10nId="pdfjs-editor-highlight-editor",t.highlightId>-1?(R(this,ii,!0),H(this,Nt,pS).call(this,t),H(this,Nt,Od).call(this)):f(this,fc)&&(R(this,Wm,t.anchorNode),R(this,s_,t.anchorOffset),R(this,i_,t.focusNode),R(this,r_,t.focusOffset),H(this,Nt,GA).call(this),H(this,Nt,Od).call(this),this.rotate(this.rotation)),this.annotationElementId||this._uiManager.a11yAlert(cs._l10nAlert.highlight)}static get _keyboardManager(){const t=es.prototype;return Mt(this,"_keyboardManager",new w_([[["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,ii)?"free_highlight":"highlight",color:this._uiManager.getNonHCMColorName(this.color),thickness:f(this,Po),methodOfCreation:f(this,o_)}}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;cs.initialize(t,n),es._defaultColor||(es._defaultColor=((i=n.highlightColors)==null?void 0:i.values().next().value)||"#fff066")}static updateDefaultParams(t,n){switch(t){case Rt.HIGHLIGHT_COLOR:es._defaultColor=n;break;case Rt.HIGHLIGHT_THICKNESS:es._defaultThickness=n;break}}translateInPage(t,n){}get toolbarPosition(){return f(this,jm)}get commentButtonPosition(){return f(this,zm)}updateParams(t,n){switch(t){case Rt.HIGHLIGHT_COLOR:H(this,Nt,eB).call(this,n);break;case Rt.HIGHLIGHT_THICKNESS:H(this,Nt,tB).call(this,n);break}}static get defaultPropertiesToUpdate(){return[[Rt.HIGHLIGHT_COLOR,es._defaultColor],[Rt.HIGHLIGHT_THICKNESS,es._defaultThickness]]}get propertiesToUpdate(){return[[Rt.HIGHLIGHT_COLOR,this.color||es._defaultColor],[Rt.HIGHLIGHT_THICKNESS,f(this,Po)||es._defaultThickness],[Rt.HIGHLIGHT_FREE,f(this,ii)]]}onUpdatedColor(){var t,n;(t=this.parent)==null||t.drawLayer.updateProperties(f(this,Xr),{root:{fill:this.color,"fill-opacity":this.opacity}}),(n=f(this,n_))==null||n.updateColor(this.color),super.onUpdatedColor()}get toolbarButtons(){return this._uiManager.highlightColors?[["colorPicker",R(this,n_,new E0({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(H(this,Nt,gS).call(this))}getBaseTranslation(){return[0,0]}getRect(t,n){return super.getRect(t,n,H(this,Nt,gS).call(this))}onceAdded(t){this.annotationElementId||this.parent.addUndoableEditor(this),t&&this.div.focus()}remove(){H(this,Nt,KA).call(this),this._reportTelemetry({action:"deleted"}),super.remove()}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(H(this,Nt,Od).call(this),this.isAttachedToDOM||this.parent.add(this)))}setParent(t){var i;let n=!1;this.parent&&!t?H(this,Nt,KA).call(this):t&&(H(this,Nt,Od).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,ii)?(t=(t-this.rotation+360)%360,i=H(r=es,Fo,kp).call(r,f(this,Qr).box,t)):i=H(o=es,Fo,kp).call(o,[this.x,this.y,this.width,this.height],t),n.updateProperties(f(this,Xr),{bbox:i,root:{"data-main-rotation":t}}),n.updateProperties(f(this,Si),{bbox:H(a=es,Fo,kp).call(a,f(this,yr).box,t),root:{"data-main-rotation":t}})}render(){if(this.div)return this.div;const t=super.render();f(this,Vm)&&(t.setAttribute("aria-label",f(this,Vm)),t.setAttribute("role","mark")),f(this,ii)?t.classList.add("free"):this.div.addEventListener("keydown",H(this,Nt,nB).bind(this),{signal:this._uiManager._signal});const n=R(this,uf,document.createElement("div"));return t.append(n),n.setAttribute("aria-hidden","true"),n.className="internal",n.style.clipPath=f(this,cf),this.setDims(),pN(this,f(this,uf),["pointerover","pointerleave"]),this.enableEditing(),t}pointerover(){var t;this.isSelected||(t=this.parent)==null||t.drawLayer.updateProperties(f(this,Si),{rootClass:{hovered:!0}})}pointerleave(){var t;this.isSelected||(t=this.parent)==null||t.drawLayer.updateProperties(f(this,Si),{rootClass:{hovered:!1}})}_moveCaret(t){switch(this.parent.unselect(this),t){case 0:case 2:H(this,Nt,mS).call(this,!0);break;case 1:case 3:H(this,Nt,mS).call(this,!1);break}}select(){var t;super.select(),f(this,Si)&&((t=this.parent)==null||t.drawLayer.updateProperties(f(this,Si),{rootClass:{hovered:!1,selected:!0}}))}unselect(){var t;super.unselect(),f(this,Si)&&((t=this.parent)==null||t.drawLayer.updateProperties(f(this,Si),{rootClass:{selected:!1}}),f(this,ii)||H(this,Nt,mS).call(this,!1))}get _mustFixPosition(){return!f(this,ii)}show(t=this._isVisible){super.show(t),this.parent&&(this.parent.drawLayer.updateProperties(f(this,Xr),{rootClass:{hidden:!t}}),this.parent.drawLayer.updateProperties(f(this,Si),{rootClass:{hidden:!t}}))}static startHighlighting(t,n,{target:i,x:r,y:o}){const{x:a,y:c,width:l,height:u}=i.getBoundingClientRect(),d=new AbortController,h=t.combinedSignal(d),p=g=>{d.abort(),H(this,Fo,aB).call(this,t,g)};window.addEventListener("blur",p,{signal:h}),window.addEventListener("pointerup",p,{signal:h}),window.addEventListener("pointerdown",Xs,{capture:!0,passive:!1,signal:h}),window.addEventListener("contextmenu",Go,{signal:h}),i.addEventListener("pointermove",H(this,Fo,oB).bind(this,t),{signal:h}),this._freeHighlight=new VA({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 m,y,_,b;let r=null;if(t instanceof N$){const{data:{quadPoints:k,rect:w,rotation:T,id:A,color:C,opacity:E,popupRef:x,richText:D,contentsObj:N,creationDate:O,modificationDate:G},parent:{page:{pageNumber:Z}}}=t;r=t={annotationType:Et.HIGHLIGHT,color:Array.from(C),opacity:E,quadPoints:k,boxes:null,pageIndex:Z-1,rect:w.slice(0),rotation:T,annotationElementId:A,id:A,deleted:!1,popupRef:x,richText:D,comment:(N==null?void 0:N.str)||null,creationDate:O,modificationDate:G}}else if(t instanceof OM){const{data:{inkLists:k,rect:w,rotation:T,id:A,color:C,borderStyle:{rawWidth:E},popupRef:x,richText:D,contentsObj:N,creationDate:O,modificationDate:G},parent:{page:{pageNumber:Z}}}=t;r=t={annotationType:Et.HIGHLIGHT,color:Array.from(C),thickness:E,inkLists:k,boxes:null,pageIndex:Z-1,rect:w.slice(0),rotation:T,annotationElementId:A,id:A,deleted:!1,popupRef:x,richText:D,comment:(N==null?void 0:N.str)||null,creationDate:O,modificationDate:G}}const{color:o,quadPoints:a,inkLists:c,outlines:l,opacity:u}=t,d=await super.deserialize(t,n,i);d.color=Fe.makeHexColor(...o),d.opacity=u||1,c&&R(d,Po,t.thickness),d._initialData=r,t.comment&&d.setCommentData(t);const[h,p]=d.pageDimensions,[g,v]=d.pageTranslation;if(a){const k=R(d,fc,[]);for(let w=0;w<a.length;w+=8)k.push({x:(a[w]-g)/h,y:1-(a[w+1]-v)/p,width:(a[w+2]-a[w])/h,height:(a[w+1]-a[w+5])/p});H(m=d,Nt,GA).call(m),H(y=d,Nt,Od).call(y),d.rotate(d.rotation)}else if(c||l){R(d,ii,!0);const k=(c||l.points)[0],w={x:k[0]-g,y:p-(k[1]-v)},T=new VA(w,[0,0,h,p],1,f(d,Po)/2,!0,.001);for(let E=0,x=k.length;E<x;E+=2)w.x=k[E]-g,w.y=p-(k[E+1]-v),T.add(w);const{id:A,clipPathId:C}=n.drawLayer.draw({bbox:[0,0,1,1],root:{viewBox:"0 0 1 1",fill:d.color,"fill-opacity":d._defaultOpacity},rootClass:{highlight:!0,free:!0},path:{d:T.toSVGPath()}},!0,!0);H(_=d,Nt,pS).call(_,{highlightOutlines:T.getOutlines(),highlightId:A,clipPathId:C}),H(b=d,Nt,Od).call(b),d.rotate(d.parentRotation)}return d}serialize(t=!1){if(this.isEmpty()||t)return null;if(this.deleted)return this.serializeDeleted();const n=cs._colorManager.convert(this._uiManager.getNonHCMColor(this.color)),i=super.serialize(t);return Object.assign(i,{color:n,opacity:this.opacity,thickness:f(this,Po),quadPoints:H(this,Nt,iB).call(this),outlines:H(this,Nt,rB).call(this,i.rect)}),this.addComment(i),this.annotationElementId&&!H(this,Nt,lB).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}};Wm=new WeakMap,s_=new WeakMap,fc=new WeakMap,cf=new WeakMap,n_=new WeakMap,yr=new WeakMap,i_=new WeakMap,r_=new WeakMap,uf=new WeakMap,Qr=new WeakMap,Xr=new WeakMap,ii=new WeakMap,zm=new WeakMap,jm=new WeakMap,Si=new WeakMap,Vm=new WeakMap,Po=new WeakMap,o_=new WeakMap,Nt=new WeakSet,GA=function(){const t=new zA(f(this,fc),.001);R(this,Qr,t.getOutlines()),[this.x,this.y,this.width,this.height]=f(this,Qr).box;const n=new zA(f(this,fc),.0025,.001,this._uiManager.direction==="ltr");R(this,yr,n.getOutlines());const{firstPoint:i}=f(this,Qr);R(this,zm,[(i[0]-this.x)/this.width,(i[1]-this.y)/this.height]);const{lastPoint:r}=f(this,yr);R(this,jm,[(r[0]-this.x)/this.width,(r[1]-this.y)/this.height])},pS=function({highlightOutlines:t,highlightId:n,clipPathId:i}){var h,p;if(R(this,Qr,t),R(this,yr,t.getNewOutline(f(this,Po)/2+1.5,.0025)),n>=0)R(this,Xr,n),R(this,cf,i),this.parent.drawLayer.finalizeDraw(n,{bbox:t.box,path:{d:t.toSVGPath()}}),R(this,Si,this.parent.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:!0},bbox:f(this,yr).box,path:{d:f(this,yr).toSVGPath()}},!0));else if(this.parent){const g=this.parent.viewport.rotation;this.parent.drawLayer.updateProperties(f(this,Xr),{bbox:H(h=es,Fo,kp).call(h,f(this,Qr).box,(g-this.rotation+360)%360),path:{d:t.toSVGPath()}}),this.parent.drawLayer.updateProperties(f(this,Si),{bbox:H(p=es,Fo,kp).call(p,f(this,yr).box,g),path:{d:f(this,yr).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[g,v]=this.parentDimensions;this.x=a,this.y=1-o,this.width=c*v/g,this.height=l*g/v;break}case 180:this.x=1-o,this.y=1-a,this.width=c,this.height=l;break;case 270:{const[g,v]=this.parentDimensions;this.x=1-a,this.y=o,this.width=c*v/g,this.height=l*g/v;break}}const{firstPoint:u}=t;R(this,zm,[(u[0]-o)/c,(u[1]-a)/l]);const{lastPoint:d}=f(this,yr);R(this,jm,[(d[0]-o)/c,(d[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,es._defaultOpacity),undo:n.bind(this,i,r),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:Rt.HIGHLIGHT_COLOR,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"color_changed",color:this._uiManager.getNonHCMColorName(t)},!0)},tB=function(t){const n=f(this,Po),i=r=>{R(this,Po,r),H(this,Nt,sB).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:Rt.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"thickness_changed",thickness:t},!0)},sB=function(t){f(this,ii)&&(H(this,Nt,pS).call(this,{highlightOutlines:f(this,Qr).getNewOutline(t/2)}),this.fixAndSetPosition(),this.setDims())},KA=function(){f(this,Xr)===null||!this.parent||(this.parent.drawLayer.remove(f(this,Xr)),R(this,Xr,null),this.parent.drawLayer.remove(f(this,Si)),R(this,Si,null))},Od=function(t=this.parent){f(this,Xr)===null&&({id:Ls(this,Xr)._,clipPathId:Ls(this,cf)._}=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,ii)},path:{d:f(this,Qr).toSVGPath()}},!1,!0),R(this,Si,t.drawLayer.drawOutline({rootClass:{highlightOutline:!0,free:f(this,ii)},bbox:f(this,yr).box,path:{d:f(this,yr).toSVGPath()}},f(this,ii))),f(this,uf)&&(f(this,uf).style.clipPath=f(this,cf)))},Fo=new WeakSet,kp=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]},nB=function(t){es._keyboardManager.exec(this,t)},mS=function(t){if(!f(this,Wm))return;const n=window.getSelection();t?n.setPosition(f(this,Wm),f(this,s_)):n.setPosition(f(this,i_),f(this,r_))},gS=function(){return f(this,ii)?this.rotation:0},iB=function(){if(f(this,ii))return null;const[t,n]=this.pageDimensions,[i,r]=this.pageTranslation,o=f(this,fc),a=new Float32Array(o.length*8);let c=0;for(const{x:l,y:u,width:d,height:h}of o){const p=l*t+i,g=(1-u)*n+r;a[c]=a[c+4]=p,a[c+1]=a[c+3]=g,a[c+2]=a[c+6]=p+d*t,a[c+5]=a[c+7]=g-h*n,c+=8}return a},rB=function(t){return f(this,Qr).serialize(t,H(this,Nt,gS).call(this))},oB=function(t,n){this._freeHighlight.add(n)&&t.drawLayer.updateProperties(this._freeHighlightId,{path:{d:this._freeHighlight.toSVGPath()}})},aB=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=""},lB=function(t){const{color:n}=this._initialData;return this.hasEditedComment||t.color.some((i,r)=>i!==n[r])},B(es,Fo),Se(es,"_defaultColor",null),Se(es,"_defaultOpacity",1),Se(es,"_defaultThickness",12),Se(es,"_type","highlight"),Se(es,"_editorType",Et.HIGHLIGHT),Se(es,"_freeHighlightId",-1),Se(es,"_freeHighlight",null),Se(es,"_freeHighlightClipId","");let I0=es;var df;class cB{constructor(){B(this,df,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,df)[e]=t}toSVGProperties(){const e=f(this,df);return R(this,df,Object.create(null)),{root:e}}reset(){R(this,df,Object.create(null))}updateAll(e=this){this.updateProperties(e)}clone(){ss("Not implemented")}}df=new WeakMap;var Qi,Gm,zn,hf,ff,Xt,qA,QA,XA,Mv,uB,vS,xv,Cp;const Vt=class Vt extends cs{constructor(t){super(t);B(this,Xt);B(this,Qi,null);B(this,Gm);Se(this,"_colorPicker",null);Se(this,"_drawId",null);R(this,Gm,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&&(H(this,Xt,qA).call(this,t),H(this,Xt,Mv).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){ss("Not implemented")}static get typesMap(){ss("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(Vt,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,Qi).updateProperty(n,c);l&&H(this,Xt,xv).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,d)=>{var h;o.updateProperty(i,u),o.updateProperty(r,d),f(this,Qi).updateProperty(i,u),f(this,Qi).updateProperty(r,d),(h=this.parent)==null||h.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:Rt.INK_COLOR_AND_OPACITY,overwriteIfSameType:!0,keepUndo:!0})}_onResizing(){var t;(t=this.parent)==null||t.drawLayer.updateProperties(this._drawId,Vt._mergeSVGProperties(f(this,Qi).getPathResizingSVGProperties(H(this,Xt,vS).call(this)),{bbox:H(this,Xt,Cp).call(this)}))}_onResized(){var t;(t=this.parent)==null||t.drawLayer.updateProperties(this._drawId,Vt._mergeSVGProperties(f(this,Qi).getPathResizedSVGProperties(H(this,Xt,vS).call(this)),{bbox:H(this,Xt,Cp).call(this)}))}_onTranslating(t,n){var i;(i=this.parent)==null||i.drawLayer.updateProperties(this._drawId,{bbox:H(this,Xt,Cp).call(this)})}_onTranslated(){var t;(t=this.parent)==null||t.drawLayer.updateProperties(this._drawId,Vt._mergeSVGProperties(f(this,Qi).getPathTranslatedSVGProperties(H(this,Xt,vS).call(this),this.parentDimensions),{bbox:H(this,Xt,Cp).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,Gm)&&(R(this,Gm,!1),this.commit(),this.parent.setSelected(this),t&&this.isOnScreen&&this.div.focus())}remove(){H(this,Xt,XA).call(this),super.remove()}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(H(this,Xt,Mv).call(this),H(this,Xt,xv).call(this,f(this,Qi).box),this.isAttachedToDOM||this.parent.add(this)))}setParent(t){var i;let n=!1;this.parent&&!t?(this._uiManager.removeShouldRescale(this),H(this,Xt,XA).call(this)):t&&(this._uiManager.addShouldRescale(this),H(this,Xt,Mv).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,Vt._mergeSVGProperties({bbox:H(this,Xt,Cp).call(this)},f(this,Qi).updateRotation((this.parentRotation-this.rotation+360)%360)))}onScaleChanging(){this.parent&&H(this,Xt,xv).call(this,f(this,Qi).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){ss("Not implemented")}static startDrawing(t,n,i,r){var m;const{target:o,offsetX:a,offsetY:c,pointerId:l,pointerType:u}=r;if(bi.isInitializedAndDifferentPointerType(u))return;const{viewport:{rotation:d}}=t,{width:h,height:p}=o.getBoundingClientRect(),g=R(Vt,hf,new AbortController),v=t.combinedSignal(g);if(bi.setPointer(u,l),window.addEventListener("pointerup",y=>{bi.isSamePointerIdOrRemove(y.pointerId)&&this._endDraw(y)},{signal:v}),window.addEventListener("pointercancel",y=>{bi.isSamePointerIdOrRemove(y.pointerId)&&this._currentParent.endDrawingSession()},{signal:v}),window.addEventListener("pointerdown",y=>{bi.isSamePointerType(y.pointerType)&&(bi.initializeAndAddPointerId(y.pointerId),f(Vt,zn).isCancellable()&&(f(Vt,zn).removeLastElement(),f(Vt,zn).isEmpty()?this._currentParent.endDrawingSession(!0):this._endDraw(null)))},{capture:!0,passive:!1,signal:v}),window.addEventListener("contextmenu",Go,{signal:v}),o.addEventListener("pointermove",this._drawMove.bind(this),{signal:v}),o.addEventListener("touchmove",y=>{bi.isSameTimeStamp(y.timeStamp)&&Xs(y)},{signal:v}),t.toggleDrawing(),(m=n._editorUndoBar)==null||m.hide(),f(Vt,zn)){t.drawLayer.updateProperties(this._currentDrawId,f(Vt,zn).startNew(a,c,h,p,d));return}n.updateUIForDefaultProperties(this),R(Vt,zn,this.createDrawerInstance(a,c,h,p,d)),R(Vt,ff,this.getDefaultDrawingOptions()),this._currentParent=t,{id:this._currentDrawId}=t.drawLayer.draw(this._mergeSVGProperties(f(Vt,ff).toSVGProperties(),f(Vt,zn).defaultSVGProperties),!0,!1)}static _drawMove(t){if(bi.isSameTimeStamp(t.timeStamp),!f(Vt,zn))return;const{offsetX:n,offsetY:i,pointerId:r}=t;if(bi.isSamePointerId(r)){if(bi.isUsingMultiplePointers()){this._endDraw(t);return}this._currentParent.drawLayer.updateProperties(this._currentDrawId,f(Vt,zn).add(n,i)),bi.setTimeStamp(t.timeStamp),Xs(t)}}static _cleanup(t){t&&(this._currentDrawId=-1,this._currentParent=null,R(Vt,zn,null),R(Vt,ff,null),bi.clearTimeStamp()),f(Vt,hf)&&(f(Vt,hf).abort(),R(Vt,hf,null),bi.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(Vt,zn).end(t.offsetX,t.offsetY)),this.supportMultipleDrawings){const i=f(Vt,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:Rt.DRAW_STEP});return}this.endDrawing(!1)}}static endDrawing(t){const n=this._currentParent;if(!n)return null;if(n.toggleDrawing(!0),n.cleanUndoStack(Rt.DRAW_STEP),!f(Vt,zn).isEmpty()){const{pageDimensions:[i,r],scale:o}=n,a=n.createAndAddNewEditor({offsetX:0,offsetY:0},!1,{drawId:this._currentDrawId,drawOutlines:f(Vt,zn).getOutlines(i*o,r*o,o,this._INNER_MARGIN),drawingOptions:f(Vt,ff),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){ss("Not implemented")}static async deserialize(t,n,i){var d,h;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),H(d=u,Xt,qA).call(d,{drawOutlines:l}),H(h=u,Xt,Mv).call(h),u.onScaleChanging(),u.rotate(),u}serializeDraw(t){const[n,i]=this.pageTranslation,[r,o]=this.pageDimensions;return f(this,Qi).serialize([n,i,r,o],t)}renderAnnotationElement(t){return t.updateEdited({rect:this.getPDFRect()}),null}static canCreateNewEmptyEditor(){return!1}};Qi=new WeakMap,Gm=new WeakMap,zn=new WeakMap,hf=new WeakMap,ff=new WeakMap,Xt=new WeakSet,qA=function({drawOutlines:t,drawId:n,drawingOptions:i}){R(this,Qi,t),this._drawingOptions||(this._drawingOptions=i),this.annotationElementId||this._uiManager.a11yAlert(cs._l10nAlert[this.editorType]),n>=0?(this._drawId=n,this.parent.drawLayer.finalizeDraw(n,t.defaultProperties)):this._drawId=H(this,Xt,QA).call(this,t,this.parent),H(this,Xt,xv).call(this,t.box)},QA=function(t,n){const{id:i}=n.drawLayer.draw(Vt._mergeSVGProperties(this._drawingOptions.toSVGProperties(),t.defaultSVGProperties),!1,!1);return i},XA=function(){this._drawId===null||!this.parent||(this.parent.drawLayer.remove(this._drawId),this._drawId=null,this._drawingOptions.reset())},Mv=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=H(this,Xt,QA).call(this,f(this,Qi),t)}},uB=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]}},vS=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]}},xv=function(t){[this.x,this.y,this.width,this.height]=H(this,Xt,uB).call(this,t),this.div&&(this.fixAndSetPosition(),this.setDims()),this._onResized()},Cp=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]}},Se(Vt,"_currentDrawId",-1),Se(Vt,"_currentParent",null),B(Vt,zn,null),B(Vt,hf,null),B(Vt,ff,null),Se(Vt,"_INNER_MARGIN",3);let P0=Vt;var Za,jn,Vn,pf,Km,Xi,ri,Lo,mf,gf,vf,qm,yS;class Gne{constructor(e,t,n,i,r,o){B(this,qm);B(this,Za,new Float64Array(6));B(this,jn);B(this,Vn);B(this,pf);B(this,Km);B(this,Xi);B(this,ri,"");B(this,Lo,0);B(this,mf,new S_);B(this,gf);B(this,vf);R(this,gf,n),R(this,vf,i),R(this,pf,r),R(this,Km,o),[e,t]=H(this,qm,yS).call(this,e,t);const a=R(this,jn,[NaN,NaN,NaN,NaN,e,t]);R(this,Xi,[e,t]),R(this,Vn,[{line:a,points:f(this,Xi)}]),f(this,Za).set(a,0)}updateProperty(e,t){e==="stroke-width"&&R(this,Km,t)}isEmpty(){return!f(this,Vn)||f(this,Vn).length===0}isCancellable(){return f(this,Xi).length<=10}add(e,t){[e,t]=H(this,qm,yS).call(this,e,t);const[n,i,r,o]=f(this,Za).subarray(2,6),a=e-r,c=t-o;return Math.hypot(f(this,gf)*a,f(this,vf)*c)<=2?null:(f(this,Xi).push(e,t),isNaN(n)?(f(this,Za).set([r,o,e,t],2),f(this,jn).push(NaN,NaN,NaN,NaN,e,t),{path:{d:this.toSVGPath()}}):(isNaN(f(this,Za)[0])&&f(this,jn).splice(6,6),f(this,Za).set([n,i,r,o,e,t],0),f(this,jn).push(...Je.createBezierPoints(n,i,r,o,e,t)),{path:{d:this.toSVGPath()}}))}end(e,t){const n=this.add(e,t);return n||(f(this,Xi).length===2?{path:{d:this.toSVGPath()}}:null)}startNew(e,t,n,i,r){R(this,gf,n),R(this,vf,i),R(this,pf,r),[e,t]=H(this,qm,yS).call(this,e,t);const o=R(this,jn,[NaN,NaN,NaN,NaN,e,t]);R(this,Xi,[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,Xi)}),f(this,Za).set(o,0),R(this,Lo,0),this.toSVGPath(),null}getLastElement(){return f(this,Vn).at(-1)}setLastElement(e){return f(this,Vn)?(f(this,Vn).push(e),R(this,jn,e.line),R(this,Xi,e.points),R(this,Lo,0),{path:{d:this.toSVGPath()}}):f(this,mf).setLastElement(e)}removeLastElement(){if(!f(this,Vn))return f(this,mf).removeLastElement();f(this,Vn).pop(),R(this,ri,"");for(let e=0,t=f(this,Vn).length;e<t;e++){const{line:n,points:i}=f(this,Vn)[e];R(this,jn,n),R(this,Xi,i),R(this,Lo,0),this.toSVGPath()}return{path:{d:f(this,ri)}}}toSVGPath(){const e=Je.svgRound(f(this,jn)[4]),t=Je.svgRound(f(this,jn)[5]);if(f(this,Xi).length===2)return R(this,ri,`${f(this,ri)} M ${e} ${t} Z`),f(this,ri);if(f(this,Xi).length<=6){const i=f(this,ri).lastIndexOf("M");R(this,ri,`${f(this,ri).slice(0,i)} M ${e} ${t}`),R(this,Lo,6)}if(f(this,Xi).length===4){const i=Je.svgRound(f(this,jn)[10]),r=Je.svgRound(f(this,jn)[11]);return R(this,ri,`${f(this,ri)} L ${i} ${r}`),R(this,Lo,12),f(this,ri)}const n=[];f(this,Lo)===0&&(n.push(`M ${e} ${t}`),R(this,Lo,6));for(let i=f(this,Lo),r=f(this,jn).length;i<r;i+=6){const[o,a,c,l,u,d]=f(this,jn).slice(i,i+6).map(Je.svgRound);n.push(`C${o} ${a} ${c} ${l} ${u} ${d}`)}return R(this,ri,f(this,ri)+n.join(" ")),R(this,Lo,f(this,jn).length),f(this,ri)}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,mf).build(f(this,Vn),e,t,n,f(this,pf),f(this,Km),i),R(this,Za,null),R(this,jn,null),R(this,Vn,null),R(this,ri,null),f(this,mf)}get defaultSVGProperties(){return{root:{viewBox:"0 0 10000 10000"},rootClass:{draw:!0},bbox:[0,0,1,1]}}}Za=new WeakMap,jn=new WeakMap,Vn=new WeakMap,pf=new WeakMap,Km=new WeakMap,Xi=new WeakMap,ri=new WeakMap,Lo=new WeakMap,mf=new WeakMap,gf=new WeakMap,vf=new WeakMap,qm=new WeakSet,yS=function(e,t){return Je._normalizePoint(e,t,f(this,gf),f(this,vf),f(this,pf))};var Yi,a_,l_,Yr,el,tl,Qm,Xm,yf,li,Pl,dB,hB,fB;class S_ extends Je{constructor(){super(...arguments);B(this,li);B(this,Yi);B(this,a_,0);B(this,l_);B(this,Yr);B(this,el);B(this,tl);B(this,Qm);B(this,Xm);B(this,yf)}build(t,n,i,r,o,a,c){R(this,el,n),R(this,tl,i),R(this,Qm,r),R(this,Xm,o),R(this,yf,a),R(this,l_,c??0),R(this,Yr,t),H(this,li,hB).call(this)}get thickness(){return f(this,yf)}setLastElement(t){return f(this,Yr).push(t),{path:{d:this.toSVGPath()}}}removeLastElement(){return f(this,Yr).pop(),{path:{d:this.toSVGPath()}}}toSVGPath(){const t=[];for(const{line:n}of f(this,Yr)){if(t.push(`M${Je.svgRound(n[4])} ${Je.svgRound(n[5])}`),n.length===6){t.push("Z");continue}if(n.length===12&&isNaN(n[6])){t.push(`L${Je.svgRound(n[10])} ${Je.svgRound(n[11])}`);continue}for(let i=6,r=n.length;i<r;i+=6){const[o,a,c,l,u,d]=n.subarray(i,i+6).map(Je.svgRound);t.push(`C${o} ${a} ${c} ${l} ${u} ${d}`)}}return t.join("")}serialize([t,n,i,r],o){const a=[],c=[],[l,u,d,h]=H(this,li,dB).call(this);let p,g,v,m,y,_,b,k,w;switch(f(this,Xm)){case 0:w=Je._rescale,p=t,g=n+r,v=i,m=-r,y=t+l*i,_=n+(1-u-h)*r,b=t+(l+d)*i,k=n+(1-u)*r;break;case 90:w=Je._rescaleAndSwap,p=t,g=n,v=i,m=r,y=t+u*i,_=n+l*r,b=t+(u+h)*i,k=n+(l+d)*r;break;case 180:w=Je._rescale,p=t+i,g=n,v=-i,m=r,y=t+(1-l-d)*i,_=n+u*r,b=t+(1-l)*i,k=n+(u+h)*r;break;case 270:w=Je._rescaleAndSwap,p=t+i,g=n+r,v=-i,m=-r,y=t+(1-u-h)*i,_=n+(1-l-d)*r,b=t+(1-u)*i,k=n+(1-l)*r;break}for(const{line:T,points:A}of f(this,Yr))a.push(w(T,p,g,v,m,o?new Array(T.length):null)),c.push(w(A,p,g,v,m,o?new Array(A.length):null));return{lines:a,points:c,rect:[y,_,b,k]}}static deserialize(t,n,i,r,o,{paths:{lines:a,points:c},rotation:l,thickness:u}){const d=[];let h,p,g,v,m;switch(l){case 0:m=Je._rescale,h=-t/i,p=n/r+1,g=1/i,v=-1/r;break;case 90:m=Je._rescaleAndSwap,h=-n/r,p=-t/i,g=1/r,v=1/i;break;case 180:m=Je._rescale,h=t/i+1,p=-n/r,g=-1/i,v=1/r;break;case 270:m=Je._rescaleAndSwap,h=n/r+1,p=t/i+1,g=-1/r,v=-1/i;break}if(!a){a=[];for(const _ of c){const b=_.length;if(b===2){a.push(new Float32Array([NaN,NaN,NaN,NaN,_[0],_[1]]));continue}if(b===4){a.push(new Float32Array([NaN,NaN,NaN,NaN,_[0],_[1],NaN,NaN,NaN,NaN,_[2],_[3]]));continue}const k=new Float32Array(3*(b-2));a.push(k);let[w,T,A,C]=_.subarray(0,4);k.set([NaN,NaN,NaN,NaN,w,T],0);for(let E=4;E<b;E+=2){const x=_[E],D=_[E+1];k.set(Je.createBezierPoints(w,T,A,C,x,D),(E-2)*3),[w,T,A,C]=[A,C,x,D]}}}for(let _=0,b=a.length;_<b;_++)d.push({line:m(a[_].map(k=>k??NaN),h,p,g,v),points:m(c[_].map(k=>k??NaN),h,p,g,v)});const y=new this.prototype.constructor;return y.build(d,i,r,1,l,u,o),y}get box(){return f(this,Yi)}updateProperty(t,n){return t==="stroke-width"?H(this,li,fB).call(this,n):null}updateParentDimensions([t,n],i){const[r,o]=H(this,li,Pl).call(this);R(this,el,t),R(this,tl,n),R(this,Qm,i);const[a,c]=H(this,li,Pl).call(this),l=a-r,u=c-o,d=f(this,Yi);return d[0]-=l,d[1]-=u,d[2]+=2*l,d[3]+=2*u,d}updateRotation(t){return R(this,a_,t),{path:{transform:this.rotationTransform}}}get viewBox(){return f(this,Yi).map(Je.svgRound).join(" ")}get defaultProperties(){const[t,n]=f(this,Yi);return{root:{viewBox:this.viewBox},path:{"transform-origin":`${Je.svgRound(t)} ${Je.svgRound(n)}`}}}get rotationTransform(){const[,,t,n]=f(this,Yi);let i=0,r=0,o=0,a=0,c=0,l=0;switch(f(this,a_)){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} ${Je.svgRound(c)} ${Je.svgRound(l)})`}getPathResizingSVGProperties([t,n,i,r]){const[o,a]=H(this,li,Pl).call(this),[c,l,u,d]=f(this,Yi);if(Math.abs(u-o)<=Je.PRECISION||Math.abs(d-a)<=Je.PRECISION){const m=t+i/2-(c+u/2),y=n+r/2-(l+d/2);return{path:{"transform-origin":`${Je.svgRound(t)} ${Je.svgRound(n)}`,transform:`${this.rotationTransform} translate(${m} ${y})`}}}const h=(i-2*o)/(u-2*o),p=(r-2*a)/(d-2*a),g=u/i,v=d/r;return{path:{"transform-origin":`${Je.svgRound(c)} ${Je.svgRound(l)}`,transform:`${this.rotationTransform} scale(${g} ${v}) translate(${Je.svgRound(o)} ${Je.svgRound(a)}) scale(${h} ${p}) translate(${Je.svgRound(-o)} ${Je.svgRound(-a)})`}}}getPathResizedSVGProperties([t,n,i,r]){const[o,a]=H(this,li,Pl).call(this),c=f(this,Yi),[l,u,d,h]=c;if(c[0]=t,c[1]=n,c[2]=i,c[3]=r,Math.abs(d-o)<=Je.PRECISION||Math.abs(h-a)<=Je.PRECISION){const y=t+i/2-(l+d/2),_=n+r/2-(u+h/2);for(const{line:b,points:k}of f(this,Yr))Je._translate(b,y,_,b),Je._translate(k,y,_,k);return{root:{viewBox:this.viewBox},path:{"transform-origin":`${Je.svgRound(t)} ${Je.svgRound(n)}`,transform:this.rotationTransform||null,d:this.toSVGPath()}}}const p=(i-2*o)/(d-2*o),g=(r-2*a)/(h-2*a),v=-p*(l+o)+t+o,m=-g*(u+a)+n+a;if(p!==1||g!==1||v!==0||m!==0)for(const{line:y,points:_}of f(this,Yr))Je._rescale(y,v,m,p,g,y),Je._rescale(_,v,m,p,g,_);return{root:{viewBox:this.viewBox},path:{"transform-origin":`${Je.svgRound(t)} ${Je.svgRound(n)}`,transform:this.rotationTransform||null,d:this.toSVGPath()}}}getPathTranslatedSVGProperties([t,n],i){const[r,o]=i,a=f(this,Yi),c=t-a[0],l=n-a[1];if(f(this,el)===r&&f(this,tl)===o)for(const{line:u,points:d}of f(this,Yr))Je._translate(u,c,l,u),Je._translate(d,c,l,d);else{const u=f(this,el)/r,d=f(this,tl)/o;R(this,el,r),R(this,tl,o);for(const{line:h,points:p}of f(this,Yr))Je._rescale(h,c,l,u,d,h),Je._rescale(p,c,l,u,d,p);a[2]*=u,a[3]*=d}return a[0]=t,a[1]=n,{root:{viewBox:this.viewBox},path:{d:this.toSVGPath(),"transform-origin":`${Je.svgRound(t)} ${Je.svgRound(n)}`}}}get defaultSVGProperties(){const t=f(this,Yi);return{root:{viewBox:this.viewBox},rootClass:{draw:!0},path:{d:this.toSVGPath(),"transform-origin":`${Je.svgRound(t[0])} ${Je.svgRound(t[1])}`,transform:this.rotationTransform||null},bbox:t}}}Yi=new WeakMap,a_=new WeakMap,l_=new WeakMap,Yr=new WeakMap,el=new WeakMap,tl=new WeakMap,Qm=new WeakMap,Xm=new WeakMap,yf=new WeakMap,li=new WeakSet,Pl=function(t=f(this,yf)){const n=f(this,l_)+t/2*f(this,Qm);return f(this,Xm)%180===0?[n/f(this,el),n/f(this,tl)]:[n/f(this,tl),n/f(this,el)]},dB=function(){const[t,n,i,r]=f(this,Yi),[o,a]=H(this,li,Pl).call(this,0);return[t+o,n+a,i-2*o,r-2*a]},hB=function(){const t=R(this,Yi,Kd.slice());for(const{line:r}of f(this,Yr)){if(r.length<=12){for(let c=4,l=r.length;c<l;c+=6)Fe.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,d,h,p,g,v]=r.subarray(c,c+6);Fe.bezierBoundingBox(o,a,u,d,h,p,g,v,t),o=g,a=v}}const[n,i]=H(this,li,Pl).call(this);t[0]=zs(t[0]-n,0,1),t[1]=zs(t[1]-i,0,1),t[2]=zs(t[2]+n,0,1),t[3]=zs(t[3]+i,0,1),t[2]-=t[0],t[3]-=t[1]},fB=function(t){const[n,i]=H(this,li,Pl).call(this);R(this,yf,t);const[r,o]=H(this,li,Pl).call(this),[a,c]=[r-n,o-i],l=f(this,Yi);return l[0]-=a,l[1]-=c,l[2]+=2*a,l[3]+=2*c,l};class Bk extends cB{constructor(e){super(),this._viewParameters=e,super.updateProperties({fill:"none",stroke:cs._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 Bk(this._viewParameters);return e.updateAll(this),e}}var ik,pB;const Mp=class Mp extends P0{constructor(t){super({...t,name:"inkEditor"});B(this,ik);this._willKeepAspectRatio=!0,this.defaultL10nId="pdfjs-editor-ink-editor"}static initialize(t,n){cs.initialize(t,n),this._defaultDrawingOptions=new Bk(n.viewParameters)}static getDefaultDrawingOptions(t){const n=this._defaultDrawingOptions.clone();return n.updateProperties(t),n}static get supportMultipleDrawings(){return!0}static get typesMap(){return Mt(this,"typesMap",new Map([[Rt.INK_THICKNESS,"stroke-width"],[Rt.INK_COLOR,"stroke"],[Rt.INK_OPACITY,"stroke-opacity"]]))}static createDrawerInstance(t,n,i,r,o){return new Gne(t,n,i,r,o,this._defaultDrawingOptions["stroke-width"])}static deserializeDraw(t,n,i,r,o,a){return S_.deserialize(t,n,i,r,o,a)}static async deserialize(t,n,i){let r=null;if(t instanceof OM){const{data:{inkLists:a,rect:c,rotation:l,id:u,color:d,opacity:h,borderStyle:{rawWidth:p},popupRef:g,richText:v,contentsObj:m,creationDate:y,modificationDate:_},parent:{page:{pageNumber:b}}}=t;r=t={annotationType:Et.INK,color:Array.from(d),thickness:p,opacity:h,paths:{points:a},boxes:null,pageIndex:b-1,rect:c.slice(0),rotation:l,annotationElementId:u,id:u,deleted:!1,popupRef:g,richText:v,comment:(m==null?void 0:m.str)||null,creationDate:y,modificationDate:_}}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 M0(this)),[["colorPicker",this._colorPicker]]}get colorType(){return Rt.INK_COLOR}get colorAndOpacityType(){return Rt.INK_COLOR_AND_OPACITY}get opacityType(){return Rt.INK_OPACITY}updateParams(t,n){if(t===Rt.INK_COLOR_AND_OPACITY){this._updateColorAndOpacity(n.color,n.opacity);return}super.updateParams(t,n)}static updateDefaultParams(t,n){if(t===Rt.INK_COLOR_AND_OPACITY){super.updateDefaultParams(Rt.INK_COLOR,n.color),super.updateDefaultParams(Rt.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=Mp.getDefaultDrawingOptions({stroke:Fe.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:cs._colorManager.convert(r),opacity:o,thickness:a,paths:{lines:n,points:i}});return this.addComment(c),t?(c.isCopy=!0,c):this.annotationElementId&&!H(this,ik,pB).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}};ik=new WeakSet,pB=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},Se(Mp,"_type","ink"),Se(Mp,"_editorType",Et.INK),Se(Mp,"_defaultDrawingOptions",null);let YA=Mp;class JA extends S_{toSVGPath(){let e=super.toSVGPath();return e.endsWith("Z")||(e+="Z"),e}}Ct(5213);const fw=8,Hg=3;var bf,us,ZA,ma,mB,gB,eE,bS,vB,yB,bB,tE,sE,_B;class _c{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 d=200,h=u.font=`${n} ${i} ${d}px ${t}`,{actualBoundingBoxLeft:p,actualBoundingBoxRight:g,actualBoundingBoxAscent:v,actualBoundingBoxDescent:m,fontBoundingBoxAscent:y,fontBoundingBoxDescent:_,width:b}=u.measureText(e),k=1.5,w=Math.ceil(Math.max(Math.abs(p)+Math.abs(g)||0,b)*k),T=Math.ceil(Math.max(Math.abs(v)+Math.abs(m)||d,Math.abs(y)+Math.abs(_)||d)*k);l=new OffscreenCanvas(w,T),u=l.getContext("2d",{alpha:!0,willReadFrequently:!0}),u.font=h,u.filter="grayscale(1)",u.fillStyle="white",u.fillRect(0,0,w,T),u.fillStyle="black",u.fillText(e,w*(k-1)/2,T*(3-k)/2);const A=H(this,us,tE).call(this,u.getImageData(0,0,w,T).data),C=H(this,us,bB).call(this,A),E=H(this,us,sE).call(this,C),x=H(this,us,eE).call(this,A,w,T,E);return this.processDrawnLines({lines:{curves:x,width:w,height:T},pageWidth:r,pageHeight:o,rotation:a,innerMargin:c,mustSmooth:!0,areContours:!0})}static process(e,t,n,i,r){const[o,a,c]=H(this,us,_B).call(this,e),[l,u]=H(this,us,yB).call(this,o,a,c,Math.hypot(a,c)*f(this,bf).sigmaSFactor,f(this,bf).sigmaR,f(this,bf).kernelSize),d=H(this,us,sE).call(this,u),h=H(this,us,eE).call(this,l,a,c,d);return this.processDrawnLines({lines:{curves:h,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,d=e.thickness??0,h=[],p=Math.min(t/l,n/u),g=p/t,v=p/n,m=[];for(const{points:_}of c){const b=o?H(this,us,vB).call(this,_):_;if(!b)continue;m.push(b);const k=b.length,w=new Float32Array(k),T=new Float32Array(3*(k===2?2:k-2));if(h.push({line:T,points:w}),k===2){w[0]=b[0]*g,w[1]=b[1]*v,T.set([NaN,NaN,NaN,NaN,w[0],w[1]],0);continue}let[A,C,E,x]=b;A*=g,C*=v,E*=g,x*=v,w.set([A,C,E,x],0),T.set([NaN,NaN,NaN,NaN,A,C],0);for(let D=4;D<k;D+=2){const N=w[D]=b[D]*g,O=w[D+1]=b[D+1]*v;T.set(Je.createBezierPoints(A,C,E,x,N,O),(D-2)*3),[A,C,E,x]=[E,x,N,O]}}if(h.length===0)return null;const y=a?new JA:new S_;return y.build(h,t,n,1,i,a?0:d,r),{outline:y,newCurves:m,areContours:a,thickness:d,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 _ of e){c+=_.length;for(let b=2,k=_.length;b<k;b++){const w=_[b]-_[b-2];o=Math.min(o,w),a=Math.max(a,w)}}let l;o>=-128&&a<=127?l=Int8Array:o>=-32768&&a<=32767?l=Int16Array:l=Int32Array;const u=e.length,d=fw+Hg*u,h=new Uint32Array(d);let p=0;h[p++]=d*Uint32Array.BYTES_PER_ELEMENT+(c-2*u)*l.BYTES_PER_ELEMENT,h[p++]=0,h[p++]=i,h[p++]=r,h[p++]=t?0:1,h[p++]=Math.max(0,Math.floor(n??0)),h[p++]=u,h[p++]=l.BYTES_PER_ELEMENT;for(const _ of e)h[p++]=_.length-2,h[p++]=_[0],h[p++]=_[1];const g=new CompressionStream("deflate-raw"),v=g.writable.getWriter();await v.ready,v.write(h);const m=l.prototype.constructor;for(const _ of e){const b=new m(_.length-2);for(let k=2,w=_.length;k<w;k++)b[k-2]=_[k]-_[k-2];v.write(b)}return v.close(),(await new Response(g.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 b of n)o||(o=new Uint8Array(new Uint32Array(b.buffer,0,4)[0])),o.set(b,a),a+=b.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],d=c[3],h=c[4]===0,p=c[5],g=c[6],v=c[7],m=[],y=(fw+Hg*g)*Uint32Array.BYTES_PER_ELEMENT;let _;switch(v){case Int8Array.BYTES_PER_ELEMENT:_=new Int8Array(o.buffer,y);break;case Int16Array.BYTES_PER_ELEMENT:_=new Int16Array(o.buffer,y);break;case Int32Array.BYTES_PER_ELEMENT:_=new Int32Array(o.buffer,y);break}a=0;for(let b=0;b<g;b++){const k=c[Hg*b+fw],w=new Float32Array(k+2);m.push(w);for(let T=0;T<Hg-1;T++)w[T]=c[Hg*b+fw+T+1];for(let T=0;T<k;T++)w[T+2]=w[T]+_[a++]}return{areContours:h,thickness:p,outlines:m,width:u,height:d}}catch(t){return At(`decompressSignature: ${t}`),null}}}bf=new WeakMap,us=new WeakSet,ZA=function(e,t,n,i){return n-=e,i-=t,n===0?i>0?0:4:n===1?i+6:2-i},ma=new WeakMap,mB=function(e,t,n,i,r,o,a){const c=H(this,us,ZA).call(this,n,i,r,o);for(let l=0;l<8;l++){const u=(-l+c-a+16)%8,d=f(this,ma)[2*u],h=f(this,ma)[2*u+1];if(e[(n+d)*t+(i+h)]!==0)return u}return-1},gB=function(e,t,n,i,r,o,a){const c=H(this,us,ZA).call(this,n,i,r,o);for(let l=0;l<8;l++){const u=(l+c+a+16)%8,d=f(this,ma)[2*u],h=f(this,ma)[2*u+1];if(e[(n+d)*t+(i+h)]!==0)return u}return-1},eE=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 d=1;d<t-1;d++){const h=u*t+d,p=o[h];if(p===0)continue;let g=u,v=d;if(p===1&&o[h-1]===0)a+=1,v-=1;else if(p>=1&&o[h+1]===0)a+=1,v+=1,p>1&&(c=p);else{p!==1&&(c=Math.abs(p));continue}const m=[d,u],y=v===d+1,_={isHole:y,points:m,id:a,parent:0};l.push(_);let b;for(const D of l)if(D.id===c){b=D;break}b?b.isHole?_.parent=y?b.parent:c:_.parent=y?c:b.parent:_.parent=y?c:0;const k=H(this,us,mB).call(this,o,t,u,d,g,v,0);if(k===-1){o[h]=-a,o[h]!==1&&(c=Math.abs(o[h]));continue}let w=f(this,ma)[2*k],T=f(this,ma)[2*k+1];const A=u+w,C=d+T;g=A,v=C;let E=u,x=d;for(;;){const D=H(this,us,gB).call(this,o,t,E,x,g,v,1);w=f(this,ma)[2*D],T=f(this,ma)[2*D+1];const N=E+w,O=x+T;m.push(O,N);const G=E*t+x;if(o[G+1]===0?o[G]=-a:o[G]===1&&(o[G]=a),N===u&&O===d&&E===A&&x===C){o[h]!==1&&(c=Math.abs(o[h]));break}else g=E,v=x,E=N,x=O}}}return l},bS=function(e,t,n,i){if(n-t<=4){for(let A=t;A<n-2;A+=2)i.push(e[A],e[A+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,d=c/l,h=u*o-d*r,p=c/a,g=1/l,v=Math.atan(p),m=Math.cos(v),y=Math.sin(v),_=g*(Math.abs(m)+Math.abs(y)),b=g*(1-_+_**2),k=Math.max(Math.atan(Math.abs(y+m)*b),Math.atan(Math.abs(y-m)*b));let w=0,T=t;for(let A=t+2;A<n-2;A+=2){const C=Math.abs(h-u*e[A+1]+d*e[A]);C>w&&(T=A,w=C)}w>(l*k)**2?(H(this,us,bS).call(this,e,t,T+2,i),H(this,us,bS).call(this,e,T,n,i)):i.push(r,o)},vB=function(e){const t=[],n=e.length;return H(this,us,bS).call(this,e,0,n,t),t.push(e[n-2],e[n-1]),t.length<=4?null:t},yB=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 m=(v-l)**2;for(let y=0;y<o;y++)a[v*o+y]=Math.exp((m+(y-l)**2)/c)}const u=new Float32Array(256),d=-2*r**2;for(let v=0;v<256;v++)u[v]=Math.exp(v**2/d);const h=e.length,p=new Uint8Array(h),g=new Uint32Array(256);for(let v=0;v<n;v++)for(let m=0;m<t;m++){const y=v*t+m,_=e[y];let b=0,k=0;for(let T=0;T<o;T++){const A=v+T-l;if(!(A<0||A>=n))for(let C=0;C<o;C++){const E=m+C-l;if(E<0||E>=t)continue;const x=e[A*t+E],D=a[T*o+C]*u[Math.abs(x-_)];b+=x*D,k+=D}}const w=p[y]=Math.round(b/k);g[w]++}return[p,g]},bB=function(e){const t=new Uint32Array(256);for(const n of e)t[n]++;return t},tE=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},sE=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},_B=function(e){const t=e,{width:n,height:i}=e,{maxDim:r}=f(this,bf);let o=n,a=i;if(n>r||i>r){let h=n,p=i,g=Math.log2(Math.max(n,i)/r);const v=Math.floor(g);g=g===v?v-1:v;for(let y=0;y<g;y++){o=Math.ceil(h/2),a=Math.ceil(p/2);const _=new OffscreenCanvas(o,a);_.getContext("2d").drawImage(e,0,0,h,p,0,0,o,a),h=o,p=a,e!==t&&e.close(),e=_.transferToImageBitmap()}const m=Math.min(r/o,r/a);o=Math.round(o*m),a=Math.round(a*m)}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[H(this,us,tE).call(this,u),o,a]},B(_c,us),B(_c,bf,{maxDim:512,sigmaSFactor:.02,sigmaR:25,kernelSize:16}),B(_c,ma,new Int32Array([0,1,-1,1,-1,0,-1,-1,0,-1,1,-1,1,0,1,1]));class DM extends cB{constructor(){super(),super.updateProperties({fill:cs._defaultLineColor,"stroke-width":0})}clone(){const e=new DM;return e.updateAll(this),e}}class NM extends Bk{constructor(e){super(e),super.updateProperties({stroke:cs._defaultLineColor,"stroke-width":1})}clone(){const e=new NM(this._viewParameters);return e.updateAll(this),e}}var Ku,sl,qu,_f;const Or=class Or extends P0{constructor(t){super({...t,mustBeCommitted:!0,name:"signatureEditor"});B(this,Ku,!1);B(this,sl,null);B(this,qu,null);B(this,_f,null);this._willKeepAspectRatio=!0,R(this,qu,t.signatureData||null),R(this,sl,null),this.defaultL10nId="pdfjs-editor-signature-editor1"}static initialize(t,n){cs.initialize(t,n),this._defaultDrawingOptions=new DM,this._defaultDrawnSignatureOptions=new NM(n.viewParameters)}static getDefaultDrawingOptions(t){const n=this._defaultDrawingOptions.clone();return n.updateProperties(t),n}static get supportMultipleDrawings(){return!1}static get typesMap(){return Mt(this,"typesMap",new Map)}static get isDrawer(){return!1}get telemetryFinalData(){return{type:"signature",hasDescription:!!f(this,sl)}}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,qu)){const{lines:r,mustSmooth:o,areContours:a,description:c,uuid:l,heightInPage:u}=f(this,qu),{rawDims:{pageWidth:d,pageHeight:h},rotation:p}=this.parent.viewport,g=_c.processDrawnLines({lines:r,pageWidth:d,pageHeight:h,rotation:p,innerMargin:Or._INNER_MARGIN,mustSmooth:o,areContours:a});this.addSignature(g,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,sl)||""}));return i&&(this._isCopy=!0,this._moveAfterPaste(t,n)),this.div}setUuid(t){R(this,_f,t),this.addEditToolbar()}getUuid(){return f(this,_f)}get description(){return f(this,sl)}set description(t){R(this,sl,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,qu),a=Math.max(r,o),c=_c.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}=R(this,qu,t);R(this,Ku,c instanceof JA),this.description=i;let l;f(this,Ku)?l=Or.getDefaultDrawingOptions():(l=Or._defaultDrawnSignatureOptions.clone(),l.updateProperties({"stroke-width":c.thickness})),this._addOutlines({drawOutlines:c,drawingOptions:l});const[,u]=this.pageDimensions;let d=n/u;d=d>=1?.5:d,this.width*=d/this.height,this.width>=1&&(d*=.9/this.width,this.width=.9),this.height=d,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 _c.process(t,n,i,r,Or._INNER_MARGIN)}getFromText(t,n){const{rawDims:{pageWidth:i,pageHeight:r},rotation:o}=this.parent.viewport;return _c.extractContoursFromText(t,n,i,r,o,Or._INNER_MARGIN)}getDrawnSignature(t){const{rawDims:{pageWidth:n,pageHeight:i},rotation:r}=this.parent.viewport;return _c.processDrawnLines({lines:t,pageWidth:n,pageHeight:i,rotation:r,innerMargin:Or._INNER_MARGIN,mustSmooth:!1,areContours:!1})}createDrawingOptions({areContours:t,thickness:n}){t?this._drawingOptions=Or.getDefaultDrawingOptions():(this._drawingOptions=Or._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,Ku),color:[0,0,0],thickness:f(this,Ku)?0:r});return this.addComment(o),t?(o.paths={lines:n,points:i},o.uuid=f(this,_f),o.isCopy=!0):o.lines=n,f(this,sl)&&(o.accessibilityData={type:"Figure",alt:f(this,sl)}),o}static deserializeDraw(t,n,i,r,o,a){return a.areContours?JA.deserialize(t,n,i,r,o,a):S_.deserialize(t,n,i,r,o,a)}static async deserialize(t,n,i){var o;const r=await super.deserialize(t,n,i);return R(r,Ku,t.areContours),r.description=((o=t.accessibilityData)==null?void 0:o.alt)||"",R(r,_f,t.uuid),r}};Ku=new WeakMap,sl=new WeakMap,qu=new WeakMap,_f=new WeakMap,Se(Or,"_type","signature"),Se(Or,"_editorType",Et.SIGNATURE),Se(Or,"_defaultDrawingOptions",null);let nE=Or;var Ws,Gn,Qu,pc,Xu,Ym,mc,wf,nl,Jr,Jm,Yt,Rv,Iv,_S,wS,SS,rE,kS,wB;class iE extends cs{constructor(t){super({...t,name:"stampEditor"});B(this,Yt);B(this,Ws,null);B(this,Gn,null);B(this,Qu,null);B(this,pc,null);B(this,Xu,null);B(this,Ym,"");B(this,mc,null);B(this,wf,!1);B(this,nl,null);B(this,Jr,!1);B(this,Jm,!1);R(this,pc,t.bitmapUrl),R(this,Xu,t.bitmapFile),this.defaultL10nId="pdfjs-editor-stamp-editor"}static initialize(t,n){cs.initialize(t,n)}static isHandlingMimeForPasting(t){return U1.includes(t)}static paste(t,n){n.pasteEditor({mode:Et.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)&&(R(this,Ws,null),this._uiManager.imageManager.deleteId(f(this,Gn)),(t=f(this,mc))==null||t.remove(),R(this,mc,null),f(this,nl)&&(clearTimeout(f(this,nl)),R(this,nl,null))),super.remove()}rebuild(){if(!this.parent){f(this,Gn)&&H(this,Yt,_S).call(this);return}super.rebuild(),this.div!==null&&(f(this,Gn)&&f(this,mc)===null&&H(this,Yt,_S).call(this),this.isAttachedToDOM||this.parent.add(this))}onceAdded(t){this._isDraggable=!0,t&&this.div.focus()}isEmpty(){return!(f(this,Qu)||f(this,Ws)||f(this,pc)||f(this,Xu)||f(this,Gn)||f(this,wf))}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,wf)||(f(this,Ws)?H(this,Yt,wS).call(this):H(this,Yt,_S).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)&&(R(this,Gn,i),r&&R(this,Ws,r),R(this,wf,!1),H(this,Yt,wS).call(this))}_onResized(){this.onScaleChanging()}onScaleChanging(){if(!this.parent)return;f(this,nl)!==null&&clearTimeout(f(this,nl)),R(this,nl,setTimeout(()=>{R(this,nl,null),H(this,Yt,rE).call(this)},200))}copyCanvas(t,n,i=!1){t||(t=224);const{width:r,height:o}=f(this,Ws),a=new hl;let c=f(this,Ws),l=r,u=o,d=null;if(n){if(r>n||o>n){const A=Math.min(n/r,n/o);l=Math.floor(r*A),u=Math.floor(o*A)}d=document.createElement("canvas");const p=d.width=Math.ceil(l*a.sx),g=d.height=Math.ceil(u*a.sy);f(this,Jr)||(c=H(this,Yt,SS).call(this,p,g));const v=d.getContext("2d");v.filter=this._uiManager.hcmFilter;let m="white",y="#cfcfd8";this._uiManager.hcmFilter!=="none"?y="black":ise.isDarkMode&&(m="#8f8f9d",y="#42414d");const _=15,b=_*a.sx,k=_*a.sy,w=new OffscreenCanvas(b*2,k*2),T=w.getContext("2d");T.fillStyle=m,T.fillRect(0,0,b*2,k*2),T.fillStyle=y,T.fillRect(0,0,b,k),T.fillRect(b,k,b,k),v.fillStyle=v.createPattern(w,"repeat"),v.fillRect(0,0,p,g),v.drawImage(c,0,0,c.width,c.height,0,0,p,g)}let h=null;if(i){let p,g;if(a.symmetric&&c.width<t&&c.height<t)p=c.width,g=c.height;else if(c=f(this,Ws),r>t||o>t){const y=Math.min(t/r,t/o);p=Math.floor(r*y),g=Math.floor(o*y),f(this,Jr)||(c=H(this,Yt,SS).call(this,p,g))}const m=new OffscreenCanvas(p,g).getContext("2d",{willReadFrequently:!0});m.drawImage(c,0,0,c.width,c.height,0,0,p,g),h={width:p,height:g,data:m.getImageData(0,0,p,g).data}}return{canvas:d,width:l,height:u,imageData:h}}static async deserialize(t,n,i){var m;let r=null,o=!1;if(t instanceof $$){const{data:{rect:y,rotation:_,id:b,structParent:k,popupRef:w,richText:T,contentsObj:A,creationDate:C,modificationDate:E},container:x,parent:{page:{pageNumber:D}},canvas:N}=t;let O,G;N?(delete t.canvas,{id:O,bitmap:G}=i.imageManager.getFromCanvas(x.id,N),N.remove()):(o=!0,t._hasNoCanvas=!0);const Z=((m=await n._structTree.getAriaAttributes(`${Ap}${b}`))==null?void 0:m.get("aria-label"))||"";r=t={annotationType:Et.STAMP,bitmapId:O,bitmap:G,pageIndex:D-1,rect:y.slice(0),rotation:_,annotationElementId:b,id:b,deleted:!1,accessibilityData:{decorative:!1,altText:Z},isSvg:!1,structParent:k,popupRef:w,richText:T,comment:(A==null?void 0:A.str)||null,creationDate:C,modificationDate:E}}const a=await super.deserialize(t,n,i),{rect:c,bitmap:l,bitmapUrl:u,bitmapId:d,isSvg:h,accessibilityData:p}=t;o?(i.addMissingCanvas(t.id,a),R(a,wf,!0)):d&&i.imageManager.isValidId(d)?(R(a,Gn,d),l&&R(a,Ws,l)):R(a,pc,u),R(a,Jr,h);const[g,v]=a.pageDimensions;return a.width=(c[2]-c[0])/g,a.height=(c[3]-c[1])/v,p&&(a.altTextData=p),a._initialData=r,t.comment&&a.setCommentData(t),R(a,Jm,!!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,Jr)});if(this.addComment(i),t)return i.bitmapUrl=H(this,Yt,kS).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=H(this,Yt,wB).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,Jr)?(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=H(this,Yt,kS).call(this,!1);else if(f(this,Jr)){const c=n.stamps.get(f(this,Gn));a>c.area&&(c.area=a,c.serialized.bitmap.close(),c.serialized.bitmap=H(this,Yt,kS).call(this,!1))}return i}renderAnnotationElement(t){return this.deleted?(t.hide(),null):(t.updateEdited({rect:this.getPDFRect(),popup:this.comment}),null)}}Ws=new WeakMap,Gn=new WeakMap,Qu=new WeakMap,pc=new WeakMap,Xu=new WeakMap,Ym=new WeakMap,mc=new WeakMap,wf=new WeakMap,nl=new WeakMap,Jr=new WeakMap,Jm=new WeakMap,Yt=new WeakSet,Rv=function(t,n=!1){if(!t){this.remove();return}R(this,Ws,t.bitmap),n||(R(this,Gn,t.id),R(this,Jr,t.isSvg)),t.file&&R(this,Ym,t.file.name),H(this,Yt,wS).call(this)},Iv=function(){if(R(this,Qu,null),this._uiManager.enableWaiting(!1),!!f(this,mc)){if(this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&f(this,Ws)){this.addEditToolbar().then(()=>{this._editToolbar.hide(),this._uiManager.editAltText(this,!0)});return}if(!this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&f(this,Ws)){this._reportTelemetry({action:"pdfjs.image.image_added",data:{alt_text_modal:!1,alt_text_type:"empty"}});try{this.mlGuessAltText()}catch{}}this.div.focus()}},_S=function(){if(f(this,Gn)){this._uiManager.enableWaiting(!0),this._uiManager.imageManager.getFromId(f(this,Gn)).then(i=>H(this,Yt,Rv).call(this,i,!0)).finally(()=>H(this,Yt,Iv).call(this));return}if(f(this,pc)){const i=f(this,pc);R(this,pc,null),this._uiManager.enableWaiting(!0),R(this,Qu,this._uiManager.imageManager.getFromUrl(i).then(r=>H(this,Yt,Rv).call(this,r)).finally(()=>H(this,Yt,Iv).call(this)));return}if(f(this,Xu)){const i=f(this,Xu);R(this,Xu,null),this._uiManager.enableWaiting(!0),R(this,Qu,this._uiManager.imageManager.getFromFile(i).then(r=>H(this,Yt,Rv).call(this,r)).finally(()=>H(this,Yt,Iv).call(this)));return}const t=document.createElement("input");t.type="file",t.accept=U1.join(",");const n=this._uiManager._signal;R(this,Qu,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}}),H(this,Yt,Rv).call(this,r)}i()},{signal:n}),t.addEventListener("cancel",()=>{this.remove(),i()},{signal:n})}).finally(()=>H(this,Yt,Iv).call(this))),t.click()},wS=function(){var l;const{div:t}=this;let{width:n,height:i}=f(this,Ws);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=R(this,mc,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),H(this,Yt,rE).call(this),f(this,Jm)||(this.parent.addUndoableEditor(this),R(this,Jm,!0)),this._reportTelemetry({action:"inserted_image"}),f(this,Ym)&&this.div.setAttribute("aria-description",f(this,Ym)),this.annotationElementId||this._uiManager.a11yAlert(cs._l10nAlert.stamp)},SS=function(t,n){const{width:i,height:r}=f(this,Ws);let o=i,a=r,c=f(this,Ws);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 d=new OffscreenCanvas(o,a);d.getContext("2d").drawImage(c,0,0,l,u,0,0,o,a),c=d.transferToImageBitmap()}return c},rE=function(){const[t,n]=this.parentDimensions,{width:i,height:r}=this,o=new hl,a=Math.ceil(i*t*o.sx),c=Math.ceil(r*n*o.sy),l=f(this,mc);if(!l||l.width===a&&l.height===c)return;l.width=a,l.height=c;const u=f(this,Jr)?f(this,Ws):H(this,Yt,SS).call(this,a,c),d=l.getContext("2d");d.filter=this._uiManager.hcmFilter,d.drawImage(u,0,0,u.width,u.height,0,0,a,c)},kS=function(t){if(t){if(f(this,Jr)){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,Ws),n.getContext("2d").drawImage(f(this,Ws),0,0),n.toDataURL()}if(f(this,Jr)){const[n,i]=this.pageDimensions,r=Math.round(this.width*n*md.PDF_TO_CSS_UNITS),o=Math.round(this.height*i*md.PDF_TO_CSS_UNITS),a=new OffscreenCanvas(r,o);return a.getContext("2d").drawImage(f(this,Ws),0,0,f(this,Ws).width,f(this,Ws).height,0,0,r,o),a.transferToImageBitmap()}return structuredClone(f(this,Ws))},wB=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}},Se(iE,"_type","stamp"),Se(iE,"_editorType",Et.STAMP);var Sf,Zm,Yu,Ju,gc,br,Zu,eg,tg,ga,vc,Kn,yc,ed,sg,nt,td,Ts,aE,SB,Ra,lE,cE,CS;const na=class na{constructor({uiManager:e,pageIndex:t,div:n,structTreeLayer:i,accessibilityManager:r,annotationLayer:o,drawLayer:a,textLayer:c,viewport:l,l10n:u}){B(this,Ts);B(this,Sf);B(this,Zm,!1);B(this,Yu,null);B(this,Ju,null);B(this,gc,null);B(this,br,new Map);B(this,Zu,!1);B(this,eg,!1);B(this,tg,!1);B(this,ga,null);B(this,vc,null);B(this,Kn,null);B(this,yc,null);B(this,ed,null);B(this,sg,-1);B(this,nt);const d=[...f(na,td).values()];if(!na._initialized){na._initialized=!0;for(const h of d)h.initialize(u,e)}e.registerEditorTypes(d),R(this,nt,e),this.pageIndex=t,this.div=n,R(this,Sf,r),R(this,Yu,o),this.viewport=l,R(this,Kn,c),this.drawLayer=a,this._structTree=i,f(this,nt).addLayer(this)}get isEmpty(){return f(this,br).size===0}get isInvisible(){return this.isEmpty&&f(this,nt).getMode()===Et.NONE}updateToolbar(e){f(this,nt).updateToolbar(e)}updateMode(e=f(this,nt).getMode()){switch(H(this,Ts,CS).call(this),e){case Et.NONE:this.div.classList.toggle("nonEditing",!0),this.disableTextSelection(),this.togglePointerEvents(!1),this.toggleAnnotationLayerPointerEvents(!0),this.disableClick();return;case Et.INK:this.disableTextSelection(),this.togglePointerEvents(!0),this.enableClick();break;case Et.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===Et.POPUP)t.toggle("commentEditing",!0);else{t.toggle("commentEditing",!1);for(const n of f(na,td).values())t.toggle(`${n._type}Editing`,e===n._editorType)}this.div.hidden=!1}hasTextLayer(e){var t;return e===((t=f(this,Kn))==null?void 0:t.div)}setEditingState(e){f(this,nt).setEditingState(e)}addCommands(e){f(this,nt).addCommands(e)}cleanUndoStack(e){f(this,nt).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,Yu))==null||t.togglePointerEvents(e)}async enable(){var n;R(this,tg,!0),this.div.tabIndex=0,this.togglePointerEvents(!0),this.div.classList.toggle("nonEditing",!1),(n=f(this,ed))==null||n.abort(),R(this,ed,null);const e=new Set;for(const i of f(this,Ts,aE))i.enableEditing(),i.show(!0),i.annotationElementId&&(f(this,nt).removeChangedExistingAnnotation(i),e.add(i.annotationElementId));const t=f(this,Yu);if(t)for(const i of t.getEditableAnnotations()){if(i.hide(),f(this,nt).isDeletedAnnotationElement(i.data.id)||e.has(i.data.id))continue;const r=await this.deserialize(i);r&&(this.addOrRebuild(r),r.enableEditing())}R(this,tg,!1),f(this,nt)._eventBus.dispatch("editorsrendered",{source:this,pageNumber:this.pageIndex+1})}disable(){var i;if(R(this,eg,!0),this.div.tabIndex=-1,this.togglePointerEvents(!1),this.div.classList.toggle("nonEditing",!0),f(this,Kn)&&!f(this,ed)){R(this,ed,new AbortController);const r=f(this,nt).combinedSignal(f(this,ed));f(this,Kn).div.addEventListener("pointerdown",o=>{const{clientX:c,clientY:l,timeStamp:u}=o,d=f(this,sg);if(u-d>500){R(this,sg,u);return}R(this,sg,-1);const{classList:h}=this.div;h.toggle("getElements",!0);const p=document.elementsFromPoint(c,l);if(h.toggle("getElements",!1),!this.div.contains(p[0]))return;let g;const v=new RegExp(`^${Sy}[0-9]+$`);for(const y of p)if(v.test(y.id)){g=y.id;break}if(!g)return;const m=f(this,br).get(g);(m==null?void 0:m.annotationElementId)===null&&(Xs(o),m.dblclick(o))},{signal:r,capture:!0})}const e=f(this,Yu),t=[];if(e){const r=new Map,o=new Map;for(const a of f(this,Ts,aE)){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,nt).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,nt).addChangedExistingAnnotation(l),l.renderAnnotationElement(a)&&l.show(!1)),a.show()}}H(this,Ts,CS).call(this),this.isEmpty&&(this.div.hidden=!0);const{classList:n}=this.div;for(const r of f(na,td).values())n.remove(`${r._type}Editing`);this.disableTextSelection(),this.toggleAnnotationLayerPointerEvents(!0),e==null||e.updateFakeAnnotations(t),R(this,eg,!1)}getEditableAnnotation(e){var t;return((t=f(this,Yu))==null?void 0:t.getEditableAnnotation(e))||null}setActiveEditor(e){f(this,nt).getActive()!==e&&f(this,nt).setActiveEditor(e)}enableTextSelection(){var e;if(this.div.tabIndex=-1,(e=f(this,Kn))!=null&&e.div&&!f(this,yc)){R(this,yc,new AbortController);const t=f(this,nt).combinedSignal(f(this,yc));f(this,Kn).div.addEventListener("pointerdown",H(this,Ts,SB).bind(this),{signal:t}),f(this,Kn).div.classList.add("highlighting")}}disableTextSelection(){var e;this.div.tabIndex=0,(e=f(this,Kn))!=null&&e.div&&f(this,yc)&&(f(this,yc).abort(),R(this,yc,null),f(this,Kn).div.classList.remove("highlighting"))}enableClick(){if(f(this,Ju))return;R(this,Ju,new AbortController);const e=f(this,nt).combinedSignal(f(this,Ju));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,Ju))==null||e.abort(),R(this,Ju,null)}attach(e){f(this,br).set(e.id,e);const{annotationElementId:t}=e;t&&f(this,nt).isDeletedAnnotationElement(t)&&f(this,nt).removeDeletedAnnotationElement(e)}detach(e){var t;f(this,br).delete(e.id),(t=f(this,Sf))==null||t.removePointerInTextLayer(e.contentDiv),!f(this,eg)&&e.annotationElementId&&f(this,nt).addDeletedAnnotationElement(e)}remove(e){this.detach(e),f(this,nt).removeEditor(e),e.div.remove(),e.isAttachedToDOM=!1}changeParent(e){var t;e.parent!==this&&(e.parent&&e.annotationElementId&&(f(this,nt).addDeletedAnnotationElement(e),cs.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,nt).addEditor(e),this.attach(e),!e.isAttachedToDOM){const t=e.render();this.div.append(t),e.isAttachedToDOM=!0}e.fixAndSetPosition(),e.onceAdded(!f(this,tg)),f(this,nt).addToAnnotationStorage(e),e._reportTelemetry(e.telemetryInitialData)}}moveEditorInDOM(e){var n;if(!e.isAttachedToDOM)return;const{activeElement:t}=document;e.div.contains(t)&&!f(this,gc)&&(e._focusEventsAllowed=!1,R(this,gc,setTimeout(()=>{R(this,gc,null),e.div.contains(document.activeElement)?e._focusEventsAllowed=!0:(e.div.addEventListener("focusin",()=>{e._focusEventsAllowed=!0},{once:!0,signal:f(this,nt)._signal}),t.focus())},0))),e._structTreeParentId=(n=f(this,Sf))==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,br).values())if(t.uid===e)return t;return null}combinedSignal(e){return f(this,nt).combinedSignal(e)}canCreateNewEmptyEditor(){var e;return(e=f(this,Ts,Ra))==null?void 0:e.canCreateNewEmptyEditor()}async pasteEditor(e,t){this.updateToolbar(e),await f(this,nt).updateMode(e.mode);const{offsetX:n,offsetY:i}=H(this,Ts,cE).call(this),r=f(this,nt).getId(),o=H(this,Ts,lE).call(this,{parent:this,id:r,x:n,y:i,uiManager:f(this,nt),isCentered:!0,...t});o&&this.add(o)}async deserialize(e){var t;return await((t=f(na,td).get(e.annotationType??e.annotationEditorType))==null?void 0:t.deserialize(e,this,f(this,nt)))||null}createAndAddNewEditor(e,t,n={}){const i=f(this,nt).getId(),r=H(this,Ts,lE).call(this,{parent:this,id:i,x:e.offsetX,y:e.offsetY,uiManager:f(this,nt),isCentered:t,...n});return r&&this.add(r),r}get boundingClientRect(){return this.div.getBoundingClientRect()}addNewEditor(e={}){this.createAndAddNewEditor(H(this,Ts,cE).call(this),!0,e)}setSelected(e){f(this,nt).setSelected(e)}toggleSelected(e){f(this,nt).toggleSelected(e)}unselect(e){f(this,nt).unselect(e)}pointerup(e){var i;const{isMac:t}=Rs.platform;if(e.button!==0||e.ctrlKey&&t||e.target!==this.div||!f(this,Zu)||(R(this,Zu,!1),(i=f(this,Ts,Ra))!=null&&i.isDrawer&&f(this,Ts,Ra).supportMultipleDrawings))return;if(!f(this,Zm)){R(this,Zm,!0);return}const n=f(this,nt).getMode();if(n===Et.STAMP||n===Et.POPUP||n===Et.SIGNATURE){f(this,nt).unselectAll();return}this.createAndAddNewEditor(e,!1)}pointerdown(e){var i;if(f(this,nt).getMode()===Et.HIGHLIGHT&&this.enableTextSelection(),f(this,Zu)){R(this,Zu,!1);return}const{isMac:t}=Rs.platform;if(e.button!==0||e.ctrlKey&&t||e.target!==this.div)return;if(R(this,Zu,!0),(i=f(this,Ts,Ra))!=null&&i.isDrawer){this.startDrawingSession(e);return}const n=f(this,nt).getActive();R(this,Zm,!n||n.isEmpty())}startDrawingSession(e){if(this.div.focus({preventScroll:!0}),f(this,ga)){f(this,Ts,Ra).startDrawing(this,f(this,nt),!1,e);return}f(this,nt).setCurrentDrawingSession(this),R(this,ga,new AbortController);const t=f(this,nt).combinedSignal(f(this,ga));this.div.addEventListener("blur",({relatedTarget:n})=>{n&&!this.div.contains(n)&&(R(this,vc,null),this.commitOrRemove())},{signal:t}),f(this,Ts,Ra).startDrawing(this,f(this,nt),!1,e)}pause(e){if(e){const{activeElement:t}=document;this.div.contains(t)&&R(this,vc,t);return}f(this,vc)&&setTimeout(()=>{var t;(t=f(this,vc))==null||t.focus(),R(this,vc,null)},0)}endDrawingSession(e=!1){return f(this,ga)?(f(this,nt).setCurrentDrawingSession(null),f(this,ga).abort(),R(this,ga,null),R(this,vc,null),f(this,Ts,Ra).endDrawing(e)):null}findNewParent(e,t,n){const i=f(this,nt).findParent(t,n);return i===null||i===this?!1:(i.changeParent(e),!0)}commitOrRemove(){return f(this,ga)?(this.endDrawingSession(),!0):!1}onScaleChanging(){f(this,ga)&&f(this,Ts,Ra).onScaleChangingWhenDrawing(this)}destroy(){var e,t;this.commitOrRemove(),((e=f(this,nt).getActive())==null?void 0:e.parent)===this&&(f(this,nt).commitOrRemove(),f(this,nt).setActiveEditor(null)),f(this,gc)&&(clearTimeout(f(this,gc)),R(this,gc,null));for(const n of f(this,br).values())(t=f(this,Sf))==null||t.removePointerInTextLayer(n.contentDiv),n.setParent(null),n.isAttachedToDOM=!1,n.div.remove();this.div=null,f(this,br).clear(),f(this,nt).removeLayer(this)}async render({viewport:e}){this.viewport=e,$f(this.div,e);for(const t of f(this,nt).getEditors(this.pageIndex))this.add(t),t.rebuild();await f(this,nt).findClonesForPage(this),this.div.hidden=this.isEmpty,this.updateMode()}update({viewport:e}){f(this,nt).commitOrRemove(),H(this,Ts,CS).call(this);const t=this.viewport.rotation,n=e.rotation;if(this.viewport=e,$f(this.div,{rotation:n}),t!==n)for(const i of f(this,br).values())i.rotate(n)}get pageDimensions(){const{pageWidth:e,pageHeight:t}=this.viewport.rawDims;return[e,t]}get scale(){return f(this,nt).viewParameters.realScale}};Sf=new WeakMap,Zm=new WeakMap,Yu=new WeakMap,Ju=new WeakMap,gc=new WeakMap,br=new WeakMap,Zu=new WeakMap,eg=new WeakMap,tg=new WeakMap,ga=new WeakMap,vc=new WeakMap,Kn=new WeakMap,yc=new WeakMap,ed=new WeakMap,sg=new WeakMap,nt=new WeakMap,td=new WeakMap,Ts=new WeakSet,aE=function(){return f(this,br).size!==0?f(this,br).values():f(this,nt).getEditors(this.pageIndex)},SB=function(e){f(this,nt).unselectAll();const{target:t}=e;if(t===f(this,Kn).div||(t.getAttribute("role")==="img"||t.classList.contains("endOfContent")||t.classList.contains("textLayerImages")||t.classList.contains("textLayerImagePlaceholder"))&&f(this,Kn).div.contains(t)){const{isMac:n}=Rs.platform;if(e.button!==0||e.ctrlKey&&n)return;f(this,nt).showAllEditors("highlight",!0,!0),f(this,Kn).div.classList.add("free"),this.toggleDrawing(),I0.startHighlighting(this,f(this,nt).direction==="ltr",{target:f(this,Kn).div,x:e.x,y:e.y}),f(this,Kn).div.addEventListener("pointerup",()=>{f(this,Kn).div.classList.remove("free"),this.toggleDrawing(!0)},{once:!0,signal:f(this,nt)._signal}),e.preventDefault()}},Ra=function(){return f(na,td).get(f(this,nt).getMode())},lE=function(e){const t=f(this,Ts,Ra);return t?new t.prototype.constructor(e):null},cE=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,[d,h]=this.viewport.rotation%180===0?[l,u]:[u,l];return{offsetX:d,offsetY:h}},CS=function(){for(const e of f(this,br).values())e.isEmpty()&&e.remove()},Se(na,"_initialized",!1),B(na,td,new Map([UA,YA,iE,I0,nE].map(e=>[e._editorType,e])));let oE=na;function Kne(s,e){return s===e?0:s.compareDocumentPosition(e)&Node.DOCUMENT_POSITION_FOLLOWING?-1:1}function pw(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 qne(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 uP(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 _r,Ji,Oo,c_,u_,kf,Cf,d_,rk,sd,nd,id,rd,bc,Ri,dE,hE,kB,TS,CB,pl,fE,TB,pE;const pt=class pt{constructor({filterFactory:e=null,pageColors:t=null,pageIndex:n,textLayer:i=null}){B(this,pl);B(this,_r,null);B(this,Ji,new Map);B(this,Oo,null);B(this,c_,null);B(this,u_,null);B(this,kf,null);B(this,Cf,new Map);if(this.pageIndex=n,R(this,c_,e),R(this,u_,t),i){const r=f(pt,bc).get(i);if(r!=null&&r.selectionDiv&&(r.selectionDiv.remove(),f(pt,nd).delete(r.selectionDiv)),f(pt,bc).set(i,{drawLayer:this}),f(pt,rd).add(i),R(this,Oo,i),R(this,kf,new MutationObserver(o=>{var a,c,l;if(!(!f(this,_r)||!((a=f(this,Oo))!=null&&a.isConnected)||!H(c=pt,Ri,hE).call(c))){for(const{addedNodes:u}of o)for(const d of u)if(d.nodeType===Node.ELEMENT_NODE&&d.classList.contains("endOfContent")){H(l=pt,Ri,TS).call(l);return}}})),f(this,kf).observe(i,{childList:!0}),f(pt,sd)===null){R(pt,sd,new AbortController);const{signal:o}=f(pt,sd);document.addEventListener("selectionchange",H(pt,Ri,TS).bind(pt),{signal:o}),document.addEventListener("pointerdown",()=>{R(pt,id,!0)},{signal:o}),document.addEventListener("pointerup",()=>{R(pt,id,!1)},{signal:o}),window.addEventListener("blur",()=>{R(pt,id,!1)},{signal:o})}}}setParent(e){var t,n,i;if(!f(this,_r)){R(this,_r,e),(t=f(this,Oo))!=null&&t.isConnected&&H(n=pt,Ri,hE).call(n)&&H(i=pt,Ri,TS).call(i);return}if(f(this,_r)!==e){if(f(this,Ji).size>0)for(const r of f(this,Ji).values())r.remove(),e.append(r);R(this,_r,e)}}static get _svgFactory(){return Mt(this,"_svgFactory",new x0)}draw(e,t=!1,n=!1){const i=Ls(pt,d_)._++,r=H(this,pl,fE).call(this),o=pt._svgFactory.createElement("defs");r.append(o);const a=pt._svgFactory.createElement("path");o.append(a);const c=`path_${i}`;a.setAttribute("id",c),a.setAttribute("vector-effect","non-scaling-stroke"),t&&f(this,Cf).set(i,a);const l=n?H(this,pl,TB).call(this,o,c):null,u=pt._svgFactory.createElement("use");return r.append(u),u.setAttribute("href",`#${c}`),this.updateProperties(r,e),f(this,Ji).set(i,r),{id:i,clipPathId:`url(#${l})`}}drawOutline(e,t){const n=Ls(pt,d_)._++,i=H(this,pl,fE).call(this),r=pt._svgFactory.createElement("defs");i.append(r);const o=pt._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 d=pt._svgFactory.createElement("mask");r.append(d),c=`mask_${n}`,d.setAttribute("id",c),d.setAttribute("maskUnits","objectBoundingBox");const h=pt._svgFactory.createElement("rect");d.append(h),h.setAttribute("width","1"),h.setAttribute("height","1"),h.setAttribute("fill","white");const p=pt._svgFactory.createElement("use");d.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=pt._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,Ji).set(n,i),n}finalizeDraw(e,t){f(this,Cf).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,Ji).get(e):e;if(a){if(n&&H(this,pl,pE).call(this,a,n),i&&H(c=pt,Ri,CB).call(c,a,i),r){const{classList:l}=a;for(const[u,d]of Object.entries(r))l.toggle(u,d)}if(o){const u=a.firstElementChild.firstElementChild;H(this,pl,pE).call(this,u,o)}}}updateParent(e,t){if(t===this)return;const n=f(this,Ji).get(e);n&&(f(t,_r).append(n),f(this,Ji).delete(e),f(t,Ji).set(e,n))}remove(e){f(this,Cf).delete(e),f(this,_r)!==null&&(f(this,Ji).get(e).remove(),f(this,Ji).delete(e))}destroy(){var e,t,n;R(this,_r,null);for(const i of f(this,Ji).values())i.remove();if(f(this,Ji).clear(),f(this,Cf).clear(),(e=f(this,kf))==null||e.disconnect(),R(this,kf,null),f(this,Oo)){const i=f(pt,bc).get(f(this,Oo));(i==null?void 0:i.drawLayer)===this&&(H(t=pt,Ri,dE).call(t,f(this,Oo)),f(pt,bc).delete(f(this,Oo)),f(pt,rd).delete(f(this,Oo)),f(pt,rd).size===0&&((n=f(pt,sd))==null||n.abort(),R(pt,sd,null),R(pt,id,!1))),R(this,Oo,null)}}};_r=new WeakMap,Ji=new WeakMap,Oo=new WeakMap,c_=new WeakMap,u_=new WeakMap,kf=new WeakMap,Cf=new WeakMap,d_=new WeakMap,rk=new WeakMap,sd=new WeakMap,nd=new WeakMap,id=new WeakMap,rd=new WeakMap,bc=new WeakMap,Ri=new WeakSet,dE=function(e){const t=f(this,bc).get(e);t!=null&&t.selectionDiv&&(t.selectionDiv.remove(),f(this,nd).delete(t.selectionDiv),t.selectionDiv=null,t.path=null)},hE=function(){const e=document.getSelection();return!!e&&!e.isCollapsed},kB=function(){return[...f(this,rd)].filter(e=>e.isConnected).sort(Kne)},TS=function(){var o;const e=document.getSelection();if(!e||e.isCollapsed){for(const a of f(this,nd))a.remove();f(this,nd).clear();return}const t=new WeakMap,n=H(this,Ri,kB).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:d,endContainer:h,endOffset:p}=l,g=pw(u),v=pw(h);const m=g===null,y=v===null;if(f(this,id)&&m!==y)return;if(e.rangeCount===1){const{anchorNode:k,anchorOffset:w,focusNode:T,focusOffset:A}=e,C=pw(k),E=pw(T),x=qne(k,w,T,A);C&&E&&x!==null&&(x?(u=k,d=w,g=C,h=T,p=A,v=E):(u=T,d=A,g=E,h=k,p=w,v=C))}const _=n.filter(k=>l.intersectsNode(k));if(_.length===0)continue;let b=!1;if(g||(g=_[0],u=g,d=0,b=!0),v||(v=_.at(-1),h=v,p=v.childNodes.length,b=!0),h.nodeType===Node.ELEMENT_NODE){if(h.classList.contains("endOfContent")){const k=h.previousSibling;if(!k)continue;h=k,p=k.nodeType===Node.TEXT_NODE?k.textContent.length:k.childNodes.length}else if(h.classList.contains("textLayer")&&h.childNodes.length===p){const k=uP(h,p,v);if(!k)continue;h=k.container,p=k.offset}}if(u.nodeType===Node.ELEMENT_NODE){const k=uP(u,d,g);if(!k)continue;u=k.container,d=k.offset}if(g===v&&!b&&_.includes(g)){i.push([l,g]);continue}for(const k of _){const w=k.firstChild;if(!w)continue;const T=document.createRange();if(k===g?T.setStart(u,d):T.setStartBefore(w),k===v)T.setEnd(h,p);else{const A=k.lastChild;if(!A)continue;if(A.nodeType===Node.ELEMENT_NODE&&A.classList.contains("endOfContent")){const C=A.previousSibling;if(!C)continue;T.setEndAfter(C)}else T.setEndAfter(A)}T.collapsed||i.push([T,k])}}const r=new Set(i.map(a=>a[1]));for(const a of f(this,rd))r.has(a)||H(this,Ri,dE).call(this,a);for(const[a,c]of i){const l=f(pt,bc).get(c);if(!l)continue;let u=t.get(c);if(!u){const v=c.getBoundingClientRect();u=(m,y,_,b)=>({x:(m-v.x)/v.width,y:(y-v.y)/v.height,width:_/v.width,height:b/v.height}),t.set(c,u)}const d=[];for(let{x:v,y:m,width:y,height:_}of a.getClientRects())y===0||_===0||({x:v,y:m,width:y,height:_}=u(v,m,y,_),!(y===1&&_===1)&&d.push(`M${v} ${m} h${y} v${_} h-${y} Z`));if(d.length===0)continue;const h=l.drawLayer;let p=l.selectionDiv,g=l.path;if(!p){const v=`clip_selection_${Ls(pt,rk)._++}`;p=document.createElement("div"),p.className="selection",p.style.clipPath=`url(#${v})`;const m=(o=f(h,c_))==null?void 0:o.createSelectionStyle(f(h,u_));if(m)for(const[b,k]of Object.entries(m))p.style.setProperty(b,k);const y=pt._svgFactory.create(1,1,!0);y.setAttribute("aria-hidden","true"),y.setAttribute("width","100%"),y.setAttribute("height","100%");const _=pt._svgFactory.createElement("clipPath");_.setAttribute("id",v),_.setAttribute("clipPathUnits","objectBoundingBox"),g=pt._svgFactory.createElement("path"),_.append(g),y.append(_),p.append(y),l.path=g,l.selectionDiv=p}!p.parentNode&&f(h,_r)&&(f(h,_r).append(p),f(this,nd).add(p)),g.setAttribute("d",d.join(" "))}},CB=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}%`},pl=new WeakSet,fE=function(){const e=pt._svgFactory.create(1,1,!0);return f(this,_r).append(e),e.setAttribute("aria-hidden","true"),e},TB=function(e,t){const n=pt._svgFactory.createElement("clipPath");e.append(n);const i=`clip_${t}`;n.setAttribute("id",i),n.setAttribute("clipPathUnits","objectBoundingBox");const r=pt._svgFactory.createElement("use");return n.append(r),r.setAttribute("href",`#${t}`),r.classList.add("clip"),i},pE=function(e,t){for(const[n,i]of Object.entries(t))i===null?e.removeAttribute(n):e.setAttribute(n,i)},B(pt,Ri),B(pt,d_,0),B(pt,rk,0),B(pt,sd,null),B(pt,nd,new Set),B(pt,id,!1),B(pt,rd,new Set),B(pt,bc,new WeakMap);let uE=pt;function mw(s){return`${(s*100).toFixed(2)}%`}var ng,h_,f_,ig,il,rl,p_,ok,AB;const iy=class iy{constructor(e,t,n,i){B(this,ok);B(this,ng,[]);B(this,h_,new Map);B(this,f_,null);B(this,ig,0);B(this,il,0);B(this,rl,0);R(this,ig,e),R(this,ng,t),R(this,il,n.rawDims.pageWidth),R(this,rl,n.rawDims.pageHeight),R(this,f_,i)}render(){const e=document.createElement("div");e.className="textLayerImages";for(let t=0;t<f(this,ng).length;t+=6){const n=H(this,ok,AB).call(this,f(this,ng).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,h_).get(n);if(!i)return;const r=(y=f(iy,p_))==null?void 0:y.deref();if(r===n)return;r&&(r.width=0,r.height=0),R(iy,p_,new WeakRef(n));const{inverseTransform:o,x1:a,y1:c,width:l,height:u}=i,d=f(this,f_).call(this),h=Math.ceil(a*d.width),p=Math.ceil(c*d.height),g=Math.floor((a+l/f(this,il))*d.width),v=Math.floor((c+u/f(this,rl))*d.height);n.width=g-h,n.height=v-p;const m=n.getContext("2d");m.setTransform(...o),m.translate(-h,-p),m.drawImage(d,0,0)}),e}};ng=new WeakMap,h_=new WeakMap,f_=new WeakMap,ig=new WeakMap,il=new WeakMap,rl=new WeakMap,p_=new WeakMap,ok=new WeakSet,AB=function([e,t,n,i,r,o]){const a=Math.hypot((r-e)*f(this,il),(o-t)*f(this,rl)),c=Math.hypot((n-e)*f(this,il),(i-t)*f(this,rl));if(a<f(this,ig)||c<f(this,ig))return null;const l=[(r-e)*f(this,il)/a,(o-t)*f(this,rl)/a,(n-e)*f(this,il)/c,(i-t)*f(this,rl)/c,0,0],u=Fe.inverseTransform(l),d=document.createElement("canvas");return d.className="textLayerImagePlaceholder",d.width=0,d.height=0,Object.assign(d.style,{opacity:0,position:"absolute",left:mw(e),top:mw(t),width:mw(a/f(this,il)),height:mw(c/f(this,rl)),transformOrigin:"0% 0%",transform:`matrix(${l.join(",")})`}),f(this,h_).set(d,{inverseTransform:u,width:a,height:c,x1:e,y1:t}),d},B(iy,p_,null);let mE=iy;globalThis._pdfjsTestingUtils={HighlightOutliner:zA};globalThis.pdfjsLib={AbortException:pd,AnnotationEditorLayer:oE,AnnotationEditorParamsType:Rt,AnnotationEditorType:Et,AnnotationEditorUIManager:Bf,AnnotationLayer:FA,AnnotationMode:iu,AnnotationType:Sn,applyOpacity:ose,build:kne,ColorPicker:E0,createValidAbsoluteUrl:nN,CSSConstants:rse,DOMSVGFactory:x0,DrawLayer:uE,FeatureTest:Rs,fetchData:MM,findContrastColor:ase,getDocument:S$,getFilenameFromUrl:tse,getPdfFilenameFromUrl:sse,getRGB:__,getRGBA:b_,getUuid:rN,GlobalWorkerOptions:ol,ImageKind:Hw,InvalidPDFException:B1,isDataScheme:xk,isPdfFile:RM,isValidExplicitDest:Mse,makeArr:AM,makeMap:EM,makeObj:H1,MathClamp:zs,noContextMenu:Go,normalizeUnicode:Zte,OPS:$l,OutputScale:hl,PasswordResponses:Gte,PDFDataRangeTransport:k$,PDFDateString:C0,PDFWorker:Ey,PermissionFlag:Vte,PixelsPerInch:md,RenderingCancelledException:xM,renderRichText:aN,ResponseException:k0,setLayerDimensions:$f,shadow:Mt,SignatureExtractor:_c,stopEvent:Xs,SupportedImageMimeTypes:U1,TextLayer:Ay,TextLayerImages:mE,TouchManager:A0,updateUrlHash:iN,Util:Fe,VerbosityLevel:Tk,version:Sne,XfaLayer:oN};const Qne="/static/dist/assets/pdf.worker.min.mjs",Xne={key:0,class:"pdf-preview-loading"},Yne={key:1,class:"pdf-preview-error"},Jne=ct({name:"PdfPreview",__name:"PdfPreview",props:{source:{}},setup(s){ol.workerSrc=Qne;const e=s,t=ge(null),n=ge(!0),i=ge("");let r=null,o=[];function a(){const d=t.value;d&&d.querySelectorAll("canvas").forEach(h=>h.remove())}function c(){o.forEach(d=>{try{d.cancel()}catch{}}),o=[]}async function l(){if(c(),a(),r){try{await r.destroy()}catch{}r=null}}async function u(){const d=t.value;if(!(!d||!e.source)){await l(),n.value=!0,i.value="";try{const h=await fetch(e.source,{credentials:"same-origin"});if(!h.ok)throw new Error(h.statusText||S("chat.pdfLoadFailed"));const p=await h.arrayBuffer();if(!p.byteLength)throw new Error(S("chat.pdfEmpty"));r=await S$({data:p}).promise;const v=r.numPages,m=d.clientWidth;for(let y=1;y<=v;y++){const _=await r.getPage(y),b=_.getViewport({scale:1}),k=m>0?m/b.width:1,w=_.getViewport({scale:k}),T=document.createElement("canvas");T.className="pdf-preview-page",T.style.display="block",T.style.width="100%",T.style.height="auto";const A=window.devicePixelRatio||1;T.width=Math.floor(w.width*A),T.height=Math.floor(w.height*A),d.appendChild(T);const C=T.getContext("2d");if(!C)continue;C.scale(A,A);const E=_.render({canvasContext:C,viewport:w});o.push(E),await E.promise,o=o.filter(x=>x!==E)}n.value=!1}catch(h){const p=(h==null?void 0:h.message)||S("chat.pdfRenderFailed");if(p.toLowerCase().includes("cancel"))return;i.value=p,n.value=!1}}}return dn(()=>{u()}),Rn(()=>{l()}),Ke(()=>e.source,()=>{u()}),(d,h)=>(F(),U("div",{ref_key:"containerRef",ref:t,class:"pdf-preview"},[n.value?(F(),U("div",Xne,[h[0]||(h[0]=M("span",{class:"pdf-preview-spinner"},null,-1)),M("span",null,Q(d.$t("chat.pdfLoading")),1)])):i.value?(F(),U("div",Yne,Q(i.value),1)):me("",!0)],512))}}),Zne=qt(Jne,[["__scopeId","data-v-00a5a3f6"]]),eie={class:"show-file-card"},tie={class:"sfc-header"},sie=["title"],nie={class:"sfc-actions"},iie=["disabled"],rie={key:0,class:"sfc-loading"},oie={key:1,class:"sfc-error"},aie=["innerHTML"],lie={class:"sfc-csv-table"},cie={key:0,class:"sfc-csv-meta"},uie=["innerHTML"],die=["src","alt"],hie=5*60*1e3,fie=ct({name:"ShowFileCard",__name:"ShowFileCard",props:{path:{},name:{},type:{},description:{},preview:{}},setup(s){const e=new Map;function t(V){const I=e.get(V);return I?Date.now()-I.ts>hie?(e.delete(V),null):I.content:null}function n(V,I){e.set(V,{content:I,ts:Date.now()})}const i=s,r=ge(!1),o=ge(""),a=ge(""),c=ge(!1),l=ge(""),u=ge(!1),d=be(()=>i.type||C(i.path)),h=be(()=>i.name||i.path.split("/").pop()||"file"),p=be(()=>i.preview==="off"?!1:["text","code","json","csv","markdown","image","pdf"].includes(d.value)),g=be(()=>["text","code","json","csv","markdown"].includes(d.value)),v=be(()=>/\.html?$/i.test(i.path)),m=be(()=>typeof window.AndroidDownloadBridge<"u"||typeof window.AndroidThemeBridge<"u"),y=be(()=>ZD(i.path)),_=be(()=>{if(!a.value)return"";let V=a.value;if(d.value==="json")try{V=JSON.stringify(JSON.parse(V),null,2)}catch{}return O1(V,y.value)}),b=be(()=>a.value?KP(a.value,!1):""),k=be(()=>{if(d.value!=="csv"||!a.value)return null;const V=a.value.split(/\r?\n/).filter(se=>se.trim()),I=se=>{const oe=[];let ve="",le=!1;for(let ue=0;ue<se.length;ue++){const P=se[ue];le?P==='"'&&se[ue+1]==='"'?(ve+='"',ue++):P==='"'?le=!1:ve+=P:P==='"'?le=!0:P===","?(oe.push(ve),ve=""):ve+=P}return oe.push(ve),oe},$=100,L=I(V[0]||""),K=V.slice(1,$+1).map(I);return{header:L,rows:K,truncated:V.length>$+1}}),w=be(()=>{var V;return((V=k.value)==null?void 0:V.header)||[]}),T=be(()=>{var V;return((V=k.value)==null?void 0:V.rows)||[]}),A=be(()=>{var V;return((V=k.value)==null?void 0:V.truncated)||!1});function C(V){const I={".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"},$=V.toLowerCase(),L=$.lastIndexOf(".");if(L>=0){const K=$.slice(L);if(I[K])return I[K]}return"binary"}function E(){return`/api/file/content?path=${encodeURIComponent(i.path)}`}function x(V){const I=/\b(?:src|href)\s*=\s*["']([^"']*)["']/gi;let $;for(;$=I.exec(V);){const L=($[1]||"").trim();if(!(!L||L.startsWith("#"))&&!/^(https?:)?\/\//i.test(L)&&!/^(data|blob|mailto|tel|javascript):/i.test(L))return!0}return!1}async function D(){if(!u.value){u.value=!0,o.value="";try{let V=a.value||t(i.path)||"";if(!V){const I=await fetch(E());if(!I.ok){let $=I.statusText;try{$=(await I.json()).error||$}catch{}o.value=$||S("common.loadFailed");return}V=await I.text(),n(i.path,V),a.value=V}if(!V.trim()){o.value=S("chat.fileEmpty");return}sN({srcdoc:D1(V),allowScripts:!0,title:h.value,notice:x(V)?S("chat.htmlPreviewNotice"):void 0})}catch(V){o.value=V.message||S("chat.networkError")}finally{u.value=!1}}}async function N(){if(p.value){if(o.value="",!["image","pdf"].includes(d.value)){const V=t(i.path);if(V!==null){a.value=V;return}}r.value=!0;try{if(["image","pdf"].includes(d.value))l.value=E();else{const V=await fetch(E());if(!V.ok){let $=V.statusText;try{$=(await V.json()).error||$}catch{}o.value=$||S("common.loadFailed");return}const I=await V.text();a.value=I,n(i.path,I)}}catch(V){o.value=V.message||S("chat.networkError")}finally{r.value=!1}}}async function O(){const V=`/api/download/file?path=${encodeURIComponent(i.path)}`,I=i.path.split("/").pop()||"file",$=window.AndroidDownloadBridge;if($&&typeof $.downloadFile=="function")try{$.downloadFile(V,I);return}catch(L){console.warn("[ShowFileCard] Android 桥接下载失败,回退:",L)}try{const L=await fetch(V);if(!L.ok){let ve=L.statusText;try{ve=(await L.json()).error||ve}catch{}throw new Error(ve||S("common.downloadFailed"))}const K=await L.blob(),se=URL.createObjectURL(K),oe=document.createElement("a");oe.href=se,oe.download=I,document.body.appendChild(oe),oe.click(),document.body.removeChild(oe),setTimeout(()=>URL.revokeObjectURL(se),1e3)}catch(L){console.warn("[ShowFileCard] 下载失败:",L),window.open(V,"_blank")}}async function G(){if(a.value)try{await navigator.clipboard.writeText(a.value),c.value=!0,setTimeout(()=>{c.value=!1},2e3)}catch{}}function Z(){l.value&&Is().openImagePreview({url:l.value,name:h.value||""})}function q(){o.value=S("chat.imageLoadFailed")}return dn(()=>{p.value&&N()}),(V,I)=>(F(),U("div",eie,[M("div",tie,[I[1]||(I[1]=M("span",{class:"sfc-file-icon","aria-hidden":"true"},null,-1)),M("span",{class:"sfc-name",title:h.value},Q(h.value),9,sie),M("div",nie,[v.value?(F(),U("button",{key:0,type:"button",class:"sfc-btn",disabled:u.value,onClick:D},Q(u.value?V.$t("common.loading"):V.$t("chat.preview")),9,iie)):me("",!0),g.value?(F(),U("button",{key:1,type:"button",class:"sfc-btn",onClick:G},Q(c.value?V.$t("common.copied"):V.$t("common.copy")),1)):me("",!0),M("button",{type:"button",class:"sfc-btn sfc-btn-download",onClick:O},Q(V.$t("common.download")),1)])]),p.value?(F(),U("div",{key:0,class:Ce(["sfc-preview",{"sfc-preview--csv":d.value==="csv"}])},[r.value?(F(),U("div",rie,[I[2]||(I[2]=M("span",{class:"sfc-spinner"},null,-1)),M("span",null,Q(V.$t("common.loading")),1)])):o.value?(F(),U("div",oie,Q(o.value),1)):d.value==="text"||d.value==="code"||d.value==="json"?(F(),U("pre",{key:2,class:"sfc-code",innerHTML:_.value},null,8,aie)):d.value==="csv"?(F(),U(Ie,{key:3},[M("div",{class:Ce(["sfc-csv-scroll",{"sfc-csv-scroll--loading":r.value}])},[M("table",lie,[M("thead",null,[M("tr",null,[(F(!0),U(Ie,null,Ze(w.value,($,L)=>(F(),U("th",{key:L},Q($),1))),128))])]),M("tbody",null,[(F(!0),U(Ie,null,Ze(T.value,($,L)=>(F(),U("tr",{key:L},[(F(!0),U(Ie,null,Ze($,(K,se)=>(F(),U("td",{key:se},Q(K),1))),128))]))),128))])])],2),A.value?(F(),U("div",cie,Q(V.$t("chat.csvTruncated",{n:T.value.length})),1)):me("",!0)],64)):d.value==="markdown"?(F(),U("div",{key:4,class:"sfc-md",innerHTML:b.value},null,8,uie)):d.value==="image"?(F(),U("img",{key:5,class:Ce(["sfc-image",{"sfc-image--android":m.value}]),src:l.value,alt:h.value,onClick:I[0]||(I[0]=$=>Z()),onError:q},null,42,die)):d.value==="pdf"?(F(),Ft(Zne,{key:6,source:l.value},null,8,["source"])):me("",!0)],2)):me("",!0)]))}}),pie=qt(fie,[["__scopeId","data-v-bea3c149"]]);let mie=0,vT=0;const EB="v2-lite-throttled",yT=200;let bT=0;const _T=500;function L0(){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 Oa(s,e={}){const t=L0();if(t!=="off"&&!(t==="lite"&&!["observer:setup","observer:show-image-mutation","render:start","render:end"].includes(s))&&!(vT>=yT)){if(vT+=1,vT===yT){console.warn("[SHOW_IMAGE_DEBUG]","log-limit-reached",{max:yT,version:EB});return}console.log("[SHOW_IMAGE_DEBUG]",s,e)}}function gie(){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 bo(s,e={}){if(gie()&&!(bT>=_T)){if(bT+=1,bT===_T){console.warn("[SHOW_HTML_DEBUG]","log-limit-reached",{max:_T});return}console.log("[SHOW_HTML_DEBUG]",s,e)}}function gE(s=1600){if(!(typeof window>"u"))try{window.__SHOW_TAG_DRAWING_UNTIL__=Date.now()+s}catch{}}function $o(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 dP(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=${RB(i)},js=${IB(i)})`)}n=e.nextNode()}return t.slice(0,200)}function vie(){try{return window.localStorage.getItem("agents_workspace_mode")==="host"?"host":"docker"}catch{return"docker"}}function yie(s){if(!s)return"";let e=s.trim();if(!e)return"";if(/^https?:\/\//i.test(e)||(/^file:\/\//i.test(e)&&(e=e.replace(/^file:\/\//i,""),e=e.replace(/^\/(?=[A-Za-z]:\/)/,"")),e.startsWith("/user_upload/")))return e;if(e.startsWith("/")){const t=e.toLowerCase().indexOf("/user_upload/");if(t>=0)return"/user_upload/"+e.slice(t+13)}if(e==="/workspace"||(e.startsWith("/workspace/")&&(e=e.slice(11)),e.startsWith("./")&&(e=e.slice(2)),!e))return"";if(e.startsWith("/")){if(vie()==="host")return`/api/file/content?path=${encodeURIComponent(e)}`;if(e=e.replace(/^\/+/,""),!e)return""}return`/api/file/content?path=${encodeURIComponent(e)}`}function hP(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 MB=["1:1","16:9","9:16","4:3","3:4"],xB={"1:1":1,"16:9":16/9,"9:16":9/16,"4:3":4/3,"3:4":3/4};function bie(s){if(!s)return"1:1";const e=s.trim().toLowerCase().replace(/[x/]/g,":").replace(/\s+/g,"");return MB.includes(e)?e:"1:1"}function _ie(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 MB){const o=Math.abs(xB[r]-t);o<i&&(i=o,n=r)}return n}function RB(s){const e=s.getAttribute("ratio");if(e)return bie(e);const t=hP(s.getAttribute("width"),0),n=hP(s.getAttribute("height"),0);return t>0&&n>0?_ie(t,n):"1:1"}function wie(s){if(!s)return"off";const e=s.trim().toLowerCase();return["on","1","true","yes","enabled","enable"].includes(e)?"on":"off"}function IB(s){return wie(s.getAttribute("js"))}function fP(s){if(!s)return"";try{return decodeURIComponent(escape(atob(s)))}catch{return""}}function pP(s){return s?s.replace(/expression\s*\([^)]*\)/gi,"").replace(/url\s*\(\s*['"]?\s*javascript:[^)]+\)/gi,"url(about:blank)").replace(/@import[^;]+;/gi,""):""}function Sie(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 kie(s){const e=Dte.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",pP(c))})}),n.querySelectorAll("style").forEach(r=>{r.textContent=Sie(pP(r.textContent||""))}),n.body.innerHTML}function Cie(s){return s.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}const PB="__showHtmlCardControls";function LB(s){return s[PB]||null}function Tie(s,e){const t=LB(s);if(t){gE(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){bo("refresh:error",{message:n instanceof Error?n.message:String(n||"")})}}}let kc=null,Ip=null,mP=!1;function Cc(){kc&&(kc.remove(),kc=null,Ip=null)}function Aie(){mP||typeof document>"u"||(mP=!0,document.addEventListener("click",s=>{if(!kc)return;const e=s.target;e&&kc.contains(e)||e&&(Ip!=null&&Ip.contains(e))||Cc()},!0),document.addEventListener("keydown",s=>{s.key==="Escape"&&kc&&(s.stopPropagation(),Cc())},!0),window.addEventListener("resize",Cc),document.addEventListener("scroll",()=>{kc&&Cc()},!0))}function gP(s){const e=document.createElement("button");return e.type="button",e.className="show-html-card-menu__item",e.textContent=s,e}function Eie(s,e){if(Aie(),kc&&Ip===s){Cc();return}Cc();const t=document.createElement("div");t.className="show-html-card-menu",t.setAttribute("role","menu");const n=gP(S("appCore.refresh"));n.onclick=c=>{c.preventDefault(),c.stopPropagation(),Cc(),Tie(e,s)};const i=gP(S("appCore.fullscreen"));i.onclick=c=>{var d;c.preventDefault(),c.stopPropagation();const l=LB(e);Cc();const u=(d=l==null?void 0:l.getFullscreenPayload)==null?void 0:d.call(l);!u||!u.srcdoc||sN(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`,kc=t,Ip=s}function vP(s,e){s[PB]=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=S("appCore.cardActions"),n.setAttribute("aria-label",S("appCore.cardActions")),n.setAttribute("aria-haspopup","menu"),n.textContent="⋯",t.appendChild(n)),n.onclick=i=>{i.preventDefault(),i.stopPropagation(),Eie(n,s)}}function OB(s=document){if(!s)return;const t=L0()==="verbose",n=++mie,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)&&gE(),!t&&i.length===0&&r.length===0&&o.length===0&&!a)return;const c=s;Oa("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:dP(s)}),t&&Oa("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&&Oa("render:node-start",{renderId:n,src:l.getAttribute("src")||"",parent:$o(l.parentNode),prevSibling:$o(l.previousSibling),nextSibling:$o(l.nextSibling),childCount:l.childNodes.length,childPreview:Array.from(l.childNodes).slice(0,6).map(m=>$o(m))}),l.parentNode&&l.firstChild){const m=l.parentNode,y=l.nextSibling,_=Array.from(l.childNodes);t&&Oa("render:unwrap-children",{renderId:n,src:l.getAttribute("src")||"",moveCount:_.length,ref:$o(y),children:_.slice(0,10).map(b=>$o(b))}),_.forEach(b=>m.insertBefore(b,y))}const u=l.getAttribute("src")||"",d=yie(u);if(!d){const m=document.createElement("figure");m.className="chat-inline-card chat-inline-card--image chat-inline-image chat-inline-card--error chat-inline-image--error";const y=document.createElement("div");y.className="chat-inline-card__error chat-inline-image__error",y.textContent=u?S("appCore.imageUnsupportedPath",{src:u}):S("appCore.imageMissingPath"),m.appendChild(y),l.replaceChildren(m),l.setAttribute("data-rendered","1"),l.setAttribute("data-rendered-error","invalid-src"),t&&Oa("render:invalid-src",{renderId:n,rawSrc:u});return}const h=l.getAttribute("alt")||"",p=Cie(h.trim()),g=document.createElement("figure");g.className="chat-inline-card chat-inline-card--image chat-inline-image";const v=document.createElement("img");if(v.loading="lazy",v.src=d,v.alt=p,v.onerror=()=>{g.classList.add("chat-inline-card--error","chat-inline-image--error");const m=document.createElement("div");m.className="chat-inline-card__error chat-inline-image__error",m.textContent=S("appCore.imageLoadFailed"),g.appendChild(m)},g.appendChild(v),p){const m=document.createElement("figcaption");m.className="chat-inline-card__caption",m.innerHTML=p,g.appendChild(m)}l.replaceChildren(g),l.setAttribute("data-rendered","1"),t&&Oa("render:node-done",{renderId:n,rawSrc:u,mappedSrc:d,alt:h})}),r.forEach(l=>{if(gE(),!l.isConnected)return;const u=!!l.closest(".streaming-text"),d=xie(l),h=l.getAttribute("data-partial")==="1",p=l.getAttribute("data-encoded")||"",g=IB(l),v=RB(l);let m=v;if(u&&!h&&p){const C=Pv.get(d);(!C||C.encoded!==p||C.ratioKey!==m)&&Pv.set(d,{encoded:p,ratioKey:m})}else u||Pv.delete(d);const y=u?Pv.get(d):null,_=(y==null?void 0:y.encoded)||p;if(y!=null&&y.ratioKey&&(m=y.ratioKey),u){const C=Lv.get(d);C?m!==C&&(C==="1:1"||m!=="1:1")?(m=v,Lv.set(d,m)):m=C:Lv.set(d,m)}else Lv.delete(d);if(l.style.setProperty("--show-html-ar",String(xB[m]||1)),bo("render:node-seen",{renderId:n,inStreaming:u,pathKey:d,hasRendered:l.hasAttribute("data-rendered"),ratioAttr:l.getAttribute("ratio")||"",jsMode:g,ratioKey:m,partial:l.getAttribute("data-partial")||"",encodedLength:p.length,effectiveEncodedLength:_.length,innerLength:(l.innerHTML||"").length}),g==="on"&&h){let C=xS.get(d);if(!C){const E=document.createElement("div");E.className="chat-inline-card chat-inline-card--html chat-inline-card--pending chat-inline-html chat-inline-html--pending";const x=document.createElement("div");x.className="chat-inline-card__body chat-inline-html__host chat-inline-html__host--pending";const D=document.createElement("div");D.className="chat-inline-card__pending-tip chat-inline-html__pending-tip",D.textContent=S("appCore.renderingContent"),x.appendChild(D),E.appendChild(x),C={wrapper:E,host:x,tip:D},xS.set(d,C)}l.replaceChildren(C.wrapper),l.setAttribute("data-rendered","1"),bo("render:node-js-pending",{renderId:n,pathKey:d,ratioKey:m});return}if(g==="on"){const C=_?fP(_):l.innerHTML||"",E=D1(C);let x=vE.get(d);if(!x){const N=document.createElement("div");N.className="chat-inline-card chat-inline-card--html chat-inline-card--iframe chat-inline-html chat-inline-html--iframe";const O=document.createElement("iframe");O.className="chat-inline-html__iframe",O.setAttribute("sandbox","allow-scripts"),O.setAttribute("referrerpolicy","no-referrer"),O.setAttribute("loading","lazy"),O.setAttribute("allow","fullscreen 'none'"),N.appendChild(O),x={encoded:"",ratioKey:"1:1",srcdoc:"",wrapper:N,iframe:O},vE.set(d,x)}vP(x.wrapper,{onRefresh:()=>{const N=(x==null?void 0:x.srcdoc)||E;x.iframe.srcdoc='<!doctype html><html><head><meta charset="utf-8"></head><body></body></html>',requestAnimationFrame(()=>{x!=null&&x.iframe&&(x.iframe.srcdoc=N)}),bo("refresh:iframe",{pathKey:d,ratioKey:(x==null?void 0:x.ratioKey)||m,srcdocLength:N.length})},getFullscreenPayload:()=>{const N=(x==null?void 0:x.srcdoc)||"";return N?{srcdoc:N,allowScripts:!0}:null}});const D=x.encoded!==_||x.ratioKey!==m||x.srcdoc!==E;D&&(x.iframe.srcdoc=E,x.encoded=_,x.ratioKey=m,x.srcdoc=E),(!u||h||D||!l.hasAttribute("data-rendered"))&&l.replaceChildren(x.wrapper),l.setAttribute("data-rendered","1"),xS.delete(d),bo("render:node-js-iframe",{renderId:n,pathKey:d,ratioKey:m,encodedLength:_.length,srcdocLength:E.length,needsUpdate:D});return}if(u){const C=Date.now(),E=ES.get(d)||0;if(C-E<yP){const x=MS.get(d);x&&(l.replaceChildren(x.wrapper),l.setAttribute("data-rendered","1"),bo("render:node-throttled-rehydrate",{renderId:n,pathKey:d,ratioKey:m})),bo("render:node-throttled",{renderId:n,pathKey:d,now:C,lastTs:E,interval:yP});return}ES.set(d,C)}else ES.delete(d);const b=_?fP(_):l.innerHTML||"",k=kie(b);bo("render:node-content",{renderId:n,pathKey:d,jsMode:g,encodedLength:p.length,effectiveEncodedLength:_.length,rawLength:b.length,safeLength:k.length,ratioKey:m});let w=MS.get(d);if(!w){const C=document.createElement("div");C.className="chat-inline-card chat-inline-card--html chat-inline-html";const E=document.createElement("div");E.className="chat-inline-card__body chat-inline-html__host";const x=E.attachShadow({mode:"open"}),D=document.createElement("style");D.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 N=document.createElement("div");N.className="show-html-root",x.appendChild(D),x.appendChild(N),C.appendChild(E),w={encoded:"",safeHtml:"",ratioKey:"1:1",wrapper:C,host:E,root:N},MS.set(d,w)}vP(w.wrapper,{onRefresh:()=>{const C=(w==null?void 0:w.safeHtml)||"";w.root.innerHTML="",requestAnimationFrame(()=>{w!=null&&w.root&&(w.root.innerHTML=C)}),bo("refresh:shadow-root",{pathKey:d,ratioKey:(w==null?void 0:w.ratioKey)||m,safeLength:C.length})},getFullscreenPayload:()=>{const C=(w==null?void 0:w.safeHtml)||"";return C.trim()?{srcdoc:D1(C),allowScripts:!1}:null}});const T=w.encoded!==_||w.ratioKey!==m;T?(w.root.innerHTML=k,w.encoded=_,w.safeHtml=k,w.ratioKey=m,bo("render:node-persistent-update",{renderId:n,pathKey:d,encodedLength:_.length,ratioKey:m})):bo("render:node-persistent-reuse",{renderId:n,pathKey:d,encodedLength:_.length}),(!u||h||T||!l.hasAttribute("data-rendered"))&&l.replaceChildren(w.wrapper),l.setAttribute("data-rendered","1");const A=w.wrapper.getBoundingClientRect();bo("render:node-done",{renderId:n,pathKey:d,jsMode:g,ratioKey:m,rect:{x:Math.round(A.x),y:Math.round(A.y),w:Math.round(A.width),h:Math.round(A.height)},partial:l.getAttribute("data-partial")||"",inStreaming:u}),t&&Oa("render:show-html-done",{renderId:n,ratioKey:m,contentLength:b.length})}),o.forEach(l=>{!l.isConnected||l.hasAttribute("data-rendered")||(Oie(l),l.setAttribute("data-rendered","1"))}),Die(s),Oa("render:end",{renderId:n,orderAfter:dP(s)})}let Da=null,Pp=null,wT=!1,Bl=null,AS=null;const ES=new Map,yP=180,Pv=new Map,Lv=new Map,MS=new Map,xS=new Map,vE=new Map;let sy=null,qd=null,yE=!1,Qd=null,RS=0;const ST=300,bE=new Map;function Mie(s){if(wT)return;wT=!0;const e=()=>{wT=!1,OB(s)};if(typeof queueMicrotask=="function"){queueMicrotask(e);return}Promise.resolve().then(e)}function bP(){return document.querySelector(".messages-area")}function DB(){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 Ug(s,e={},t=s){if(!DB()||RS>=ST)return;const n=Date.now(),i=bE.get(t)||0;if(!(n-i<120)){if(bE.set(t,n),RS+=1,RS===ST){console.warn("[LAYOUT_DEBUG]","log-limit-reached",{max:ST});return}console.log("[LAYOUT_DEBUG]",s,e)}}function Wg(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 NB(){if(yE||!DB())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){Ug("layout:setup-wait",{reason:"targets-not-mounted"},"layout:setup-wait"),Qd&&window.clearTimeout(Qd),Qd=window.setTimeout(()=>{Qd=null,NB()},250);return}yE=!0,Ug("layout:setup",{trackedCount:e.length,tracked:e.map(n=>n.className||n.tagName.toLowerCase())});const t=()=>{Ug("layout:snapshot",{window:{innerWidth:window.innerWidth,innerHeight:window.innerHeight},main:Wg(document.querySelector(".main-container")),workspace:Wg(document.querySelector(".workspace-region")),panel:Wg(document.querySelector(".workspace-panel")),chat:Wg(document.querySelector(".chat-container")),messages:Wg(document.querySelector(".messages-area"))},"layout:snapshot")};t(),sy=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&&(Ug("layout:mutation",{count:i.length,items:i.slice(0,8).map(r=>({attr:r.attributeName,target:$o(r.target)}))}),t())}),sy.observe(document.body,{subtree:!0,attributes:!0,attributeFilter:["class","style"]}),qd=new ResizeObserver(n=>{n.length&&(Ug("layout:resize",{items:n.slice(0,8).map(i=>({target:$o(i.target),width:Math.round(i.contentRect.width),height:Math.round(i.contentRect.height)}))}),t())}),e.forEach(n=>qd==null?void 0:qd.observe(n)),window.addEventListener("resize",t)}function xie(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("/")}let _P=!1;function Rie(){_P||(_P=!0,document.addEventListener("click",s=>{const e=s.target;if(!e||typeof e.closest!="function")return;const t=e.closest("img");if(!t||t.closest(".show-file-card")||!(t.closest("figure.chat-inline-image")||t.closest(".tool-result-image")||t.closest(".text-content")))return;const i=t.currentSrc||t.src;i&&Is().openImagePreview({url:i,name:t.alt||""})}))}function Iie(){if(Da||Pp)return;NB();const s=()=>{const e=bP();if(!e){Bl&&window.clearTimeout(Bl),Bl=window.setTimeout(s,250);return}Bl&&(window.clearTimeout(Bl),Bl=null),!(AS===e&&Da)&&(Da&&(Da.disconnect(),Da=null),AS=e,Oa("observer:setup",{container:$o(e),debugMode:L0(),version:EB}),OB(e),Da=new MutationObserver(t=>{const i=L0()==="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})&&(Oa("observer:show-image-mutation",{mutationCount:t.length,mutations:i?t.slice(0,20).map(o=>({type:o.type,target:$o(o.target),added:Array.from(o.addedNodes).slice(0,6).map(a=>$o(a)),removed:Array.from(o.removedNodes).slice(0,6).map(a=>$o(a))})):void 0}),Mie(e))}),Da.observe(e,{childList:!0,subtree:!0}))};s(),Pp=new MutationObserver(()=>{const e=bP();e&&e!==AS&&s()}),Pp.observe(document.body,{childList:!0,subtree:!0})}function Pie(){Bl&&(window.clearTimeout(Bl),Bl=null),Da&&(Da.disconnect(),Da=null),Pp&&(Pp.disconnect(),Pp=null),sy&&(sy.disconnect(),sy=null),qd&&(qd.disconnect(),qd=null),Qd&&(window.clearTimeout(Qd),Qd=null),yE=!1,RS=0,bE.clear(),ES.clear(),Pv.clear(),Lv.clear(),MS.clear(),xS.clear(),vE.clear(),AS=null,Cc(),TM()}function lp(){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 Lie(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||S("common.downloadFailed"))})).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 kT=new WeakMap;function Oie(s){const e=(s.getAttribute("path")||"").trim().replace(/^\/+/,"");if(!e){s.replaceChildren(document.createTextNode(S("appCore.showFileMissingPath")));return}const t=kT.get(s);if(t){try{t.unmount()}catch{}kT.delete(s)}const n=document.createElement("div");n.className="show-file-card-root",s.replaceChildren(n);const i=GP(pie,{path:e});i.use(lF),i.mount(n),kT.set(s,i)}function Die(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&&Lie(i)})})}typeof window<"u"&&(window.katex=pF,lp(),window.addEventListener("resize",lp),window.addEventListener("orientationchange",lp),window.addEventListener("pageshow",lp),window.visualViewport&&(window.visualViewport.addEventListener("resize",lp),window.visualViewport.addEventListener("scroll",lp)));function Nie(){Xee().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 $ie(){var t;window.ensureCsrfToken&&window.ensureCsrfToken().catch(n=>{console.warn("CSRF token 初始化失败:",n)}),this.setupMobileViewportWatcher(),await this.bootstrapRoute(),this.$nextTick(()=>{this.ensureScrollListener(),nte(this)}),Iie(),Rie();const e=this.loadInitialData();(t=this.startProjectGitSummaryIdleRefresh)==null||t.call(this),this.startConnectionHeartbeat(),this.fetchTerminalCount(),this.startTerminalCountIdleRefresh(),this.checkTutorialPrompt(),ete().autoCheck(),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 Bie(){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(),Pie(),this.teardownDragAndDrop(),this.titleTypingTimer&&(clearInterval(this.titleTypingTimer),this.titleTypingTimer=null);const s=this.destroyEasterEggEffect(!0);s&&typeof s.catch=="function"&&s.catch(()=>{})}const Fie={resetAllStates(s="unspecified",e={}){this.waitingForSubAgent||(Be("重置所有前端状态",{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.chatClearStreamingResidualState(),this.apiRequestPending=!1,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=S("appTasks.autoApprovalRecordTitle"),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()}},Hie={async handleSidebarConversationTypeChange(s){var i,r,o;const{useConversationStore:e}=await St(async()=>{const{useConversationStore:a}=await Promise.resolve().then(()=>Ti);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 St(async()=>{const{useConversationStore:a}=await Promise.resolve().then(()=>Ti);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){Be("忽略已过期的对话列表响应",{requestSeq:o,responseOffset:s,refreshToken:r,currentRefreshToken:this.conversationListRefreshToken});return}const u=n.conversationsCache[i],d=l.data.conversations;if(s===0?u.list.splice(0,u.list.length,...d):u.list.push(...d),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)}Be(`已加载 ${u.list.length} 个对话`);const h=i==="multi_agent"?"normal":"multi_agent";s===0&&!n.conversationsCache[h].loaded&&this.loadConversationTypeCache(h).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 St(async()=>{const{useConversationStore:c}=await Promise.resolve().then(()=>Ti);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(al("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 St(async()=>{const{useTaskStore:d}=await Promise.resolve().then(()=>io);return{useTaskStore:d}},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){Be("对话 bootstrap 成功:",l),al("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,d=String((u==null?void 0:u.status)||"");u&&new Set(["succeeded","failed","canceled"]).has(d)&&((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(),al("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:S("appMessages.loadConversationFailedTitle"),message:l.message||S("appMessages.serverNotSuccessMessage"),type:"error"})}catch(l){console.error("加载对话异常:",l),al("loadConversation:error",{conversationId:s,error:(l==null?void 0:l.message)||String(l)}),this.suppressTitleTyping=!1,this.titleReady=!0,this.uiPushToast({title:S("appMessages.loadConversationErrorTitle"),message:l.message||String(l),type:"error"})}}},Uie={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;al("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=Js())==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 St(async()=>{const{useConversationStore:u}=await Promise.resolve().then(()=>Ti);return{useConversationStore:u}},void 0);this.newConversationType=l().sidebarConversationType==="multi_agent"?"multi_agent":"agent",QD(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=Js();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,Be("应用默认运行模式:",c)),this.reasoningEffort=u,l&&(this.currentModelKey=l,Be("应用默认模型:",l)),c==="thinking"?this.thinkingMode=!0:c==="fast"&&(this.thinkingMode=!1)}}catch(a){console.warn("应用个性化默认设置失败:",a)}try{const{useTaskStore:a}=await St(async()=>{const{useTaskStore:l}=await Promise.resolve().then(()=>io);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=Js();this.versioningHostMode&&a.form.versioning_enabled_by_default&&a.form.versioning_backup_mode==="full"&&(e=this.uiPushToast({title:S("appMessages.initializingBackupTitle"),message:S("appMessages.initializingBackupMessage"),type:"info",duration:null,closable:!1}),this.versioningInitializingBackupToastId=e);const{useConversationStore:l}=await St(async()=>{const{useConversationStore:v}=await Promise.resolve().then(()=>Ti);return{useConversationStore:v}},void 0),u=l().sidebarConversationType==="multi_agent",d=u?"/api/multiagent/conversations":"/api/conversations",h=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}),g=await(await fetch(d,{method:"POST",headers:{"Content-Type":"application/json"},body:h})).json();if(g.success){const v=g.conversation_id,m=_=>new Promise(b=>{window.setTimeout(b,_)});Be("新对话创建成功:",v),al("createNewConversation:created",{newConversationId:v});const y={id:v,title:S("common.newConversation"),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(_=>_&&_.id!==v));try{const{useConversationStore:_}=await St(async()=>{const{useConversationStore:w}=await Promise.resolve().then(()=>Ti);return{useConversationStore:w}},void 0),b=_(),k=this.currentHostWorkspaceId;if(k){b.ensureWorkspaceGroup(k);const w=b.workspaceGroups.find(T=>T.workspaceId===k);w&&(w.conversations.splice(0,w.conversations.length,y,...w.conversations.filter(T=>T.id!==v)),w.expanded=!0,w.visibleOffset=0)}}catch{}window.setTimeout(()=>{const _={...this.conversationInsertAnimations};delete _[v],this.conversationInsertAnimations=_,this.conversationListAnimationMode="idle"},700),await m(540),await this.loadConversation(v,{force:!0}),al("createNewConversation:after-load",{newConversationId:v,currentConversationId:this.currentConversationId}),this.conversationsOffset=0,await this.loadConversationsList(),al("createNewConversation:after-refresh",{newConversationId:v,conversationsLen:Array.isArray(this.conversations)?this.conversations.length:"n/a"});try{const{useConversationStore:_}=await St(async()=>{const{useConversationStore:w}=await Promise.resolve().then(()=>Ti);return{useConversationStore:w}},void 0),b=_(),k=this.currentHostWorkspaceId;k&&await b.loadWorkspaceConversations(k,{refresh:!0})}catch{}await((o=this.refreshRunningWorkspaceTasks)==null?void 0:o.call(this))}else console.error("创建对话失败:",g.message),this.uiPushToast({title:S("appMessages.createConversationFailed"),message:g.message||S("appMessages.serverNotSuccessMessage"),type:"error"})}catch(a){console.error("创建对话异常:",a),this.uiPushToast({title:S("appMessages.createConversationErrorTitle"),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 St(async()=>{const{useConversationStore:c}=await Promise.resolve().then(()=>Ti);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;Be("工作区新对话创建成功:",c);const l={id:c,title:S("common.newConversation"),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 St(async()=>{const{useConversationStore:p}=await Promise.resolve().then(()=>Ti);return{useConversationStore:p}},void 0),d=u();d.ensureWorkspaceGroup(s);const h=d.workspaceGroups.find(p=>p.workspaceId===s);h&&(h.conversations.splice(0,h.conversations.length,l,...h.conversations.filter(p=>p.id!==c)),h.expanded=!0,h.visibleOffset=0),window.setTimeout(()=>{d.loadWorkspaceConversations(s,{refresh:!0}).catch(()=>{})},300)}catch{}}else console.error("创建对话失败:",a.message),this.uiPushToast({title:S("appMessages.createConversationFailed"),message:a.message||S("appMessages.serverNotSuccessMessage"),type:"error"})}catch(e){console.error("创建工作区对话异常:",e),this.uiPushToast({title:S("appMessages.createWorkspaceConversationErrorTitle"),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:S("appMessages.deleteConversationTitle"),message:S("appMessages.deleteConversationConfirmMessage"),confirmText:S("common.delete"),cancelText:S("common.cancel")}))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){Be("对话删除成功"),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 St(async()=>{const{useConversationStore:d}=await Promise.resolve().then(()=>Ti);return{useConversationStore:d}},void 0);l().workspaceGroups.forEach(d=>{d.conversations.splice(0,d.conversations.length,...d.conversations.filter(p=>p.id!==e));const h=Math.max(0,d.conversations.length-d.visibleLimit);d.visibleOffset>h&&(d.visibleOffset=h)})}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:S("appMessages.deleteConversationFailedTitle"),message:a.message||S("appMessages.serverNotSuccessMessage"),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:S("appMessages.deleteConversationErrorTitle"),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(h=>h&&h.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)||S("appMessages.duplicateConversationTitle"),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(h=>h&&h.id!==i),d=u.findIndex(h=>h&&h.id===s);d>=0?this.conversations.splice(0,this.conversations.length,...u.slice(0,d+1),l,...u.slice(d+1)):this.conversations.splice(0,this.conversations.length,l,...u),window.setTimeout(()=>{const h={...this.conversationInsertAnimations};delete h[s],delete h[i],this.conversationInsertAnimations=h,this.conversationListAnimationMode="idle"},860);try{const{useConversationStore:h}=await St(async()=>{const{useConversationStore:v}=await Promise.resolve().then(()=>Ti);return{useConversationStore:v}},void 0),g=h().workspaceGroups.find(v=>v.conversations.some(m=>m.id===s));if(g){const v=g.conversations.findIndex(y=>y.id===s),m=g.conversations.filter(y=>y.id!==i);v>=0?g.conversations.splice(0,g.conversations.length,...m.slice(0,v+1),l,...m.slice(v+1)):g.conversations.splice(0,g.conversations.length,l,...m),g.expanded=!0}}catch{}await r(860),await this.loadConversation(i,{force:!0,preserveListPosition:!0})}}else{const i=n.message||n.error||S("common.copyFailed");this.uiPushToast({title:S("appMessages.duplicateConversationFailedTitle"),message:i,type:"error"})}}catch(t){console.error("复制对话异常:",t),this.uiPushToast({title:S("appMessages.duplicateConversationErrorTitle"),message:t.message||String(t),type:"error"})}}},Wie={async enterConversation(s,e={}){var m,y,_;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 Be("enterConversation:failed",{conversationId:s,error:u.error||u.message}),u;const d=u.data||{},h=d.meta||{},p=d.conversation_id||s;typeof h.run_mode=="string"?(this.runMode=h.run_mode==="deep"?"thinking":h.run_mode,this.thinkingMode=typeof h.thinking_mode=="boolean"?h.thinking_mode:h.run_mode!=="fast"):typeof h.thinking_mode=="boolean"&&(this.thinkingMode=h.thinking_mode,this.runMode=h.thinking_mode?"thinking":"fast"),typeof h.model_key=="string"&&h.model_key&&this.modelSet(h.model_key),this.reasoningEffort=typeof h.reasoning_effort=="string"?h.reasoning_effort:null,this.currentConversationType=h.multi_agent_mode===!0?"multi_agent":"normal",kr().$patch({multiAgentMode:h.multi_agent_mode===!0}),this.skipConversationHistoryReload=!0,this.currentConversationId=p,(m=this.refreshProjectGitSummary)==null||m.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 g=Array.isArray(d.messages)?d.messages:[];(y=this.logMessageState)==null||y.call(this,"enterConversation:before-render",{conversationId:p,count:g.length}),this.messages=[],g.length>0&&(this.renderHistoryMessages(g),typeof this.settleHistoryRenderAndScroll=="function"?await this.settleHistoryRenderAndScroll():(await this.$nextTick(),this.scrollHistoryToBottomInstant())),this.lastHistoryLoadedConversationId=p,this.refreshBlankHeroState(),await new Promise(b=>setTimeout(b,0)),oo().setEditedFiles(Array.isArray(d.edited_files)?d.edited_files:[]);try{const b=await fetch(`/api/workflow/status?conversation_id=${encodeURIComponent(p)}`);if(b.ok){const k=await b.json();yg().setWorkflow(k==null?void 0:k.snapshot,!1)}}catch{}const v=d.running||{};return v.is_main_running&&d.task_replay&&await this.restoreTaskState({bootstrapReplay:d.task_replay}),al("enterConversation:done",{conversationId:p,messagesCount:g.length,isTrulyActive:!!v.is_truly_active,needsRebuild:(_=d.task_replay)==null?void 0:_.needs_rebuild}),{success:!0,title:h.title||"",run_mode:h.run_mode,thinking_mode:h.thinking_mode,model_key:h.model_key,multi_agent_mode:h.multi_agent_mode,conversation_id:p}}},zie={...Fie,...Hie,...Uie,...Wie},cp=(...s)=>{},jie="[RESTORE_DEBUG]",Vie=new Set(["history:fetch:start","history:fetch:response","history:render:done"]);function Gie(){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 CT(s,e={}){Gie()&&Vie.has(s)&&console.log(jie,s,e)}const Kie=/^(?:✅\s*)?(?:\u5b50\u667a\u80fd\u4f53|Sub-agent)\s*#?\s*(\d+)\s*(?:\u4efb\u52a1\u6458\u8981|task summary)[::]/,qie=/^\[(?:\u540e\u53f0\s*run_command\s*\u5b8c\u6210|Background\s*run_command\s*finished)\]/;function Qie(s){const e=(s||"").toString().trim();if(!e)return null;const t=e.match(Kie);return!t||!/(?:\u5df2\u5b8c\u6210|Completed\.)/.test(e)?null:S("appUi.subAgentTaskDone",{agentId:t[1]})}function Xie(s){const e=(s||"").toString().trim();return!e||!qie.test(e)?null:S("appUi.backgroundRunCommandDone")}function Yie(s){const e=(s||"").toString().trim();return e?Qie(e)||Xie(e):null}const Jie={async fetchAndDisplayHistory(s={}){var r,o,a,c,l,u,d;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;CT("history:fetch:start",{loadSeq:i,targetConversationId:t,currentConversationId:this.currentConversationId,force:e}),cp("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{Be("开始获取历史对话内容..."),this.logMessageState("fetchAndDisplayHistory:start",{conversationId:this.currentConversationId});try{const h=await fetch(`/api/conversations/${t}/messages`);if(!h.ok){console.warn("无法获取消息历史,尝试备用方法");const y=await(await fetch("/api/status")).json();if(Be("系统状态:",y),this.applyStatusSnapshot(y),y.conversation_history&&Array.isArray(y.conversation_history)){this.renderHistoryMessages(y.conversation_history);return}Be("备用方案也无法获取历史消息");return}if(i!==this.historyLoadSeq||this.currentConversationId!==t){Be("检测到对话已切换,丢弃过期的历史加载结果");return}const p=await h.json(),g=Array.isArray((r=p==null?void 0:p.data)==null?void 0:r.messages)?p.data.messages:[];oo().setEditedFiles(Array.isArray((o=p==null?void 0:p.data)==null?void 0:o.edited_files)?p.data.edited_files:[]);const v=[...g].reverse().find(m=>(m==null?void 0:m.role)==="assistant");if(CT("history:fetch:response",{loadSeq:i,success:!!(p!=null&&p.success),rawCount:g.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)||"")}),cp("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}),Be("获取到消息数据:",p),p.success&&p.data&&p.data.messages){const m=p.data.messages;Be(`发现 ${m.length} 条历史消息`),m.length>0?(this.logMessageState("fetchAndDisplayHistory:before-clear-existing"),this.messages=[],this.logMessageState("fetchAndDisplayHistory:after-clear-existing"),this.renderHistoryMessages(m),cp("history.fetch:rendered",{loadSeq:i,renderedMessagesCount:Array.isArray(this.messages)?this.messages.length:-1,lastRole:((d=(u=this.messages)==null?void 0:u[this.messages.length-1])==null?void 0:d.role)||null}),typeof this.settleHistoryRenderAndScroll=="function"?await this.settleHistoryRenderAndScroll():(await this.$nextTick(),this.scrollHistoryToBottomInstant()),Be("历史对话内容显示完成")):(Be("对话存在但没有历史消息"),this.logMessageState("fetchAndDisplayHistory:no-history-clear"),this.messages=[],this.logMessageState("fetchAndDisplayHistory:no-history-cleared"))}else Be("消息数据格式不正确:",p),this.logMessageState("fetchAndDisplayHistory:invalid-data-clear"),this.messages=[],this.logMessageState("fetchAndDisplayHistory:invalid-data-cleared")}catch(h){console.error("获取历史对话失败:",h),Be("尝试不显示错误弹窗,仅在控制台记录"),this.logMessageState("fetchAndDisplayHistory:error-clear",{error:(h==null?void 0:h.message)||String(h)}),this.messages=[],this.logMessageState("fetchAndDisplayHistory:error-cleared")}}finally{i===this.historyLoadSeq&&(this.historyLoading=!1,this.historyLoadingFor=null),this.refreshBlankHeroState()}},renderHistoryMessages(s){var l,u,d;if(Be("历史消息数量:",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((h,p)=>{var v,m,y,_;Be(`处理消息 ${p+1}/${s.length}:`,h.role,h);const g=h.metadata||{};if(!(h.role==="user"&&(g.system_injected_image||g.system_injected_video)))if(h.role==="user"){e&&e.actions.length>0&&(this.messages.push(e),e=null);const b=h.images||h.metadata&&h.metadata.images||[],k=h.videos||h.metadata&&h.metadata.videos||[],w=h.media_refs||h.metadata&&h.metadata.media_refs||[];Array.isArray(b)&&b.length&&(t=!0),Array.isArray(k)&&k.length&&(n=!0);const T=h.created_at??h.createdAt??h.timestamp??null,A=typeof T=="number"&&T>0?new Date(T*1e3).toISOString():T||null;this.messages.push({role:"user",content:h.content||"",images:b,videos:k,media_refs:Array.isArray(w)?w:[],metadata:h.metadata||{},created_at:A}),Be("添加用户消息:",((v=h.content)==null?void 0:v.substring(0,50))+"...")}else if(h.role==="assistant"){e||(e={role:"assistant",actions:[],streamingThinking:"",streamingText:"",currentStreamingType:null,activeThinkingId:null,awaitingFirstContent:!1,generatingLabel:""});const b=(m=h.metadata)==null?void 0:m.citations;if(Array.isArray(b)&&b.length){const A=Array.isArray((y=e.metadata)==null?void 0:y.citations)?[...e.metadata.citations]:[],C=new Set(A.map(E=>E==null?void 0:E.id));b.forEach(E=>{E&&E.id&&!C.has(E.id)&&(C.add(E.id),A.push(E))}),e.metadata={...e.metadata||{},citations:A}}const k=h.content||"",w=(h.reasoning_content||"").trim();if(w){const A=`history-thinking-${Date.now()}-${Math.random().toString(36).slice(2)}`;e.actions.push({id:`history-think-${Date.now()}-${Math.random()}`,type:"thinking",content:w,streaming:!1,collapsed:!0,timestamp:Date.now(),blockId:A}),Be("添加思考内容:",w.substring(0,50)+"...")}const T=k.trim();T&&(e.actions.push({id:`history-text-${Date.now()}-${Math.random()}`,type:"text",content:T,streaming:!1,timestamp:Date.now()}),Be("添加文本内容:",T.substring(0,50)+"...")),h.tool_calls&&Array.isArray(h.tool_calls)&&h.tool_calls.forEach((A,C)=>{var D;let E={};try{E=typeof A.function.arguments=="string"?JSON.parse(A.function.arguments||"{}"):A.function.arguments||{}}catch(N){console.warn("解析工具参数失败:",N),E={},i+=1,cp("history.render:tool-args-parse-fail",{toolName:(D=A==null?void 0:A.function)==null?void 0:D.name,toolCallId:A==null?void 0:A.id,error:(N==null?void 0:N.message)||String(N)})}const x={id:`history-tool-${A.id||Date.now()}-${C}`,type:"tool",tool:{id:A.id,name:A.function.name,arguments:E,argumentSnapshot:this.cloneToolArguments(E),argumentLabel:this.buildToolLabel(E),intent_full:E.intent||"",intent_rendered:E.intent||"",status:"preparing",result:null},timestamp:Date.now()};["preparing","running","awaiting_content"].includes(x.tool.status)&&(x.tool.status="stale",x.tool.awaiting_content=!1,x.streaming=!1),e.actions.push(x),Be("添加工具调用:",A.function.name)})}else if(h.role==="tool"){if(e){let b=null;if(h.tool_call_id&&(b=e.actions.find(k=>k.type==="tool"&&k.tool.id===h.tool_call_id)),!b&&h.name){const k=e.actions.filter(w=>w.type==="tool"&&w.tool.name===h.name);b=k[k.length-1]}if(b){let k;try{k=JSON.parse(h.content)}catch(w){r+=1,cp("history.render:tool-result-parse-fail",{toolName:h==null?void 0:h.name,toolCallId:h==null?void 0:h.tool_call_id,error:(w==null?void 0:w.message)||String(w)}),h.metadata&&h.metadata.tool_payload?k=h.metadata.tool_payload:k={output:h.content,success:!0}}b.tool.status="completed",b.tool.result=k,k&&typeof k=="object"&&(k.error?b.tool.message=k.error:k.message&&!b.tool.message&&(b.tool.message=k.message)),Be(`更新工具结果: ${h.name} -> ${(_=h.content)==null?void 0:_.substring(0,50)}...`)}else console.warn("找不到对应的工具调用:",h.name,h.tool_call_id)}}else{if(e&&e.actions.length>0&&(this.messages.push(e),e=null),h.role==="system"){const b=h.content||"",k=Yie(b);k&&this.messages.push({role:"assistant",actions:[{id:`history-system-${Date.now()}-${Math.random()}`,type:"system",content:k,variant:"sub_agent_done",streaming:!1,timestamp:Date.now()}],streamingThinking:"",streamingText:"",currentStreamingType:null,activeThinkingId:null,awaitingFirstContent:!1,generatingLabel:""});return}Be("处理其他类型消息:",h.role),this.messages.push({role:h.role,content:h.content||""})}}),e&&e.actions.length>0&&this.messages.push(e),this.conversationHasImages=t,this.conversationHasVideos=n,Be(`历史消息渲染完成,共 ${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(h=>(h==null?void 0:h.type)==="text").map(h=>String((h==null?void 0:h.content)||"")).join(`
|
||
`);CT("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(h=>(h==null?void 0:h.type)==="thinking"),lastHasTextAction:a.some(h=>(h==null?void 0:h.type)==="text"),lastTextLength:c.length,lastTextHasShowHtml:/<show_html/i.test(c)}),cp("history.render:done",{historyInputCount:Array.isArray(s)?s.length:-1,finalMessagesCount:Array.isArray(this.messages)?this.messages.length:-1,lastRole:((d=(u=this.messages)==null?void 0:u[this.messages.length-1])==null?void 0:d.role)||null,toolArgsParseFailCount:i,toolResultParseFailCount:r}),this.logMessageState("renderHistoryMessages:after-render"),this.lastHistoryLoadedConversationId=this.currentConversationId||null,this.$forceUpdate(),this.$nextTick(()=>{this.scrollHistoryToBottomInstant(),setTimeout(()=>{const h=this.$el&&this.$el.querySelectorAll?this.$el.querySelectorAll(".message-block").length:"N/A";Be("[Messages] DOM 渲染统计",{blocks:h,conversationId:this.currentConversationId})},0)})}},Zie={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(),d=String(l.text||"").trim();if(!u||!d)return null;const h=t.get(u),p=Number(l.created_at??l.createdAt??Date.now()),g=Array.isArray(l.files)?l.files:Array.isArray(h==null?void 0:h.files)?h.files:[];return{id:u,text:d,createdAt:Number.isFinite(p)?p:Date.now(),source:(h==null?void 0:h.source)||"user",files:g.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 d=Number((l==null?void 0:l.createdAt)||0),h=Number((u==null?void 0:u.createdAt)||0);if(d!==h)return d-h;const p=n.has(l==null?void 0:l.id)?Number(n.get(l==null?void 0:l.id)):Number.MAX_SAFE_INTEGER,g=n.has(u==null?void 0:u.id)?Number(n.get(u==null?void 0:u.id)):Number.MAX_SAFE_INTEGER;return p!==g?p-g: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 d=a[u];return(l==null?void 0:l.id)===(d==null?void 0:d.id)&&(l==null?void 0:l.text)===(d==null?void 0:d.text)&&Number((l==null?void 0:l.createdAt)||0)===Number((d==null?void 0:d.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 St(async()=>{const{useTaskStore:d}=await Promise.resolve().then(()=>io);return{useTaskStore:d}},void 0),a=r().currentTaskId;if(!a)return this.uiPushToast({title:S("appMessages.cannotQueueTitle"),message:S("appMessages.noActiveTaskMessage"),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)||S("appMessages.queueMessageFailed"));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:S("appMessages.queueFailedTitle"),message:(r==null?void 0:r.message)||S("common.retryLater"),type:"error"}),!1}},async handleDeleteRuntimeMessage(s){var t;const e=String(s||"").trim();if(e)try{const{useTaskStore:n}=await St(async()=>{const{useTaskStore:l}=await Promise.resolve().then(()=>io);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)||S("appMessages.deleteFailed"));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:S("appMessages.deleteFailed"),message:(n==null?void 0:n.message)||S("common.retryLater"),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:S("appMessages.sendFailedTitle"),message:S("appMessages.guideMessageNotSent"),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 St(async()=>{const{useTaskStore:l}=await Promise.resolve().then(()=>io);return{useTaskStore:l}},void 0),r=n().currentTaskId;if(!r){this.uiPushToast({title:S("appMessages.cannotGuideTitle"),message:S("appMessages.noActiveTaskMessage"),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)||S("appMessages.submitGuideFailed"));const c=this.applyRuntimeQueuedMessages(((t=a==null?void 0:a.data)==null?void 0:t.messages)||[])||[];this.setRuntimeQueueSyncLock(c,2200),this.uiPushToast({title:S("appMessages.guideSetTitle"),message:S("appMessages.guideSetMessage"),type:"success",duration:1800})}catch(n){this.uiPushToast({title:S("appMessages.guideFailedTitle"),message:(n==null?void 0:n.message)||S("common.retryLater"),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],d=String((u==null?void 0:u.id)||"").trim(),h=((u==null?void 0:u.text)||"").toString().trim();if(!(!d||!h)&&!this.consumeSuppressedRuntimeQueueMessageId(d)){n=h,i=(u==null?void 0:u.source)||"runtime_queue",r=d,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(d=>String(d||"").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(d=>(d==null?void 0:d.id)!==r);this.runtimeQueuedMessages=u,this.setRuntimeQueueSyncLock(u,1500)}else{const u=l.findIndex(d=>String((d==null?void 0:d.text)||"").trim()===n);u>=0&&(l.splice(u,1),this.runtimeQueuedMessages=l,this.setRuntimeQueueSyncLock(l,1500))}}return Be("[RuntimeQueue] auto-send success",{reason:s,source:i,messagePreview:n.slice(0,60)}),!0}},ere={async executeSystemCommand(s,e={}){const t=(s||"").toString().trim();if(!t)return{success:!1,message:S("appMessages.commandEmpty")};if(!this.isConnected)return e.showToast!==!1&&this.uiPushToast({title:S("appMessages.connectionUnavailable"),message:S("appMessages.connectionUnavailableMessage"),type:"error"}),{success:!1,message:S("appMessages.connectionUnavailable")};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:S("appMessages.commandExecutionFailed"),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:S("appMessages.clearedTitle"),message:s.message||S("appMessages.conversationCleared"),type:"success"});return}if(s.command==="status"&&s.success){this.addSystemMessage(`${S("appMessages.systemStatus")}:
|
||
${JSON.stringify(s.data||{},null,2)}`),t&&this.uiPushToast({title:S("appMessages.statusUpdatedTitle"),message:S("appMessages.statusFetched"),type:"success"});return}if(!s.success){this.addSystemMessage(`${S("appMessages.commandFailedLabel")}: ${s.message||S("common.unknownError")}`),t&&this.uiPushToast({title:S("appMessages.commandExecutionFailed"),message:s.message||S("common.retryLater"),type:"error"});return}t&&this.uiPushToast({title:S("appMessages.commandExecutedTitle"),message:s.command||S("appMessages.commandDone"),type:"success"})}},wP=/\[\$([^\]\n]+)\]\(((?:[^)\n]*[\\/])?\.astrion[\\/]skills[\\/][^)\n]+[\\/]SKILL\.md)\)/g;function tre(s=""){const e=[],t=new Set,n=String(s||"");let i;for(wP.lastIndex=0;i=wP.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 sre={async handleSendOrStop(){if(this.compressionActiveForCurrentConversation){this.uiPushToast({title:S("appMessages.autoCompressingTitle"),message:S("appMessages.autoCompressingBlockSend"),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:S("appMessages.textRequiredTitle"),message:S("appMessages.textRequiredMessage"),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:S("appMessages.subAgentRunningTitle"),message:S("appMessages.subAgentRunningMessage"),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:S("appMessages.runningTextOnlyTitle"),message:S("appMessages.runningTextOnlyMessage"),type:"warning"});return}this.stopTask()}else{if(this.currentWorkspaceHasRunningTask){this.uiPushToast({title:S("appMessages.conversationRunningTitle"),message:S("appMessages.conversationRunningMessage"),type:"warning"});return}this.sendMessage()}},async sendMessage(s={}){var w,T;const e=typeof(s==null?void 0:s.presetText)=="string"?s.presetText:null,t=e!==null;if(this.compressionActiveForCurrentConversation)return this.uiPushToast({title:S("appMessages.autoCompressingTitle"),message:S("appMessages.compressionBlocksSend"),type:"warning"}),!1;if(this.streamingUi&&!t)return!1;if(!this.isConnected)return this.uiPushToast({title:S("appMessages.connectionLostTitle"),message:S("appMessages.connectionLostMessage"),type:"warning"}),!1;if(this.mediaUploading&&!t)return this.uiPushToast({title:S("appMessages.uploadingTitle"),message:S("appMessages.uploadingMessage"),type:"info"}),!1;let n=((t?e:this.inputMessage)||"").trim(),i=[];if(!t){const A=typeof this.getInputComposerRef=="function"?this.getInputComposerRef():null,C=A&&typeof A.prepareMessageForSend=="function"?A.prepareMessageForSend(this.inputMessage):null;C&&typeof C.message=="string"&&(n=C.message.trim(),i=Array.isArray(C.skillRefs)?C.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,d=a.length>0;if(!c&&!l&&!u)return!1;const h=this.thinkingMode?"thinking":"fast";if(this.isQuotaExceeded(h))return this.showQuotaToast({type:h}),!1;const g=er().models.find(A=>A.key===this.currentModelKey);if(l&&!(g!=null&&g.supportsImage))return this.uiPushToast({title:S("appMessages.modelNoImageTitle"),message:S("appMessages.modelNoImageMessage"),type:"error"}),!1;if(u&&!(g!=null&&g.supportsVideo))return this.uiPushToast({title:S("appMessages.modelNoVideoTitle"),message:S("appMessages.modelNoVideoMessage"),type:"error"}),!1;if(u&&l)return this.uiPushToast({title:S("appMessages.noMixedMediaTitle"),message:S("appMessages.noMixedMediaMessage"),type:"warning"}),!1;u&&this.uiPushToast({title:S("appMessages.videoProcessingTitle"),message:S("appMessages.videoProcessingMessage"),type:"info",duration:5e3});const v=n,m=t?[]:i.length?i:tre(v);this.isConversationBlank()&&(this.blankHeroExiting=!0,this.blankHeroActive=!0,setTimeout(()=>{this.blankHeroExiting=!1,this.blankHeroActive=!1},320));let _=this.currentConversationId,b=null;if(!_)try{const A=Js();this.versioningHostMode&&A.form.versioning_enabled_by_default&&A.form.versioning_backup_mode==="full"&&(b=this.uiPushToast({title:S("appMessages.initializingBackupTitle"),message:S("appMessages.initializingBackupMessage"),type:"info",duration:null,closable:!1}),this.versioningInitializingBackupToastId=b);const E=this.newConversationType==="multi_agent",x=E?"/api/multiagent/conversations":"/api/conversations",D=JSON.stringify(E?{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}),N=await fetch(x,{method:"POST",headers:{"Content-Type":"application/json"},body:D}),O=await N.json().catch(()=>({}));if(!N.ok||!(O!=null&&O.success)||!(O!=null&&O.conversation_id))throw new Error((O==null?void 0:O.message)||(O==null?void 0:O.error)||S("appMessages.createConversationFailed"));_=O.conversation_id,this.currentConversationType=E?"multi_agent":"normal",this.skipConversationHistoryReload=!0,this.currentConversationId=_,this.currentConversationTitle=S("common.newConversation");const G={id:_,title:S("common.newConversation"),updated_at:new Date().toISOString(),total_messages:0,total_tools:0},Z=E?"multi_agent":"normal";try{const{useConversationStore:V}=await St(async()=>{const{useConversationStore:L}=await Promise.resolve().then(()=>Ti);return{useConversationStore:L}},void 0),I=V();I.$patch({multiAgentMode:E});const $=I.conversationsCache[Z];$.list.splice(0,$.list.length,G,...$.list.filter(L=>L&&L.id!==_)),I.sidebarConversationType!==Z&&I.setSidebarConversationType(Z);try{const L=this.currentHostWorkspaceId;if(L){I.ensureWorkspaceGroup(L);const K=I.workspaceGroups.find(se=>se.workspaceId===L);if(K){const se=(w=K.conversationsByType)==null?void 0:w[Z];se&&se.splice(0,se.length,G,...se.filter(oe=>oe&&oe.id!==_)),K.expanded=!0,K.visibleOffset=0,K.visibleLimit=5}}}catch{}I.conversationsCache[Z].loaded||typeof this.handleSidebarConversationTypeChange=="function"&&this.handleSidebarConversationTypeChange(Z).catch(()=>{})}catch{}const q=this.stripConversationPrefix(_);history.replaceState({conversationId:_},"",`/${q}`)}catch(A){return this.uiPushToast({title:S("appMessages.sendFailedTitle"),message:(A==null?void 0:A.message)||S("appMessages.createNewConversationFailedMessage"),type:"error"}),!1}finally{b&&(this.uiDismissToast(b),this.versioningInitializingBackupToastId=null)}this.taskInProgress=!0,typeof this.startRunningStateReconcile=="function"&&this.startRunningStateReconcile();const k=t?(s==null?void 0:s.source)==="runtime_queue_manual_guide"?"guidance":"presend":"user";this.chatAddUserMessage(v,r,o,[],k,d?{files:[...a]}:{}),this.chatStartAssistantMessage(),this.stopRequested=!1,typeof this.monitorShowPendingReply=="function"&&this.monitorShowPendingReply(),this.autoScrollEnabled&&this.scrollToBottom();try{const{useTaskStore:A}=await St(async()=>{const{useTaskStore:x}=await Promise.resolve().then(()=>io);return{useTaskStore:x}},void 0),C=A();typeof this.clearProcessedEvents=="function"&&this.clearProcessedEvents();const E=this.goalModeArmed===!0;E&&(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 C.createTask(v,r,o,_,{model_key:this.currentModelKey,run_mode:this.runMode,thinking_mode:this.thinkingMode,message_source:k,goal_mode:E,skill_refs:m,files:a,eventHandler:x=>this.handleTaskEvent(x)}),Be("[Message] 任务已创建,开始轮询"),await((T=this.refreshRunningWorkspaceTasks)==null?void 0:T.call(this))}catch(A){return console.error("[Message] 创建任务失败:",A),this.uiPushToast({title:S("appMessages.sendFailedTitle"),message:A.message||S("appMessages.createTaskFailedMessage"),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){Cn("stopTask:debounce-rejected",{stopRequested:this.stopRequested});return}if(this._stopTaskRunning=!0,this.compressionActiveForCurrentConversation){this._stopTaskRunning=!1,this.uiPushToast({title:S("appMessages.autoCompressingTitle"),message:S("appMessages.autoCompressingBlockStop"),type:"warning"});return}const s=this.streamingUi&&!this.stopRequested;if(Cn("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 St(async()=>{const{useTaskStore:o}=await Promise.resolve().then(()=>io);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));Cn("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 St(async()=>{const{useTaskStore:a}=await Promise.resolve().then(()=>io);return{useTaskStore:a}},void 0),i=n(),r=["running","pending","cancel_requested","canceled"].includes(String(i.taskStatus));Cn("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:S("appMessages.stopRequestedTitle"),message:S("appMessages.stopRequestedMessage"),type:"info"})}finally{this.dropToolEvents=!1,this.stopRequested=!1,this._stopTaskRunning=!1}}},nre={async clearChat(){await this.confirmAction({title:S("appMessages.clearChatTitle"),message:S("appMessages.clearChatConfirmMessage"),confirmText:S("appMessages.clearChatConfirmText"),cancelText:S("common.cancel")})&&await this.executeSystemCommand("/clear",{showToast:!1})},async compressConversation(){if(!this.currentConversationId){this.uiPushToast({title:S("appMessages.cannotCompressTitle"),message:S("appMessages.cannotCompressMessage"),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:S("appMessages.compressingTitle"),message:S("appMessages.compressingMessage"),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(),Be("对话压缩完成:",e),this.uiPushToast({title:S("appMessages.compressionCompletedTitle"),message:S("appMessages.compressionCompletedMessage"),type:"success",duration:2200})}else{const t=e.message||e.error||S("appMessages.compressionFailed");this.compressionError=t,this.uiPushToast({title:S("appMessages.compressionFailed"),message:t,type:"error"})}}catch(s){console.error("压缩对话异常:",s),this.compressionError=s.message||S("common.retryLater"),this.uiPushToast({title:S("appMessages.compressionErrorTitle"),message:s.message||S("common.retryLater"),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 St(async()=>{const{useTaskStore:r}=await Promise.resolve().then(()=>io);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:S("appMessages.sendFailedTitle"),message:(n==null?void 0:n.message)||S("appMessages.createTaskFailedMessage"),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`})})}},ire={...Zie,...ere,...sre,...nre},rre=50,ore=20,are={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=Js();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 St(async()=>{const{useConversationStore:a}=await Promise.resolve().then(()=>Ti);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=${ore}&all_workspaces=1${i}`:`/api/conversations/search?q=${encodeURIComponent(e)}&limit=${rre}${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(){}},lre={triggerFileUpload(){if(this.uploading)return;const s=this.getComposerElement("fileUploadInput");s&&s.click()},handleFileSelected(s){var n;if((n=zo().uiBlocks)!=null&&n.block_upload){this.uiPushToast({title:S("appUi.uploadDisabled"),message:S("appUi.uploadDisabledByAdmin"),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=er().models.find(t=>t.key===this.currentModelKey);if(!(e!=null&&e.supportsImage)){this.uiPushToast({title:S("appUi.modelDoesNotSupportImage"),message:S("appUi.chooseImageModelMessage"),type:"error"});return}this.closeQuickMenu(),this.inputSetImagePickerOpen(!0),await this.loadWorkspaceImages()},closeImagePicker(){this.inputSetImagePickerOpen(!1)},async openVideoPicker(){const e=er().models.find(t=>t.key===this.currentModelKey);if(!(e!=null&&e.supportsVideo)){this.uiPushToast({title:S("appUi.modelDoesNotSupportVideo"),message:S("appUi.switchToVideoModelMessage"),type:"error"});return}this.closeQuickMenu(),this.inputSetVideoPickerOpen(!0),await this.loadWorkspaceVideos()},closeVideoPicker(){this.inputSetVideoPickerOpen(!1)}},cre={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:S("appUi.uploadingTitle"),message:S("appUi.waitImageUploadDone"),type:"info"});return}const e=this.normalizeLocalFiles(s);if(!e.length){this.uiPushToast({title:S("appUi.noFileReceived"),message:S("appUi.noValidFileContent"),type:"warning"});return}const t=Array.isArray(this.selectedImages)?this.selectedImages.length:0,n=Math.max(0,9-t);if(!n){this.uiPushToast({title:S("appUi.limitReachedTitle"),message:S("appUi.maxImagesMessage",{max: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:S("appUi.ignoredTitle"),message:S("appUi.skippedNonImageFiles"),type:"info"});const o=r.slice(0,n);r.length>n&&this.uiPushToast({title:S("appUi.exceededTitle"),message:S("appUi.truncatedImagesMessage",{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:S("appUi.uploadingTitle"),message:S("appUi.waitFileUploadDone"),type:"info"});return}const e=this.normalizeLocalFiles(s);if(!e.length){this.uiPushToast({title:S("appUi.noFileReceived"),message:S("appUi.noValidFileContent"),type:"warning"});return}const t=Array.isArray(this.selectedFiles)?this.selectedFiles.length:0,n=Math.max(0,9-t);if(!n){this.uiPushToast({title:S("appUi.limitReachedTitle"),message:S("appUi.maxFilesMessage",{max:9}),type:"warning"});return}const i=e.slice(0,n);e.length>n&&this.uiPushToast({title:S("appUi.exceededTitle"),message:S("appUi.truncatedFilesMessage",{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:S("appUi.uploadingTitle"),message:S("appUi.waitVideoUploadDone"),type:"info"});return}const e=this.normalizeLocalFiles(s);if(!e.length){this.uiPushToast({title:S("appUi.noFileReceived"),message:S("appUi.noValidFileContent"),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:S("appUi.ignoredTitle"),message:S("appUi.skippedNonVideoFiles"),type:"info"}),n.length>1&&this.uiPushToast({title:S("appUi.tooManyVideosTitle"),message:S("appUi.onlyOneVideoMessage"),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))}},ure={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 d=Array.isArray((o=u==null?void 0:u.data)==null?void 0:o.items)?u.data.items:[];for(const h of d){const p=(h==null?void 0:h.path)||[c,h==null?void 0:h.name].filter(Boolean).join("/").replace(/\\/g,"/").replace(/\/{2,}/g,"/"),g=String((h==null?void 0:h.type)||"").toLowerCase();if(g==="directory"||g==="folder"){e.push(p);continue}const v=String((h==null?void 0:h.extension)||"").toLowerCase()||(p.includes(".")?`.${(a=p.split(".").pop())==null?void 0:a.toLowerCase()}`:"");if(i.has(v)&&(n.push({name:(h==null?void 0:h.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 d=Array.isArray((o=u==null?void 0:u.data)==null?void 0:o.items)?u.data.items:[];for(const h of d){const p=(h==null?void 0:h.path)||[c,h==null?void 0:h.name].filter(Boolean).join("/").replace(/\\/g,"/").replace(/\/{2,}/g,"/"),g=String((h==null?void 0:h.type)||"").toLowerCase();if(g==="directory"||g==="folder"){e.push(p);continue}const v=String((h==null?void 0:h.extension)||"").toLowerCase()||(p.includes(".")?`.${(a=p.split(".").pop())==null?void 0:a.toLowerCase()}`:"");if(i.has(v)&&(n.push({name:(h==null?void 0:h.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:S("appUi.noImagesFound"),message:S("appUi.noImagesInWorkspace"),type:"info"})}catch(s){console.error("加载图片列表失败",s),this.uiPushToast({title:S("appUi.loadImagesFailed"),message:(s==null?void 0:s.message)||S("common.retryLater"),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:S("appUi.noVideosFound"),message:S("appUi.noVideosInWorkspace"),type:"info"})}catch(s){console.error("加载视频列表失败",s),this.uiPushToast({title:S("appUi.loadVideosFailed"),message:(s==null?void 0:s.message)||S("common.retryLater"),type:"error"})}finally{this.videoLoading=!1}}},dre={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)}},hre={handleQuickUpload(){this.uploading||!this.isConnected||this.isPolicyBlocked("block_upload",S("appUi.uploadDisabledByAdmin"))||this.triggerFileUpload()}},fre={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:S("appUi.notConnected"),message:S("appUi.waitForConnectionBeforeUpload"),type:"warning"});return}if((n=zo().uiBlocks)!=null&&n.block_upload){this.uiPushToast({title:S("appUi.uploadDisabled"),message:S("appUi.uploadDisabledByAdmin"),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=er().models.find(n=>n.key===this.currentModelKey);if(!(t!=null&&t.supportsImage)){this.uiPushToast({title:S("appUi.modelDoesNotSupportImage"),message:S("appUi.chooseImageModelMessage"),type:"error"});return}await this.handleLocalImageFiles(s)},async handleDroppedVideo(s){const t=er().models.find(n=>n.key===this.currentModelKey);if(!(t!=null&&t.supportsVideo)){this.uiPushToast({title:S("appUi.modelDoesNotSupportVideo"),message:S("appUi.switchToVideoModelMessage"),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}},pre={handlePastedFiles(s){var n;const e=Array.isArray(s)?s.filter(Boolean):[];if(!e.length)return;if(!this.isConnected){this.uiPushToast({title:S("appUi.notConnected"),message:S("appUi.waitForConnectionBeforeUpload"),type:"warning"});return}if((n=zo().uiBlocks)!=null&&n.block_upload){this.uiPushToast({title:S("appUi.uploadDisabled"),message:S("appUi.uploadDisabledByAdmin"),type:"warning"});return}this.processDroppedFiles(e)}},mre={...lre,...cre,...ure,...dre,...hre,...fre,...pre},SP=["B","KB","MB","GB","TB"],kP=["B/s","KB/s","MB/s","GB/s"],CP={thinking:"utils.quotaTypeThinking",search:"utils.quotaTypeSearch",fast:"utils.quotaTypeFast"};function mg(s){const e=Number(s);return Number.isFinite(e)?e:0}function gre(s){const e=mg(s);return e<1e3?e.toString():e<1e6?`${(e/1e3).toFixed(1)}K`:`${(e/1e6).toFixed(1)}M`}function vre(s){if(s===null||typeof s>"u")return"—";let e=Number(s);if(!Number.isFinite(e))return"—";let t=0;for(;e>=1024&&t<SP.length-1;)e/=1024,t++;const n=e>=10||t===0?0:1;return`${e.toFixed(n)} ${SP[t]}`}function yre(s){if(s===null||typeof s>"u")return"—";const e=Number(s);return Number.isFinite(e)?`${e.toFixed(1)}%`:"—"}function bre(s){if(s===null||typeof s>"u")return"—";let e=Number(s);if(!Number.isFinite(e))return"—";let t=0;for(;e>=1024&&t<kP.length-1;)e/=1024,t++;const n=e>=10||t===0?0:1;return`${e.toFixed(n)} ${kP[t]}`}function $M(s){return S(CP[s]||CP.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 _re(s){if(!s)return"--";const e=mg(s.count),t=mg(s.limit);return t?`${e} / ${t}`:`${e}`}function wre(s){if(!s)return"";const e=[];return["fast","thinking","search"].forEach(t=>{const n=s==null?void 0:s[t];n&&n.reset_at&&mg(n.count)>0&&e.push(`${$M(t)} ${BM(n.reset_at)}`)}),e.join(" · ")}function Sre(s,e){if(!s)return!1;const t=s[e];if(!t)return!1;const n=mg(t.limit);return n?mg(t.count)>=n:!1}function kre(s,e,t){const n=e==null?void 0:e[s],i=typeof t<"u"?t:n==null?void 0:n.reset_at;return S("utils.quotaExhaustedResetIn",{type:$M(s),time:BM(i)})}const Cre={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(lt.value,!this.containerStatus)return S("appTasks.unknown");if(this.containerStatus.mode!=="docker")return S("appTasks.hostMode");const s=this.containerStatus.state&&(this.containerStatus.state.status||this.containerStatus.state.Status)||"",e=String(s).toLowerCase();return e.includes("running")?S("common.running"):e.includes("paused")?S("appTasks.paused"):e.includes("exited")||e.includes("dead")?S("appTasks.stopped"):s||S("appTasks.containerMode")},formatTime(s){if(lt.value,!s)return S("appTasks.unknownTime");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();if(n<6e4)return S("appTasks.justNow");if(n<36e5){const r=Math.floor(n/6e4);return S("appTasks.minutesAgo",{n:r})}if(n<864e5){const r=Math.floor(n/36e5);return S("appTasks.hoursAgo",{n:r})}return 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:S("common.downloadFailed"),message:c||S("appTasks.cannotCompleteDownload"),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:S("common.downloadFailed"),message:n.message||String(n),type:"error"})}finally{this.fileHideContextMenu()}},formatTokenCount:gre,formatBytes:vre,formatPercentage:yre,formatRate:bre,formatResetTime:BM,formatQuotaValue:_re,quotaTypeLabel:$M,quotaResetSummary(){return wre(this.usageQuota)},isQuotaExceeded(s){return Sre(this.usageQuota,s)},showQuotaToast(s){if(!s)return;const e=s.type||"fast",t=kre(e,this.usageQuota,s.reset_at);this.uiShowQuotaToastMessage(t,e)}},Tre={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"};function Are(){return{create_file:S("toolResults.runningStatus.createFile"),sleep:S("toolResults.runningStatus.sleep"),delete_file:S("toolResults.runningStatus.deleteFile"),rename_file:S("toolResults.runningStatus.renameFile"),write_file:S("toolResults.runningStatus.writeFile"),edit_file:S("toolResults.runningStatus.editFile"),create_folder:S("toolResults.runningStatus.createFolder"),web_search:S("toolResults.runningStatus.webSearch"),extract_webpage:S("toolResults.runningStatus.extractWebpage"),save_webpage:S("toolResults.runningStatus.saveWebpage"),run_command:S("toolResults.runningStatus.runCommand"),update_memory:S("toolResults.runningStatus.updateMemory"),recall_project_memory:S("toolResults.runningStatus.recallProjectMemory"),search_project_memory:S("toolResults.runningStatus.searchProjectMemory"),update_project_memory:S("toolResults.runningStatus.updateProjectMemory"),terminal_session:S("toolResults.runningStatus.terminalSession"),terminal_input:S("toolResults.runningStatus.terminalInput"),terminal_snapshot:S("toolResults.runningStatus.terminalSnapshot"),read_skill:S("toolResults.runningStatus.readSkill"),create_skill:S("toolResults.runningStatus.createSkill"),ask_user:S("toolResults.runningStatus.askUser")}}function Ere(){return{create_file:S("toolResults.completedStatus.createFile"),delete_file:S("toolResults.completedStatus.deleteFile"),sleep:S("toolResults.completedStatus.sleep"),rename_file:S("toolResults.completedStatus.renameFile"),write_file:S("toolResults.completedStatus.writeFile"),edit_file:S("toolResults.completedStatus.editFile"),create_folder:S("toolResults.completedStatus.createFolder"),web_search:S("toolResults.completedStatus.webSearch"),extract_webpage:S("toolResults.completedStatus.extractWebpage"),save_webpage:S("toolResults.completedStatus.saveWebpage"),vlm_analyze:S("toolResults.completedStatus.vlmAnalyze"),run_command:S("toolResults.completedStatus.runCommand"),update_memory:S("toolResults.completedStatus.updateMemory"),recall_project_memory:S("toolResults.completedStatus.recallProjectMemory"),search_project_memory:S("toolResults.completedStatus.searchProjectMemory"),update_project_memory:S("toolResults.completedStatus.updateProjectMemory"),terminal_session:S("toolResults.completedStatus.terminalSession"),terminal_input:S("toolResults.completedStatus.terminalInput"),terminal_snapshot:S("toolResults.completedStatus.terminalSnapshot"),read_skill:S("toolResults.completedStatus.readSkill"),create_skill:S("toolResults.completedStatus.createSkill"),ask_user:S("toolResults.completedStatus.askUser")}}const Mre={py:"language-python",js:"language-javascript",html:"language-html",css:"language-css",json:"language-json",md:"language-markdown",txt:"language-plain"};function xre(){return{general:S("toolResults.search.topicGeneral"),news:S("toolResults.search.topicNews"),finance:S("toolResults.search.topicFinance")}}function Rre(){return{day:S("toolResults.search.timeLast24h"),week:S("toolResults.search.timeLast7d"),month:S("toolResults.search.timeLast30d"),year:S("toolResults.search.timeLast365d")}}function Ire(s){const e=typeof s=="string"?s:s==null?void 0:s.name;return typeof e=="string"&&e.startsWith("mcp__")?"mcpLogo":yF[e]||"settings"}function Pre(s){return s?s.status==="hinted"?"hint-animation pulse-slow":s.status==="preparing"?"preparing-animation":s.status==="running"?Tre[s.name]||"default-animation":"":""}function Lre(s){if(!(s!=null&&s.result)||typeof s.result!="object")return S("toolResults.completedStatus.readFile");const e=String(s.result.type||"read").toLowerCase();if(e==="search"){const t=s.result.query?S("toolResults.sentences.searchQuote",{text:s.result.query}):"",n=typeof s.result.returned_matches=="number"?s.result.returned_matches:s.result.actual_matches||0;return S("toolResults.sentences.readSearch",{query:t,count:n})}if(e==="extract"){const i=(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;return S("toolResults.sentences.readExtract",{n:i})}return S("toolResults.completedStatus.readFile")}function Ore(s){return String((s==null?void 0:s.name)||"").startsWith("mcp__")}function Dre(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||S("toolResults.mcpTool");const n=t.split("__").filter(Boolean);if(n.length>=3){const i=n.slice(2).join("__").trim();if(i)return i}return t||S("toolResults.mcpTool")}function Nre(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"&&Ore(s))return S("toolResults.sentences.mcpDone",{name:Dre(s)});if(t&&i)return n;if(s.message)return s.message;if(s.status==="hinted")return S("toolResults.sentences.hinted",{name:s.name});if(s.status==="preparing")return S("toolResults.sentences.preparing",{name: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:S("toolResults.runningStatus.readFile"),search:S("toolResults.runningStatus.readSearch"),extract:S("toolResults.runningStatus.readExtract")}[c]||S("toolResults.runningStatus.readFile")}const a=Are()[s.name]||s.display_name||s.name||"";return a||S("toolResults.runningStatus.fallback")}return s.status==="awaiting_user_answer"?S("toolResults.status.awaitingUserAnswer"):s.status==="awaiting_approval"||s.status==="pending_approval"||s.status==="pending"?S("toolResults.status.awaitingApprovalDots"):s.status==="completed"?s.name==="read_file"||s.name==="read_skill"?Lre(s):Ere()[s.name]||S("toolResults.completedStatus.fallback"):s.status?`${s.name} - ${s.status}`:s.name||""}function $re(s){if(!s||s.name==="ask_user")return"";const e=s.argumentSnapshot||s.arguments,t=s.argumentLabel||$B(e);return t||(s.statusDetail?s.statusDetail:s.result&&typeof s.result=="object"&&s.result.path&&String(s.result.path).split("/").pop()||"")}function Bre(s){if(!s||typeof s!="object")return null;try{return JSON.parse(JSON.stringify(s))}catch(e){return console.warn("无法克隆工具参数:",e),{...s}}}function $B(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("toolResults.duration.seconds",{seconds:s.seconds}):s.name?s.name:""}function Fre(s){const e=s!=null&&s.topic?String(s.topic).toLowerCase():"general";return xre()[e]||S("toolResults.search.topicGeneral")}function Hre(s){if(!s)return S("toolResults.search.timeUnlimited");if(s.time_range){const e=String(s.time_range).toLowerCase();return Rre()[e]||S("toolResults.search.timeRelative",{range:s.time_range})}return typeof s.days=="number"?S("toolResults.search.timeLastDays",{n:s.days}):s.start_date&&s.end_date?S("toolResults.search.timeRangeTo",{start:s.start_date,end:s.end_date}):S("toolResults.search.timeUnlimited")}function Ure(s){const e=s==null?void 0:s.include_domains;if(!Array.isArray(e)||e.length===0)return S("toolResults.search.domainsUnlimited");const t=e.map(n=>String(n||"").trim()).filter(Boolean);return t.length?t.join(", "):S("toolResults.search.domainsUnlimited")}function Wre(s){var t;if(!s)return"language-plain";const e=((t=s.split(".").pop())==null?void 0:t.toLowerCase())||"";return Mre[e]||"language-plain"}const zre={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||S("appTasks.interruptedByNewResponse"),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||S("appTasks.stopped"))})}),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]}Be("[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)){Be("[ToolSettings] Fetch start",{force:s,hasConnection:this.isConnected}),this.toolSetSettingsLoading(!0);try{const e=await fetch("/api/tool-settings"),t=await e.json();Be("[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(zo().isCategoryLocked(s)){this.uiPushToast({title:S("appTasks.cannotModify"),message:S("appTasks.categoryEnforcedByAdmin"),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:S("appTasks.cannotSwitchTool"),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",S("appTasks.toolToggleLockedByAdmin")))return;this.modeMenuOpen=!1,this.modelMenuOpen=!1,this.inputToggleToolMenu()?(this.inputSetSettingsOpen(!1),this.quickMenuOpen||this.inputOpenQuickMenu(),this.loadToolSettings(!0)):this.inputSetToolMenuOpen(!1)},getToolIcon:Ire,getToolAnimationClass:Pre,getToolStatusText(s){var n;const e=Js(),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 Nre(s,{intentEnabled:t})},getToolDescription:$re,cloneToolArguments:Bre,buildToolLabel:$B,formatSearchTopic:Fre,formatSearchTime:Hre,formatSearchDomains:Ure,getLanguageClass:Wre},jre={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)||S("appUi.loadGitChangesFailed"),s||(this.gitChangesDiff=null);return}this.gitChangesDiff=a.data||null,(t=this.gitChangesDiff)!=null&&t.has_git||(this.gitChangesPanelOpen=!1)}catch{this.gitChangesError=S("appUi.loadGitChangesFailed"),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)}},Vre=/^(?:✅\s*)?(?:\u5b50\u667a\u80fd\u4f53|Sub-agent)\s*#?\s*(\d+)\s*(?:\u4efb\u52a1\u6458\u8981|task summary)[::]/,Gre=/^\[(?:\u540e\u53f0\s*run_command\s*\u5b8c\u6210|Background\s*run_command\s*finished)\]/;let TT=0;const AT=140,TP=new Map;function Kre(){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 Kc(s,e={},t=s,n=140){if(!Kre()||TT>=AT)return;const i=Date.now(),r=TP.get(t)||0;if(!(n>0&&i-r<n)){if(TP.set(t,i),TT+=1,TT===AT){console.warn("[SCROLL_BOUNCE_TRACE_UI]","log-limit-reached",{max:AT});return}console.log("[SCROLL_BOUNCE_TRACE_UI]",s,e)}}function IS(){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 qre(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 xd(s,e,t={},n={}){const i=!!n.force;if(!IS()&&!i)return;const o={ts:new Date().toISOString(),event:e,...t};qre(o),(s==="error"?console.error:s==="warn"?console.warn:console.log)("[CONN_DIAG]",e,o)}function Qre(s){const e=(s||"").toString().trim();if(!e)return null;const t=e.match(Vre),n=/(?:\u5df2\u5b8c\u6210|Completed\.)/.test(e);if(!t||!n)return null;const i=t[1];return S("appUi.subAgentTaskDone",{agentId:i})}function Xre(s){const e=(s||"").toString().trim();return!e||!Gre.test(e)?null:S("appUi.backgroundRunCommandDone")}function Yre(s){const e=(s||"").toString().trim();return e?Qre(e)||Xre(e):null}const Jre={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(Kc("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}yI(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}),Kc("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(){Kc("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}I1(this)},conditionalScrollToBottom(){const s=typeof this.isOutputActive=="function"?this.isOutputActive():!0,e=this.getChatAreaController(),t=e&&typeof e.getStickState=="function"?e.getStickState():null;if(Kc("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)){Kc("ui.conditionalScrollToBottom:skip-manual-cooldown",{now:n,suppressUntil:this._manualScrollSuppressUntil},"ui.conditionalScrollToBottom:skip-manual-cooldown",120);return}if(t!=null&&t.escapedFromLock&&this._escapedByUserScroll){Kc("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){Kc("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}yI(this)},toggleScrollLock(){Kc("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}):I1(this,{ignoreUserScrolling:!0,resetUserScrolling:!0,behavior:"smooth",force:!0}),this._escapedByUserScroll=!1,this.chatSetScrollState({autoScrollEnabled:!0,userScrolling:!1}),!0},scrollThinkingToBottom(s){ite(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={},d=80)=>{if(!r()||t>=n)return;const h=Date.now();if(!(d>0&&h-i<d)){if(i=h,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,d=e.clientHeight,h=u-l-d<c,g=u-l-d<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:d,remain:u-l-d,isAtBottom:h,isNearBottom:g});return}this.chatSetScrollState({userScrolling:!(h||g)}),o("listener:scroll:update-state",{top:l,height:u,client:d,remain:u-l-d,isAtBottom:h,isNearBottom:g,autoScrollEnabled:this.autoScrollEnabled,userScrollingBefore:this.userScrolling,userScrollingNext:!(h||g)})})},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))}},Zre={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)}},eoe={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 d=new Blob([c],{type:"application/json"});return navigator.sendBeacon("/api/input-draft",d),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)||S("appUi.saveInputDraftFailed"));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)||S("appUi.fetchInputDraftFailed"));if(Number(this.composerDraftFetchSeq||0)!==e)return;if(this.taskInProgress||this.composerBusy){Be("[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()}),Be("[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)}},toe={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",S("appUi.policyBlockedFocusPanel"))||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",S("appUi.policyBlockedTokenPanel"))||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}},soe={openPersonalPage(){this.isPolicyBlocked("block_personal_space",S("appUi.policyBlockedPersonalSpace"))||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{}},minimizePlanApprovalDialog(){!Array.isArray(this.pendingPlanApprovals)||!this.pendingPlanApprovals.length||(this.planApprovalMinimized=!0)},restorePlanApprovalDialog(){!Array.isArray(this.pendingPlanApprovals)||!this.pendingPlanApprovals.length||(this.planApprovalMinimized=!1)},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)||S("appUi.submitPlanDecisionFailed"));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:S("appUi.planApproved"),message:S("appUi.planApprovedMessage"),type:"success",duration:2200})):this.uiPushToast({title:S("appUi.planRejected"),message:S("appUi.planRejectedMessage"),type:"info",duration:2200})}catch(t){const n=t instanceof Error?t.message:String(t||S("appUi.submitPlanDecisionFailed"));this.uiPushToast({title:S("appUi.submitPlanDecisionFailed"),message:n,type:"error"})}finally{this.answeringPlanApprovalIds=[]}}},rejectToolApproval(s){return this.decideToolApproval(s,"rejected")},openReviewDialog(){if(!this.isPolicyBlocked("block_conversation_review",S("appUi.policyBlockedReview"))){if(!this.isConnected){this.uiPushToast({title:S("appUi.unavailable"),message:S("appUi.unavailableNoConnectionMessage"),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:S("appUi.cannotReferenceCurrentConversation"),message:S("appUi.chooseOtherConversationForReview"),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)||S("appUi.submitAnswerFailed"))}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||S("appUi.submitAnswerFailed"));this.uiPushToast({title:S("appUi.submitAnswerFailed"),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)||S("appUi.submitApprovalFailed"));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||S("appUi.approvalFailed"));this.uiPushToast({title:S("appUi.approvalFailed"),message:i,type:"error"})}finally{this.decidingApprovalIds=(this.decidingApprovalIds||[]).filter(n=>n!==t)}}}},noe={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}}},ioe={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)||S("appUi.fetchProjectsFailed"));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||S("appUi.unnamedProject")),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 St(async()=>{const{useConversationStore:u}=await Promise.resolve().then(()=>Ti);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),d=this.versioningHostMode?"/api/host/workspaces/select":"/api/projects/select",h=await fetch(`${d}?workspace_id=${u}`),p=await h.json().catch(()=>({}));if(!h.ok||!(p!=null&&p.success))throw new Error((p==null?void 0:p.error)||(this.versioningHostMode?S("appUi.switchHostWorkspaceFailed"):S("appUi.switchProjectFailed")));const g=p.data||{};if(this.currentHostWorkspaceId=String(g.current_workspace_id||n),g.project_path&&(this.projectPath=String(g.project_path)),g.default_workspace_id&&(this.defaultHostWorkspaceId=String(g.default_workspace_id)),!t){this.messages=[],this.currentConversationId=null,(a=this.resetTokenStatistics)==null||a.call(this),this.currentConversationTitle=S("common.newConversation"),this.titleReady=!0,this.suppressTitleTyping=!1;try{const{useTaskStore:y}=await St(async()=>{const{useTaskStore:b}=await Promise.resolve().then(()=>io);return{useTaskStore:b}},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"]),_=(Array.isArray(this.runningWorkspaceTasks)?this.runningWorkspaceTasks:[]).filter(b=>String((b==null?void 0:b.workspace_id)||"")===this.currentHostWorkspaceId).find(b=>y.has(String((b==null?void 0:b.status)||""))&&(b==null?void 0:b.conversation_id));_!=null&&_.conversation_id?(await this.loadConversation(String(_.conversation_id),{force:!0}),this.conversationsOffset=0,await this.loadConversationsList()):(this.startTitleTyping(S("common.newConversation"),{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),m=String((v==null?void 0:v.label)||"").trim();this.uiPushToast({title:this.versioningHostMode?S("appUi.workspaceSwitched"):S("appUi.projectSwitched"),message:this.versioningHostMode?g.project_path||m||n:m||n,type:"success"}),(l=this.refreshProjectGitSummary)==null||l.call(this),this.fetchTerminalCount()}catch(u){const d=o(),h=d.conversationsCache[d.sidebarConversationType];h.list=i,h.loaded=!0,this.conversations=h.list,this.searchActive=r,this.conversationsLoading=!1;const p=u instanceof Error?u.message:String(u||S("appUi.switchFailed"));this.uiPushToast({title:this.versioningHostMode?S("appUi.switchWorkspaceFailed"):S("appUi.switchProjectFailed"),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=S("appUi.pathCannotBeEmpty");return}if(this.dockerProjectMode&&!e){this.hostWorkspaceCreateError=S("appUi.projectNameCannotBeEmpty");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?S("appUi.createWorkspaceFailed"):S("appUi.createProjectFailed")));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?S("appUi.workspaceCreated"):S("appUi.projectCreated"),message:o,type:"success"})}catch(i){const r=i instanceof Error?i.message:String(i||S("appUi.createFailed"));this.hostWorkspaceCreateError=r,this.uiPushToast({title:this.versioningHostMode?S("appUi.createWorkspaceFailed"):S("appUi.createProjectFailed"),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?S("appUi.projectNameCannotBeEmpty"):S("appUi.workspaceNameCannotBeEmpty");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)||S("appUi.renameFailed"));await this.fetchHostWorkspaces(),this.uiPushToast({title:this.versioningHostMode?S("appUi.workspaceRenamed"):S("appUi.projectRenamed"),message:t,type:"success"})}catch(n){const i=n instanceof Error?n.message:String(n||S("appUi.renameFailed"));this.hostWorkspaceCreateError=i,this.uiPushToast({title:this.versioningHostMode?S("appUi.renameWorkspaceFailed"):S("appUi.renameProjectFailed"),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=t===this.currentHostWorkspaceId;if(e.skipConfirm||await this.confirmAction({title:this.versioningHostMode?S("appUi.deleteWorkspaceConfirmTitle"):S("appUi.deleteProjectConfirmTitle"),message:this.versioningHostMode?S("appUi.deleteWorkspaceConfirmMessage",{name:(s==null?void 0:s.label)||t}):S("appUi.deleteProjectConfirmMessage",{name:(s==null?void 0:s.label)||t}),confirmText:S("common.delete"),cancelText:S("common.cancel"),confirmVariant:"danger"})){this.hostWorkspaceManageSubmitting=!0,this.hostWorkspaceCreateError="";try{const r=this.versioningHostMode?"/api/host/workspaces/delete":"/api/projects/delete",o=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"same-origin",body:JSON.stringify({workspace_id:t})}),a=await o.json().catch(()=>({}));if(!o.ok||!(a!=null&&a.success))throw new Error((a==null?void 0:a.error)||S("appUi.deleteFailed"));const c=a.data||{};if(this.currentHostWorkspaceId=String(c.current_workspace_id||this.currentHostWorkspaceId||""),c.default_workspace_id&&(this.defaultHostWorkspaceId=String(c.default_workspace_id)),await this.fetchHostWorkspaces(),n){this.messages=[],this.currentConversationId=null,this.currentConversationTitle=S("common.newConversation"),this.searchActive=!1,this.searchResults=[];const{useConversationStore:l}=await St(async()=>{const{useConversationStore:u}=await Promise.resolve().then(()=>Ti);return{useConversationStore:u}},void 0);l().resetConversationsTypeCache(),this.conversationsOffset=0,this.hasMoreConversations=!1,this.conversationsLoading=!0,history.replaceState({},"","/new"),await this.loadConversationsList()}this.uiPushToast({title:this.versioningHostMode?S("appUi.workspaceDeleted"):S("appUi.projectDeleted"),message:(s==null?void 0:s.label)||t,type:"success"})}catch(r){const o=r instanceof Error?r.message:String(r||S("appUi.deleteFailed"));this.hostWorkspaceCreateError=o,this.uiPushToast({title:this.versioningHostMode?S("appUi.deleteWorkspaceFailed"):S("appUi.deleteProjectFailed"),message:o,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)||S("appUi.openFailed"))}catch(t){const n=t instanceof Error?t.message:String(t||S("appUi.openFailed"));this.uiPushToast({title:this.versioningHostMode?S("appUi.openWorkspaceFailed"):S("appUi.openProjectFailed"),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?S("appUi.setDefaultWorkspaceFailed"):S("appUi.setDefaultProjectFailed")));const a=o.data||{};this.defaultHostWorkspaceId=String(a.default_workspace_id||e),await this.fetchHostWorkspaces(),this.uiPushToast({title:t?S("appUi.setAsDefaultWorkspace"):S("appUi.setAsDefaultProject"),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?S("appUi.setDefaultWorkspaceFailed"):S("appUi.setDefaultProjectFailed")));this.hostWorkspaceCreateError=r,this.uiPushToast({title:t?S("appUi.setDefaultWorkspaceFailed"):S("appUi.setDefaultProjectFailed"),message:r,type:"error"})}finally{this.hostWorkspaceManageSubmitting=!1}}},roe={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)||S("appUi.fetchRunningTasksFailed"));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 h=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 m=String((v==null?void 0:v.task_id)||""),y=String((v==null?void 0:v.status)||""),_=String((v==null?void 0:v.conversation_id)||"");return m?a.has(y)?(l.add(m),!0):c.has(y)&&_===this.currentConversationId?(u.has(m)||(u.add(m),this.acknowledgedCompletedTaskIds=[...Array.isArray(this.acknowledgedCompletedTaskIds)?this.acknowledgedCompletedTaskIds:[],m]),l.delete(m),!1):c.has(y)&&(h.has(m)||l.has(m))&&!u.has(m):!1});this.runningWorkspaceTasks=p,p.forEach(v=>{const m=String((v==null?void 0:v.task_id)||"");m&&l.add(m)}),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 g=p.some(v=>a.has(String((v==null?void 0:v.status)||"")));if(this.runningWorkspaceTasksRefreshTimer&&(clearTimeout(this.runningWorkspaceTasksRefreshTimer),this.runningWorkspaceTasksRefreshTimer=null),g&&(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((m,y)=>{const _=String((y==null?void 0:y.workspace_id)||""),b=String((y==null?void 0:y.status)||"");return _&&a.has(b)&&(m[_]=(m[_]||0)+1),m},{});this.hostWorkspaces=this.hostWorkspaces.map(m=>({...m,running_task_count:Number(v[m.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()}},BB="agents_tutorial_completed_v1",FB="agents_tutorial_version",HB="v1",ooe=[{id:"welcome",titleKey:"tutorial.welcomeTitle",descriptionKey:"tutorial.welcomeDesc",target:null,mode:"info",placement:"center"},{id:"sidebar-conversations-open",titleKey:"tutorial.sidebarConversationsOpenTitle",descriptionKey:"tutorial.sidebarConversationsOpenDesc",target:'[data-tutorial="conversation-menu"]',mode:"info",autoClick:!0,placement:"right",condition:"not_mobile_viewport"},{id:"sidebar-conversations-close",titleKey:"tutorial.sidebarConversationsCloseTitle",descriptionKey:"tutorial.sidebarConversationsCloseDesc",target:'[data-tutorial="conversation-collapse"]',mode:"info",autoClick:!0,placement:"right",condition:"not_mobile_viewport"},{id:"sidebar-new-chat",titleKey:"tutorial.newChatTitle",descriptionKey:"tutorial.sidebarNewChatDesc",target:'[data-tutorial="quick-new-conversation"]',mode:"info",autoClick:!0,placement:"right",condition:"not_mobile_viewport"},{id:"sidebar-workspace-toggle",titleKey:"tutorial.sidebarWorkspaceToggleTitle",descriptionKey:"tutorial.sidebarWorkspaceToggleDesc",target:'[data-tutorial="workspace-toggle"]',mode:"info",placement:"right",condition:"not_mobile_viewport"},{id:"sidebar-monitor-toggle",titleKey:"tutorial.sidebarMonitorToggleTitle",descriptionKey:"tutorial.sidebarMonitorToggleDesc",target:'[data-tutorial="monitor-toggle"]',mode:"info",placement:"right",condition:"not_mobile_viewport"},{id:"workspace-panel-switch",titleKey:"tutorial.workspacePanelSwitchTitle",descriptionKey:"tutorial.workspacePanelSwitchDesc",target:'[data-tutorial="panel-menu-toggle"]',mode:"info",autoClick:!0,placement:"right",condition:"not_mobile_viewport"},{id:"workspace-panel-options",titleKey:"tutorial.workspacePanelOptionsTitle",descriptionKey:"tutorial.workspacePanelOptionsDesc",target:'[data-tutorial="panel-menu"]',mode:"info",placement:"right",condition:"not_mobile_viewport"},{id:"workspace-mode-indicator",titleKey:"tutorial.workspaceModeIndicatorTitle",descriptionKey:"tutorial.workspaceModeIndicatorDesc",target:'[data-tutorial="run-mode-indicator"]',mode:"info",placement:"right",condition:"not_mobile_viewport"},{id:"workspace-connection-indicator",titleKey:"tutorial.workspaceConnectionIndicatorTitle",descriptionKey:"tutorial.workspaceConnectionIndicatorDesc",target:'[data-tutorial="connection-indicator"]',mode:"info",placement:"right",condition:"not_mobile_viewport"},{id:"header-model-selector",titleKey:"tutorial.headerModelSelectorTitle",descriptionKey:"tutorial.headerModelSelectorDesc",target:'[data-tutorial="header-model-selector"]',mode:"info",autoClick:!0,placement:"bottom",condition:"not_mobile_viewport"},{id:"header-model-options",titleKey:"tutorial.modelListTitle",descriptionKey:"tutorial.headerModelOptionsDesc",target:'[data-tutorial="header-model-options"]',mode:"info",placement:"bottom",condition:"not_mobile_viewport"},{id:"header-runmode-options",titleKey:"tutorial.headerRunmodeOptionsTitle",descriptionKey:"tutorial.headerRunmodeOptionsDesc",target:'[data-tutorial="header-runmode-options"]',mode:"info",placement:"bottom",condition:"not_mobile_viewport"},{id:"header-menu-close",titleKey:"tutorial.headerMenuCloseTitle",descriptionKey:"tutorial.headerMenuCloseDesc",target:".model-mode-dropdown",mode:"info",autoOutsideClick:!0,placement:"bottom",condition:"not_mobile_viewport"},{id:"mobile-menu-open-conversation",titleKey:"tutorial.openMenuTitle",descriptionKey:"tutorial.mobileMenuOpenConversationDesc",target:'[data-tutorial="mobile-menu-trigger"]',mode:"info",autoClick:!0,placement:"bottom",condition:"is_mobile_viewport"},{id:"mobile-menu-conversation",titleKey:"tutorial.mobileMenuConversationTitle",descriptionKey:"tutorial.mobileMenuConversationDesc",target:'[data-tutorial="mobile-menu-conversation"]',mode:"info",autoClick:!0,placement:"bottom",condition:"is_mobile_viewport"},{id:"mobile-conversation-close",titleKey:"tutorial.mobileConversationCloseTitle",descriptionKey:"tutorial.mobileConversationCloseDesc",target:'[data-tutorial="conversation-collapse"]',mode:"info",autoClick:!0,placement:"right",condition:"is_mobile_viewport"},{id:"mobile-menu-open-workspace",titleKey:"tutorial.openMenuAgainTitle",descriptionKey:"tutorial.mobileMenuOpenWorkspaceDesc",target:'[data-tutorial="mobile-menu-trigger"]',mode:"info",autoClick:!0,placement:"bottom",condition:"is_mobile_viewport"},{id:"mobile-menu-workspace",titleKey:"tutorial.mobileMenuWorkspaceTitle",descriptionKey:"tutorial.mobileMenuWorkspaceDesc",target:'[data-tutorial="mobile-menu-workspace"]',mode:"info",autoClick:!0,placement:"bottom",condition:"is_mobile_viewport"},{id:"mobile-workspace-panel-switch",titleKey:"tutorial.workspacePanelSwitchTitle",descriptionKey:"tutorial.mobileWorkspacePanelSwitchDesc",target:'[data-tutorial="panel-menu-toggle"]',mode:"info",autoClick:!0,placement:"bottom",condition:"is_mobile_viewport"},{id:"mobile-workspace-panel-options",titleKey:"tutorial.mobileWorkspacePanelOptionsTitle",descriptionKey:"tutorial.mobileWorkspacePanelOptionsDesc",target:'[data-tutorial="panel-menu"]',mode:"info",placement:"bottom",condition:"is_mobile_viewport"},{id:"mobile-workspace-close",titleKey:"tutorial.mobileWorkspaceCloseTitle",descriptionKey:"tutorial.mobileWorkspaceCloseDesc",target:'[data-tutorial="mobile-workspace-close"]',mode:"info",autoClick:!0,placement:"right",condition:"is_mobile_viewport"},{id:"mobile-menu-open-newchat",titleKey:"tutorial.openMenuAgainTitle",descriptionKey:"tutorial.mobileMenuOpenNewchatDesc",target:'[data-tutorial="mobile-menu-trigger"]',mode:"info",autoClick:!0,placement:"bottom",condition:"is_mobile_viewport"},{id:"mobile-menu-new-chat",titleKey:"tutorial.newChatTitle",descriptionKey:"tutorial.mobileMenuNewChatDesc",target:'[data-tutorial="mobile-menu-new-chat"]',mode:"info",autoClick:!0,placement:"bottom",condition:"is_mobile_viewport"},{id:"mobile-model-selector-open",titleKey:"tutorial.mobileModelSelectorOpenTitle",descriptionKey:"tutorial.mobileModelSelectorOpenDesc",target:'[data-tutorial="header-model-selector-mobile"]',mode:"info",autoClick:!0,placement:"bottom",condition:"is_mobile_viewport"},{id:"mobile-model-options",titleKey:"tutorial.modelListTitle",descriptionKey:"tutorial.mobileModelOptionsDesc",target:'[data-tutorial="header-model-options"]',mode:"info",placement:"bottom",condition:"is_mobile_viewport"},{id:"mobile-runmode-options",titleKey:"tutorial.mobileRunmodeOptionsTitle",descriptionKey:"tutorial.mobileRunmodeOptionsDesc",target:'[data-tutorial="header-runmode-options"]',mode:"info",placement:"bottom",condition:"is_mobile_viewport"},{id:"mobile-model-selector-close",titleKey:"tutorial.mobileModelSelectorCloseTitle",descriptionKey:"tutorial.mobileModelSelectorCloseDesc",target:".model-mode-dropdown",mode:"info",autoOutsideClick:!0,placement:"bottom",condition:"is_mobile_viewport"},{id:"open-quick-menu",titleKey:"tutorial.openQuickMenuTitle",descriptionKey:"tutorial.openQuickMenuDesc",target:'[data-tutorial="quick-menu-open"]',mode:"info",autoClick:!0,placement:"top"},{id:"quick-upload",titleKey:"tutorial.quickUploadTitle",descriptionKey:"tutorial.quickUploadDesc",target:'[data-tutorial="quick-upload"]',mode:"info",placement:"left"},{id:"quick-review",titleKey:"tutorial.quickReviewTitle",descriptionKey:"tutorial.quickReviewDesc",target:'[data-tutorial="quick-review"]',mode:"info",placement:"left"},{id:"quick-send-image",titleKey:"tutorial.quickSendImageTitle",descriptionKey:"tutorial.quickSendImageDesc",target:'[data-tutorial="quick-send-image"]',mode:"info",placement:"left",condition:"model_supports_media"},{id:"quick-send-video",titleKey:"tutorial.quickSendVideoTitle",descriptionKey:"tutorial.quickSendVideoDesc",target:'[data-tutorial="quick-send-video"]',mode:"info",placement:"left",condition:"model_supports_media"},{id:"quick-tool-disable",titleKey:"tutorial.quickToolDisableTitle",descriptionKey:"tutorial.quickToolDisableDesc",target:'[data-tutorial="quick-tool-menu"]',mode:"info",placement:"left"},{id:"quick-settings",titleKey:"tutorial.quickSettingsTitle",descriptionKey:"tutorial.quickSettingsDesc",target:'[data-tutorial="quick-settings-menu"]',mode:"info",placement:"left"},{id:"open-settings-submenu",titleKey:"tutorial.openSettingsSubmenuTitle",descriptionKey:"tutorial.openSettingsSubmenuDesc",target:'[data-tutorial="quick-settings-menu"]',mode:"info",autoClick:!0,placement:"left"},{id:"open-token-panel",titleKey:"tutorial.openTokenPanelTitle",descriptionKey:"tutorial.openTokenPanelDesc",target:'[data-tutorial="settings-token-panel"]',mode:"info",autoClick:!0,placement:"left"},{id:"token-panel",titleKey:"tutorial.tokenPanelTitle",descriptionKey:"tutorial.tokenPanelDesc",target:'[data-tutorial="token-drawer"]',mode:"info",placement:"left"},{id:"close-token-panel",titleKey:"tutorial.closeTokenPanelTitle",descriptionKey:"tutorial.closeTokenPanelDesc",target:'[data-tutorial="token-close"]',mode:"info",autoClick:!0,placement:"left"},{id:"open-personal-space",titleKey:"tutorial.openPersonalSpaceTitle",descriptionKey:"tutorial.openPersonalSpaceDesc",target:'[data-tutorial="open-personal-space"]',mode:"info",autoClick:!0,placement:"right",condition:"not_mobile_viewport"},{id:"mobile-menu-open-personal",titleKey:"tutorial.openMenuTitle",descriptionKey:"tutorial.mobileMenuOpenPersonalDesc",target:'[data-tutorial="mobile-menu-trigger"]',mode:"info",autoClick:!0,placement:"bottom",condition:"is_mobile_viewport"},{id:"mobile-menu-personal",titleKey:"tutorial.mobileMenuPersonalTitle",descriptionKey:"tutorial.mobileMenuPersonalDesc",target:'[data-tutorial="mobile-menu-personal"]',mode:"info",autoClick:!0,placement:"bottom",condition:"is_mobile_viewport"},{id:"personal-overview",titleKey:"tutorial.personalOverviewTitle",descriptionKey:"tutorial.personalOverviewDesc",target:'[data-tutorial="personal-card"]',mode:"info",placement:"right"},{id:"tab-preferences",titleKey:"tutorial.tabPreferencesTitle",descriptionKey:"tutorial.tabPreferencesDesc",target:'[data-tutorial="personal-tab-preferences"]',mode:"info",autoClick:!0,placement:"right"},{id:"page-preferences",titleKey:"tutorial.pagePreferencesTitle",descriptionKey:"tutorial.pagePreferencesDesc",target:'[data-tutorial="personal-content-shell"]',mode:"info",placement:"right"},{id:"tab-model",titleKey:"tutorial.tabModelTitle",descriptionKey:"tutorial.tabModelDesc",target:'[data-tutorial="personal-tab-model"]',mode:"info",autoClick:!0,placement:"right"},{id:"page-model",titleKey:"tutorial.pageModelTitle",descriptionKey:"tutorial.pageModelDesc",target:'[data-tutorial="personal-content-shell"]',mode:"info",placement:"right"},{id:"tab-usage",titleKey:"tutorial.tabUsageTitle",descriptionKey:"tutorial.tabUsageDesc",target:'[data-tutorial="personal-tab-general"]',mode:"info",autoClick:!0,placement:"right"},{id:"page-usage",titleKey:"tutorial.pageUsageTitle",descriptionKey:"tutorial.pageUsageDesc",target:'[data-tutorial="personal-content-shell"]',mode:"info",placement:"right"},{id:"tab-app-update",titleKey:"tutorial.tabAppUpdateTitle",descriptionKey:"tutorial.tabAppUpdateDesc",target:'[data-tutorial="personal-tab-app-update"]',mode:"info",autoClick:!0,placement:"right",condition:"is_app_shell"},{id:"page-app-update",titleKey:"tutorial.pageAppUpdateTitle",descriptionKey:"tutorial.pageAppUpdateDesc",target:'[data-tutorial="personal-content-shell"]',mode:"info",placement:"right",condition:"is_app_shell"},{id:"tab-behavior",titleKey:"tutorial.tabBehaviorTitle",descriptionKey:"tutorial.tabBehaviorDesc",target:'[data-tutorial="personal-tab-behavior"]',mode:"info",autoClick:!0,placement:"right"},{id:"page-behavior",titleKey:"tutorial.pageBehaviorTitle",descriptionKey:"tutorial.pageBehaviorDesc",target:'[data-tutorial="personal-content-shell"]',mode:"info",placement:"right"},{id:"tab-skills",titleKey:"tutorial.tabSkillsTitle",descriptionKey:"tutorial.tabSkillsDesc",target:'[data-tutorial="personal-tab-skills"]',mode:"info",autoClick:!0,placement:"right"},{id:"page-skills",titleKey:"tutorial.pageSkillsTitle",descriptionKey:"tutorial.pageSkillsDesc",target:'[data-tutorial="personal-content-shell"]',mode:"info",placement:"right"},{id:"tab-image",titleKey:"tutorial.tabImageTitle",descriptionKey:"tutorial.tabImageDesc",target:'[data-tutorial="personal-tab-image"]',mode:"info",autoClick:!0,placement:"right"},{id:"page-image",titleKey:"tutorial.pageImageTitle",descriptionKey:"tutorial.pageImageDesc",target:'[data-tutorial="personal-content-shell"]',mode:"info",placement:"right"},{id:"tab-theme",titleKey:"tutorial.tabThemeTitle",descriptionKey:"tutorial.tabThemeDesc",target:'[data-tutorial="personal-tab-theme"]',mode:"info",autoClick:!0,placement:"right"},{id:"page-theme",titleKey:"tutorial.pageThemeTitle",descriptionKey:"tutorial.pageThemeDesc",target:'[data-tutorial="personal-content-shell"]',mode:"info",placement:"right"},{id:"close-personal-space",titleKey:"tutorial.closePersonalSpaceTitle",descriptionKey:"tutorial.closePersonalSpaceDesc",target:'[data-tutorial="personal-close"]',mode:"info",autoClick:!0,placement:"bottom"},{id:"done",titleKey:"tutorial.doneTitle",descriptionKey:"tutorial.doneDesc",target:null,mode:"info",placement:"center"}],aoe=s=>({id:s.id,title:S(s.titleKey),description:S(s.descriptionKey),target:s.target,mode:s.mode,autoClick:s.autoClick,autoOutsideClick:s.autoOutsideClick,placement:s.placement,condition:s.condition}),loe=()=>typeof window>"u"?!1:new URLSearchParams(window.location.search).has("app_shell")?!0:!!(window!=null&&window.AndroidThemeBridge),AP=()=>typeof window>"u"?!1:window.innerWidth<=768,ET=s=>{if(!s.condition)return!0;if(s.condition==="is_app_shell")return loe();if(s.condition==="model_supports_media"){const t=er().currentModel;return!!(t!=null&&t.supportsImage||t!=null&&t.supportsVideo)}return s.condition==="is_mobile_viewport"?AP():s.condition==="not_mobile_viewport"?!AP():!0},coe=()=>{if(typeof window>"u"||!window.localStorage)return!1;try{return window.localStorage.getItem(FB)!==HB?!1:window.localStorage.getItem(BB)==="1"}catch{return!1}},MT=s=>{if(!(typeof window>"u"||!window.localStorage))try{window.localStorage.setItem(FB,HB),window.localStorage.setItem(BB,s?"1":"0")}catch{}},_E=hn("tutorial",{state:()=>({running:!1,completed:coe(),currentIndex:0,steps:ooe,activeSelector:null}),getters:{activeStep(s){const e=s.steps[s.currentIndex]||null;return lt.value,e?aoe(e):null},totalVisibleSteps(s){return s.steps.filter(e=>ET(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&&ET(n)&&(e+=1)}return e}},actions:{shouldIncludeStep(s){return ET(s)},startTutorial(){this.running=!0,this.completed=!1,this.currentIndex=0,this.activeSelector=null,MT(!1),this.skipHiddenSteps("forward")},exitTutorial(){this.running=!1,this.activeSelector=null},finishTutorial(){this.running=!1,this.completed=!0,this.activeSelector=null,MT(!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,MT(!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}}}),uoe={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)||S("appUi.updateTutorialStatusFailed"));return _E().markCompleted(),this.tutorialPromptVisible=!1,!0}catch(e){return console.warn("更新新手教程提示状态失败:",e),this.uiPushToast({title:S("appUi.notice"),message:S("appUi.tutorialSaveFailedMessage"),type:"warning"}),!1}finally{this.tutorialPromptLoading=!1}},async handleNewUserTutorialStart(){if(!await this.updateTutorialPromptStatus(!0))return;Js().closeDrawer();const t=_E();window.setTimeout(()=>{t.startTutorial()},220)},async handleNewUserTutorialSkip(){await this.updateTutorialPromptStatus(!0)}},$n={timer:null,rollback:void 0,latest:void 0,conversationId:null},doe={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:S("common.newConversation"),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))},async handleSelectNewConversationType(s){const e=s==="multi_agent"?"multi_agent":"agent";if(this.newConversationType=e,QD(e),this.agentTypeMenuOpen=!1,!this.currentConversationId)try{const{useConversationStore:t}=await St(async()=>{const{useConversationStore:n}=await Promise.resolve().then(()=>Ti);return{useConversationStore:n}},void 0);t().setSidebarConversationType(e==="multi_agent"?"multi_agent":"normal")}catch{}},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=er(),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:S("appUi.modeUnavailable"),message:S("appUi.fastOnlyModeMessage"),type:"warning"}),this.modeMenuOpen=!1,this.inputCloseMenus();return}if(i&&s!=="thinking"){e.suppressToast||this.uiPushToast({title:S("appUi.modeUnavailable"),message:S("appUi.thinkingOnlyModeMessage"),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||S("appUi.switchFailed"));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||S("common.unknownError"));this.uiPushToast({title:S("appUi.switchThinkingModeFailed"),message:c||S("common.retryLater"),type:"error"})}finally{this.modeMenuOpen=!1,this.inputCloseMenus()}},async toggleThinkingMode(){await this.handleCycleRunMode()},async setReasoningEffort(s){$n.rollback===void 0&&($n.rollback=this.reasoningEffort,$n.conversationId=this.currentConversationId||null),$n.latest=s,this.reasoningEffort=s,$n.timer&&clearTimeout($n.timer),$n.timer=setTimeout(()=>{$n.timer=null,this.flushReasoningEffortSave()},600)},async flushReasoningEffortSave(){if($n.timer&&(clearTimeout($n.timer),$n.timer=null),$n.rollback===void 0)return;const s=$n.latest,e=$n.rollback,t=$n.conversationId;$n.rollback=void 0,$n.latest=void 0,$n.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||S("appUi.settingFailed"));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||S("common.unknownError"));this.uiPushToast({title:S("appUi.setReasoningEffortFailed"),message:i||S("common.retryLater"),type:"error"})}},async handleStopAllSubAgents(){const s=this.currentConversationType==="multi_agent",e=s?"soft_stop":"terminate",t=s?S("appUi.pauseAllSubAgentsTitle"):S("appUi.terminateAllSubAgentsTitle"),n=s?S("appUi.pauseAllSubAgentsMessage"):S("appUi.terminateAllSubAgentsMessage"),i=s?S("appUi.pause"):S("appUi.terminate");let r=!1;try{r=await(await St(async()=>{const{useUiStore:a}=await Promise.resolve().then(()=>MF);return{useUiStore:a}},void 0)).useUiStore().requestConfirm({title:t,message:n,confirmText:i,cancelText:S("common.cancel"),confirmVariant:"danger",closeOnBackdrop:!0})}catch(o){console.error("[stopAllSubAgents] 弹窗异常:",o);return}if(r)try{const{useSubAgentStore:o}=await St(async()=>{const{useSubAgentStore:l}=await Promise.resolve().then(()=>VF);return{useSubAgentStore:l}},void 0),c=await o().stopAllAgents(e);if(!c.success){this.uiPushToast({title:S("appUi.stopSubAgentsFailed"),message:c.error||S("appUi.pleaseRetry"),type:"error"});return}this.uiPushToast({title:s?S("appUi.subAgentsPaused"):S("appUi.subAgentsTerminated"),message:S("appUi.stoppedSubAgentCount",{n:c.stoppedCount||0}),type:"info"})}catch(o){console.error("[stopAllSubAgents] 调用失败:",o),this.uiPushToast({title:S("appUi.stopSubAgentsFailed"),message:(o==null?void 0:o.message)||String(o),type:"error"})}}},hoe={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(zo().isModelDisabled(s)){this.uiPushToast({title:S("appUi.modelDisabled"),message:S("appUi.forceDisabledByAdmin"),type:"warning"});return}const t=er(),n=t.models.find(o=>o.key===s);if(this.conversationHasImages&&!(n!=null&&n.supportsImage)){this.uiPushToast({title:S("appUi.switchFailed"),message:S("appUi.conversationHasImagesMessage"),type:"error"});return}if(this.conversationHasVideos&&!(n!=null&&n.supportsVideo)){this.uiPushToast({title:S("appUi.switchFailed"),message:S("appUi.conversationHasVideosMessage"),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||S("appUi.switchFailed"));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:S("appUi.modelSwitched"),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||S("appUi.switchFailed"));this.uiPushToast({title:S("appUi.switchModelFailed"),message:a,type:"error"})}finally{this.modelMenuOpen=!1,this.inputCloseMenus(),this.inputSetQuickMenuOpen(!1)}},async handleHeaderModelSelect(s,e){e||(await this.handleModelSelect(s),this.closeHeaderMenu())}},foe={applyPolicyUiLocks(){const e=zo().uiBlocks;e.collapse_workspace&&this.uiSetWorkspaceCollapsed(!0),e.block_virtual_monitor&&this.chatDisplayMode==="monitor"&&this.uiSetChatDisplayMode("chat")},isPolicyBlocked(s,e){return zo().uiBlocks[s]?(this.uiPushToast({title:S("appUi.disabledByAdmin"),message:e||S("appUi.forceDisabledByAdmin"),type:"warning"}),!0):!1},getPermissionModeLabel(s){lt.value;const t=(Array.isArray(this.permissionModeOptions)?this.permissionModeOptions:[]).find(n=>n.value===s);return t?S(t.labelKey):s||S("appUi.unknown")},getExecutionModeLabel(s){lt.value;const t=(Array.isArray(this.executionModeOptions)?this.executionModeOptions:[]).find(n=>n.value===s);return t?S(t.labelKey):s||S("appUi.unknown")},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)||S("appUi.switchPermissionFailed"));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:S("appUi.permissionUpdated"),message:(n==null?void 0:n.message)||S("appUi.appliedImmediately"),type:"info",duration:1800})}catch(t){const n=t instanceof Error?t.message:String(t||S("appUi.switchPermissionFailed"));this.uiPushToast({title:S("appUi.switchPermissionFailed"),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)||S("appUi.switchExecutionModeFailed"));const i=(n==null?void 0:n.state)||{};typeof i.mode=="string"&&(this.currentExecutionMode=i.mode),this.pendingExecutionMode="",this.uiPushToast({title:S("appUi.executionModeUpdated"),message:(n==null?void 0:n.message)||S("appUi.appliedImmediately"),type:this.currentExecutionMode==="direct"?"warning":"info",duration:1800})}catch(t){const n=t instanceof Error?t.message:String(t||S("appUi.switchExecutionModeFailed"));this.uiPushToast({title:S("appUi.switchExecutionModeFailed"),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)||S("appUi.switchNetworkPermissionFailed"));typeof n.mode=="string"&&(this.currentNetworkPermission=n.mode),this.pendingNetworkPermission=typeof n.pending_mode=="string"?n.pending_mode:"";const i={restricted:S("appUi.networkRestricted"),full:S("appUi.networkFull")};this.uiPushToast({title:S("appUi.networkPermissionUpdated"),message:(n==null?void 0:n.message)||S("appUi.switchedToMode",{mode:i[this.currentNetworkPermission]||this.currentNetworkPermission}),type:this.currentNetworkPermission==="full"?"warning":"info",duration:1800})}catch(t){const n=t instanceof Error?t.message:String(t||S("appUi.switchNetworkPermissionFailed"));this.uiPushToast({title:S("appUi.switchNetworkPermissionFailed"),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)||S("appUi.saveFailed"));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:S("appUi.pathAuthorizationSaved"),message:S("appUi.pathAuthApplyMessage"),type:"success"}),this.pathAuthorizationDialogOpen=!1}catch(n){const i=n instanceof Error?n.message:String(n||S("appUi.saveFailed"));this.uiPushToast({title:S("appUi.savePathAuthorizationFailed"),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"&&Js().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}},poe={getWorkModeLabel(s){lt.value;const t=(Array.isArray(this.workModeOptions)?this.workModeOptions:[]).find(n=>n.value===s);return t?S(t.labelKey):s||S("appUi.unknown")},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)||S("appUi.workModeRunningMessage"));if(!t.ok||!(n!=null&&n.success))throw new Error((n==null?void 0:n.message)||(n==null?void 0:n.error)||S("appUi.switchRunModeFailed"));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:S("appUi.workModePlan"),ask:S("appUi.workModeAsk"),execute:S("appUi.workModeExecute")};this.uiPushToast({title:S("appUi.runModeUpdated"),message:(n==null?void 0:n.message)||S("appUi.switchedToMode",{mode:i[this.currentWorkMode]||this.currentWorkMode}),type:"info",duration:1800})}catch(t){const n=t instanceof Error?t.message:String(t||S("appUi.switchRunModeFailed"));this.uiPushToast({title:S("appUi.switchRunModeFailed"),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}},moe={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()}},goe={handleRealtimeTerminalClick(){this.isConnected&&(this.isPolicyBlocked("block_realtime_terminal",S("appUi.policyBlockedTerminal"))||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=Js().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{}}},voe={handleCompressConversationClick(){if(!(this.compressing||this.streamingMessage||!this.isConnected)){if(this.compressionActiveForCurrentConversation){this.uiPushToast({title:S("appUi.conversationAutoCompressing"),message:S("appUi.compressingNowPleaseWait"),type:"warning"});return}this.isPolicyBlocked("block_compress_conversation",S("appUi.policyBlockedCompress"))||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:S("appUi.selectConversation"),message:S("appUi.selectConversationForReview"),type:"info"});return}if(this.reviewSelectedConversationId===this.currentConversationId){this.uiPushToast({title:S("appUi.cannotReferenceCurrentConversation"),message:S("appUi.chooseOtherConversationForReview"),type:"warning"});return}if(!this.currentConversationId){this.uiPushToast({title:S("appUi.cannotSend"),message:S("appUi.noActiveConversationMessage"),type:"warning"});return}this.reviewSubmitting=!0;try{const{path:s,char_count:e}=await this.generateConversationReview(this.reviewSelectedConversationId);if(!s)throw new Error(S("appUi.reviewPathMissing"));const t=typeof e=="number"?e:0;this.reviewGeneratedPath=s;const n=t&&t<=1e4?S("appUi.reviewSuggestReadFull"):S("appUi.reviewSuggestReadBySearch");if(this.reviewSendToModel){const i=S("appUi.reviewAutoMessage",{path:s,count:t||S("appUi.unknown"),suggestion:n});await this.sendAutoUserMessage(i)&&(this.reviewDialogOpen=!1)}else this.uiPushToast({title:S("appUi.reviewFileGenerated"),message:s,type:"success"})}catch(s){const e=s instanceof Error?s.message:String(s||S("appUi.generateFailed"));this.uiPushToast({title:S("appUi.generateReviewFailed"),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)||S("appUi.fetchPreviewFailed");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||S("appUi.fetchPreviewFailed"));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)||S("appUi.generateFailed");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}}},yoe={async initSocket(){this.socket=null},async checkConnectionHealth(){if(this.connectionHeartbeatInFlight){xd("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=IS(),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 d=this.connectionHeartbeatFailCount||0;this.isConnected=!0,this.connectionHeartbeatFailCount=0,this.connectionHeartbeatLastLatencyMs=Date.now()-t,this.connectionHeartbeatLastStatusCode=o,this.connectionHeartbeatLastError="",r?IS()&&(this.connectionHeartbeatLastLatencyMs>=700||s<=3||s%60===0)&&xd("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(),xd("warn","health-recovered",{requestId:e,seq:s,elapsedMs:this.connectionHeartbeatLastLatencyMs,failCountBeforeRecover:d,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 d=(this.connectionHeartbeatFailCount||0)+1;this.connectionHeartbeatFailCount=d,this.connectionHeartbeatLastLatencyMs=Date.now()-t,this.connectionHeartbeatLastStatusCode=o;const h=(u==null?void 0:u.name)||"Error",p=(u==null?void 0:u.message)||String(u);this.connectionHeartbeatLastError=`${h}: ${p}`;const g=typeof this.connectionHeartbeatFailThreshold=="number"&&this.connectionHeartbeatFailThreshold>0?this.connectionHeartbeatFailThreshold:3,v=d>=g;v&&(this.isConnected=!1),r&&v&&(this.connectionHeartbeatLastChangeAt=Date.now());const m=r||d<=g||d%10===0;xd(m?"warn":"log","health-failed",{requestId:e,seq:s,elapsedMs:this.connectionHeartbeatLastLatencyMs,failCount:d,status:o,endpoint:i,diagEnabled:n,wasConnected:r,nowConnected:!!this.isConnected,failThreshold:g,shouldDisconnect:v,errorName:h,errorMessage:p,timeout:h==="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:m})}finally{this.connectionHeartbeatInFlight=!1,l&&clearTimeout(l)}},startConnectionHeartbeat(){if(this.connectionHeartbeatActive)return;this.connectionHeartbeatActive=!0,this.connectionHeartbeatFailCount=0,xd("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;IS()&&(!this.isConnected||(this.connectionHeartbeatSeq||0)<=3)&&xd("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),xd("log","heartbeat-stop",{})},async enterWorkspaceBootstrapMode(){this.versioningHostMode=!0,this.dockerProjectMode=!1,M1(!0),this.isConnected=!0;try{await this.fetchHostWorkspaces()}catch(s){console.warn("引导模式加载工作区列表失败:",s)}this.uiPushToast({title:S("appUi.workspaceBootstrapTitle"),message:S("appUi.workspaceBootstrapMessage"),type:"info"})},async loadInitialData(){var s,e;try{Be("加载初始数据...");const t=er();await t.fetchModels().catch(w=>{console.warn("加载模型列表失败,使用前端默认列表:",w)});const n=await fetch("/api/status");if(!n.ok){const w=await n.json().catch(()=>({}));if((w==null?void 0:w.code)==="no_workspace"){await this.enterWorkspaceBootstrapMode();return}throw new Error(S("appUi.statusApiRequestFailed",{status: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 zo().fetchPolicy(),this.applyPolicyUiLocks();const o=Js();!o.loaded&&!o.loading&&await o.fetchPersonalization().catch(w=>{console.warn("加载个性化设置失败:",w)});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 w=o.form.default_run_mode,T=o.form.default_model,A=o.form.default_reasoning_effort;w&&(this.runMode=w,Be("应用默认运行模式:",w)),this.reasoningEffort=A,A&&Be("应用默认推理强度:",A),T&&(t.setModel(T),this.currentModelKey=t.currentModelKey,Be("应用默认模型:",T)),w==="thinking"?this.thinkingMode=!0:w==="fast"&&(this.thinkingMode=!1)}this.isConnected=!0;const u=this.focusFetchFiles();let d=null;const h=((e=i==null?void 0:i.container)==null?void 0:e.mode)==="host";this.versioningHostMode=!!h,this.dockerProjectMode=!h,M1(!!h),h?(this.fileMarkTreeUnavailable(S("appUi.hostModeFileTreeUnavailable")),await this.fetchHostWorkspaces()):(this.fileMarkTreeUnavailable(S("appUi.dockerModeFilesChanged")),await this.fetchHostWorkspaces(),this.hostWorkspaceCreatePath="",this.hostWorkspaceCreateLabel="",this.hostWorkspaceCreateError="",this.hostWorkspaceCreateSubmitting=!1);const p=this.isExplicitNewConversationRoute(),g=await this.getRunningTaskConversationId(),m=i.conversation&&i.conversation.current_id||g,y=window.location.pathname.replace(/^\/+/,""),_=y==="multiagent/new"||y==="multiagent";if(m&&!this.currentConversationId&&!_&&!p&&!this.isConversationIndependentRoute()){this.skipConversationHistoryReload=!0,this.skipConversationLoadedEvent=!0,this.suppressTitleTyping=!0,this.titleReady=!1,this.currentConversationTitle="",this.titleTypingText="",this.currentConversationId=m;const w=this.stripConversationPrefix(m);window.location.pathname.replace(/^\/+/,"")!==w&&history.replaceState({conversationId:m},"",`/${w}`);try{const C=await(await fetch("/api/conversations/current")).json();if(C.success&&C.data)this.currentConversationTitle=C.data.title,this.titleReady=!0,this.suppressTitleTyping=!1,this.startTitleTyping(this.currentConversationTitle,{animate:!1});else{this.titleReady=!0,this.suppressTitleTyping=!1;const E=this.currentConversationTitle||S("common.newConversation");this.currentConversationTitle=E,this.startTitleTyping(E,{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(A){console.warn("获取当前对话标题失败:",A),this.titleReady=!0,this.suppressTitleTyping=!1,this.startTitleTyping(this.currentConversationTitle||S("common.newConversation"),"")}}const b=this.fileFetchTodoList(),k=[u,b];await Promise.allSettled(k),await this.loadToolSettings(!0),this.conversationsOffset=0,await this.loadConversationsList(),Be("初始数据加载完成")}catch(t){console.error("加载初始数据失败:",t),this.isConnected=!1}}},boe={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=S("common.newConversation"),this.logMessageState("bootstrapRoute:clear-messages-for-new"),this.messages=[],this.titleReady=!0,this.suppressTitleTyping=!1,this.startTitleTyping(S("common.newConversation"),{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=S("common.newConversation"),this.titleReady=!0,this.suppressTitleTyping=!1,this.startTitleTyping(S("common.newConversation"),{animate:!1}))}catch(n){console.warn("初始化路由失败:",n),history.replaceState({},"","/new"),this.currentConversationId=null,this.currentConversationTitle=S("common.newConversation"),this.titleReady=!0,this.suppressTitleTyping=!1,this.startTitleTyping(S("common.newConversation"),{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=S("common.newConversation"),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:""}},_oe={addSystemMessage(s){const e=Yre(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=S("appUi.blankWelcomeDefault");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";Be("[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 KP(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 EP(s,e,t){return Math.max(e,Math.min(s,t))}function woe(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 Soe(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=EP(o,i,r),s.rightWidth=o}else s.resizingPanel==="conversation"&&EP(e.clientX,200,400)}function koe(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 Coe={startResize(s,e){woe(this,s,e)},handleResize(s){Soe(this,s)},stopResize(){koe(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"}},Toe={...jre,...Jre,...Zre,...eoe,...toe,...soe,...noe,...ioe,...roe,...uoe,...doe,...hoe,...foe,...poe,...moe,...goe,...voe,...yoe,...boe,..._oe,...Coe},UB=(...s)=>{},WB=(...s)=>{},Ml=(...s)=>{},My=(...s)=>{},MP="[RESTORE_DEBUG]";let xT=0;const RT=800,Aoe=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 Eoe(){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 qn(s,e={}){if(Eoe()&&Aoe.has(s)&&!(xT>=RT)){if(xT+=1,xT===RT){console.warn(MP,"log-limit-reached",{max:RT});return}console.log(MP,s,e)}}function Moe(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 xoe(s){if(!s||typeof s!="object")return!1;const e=s.metadata||{};return!!(s.runtime_mode_notice||e.runtime_mode_notice)}function Roe(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 Ioe(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=Fd({content:t,metadata:i,...s}),i.starts_work=$v({content:t,metadata:i,...s}),i}function O0(s){return!s||s.role!=="assistant"?!1:(Array.isArray(s.actions)?s.actions:[]).length===0&&!!s.awaitingFirstContent}function Poe(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(O0(t)&&e>0){const n=s[e-1];if((n==null?void 0:n.role)==="user")return n}return null}function xP(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 Loe={cleanupTrailingEmptyAssistantPlaceholder(s="unspecified"){if(!Array.isArray(this.messages)||!this.messages.length)return!1;const e=this.messages[this.messages.length-1];return O0(e)?(this.messages.pop(),typeof this.currentMessageIndex=="number"&&(this.currentMessageIndex=this.messages.length-1),My("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 O0(e)?(this.messages.pop(),typeof this.currentMessageIndex=="number"&&(this.currentMessageIndex=-1),My("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)}),Be("[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==="新对话"||e==="New Chat"}},gw=(...s)=>{},RP=(...s)=>{},vw=(...s)=>{},Ooe="[CONN_DIAG]",IP=2e3,Doe=()=>{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}},xl=(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>IP&&i.__CONN_DIAG_LOGS__.splice(0,i.__CONN_DIAG_LOGS__.length-IP)}}catch{}Doe()&&console.log(Ooe,s,n)},FM=hn("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{Be("[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||S("stores.createTaskFailed"))}const o=await r.json();if(!o.success)throw new Error(o.error||S("stores.createTaskFailed"));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,Be("[Task] 任务创建成功:",o.data.task_id),xl("task-created",{taskId:o.data.task_id,conversationId:n}),this.startPolling(i.eventHandler),o.data}catch(r){throw xl("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||S("stores.pollTaskFailed"));const c=a.data;if(this.currentTaskId!==e){xl("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;vw("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)&&xl("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}),Cn("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:[],d=JSON.stringify(u.map(g=>[String((g==null?void 0:g.id)||""),String((g==null?void 0:g.text)||"")]));if(d!==this.runtimeQueueSnapshotKey){this.runtimeQueueSnapshotKey=d;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(g){console.warn("[Task] 处理 runtime_queue_sync 失败:",g)}}let h=!1,p=!1;if(c.events&&c.events.length>0){Be(`[Task] 收到 ${c.events.length} 个新事件`);for(const v of c.events){if(this.currentTaskId!==e){xl("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")&&vw("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"&&(h=!0),(v==null?void 0:v.type)==="task_stopped"&&(p=!0);try{s(v)}catch(m){console.error("[Task] 处理事件失败:",m,v)}}const g=c.events.filter(v=>["user_message","sub_agent_waiting","task_complete","task_stopped","error"].includes(v==null?void 0:v.type));g.length>0&&RP("[DEBUG_NOTIFY_KEY][task] events",{taskId:this.currentTaskId,from:this.lastEventIndex,nextOffset:c.next_offset,count:g.length,items:g.map(v=>{var m,y,_,b;return{idx:v==null?void 0:v.idx,type:v==null?void 0:v.type,sub_agent_notice:!!((m=v==null?void 0:v.data)!=null&&m.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:(_=v==null?void 0:v.data)==null?void 0:_.has_running_background_commands,task_id:(b=v==null?void 0:v.data)==null?void 0:b.task_id}})}),this.lastEventIndex=c.next_offset}if(c.status==="canceled"&&!p){Be("[Task] 状态已取消但未收到 task_stopped,补发本地事件"),vw("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(g){console.error("[Task] 处理补发 task_stopped 失败:",g)}}if(c.status==="succeeded"&&!h){Be("[Task] 状态已成功但未收到 task_complete,补发本地事件"),vw("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(g){console.error("[Task] 处理补发 task_complete 失败:",g)}}this.isTaskCompleted&&(Be("[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),xl("task-poll-failed",{requestId:n,taskId:e,from:t,elapsedMs:Date.now()-i,error:a,isTimeoutLike:c,pollingErrorCount:this.pollingErrorCount}),gw("[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:S("stores.pollingFluctuation"),message:S("stores.pollingUnstableRetry"),type:"warning",duration:5e3}))}finally{this.pollingInFlight=!1}},startPolling(s){if(this.isPolling){Cn("taskStore.startPolling_already_running",{taskId:this.currentTaskId,lastEventIndex:this.lastEventIndex}),gw("[DEBUG_NOTIFY][task] startPolling:already-running",{taskId:this.currentTaskId,lastEventIndex:this.lastEventIndex});return}if(!this.currentTaskId){Cn("taskStore.startPolling_no_task_id");return}Be("[Task] 启动轮询:",this.currentTaskId),Cn("taskStore.startPolling",{taskId:this.currentTaskId,lastEventIndex:this.lastEventIndex,hasHandler:!!(s||window.__taskEventHandler)}),gw("[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] 没有事件处理器,无法启动轮询"),xl("task-poll-start-failed-no-handler",{taskId:this.currentTaskId}),this.isPolling=!1;return}xl("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){Cn("taskStore.resumeTask_no_task_id");return}Cn("taskStore.resumeTask",{incomingTaskId:s,currentTaskId:this.currentTaskId,isPolling:this.isPolling,resetOffset:(e==null?void 0:e.resetOffset)!==!1}),gw("[DEBUG_NOTIFY][task] resumeTask",{incomingTaskId:s,currentTaskId:this.currentTaskId,options:e}),RP("[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&&Cn("taskStore.resumeTask_resetOffset_skipped",{taskId:s,reason:"same-task-polling-active",lastEventIndex:this.lastEventIndex}),this.pollingError=null,this.runtimeQueueSnapshotKey="",this.startPolling(e.eventHandler),Cn("taskStore.resumeTask_started",{taskId:s,isPolling:this.isPolling,lastEventIndex:this.lastEventIndex})},stopPolling(s="manual"){xl("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="",Cn("taskStore.stopPolling",{reason:s,taskStatus:this.taskStatus,currentTaskId:this.currentTaskId}),this.currentTaskId=null},async cancelTask(){if(this.currentTaskId)try{Be("[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(S("stores.cancelTaskFailed"));const e=await s.json();if(!e.success)throw new Error(e.error||S("stores.cancelTaskFailed"));Be("[Task] 已发送取消请求,等待后端停止确认")}catch(s){throw console.error("[Task] 取消任务失败:",s),s}},async loadRunningTask(s=null){try{Be("[Task] 查找运行中的任务"),Cn("taskStore.loadRunningTask_start",{conversationId:s});const e=await fetch("/api/tasks");if(!e.ok)throw new Error(S("stores.fetchTaskListFailed"));const t=await e.json();if(!t.success)throw new Error(t.error||S("stores.fetchTaskListFailed"));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){Be("[Task] 发现运行中的任务:",i.task_id),Cn("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,Be("[Task] 设置起始偏移量:",this.lastEventIndex)):this.lastEventIndex=0}else this.lastEventIndex=0}catch(r){console.warn("[Task] 获取任务详情失败,从头开始:",r),this.lastEventIndex=0}return i}return Be("[Task] 没有运行中的任务"),Cn("taskStore.loadRunningTask_not_found",{conversationId:s}),null}catch(e){return console.error("[Task] 加载运行中任务失败:",e),Cn("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=""}}}),io=Object.freeze(Object.defineProperty({__proto__:null,useTaskStore:FM},Symbol.toStringTag,{value:"Module"})),Noe={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(){var i;const s=this.currentConversationId;if(!s)return;let e=null;try{const r=(this.versioningHostMode||this.dockerProjectMode)&&this.currentHostWorkspaceId?`?workspace_id=${encodeURIComponent(this.currentHostWorkspaceId)}`:"",o=await fetch(`/api/conversations/${encodeURIComponent(s)}/running-status${r}`);if(!o.ok)return;const a=await o.json().catch(()=>({}));if(!(a!=null&&a.success)||!(a!=null&&a.data))return;e=a.data}catch{return}if(this.currentConversationId!==s)return;const t=FM();if(e.is_truly_active){this._runningStateIdleStreak=0;const r=!!e.main_task_id&&t.currentTaskId===e.main_task_id&&t.isPolling;e.is_main_running&&e.main_task_id&&!r?(UB("[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:o=>this.handleTaskEvent(o)}),this.taskInProgress=!0):e.is_main_running&&r&&(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,Be("[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,this.apiRequestPending=!1,(i=this.chatClearStreamingResidualState)==null||i.call(this),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()}},$oe={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(My("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||S("appTasks.thinkingLabel")));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),qn("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),qn("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()},handleStreamReset(s){var r,o,a,c;const e=Number(s==null?void 0:s.attempt)||0,t=Number(s==null?void 0:s.max_attempts)||0,n=e&&t?S("appTasks.streamRetrying",{attempt:e,max:t}):S("appTasks.streamRetryingGeneric"),i=((r=this.chatResetStreamingAttemptActions)==null?void 0:r.call(this,n))||[];for(const l of i)l!=null&&l.id&&((o=this.preparingTools)==null||o.delete(l.id)),(l==null?void 0:l.type)==="tool"&&((a=this.toolUnregisterAction)==null||a.call(this,l));(c=this.chatClearThinkingLocks)==null||c.call(this),this.monitorEndModelOutput(),this.$forceUpdate()}},Boe={handleToolPreparing(s){var i;if(Be("[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("appTasks.preparingTool",{name: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(Be("[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(Be("[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(),Be("[TaskPolling] 已更新工具意图:",s.name)}else Be("[TaskPolling] 未找到对应的工具 action:",s.id)},handleToolUpdateAction(s){var t,n;if(this.dropToolEvents)return;Be("[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 St(async()=>{const{usePersonalizationStore:a}=await Promise.resolve().then(()=>n3);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"&&Js().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),this.pendingPlanApprovals.length||(this.planApprovalMinimized=!1),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=S("appTasks.answerNeededTitle",{dot:i}),this.userQuestionTitleBlinkRed=!this.userQuestionTitleBlinkRed};n(),this.userQuestionTitleBlinkTimer=setInterval(n,900)}if(typeof window>"u"||!("Notification"in window))return;const e=S("appTasks.questionConfirmTitle"),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"?S("appTasks.approvalApproved"):S("appTasks.approvalRejected");this.autoApprovalFinalMessage=S("appTasks.approvalFinalMessage",{decision:i,reason:n||S("appTasks.reasonNotProvided")})}!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=S("appTasks.autoApprovalRecordTitle"),e.stage==="start"?(this.autoApprovalFeedLines=[S("appTasks.autoApprovalStarted")],this.autoApprovalFinalMessage=""):e.stage==="run_command"&&e.command&&this.autoApprovalFeedLines.push(String(e.command)),this.autoApprovalFeedLines=this.autoApprovalFeedLines.slice(-20),this.$forceUpdate())},handleAppendPayload(s){Be("[TaskPolling] 文件追加:",s.path),this.chatAddAppendPayloadAction(s),this.$forceUpdate(),this.conditionalScrollToBottom()},handleModifyPayload(s){Be("[TaskPolling] 文件修改:",s.path),this.chatAddModifyPayloadAction(s),this.$forceUpdate(),this.conditionalScrollToBottom()}},Foe={handleGoalProgress(s){var t;if(s!=null&&s.conversation_id&&this.currentConversationId&&s.conversation_id!==this.currentConversationId){Be("[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=S("appTasks.goalReviewTitle"),e.stage==="start"?(this.autoApprovalFeedLines=[S("appTasks.reviewStarted")],this.autoApprovalFinalMessage=""):e.stage==="model_call"?this.autoApprovalFeedLines.push(String(e.message||S("appTasks.reviewRound",{n: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!==S("appTasks.goalReviewTitle")||(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){Be("[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){Be("[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)}},Hoe={handleWorkflowProgress(s){s!=null&&s.conversation_id&&this.currentConversationId&&s.conversation_id!==this.currentConversationId||yg().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=S("appTasks.workflowReviewTitle"),e.stage==="start"?(this.autoApprovalFeedLines=[S("appTasks.reviewStarted")],this.autoApprovalFinalMessage=""):e.stage==="model_call"?this.autoApprovalFeedLines.push(String(e.message||S("appTasks.reviewRound",{n: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())}},Uoe={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 d=Date.now()-o;if(l>=i||d>=n)return;const h=Number(r[Math.min(l,r.length-1)]||1e3),p=Math.min(h,Math.max(0,n-d));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}}},Woe={handleTaskEvent(s){var d,h,p,g,v,m;if(!s||!s.type)return;const e=s.type,t=s.data||{},n=s.idx,i=FM();(e==="task_complete"||e==="task_stopped"||e==="error")&&Ml("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))&&WB("[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)&&qn("event:drop-conversation-mismatch",{eventType:e,eventIdx:n,eventConversationId:t.conversation_id,currentConversationId:this.currentConversationId}),Be(`[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)){qn("event:drop-task-mismatch",{eventType:e,eventIdx:n,eventTaskId:t.task_id,currentTaskId:i.currentTaskId,eventConversationId:t.conversation_id,currentConversationId:this.currentConversationId}),Be(`[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)&&qn("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==="api_request_start"?this.apiRequestPending=!0:(e==="thinking_start"||e==="text_start"||e==="tool_preparing"||e==="task_complete"||e==="task_stopped"||e==="error")&&(this.apiRequestPending=!1),e){case"api_request_start":break;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"stream_reset":this.handleStreamReset(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":(d=this.handleGoalProgress)==null||d.call(this,t,n);break;case"goal_review_progress":(h=this.handleGoalReviewProgress)==null||h.call(this,t,n);break;case"goal_completed":(p=this.handleGoalCompleted)==null||p.call(this,t,n);break;case"goal_stopped":(g=this.handleGoalStopped)==null||g.call(this,t,n);break;case"workflow_progress":(v=this.handleWorkflowProgress)==null||v.call(this,t,n);break;case"workflow_review_progress":(m=this.handleWorkflowReviewProgress)==null||m.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":oo().setEditedFiles(Array.isArray(t==null?void 0:t.edited_files)?t.edited_files:[],!0);break;case"edit_summary_updated":if(this._rebuildingFromScratch)break;TE().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,d,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(p=>String(p||"").trim()).filter(p=>p.length>0):[];if(t.length>0){const p=Math.max(1,Number(this.runtimeQueueLimit||5)),g=[...this.runtimeGuidanceFallbackQueue||[],...t].map(m=>String(m||"").trim()).filter(m=>m.length>0).slice(0,p),v=Math.max(0,p-g.length);Array.isArray(this.runtimeQueuedMessages)&&this.runtimeQueuedMessages.length>v&&(this.runtimeQueuedMessages=this.runtimeQueuedMessages.slice(0,v)),this.runtimeGuidanceFallbackQueue=g}Ml("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);if(Array.isArray(s==null?void 0:s.citations)&&Array.isArray(this.messages)&&this.messages.length){const p=this.messages[this.messages.length-1];p&&p.role==="assistant"&&(p.metadata={...p.metadata||{},citations:s.citations})}this.streamingMessage=!1,this.stopRequested=!1,(l=this.chatClearStreamingResidualState)==null||l.call(this),this.apiRequestPending=!1,!n&&!r&&this.markLatestUserWorkCompleted(),r?(Ml("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)&&((u=this.acknowledgeCompletedWorkspaceTask)==null||u.call(this,s.task_id)),setTimeout(()=>{var p;return(p=this.refreshRunningWorkspaceTasks)==null?void 0:p.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;Ml("handleTaskComplete:after",{taskInProgress:this.taskInProgress,streamingMessage:this.streamingMessage,stopRequested:this.stopRequested,pendingToolsAfter:o,preparingToolsSize:((d=this.preparingTools)==null?void 0:d.size)??null,activeToolsSize:((h=this.activeTools)==null?void 0:h.size)??null,waitingForSubAgent:this.waitingForSubAgent,waitingForBackgroundCommand:this.waitingForBackgroundCommand})},handleTaskStopped(s,e){var r;Cn("handleTaskStopped:entered",{eventIdx:e,data:s}),Ml("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;Cn("handleTaskStopped",{taskInProgress:this.taskInProgress,streamingMessage:this.streamingMessage,hasRunningSubAgents:t,hasRunningBackgroundCommands:n,data:s}),this.cleanupTrailingEmptyAssistantPlaceholder("task_stopped"),(r=this.chatClearStreamingResidualState)==null||r.call(this),this.apiRequestPending=!1,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")})),Cn("handleTaskStopped:after",{taskInProgress:this.taskInProgress,waitingForSubAgent:this.waitingForSubAgent,waitingForBackgroundCommand:this.waitingForBackgroundCommand,hasRunningBackground:i}),this.scheduleTodoListRefresh(100),setTimeout(()=>{var o;return(o=this.refreshRunningWorkspaceTasks)==null?void 0:o.call(this)},0),this.$forceUpdate(),Ml("handleTaskStopped:after",{taskInProgress:this.taskInProgress,streamingMessage:this.streamingMessage,stopRequested:this.stopRequested})},clearTaskState(){this.stopWaitingTaskProbe(),(async()=>{const{useTaskStore:s}=await St(async()=>{const{useTaskStore:t}=await Promise.resolve().then(()=>io);return{useTaskStore:t}},void 0);s().clearTask()})(),typeof this.clearProcessedEvents=="function"&&this.clearProcessedEvents()},handleTaskError(s){var a,c;if(Ml("handleTaskError:incoming",{data:s,taskInProgress:this.taskInProgress,streamingMessage:this.streamingMessage,stopRequested:this.stopRequested}),!!(s!=null&&s.retry)){const l=Number(s==null?void 0:s.retry_in)||5,u=Number(s==null?void 0:s.attempt)||1,d=Number(s==null?void 0:s.max_attempts)||u;Be("[TaskPolling] API错误,等待自动重试",{retryIn:l,attempt:u,maxAttempts:d,message:s==null?void 0:s.message}),this.stopRequested=!1,this.taskInProgress=!0,this.streamingMessage=!0,this.$forceUpdate(),this.uiPushToast({title:S("appTasks.retrySoonTitle"),message:S("appTasks.retryInSeconds",{n:l,attempt:u,max:d,error:(s==null?void 0:s.message)||S("common.unknownError")}),type:"info",duration:Math.max(l,1)*1e3});return}const t=s.message||S("common.unknownError"),n=s.error_type||"unknown";if(n==="parameter_format_error"||/(?:\u5de5\u5177\u53c2\u6570\u89e3\u6790\u5931\u8d25|Failed to parse tool arguments)/.test(String(t||""))){console.warn("[TaskPolling] 工具参数解析失败(非致命),继续轮询任务:",s),Ml("handleTaskError:tool-args-parse-error-ignored",{errorType:n,errorMessage:t,taskInProgress:this.taskInProgress,streamingMessage:this.streamingMessage,stopRequested:this.stopRequested}),this.uiPushToast({title:S("appTasks.toolCallFailed"),message:t,type:"warning",duration:6e3}),this.stopRequested=!1,this.$forceUpdate();return}let r=S("appTasks.taskFailedTitle"),o=t;n==="api_error"?(r=S("appTasks.apiErrorTitle"),o=S("appTasks.apiErrorMessage",{error:t})):n==="timeout"?(r=S("appTasks.timeoutTitle"),o=S("appTasks.timeoutMessage")):n==="quota_exceeded"&&(r=S("appTasks.quotaTitle"),o=S("appTasks.quotaMessage")),console.error("[TaskPolling] 任务错误:",s.message),this.uiPushToast({title:r,message:o,type:"error",duration:8e3}),(a=this.cleanupTrailingEmptyAssistantPlaceholder)==null||a.call(this,"task_error"),(c=this.chatClearStreamingResidualState)==null||c.call(this),typeof this.clearPendingTools=="function"&&this.clearPendingTools("task_error"),this.apiRequestPending=!1,this.markLatestUserWorkCompleted(),this.streamingMessage=!1,this.taskInProgress=!1,this.stopRequested=!1,this.$forceUpdate(),Ml("handleTaskError:fatal-after-state-update",{errorType:n,errorMessage:t,taskInProgress:this.taskInProgress,streamingMessage:this.streamingMessage,stopRequested:this.stopRequested}),(async()=>{const{useTaskStore:l}=await St(async()=>{const{useTaskStore:d}=await Promise.resolve().then(()=>io);return{useTaskStore:d}},void 0);l().stopPolling()})(),this.$nextTick(()=>{typeof this.tryAutoSendRuntimeQueuedMessages=="function"&&this.tryAutoSendRuntimeQueuedMessages("task_error")})}},zoe={handleUserMessage(s){var l;const e=((s==null?void 0:s.message)||(s==null?void 0:s.content)||"").trim();if(!e)return;UB("[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}),WB("[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=Moe(s),n=xoe(s),i=Roe(s),r=Ioe(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))Be("[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),d=xP(this.messages||[],e,o,a,i);if(d){d.media_refs=c,d.metadata={...d.metadata||{},...r,media_refs:c,message_source:i};const h=(s==null?void 0:s.timestamp)??(s==null?void 0:s.created_at)??(s==null?void 0:s.createdAt)??null;h&&(d.created_at=h)}else this.chatAddUserMessage(e,o,a,c,i,r);u&&(this.chatStartAssistantMessage(),this.taskInProgress=!0,this.streamingMessage=!0,this.stopRequested=!1)}else{const u=Poe(this.messages||[]),d=xP(this.messages||[],e,o,a,i),h=!!(u&&u.role==="user"&&String(u.content||"").trim()===e&&JSON.stringify(u.images||[])===JSON.stringify(o||[])&&JSON.stringify(u.videos||[])===JSON.stringify(a||[]));if(h||d){const p=h?u:d;p.media_refs=c,p.metadata={...p.metadata||{},...r,media_refs:c};const g=(s==null?void 0:s.timestamp)??(s==null?void 0:s.created_at)??(s==null?void 0:s.createdAt)??null;g&&(p.created_at=g)}else this.chatAddUserMessage(e,o,a,c,i,r);this.taskInProgress=!0,this.streamingMessage=!!O0((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();My("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),My("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))||[]}))}},joe={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){Be("[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,this.currentConversationTokens.cumulative_cached_input_tokens=s.cumulative_cached_input_tokens||0,this.currentConversationTokens.cache_exempt_input_tokens=s.cache_exempt_input_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,Be("[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,Be("[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)}}},Voe={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"?S("appTasks.compressionManual"):S("appTasks.compressionAuto");this.compressionToastId&&(this.uiDismissToast(this.compressionToastId),this.compressionToastId=null),this.compressionToastId=this.uiPushToast({title:S("appTasks.compressing"),message:S("appTasks.compressingMessage",{mode: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:S("appTasks.shallowCompressionTitle"),message:S("appTasks.shallowCompressedMessage",{n: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:S("appTasks.compressionComplete"),message:S("appTasks.compressedEarlierContent"),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(),qn("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)){qn("restore:skip-explicit-new-route",{path:typeof window<"u"?window.location.pathname:""}),this._restoreTaskStateWaitCount=0;return}try{const{useTaskStore:l}=await St(async()=>{const{useTaskStore:O}=await Promise.resolve().then(()=>io);return{useTaskStore:O}},void 0),u=l();if(this.streamingMessage||this.taskInProgress){qn("restore:skip-already-running",{streamingMessage:this.streamingMessage,taskInProgress:this.taskInProgress,currentConversationId:this.currentConversationId}),Be("[TaskPolling] 任务已在进行中,跳过恢复",{streamingMessage:this.streamingMessage,taskInProgress:this.taskInProgress,currentConversationId:this.currentConversationId});return}let d;if(e&&e.task&&e.task.task_id?(d=e.task,u.currentTaskId=d.task_id,u.taskStatus=d.status,u.taskCreatedAt=d.created_at,u.taskUpdatedAt=d.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):d=await u.loadRunningTask(this.currentConversationId),!d){qn("restore:no-running-task",{currentConversationId:this.currentConversationId}),Be("[TaskPolling] 没有运行中的任务",{currentConversationId:this.currentConversationId}),this._restoreTaskStateWaitCount=0,await this.restoreSubAgentWaitingState();return}if((this.versioningHostMode||this.dockerProjectMode)&&this.currentHostWorkspaceId&&(d!=null&&d.workspace_id)&&d.workspace_id!==this.currentHostWorkspaceId){qn("restore:skip-workspace-mismatch",{taskId:d==null?void 0:d.task_id,taskWorkspaceId:d==null?void 0:d.workspace_id,currentHostWorkspaceId:this.currentHostWorkspaceId}),u.clearTask(),await this.restoreSubAgentWaitingState();return}if(Be("[TaskPolling] 发现运行中的任务,开始恢复状态",{taskId:d==null?void 0:d.task_id,status:d==null?void 0:d.status,conversationId:d==null?void 0:d.conversation_id}),d!=null&&d.goal_mode){const O=this.goalProgress&&typeof this.goalProgress=="object"?this.goalProgress:{},G=d!=null&&d.goal_progress&&typeof d.goal_progress=="object"?d.goal_progress:{};this.goalRunning=!0,this.goalModeArmed=!1,this.goalProgress={...O,...G,goal:(G==null?void 0:G.goal)||(O==null?void 0:O.goal)||(d==null?void 0:d.message)||"",status:"running",turn_count:Number((G==null?void 0:G.turn_count)??(O==null?void 0:O.turn_count)??0),tokens_used:Number((G==null?void 0:G.tokens_used)??(O==null?void 0:O.tokens_used)??0),tool_calls:Number((G==null?void 0:G.tool_calls)??(O==null?void 0:O.tool_calls)??0),duration_seconds:Number((G==null?void 0:G.duration_seconds)??(O==null?void 0:O.duration_seconds)??0)}}qn("restore:running-task-found",{taskId:d==null?void 0:d.task_id,status:d==null?void 0:d.status,taskConversationId:d==null?void 0:d.conversation_id,currentConversationId:this.currentConversationId});const h=Array.isArray(this.messages)&&this.messages.length>0,p=!!this.historyLoading&&this.historyLoadingFor===this.currentConversationId;if(!h&&!e){this._restoreTaskStateWaitCount=(this._restoreTaskStateWaitCount||0)+1;const O=this._restoreTaskStateWaitCount>=8;if(qn("restore:history-empty",{waitCount:this._restoreTaskStateWaitCount,waitedTooLong:O,historyLoading:this.historyLoading,historyLoadingFor:this.historyLoadingFor,currentConversationId:this.currentConversationId}),p&&!O){Be("[TaskPolling] 历史未加载,等待历史加载完成",{waitCount:this._restoreTaskStateWaitCount,historyLoading:this.historyLoading,historyLoadingFor:this.historyLoadingFor}),setTimeout(()=>{this.restoreTaskState()},500);return}Be("[TaskPolling] 历史为空,启用事件重放兜底恢复",{waitCount:this._restoreTaskStateWaitCount,historyLoading:this.historyLoading,historyLoadingFor:this.historyLoadingFor})}else this._restoreTaskStateWaitCount=0;Be("[TaskPolling] 开始精细恢复",{hasMessages:h,historyLoading:this.historyLoading,historyLoadingFor:this.historyLoadingFor});let g;if(e)g=Array.isArray(e.events)?e.events:[];else{const O=await fetch(`/api/tasks/${u.currentTaskId}`);if(!O.ok){Be("[TaskPolling] 获取任务详情失败");return}const G=await O.json();if(!G.success||!G.data.events){qn("restore:task-detail-invalid",{ok:!!(G!=null&&G.success),hasData:!!(G!=null&&G.data),hasEvents:!!((n=G==null?void 0:G.data)!=null&&n.events)}),Be("[TaskPolling] 任务详情无效");return}g=G.data.events}Be(`[TaskPolling] 获取到 ${g.length} 个事件`),qn("restore:task-detail-events",{total:g.length,firstIdx:(i=g[0])==null?void 0:i.idx,firstType:(r=g[0])==null?void 0:r.type,lastIdx:(o=g[g.length-1])==null?void 0:o.idx,lastType:(a=g[g.length-1])==null?void 0:a.type});const v=this.messages[this.messages.length-1],m=v&&v.role==="assistant",y=e&&e.decision_inputs||null;let _=!1,b=!1,k=!1,w=!1,T=!1;if(y)_=!!y.in_thinking,b=!!y.in_text,k=!!y.has_text_chunk_event,w=!!y.has_assistant_response_event,T=!!y.has_assistant_content_event;else for(let O=0;O<g.length;O++){const G=g[O],Z=String((G==null?void 0:G.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(Z)&&(w=!0),["thinking_chunk","text_chunk","tool_preparing","tool_start","tool_update","tool_complete"].includes(Z)&&(T=!0),G.type==="thinking_start"?_=!0:G.type==="thinking_end"&&(_=!1),G.type==="text_start"?b=!0:G.type==="text_end"&&(b=!1),G.type==="text_chunk"&&(k=!0)}const A=b||k||_,C=m&&Array.isArray(v.actions)&&v.actions.some(O=>{if(!O)return!1;if(O.streaming)return!0;if(O.type==="tool"&&O.tool){const G=String(O.tool.status||"").toLowerCase();if(["preparing","running","pending","queued"].includes(G))return!0}return!1}),E=!!(e&&e.needs_rebuild===!0),x=!!(y&&y.has_pending_tool_calls===!0),D=!m||m&&(!v.actions||v.actions.length===0)||A||C||E||x;if(qn("restore:rebuild-decision",{needsRebuild:D,isAssistantMessage:m,hasAssistantResponseEvent:w,hasAssistantContentEvent:T,inText:b,hasTextChunkEvent:k,inThinking:_,forceRebuildForStreamingText:A,hasInProgressActions:C,serverNeedsRebuild:E,serverHasPendingToolCalls:x}),D){Be("[TaskPolling] 需要从头重建 assistant 响应");const O=V=>{if(!V||V.role!=="user")return!1;const I=V.metadata||{};if(I.runtime_injected===!0)return!0;const $=String(I.message_source||"").trim().toLowerCase();return $==="compression"||$==="compression_handoff"};let G=this.messages.length-1;for(;G>=0;){const V=this.messages[G];if(V&&V.role==="assistant"){G-=1;continue}if(O(V)){G-=1;continue}break}let Z=null,q=-1;for(let V=Math.max(G+1,0);V<this.messages.length;V+=1)if(this.messages[V]&&this.messages[V].role==="assistant"){Z=this.messages[V],q=V;break}Z&&(Be("[TaskPolling] 复用现有 assistant 消息容器,清空 actions 等待事件重建",{hasAssistantContentEvent:T,rebuildContainerIdx:q,removedAfterContainer:this.messages.length-1-q}),q<this.messages.length-1&&this.messages.splice(q+1),Z.actions=[],Z.awaitingFirstContent=!T,Z.generatingLabel=Z.generatingLabel||S("appTasks.thinkingLabel"),typeof Z.streaming=="boolean"&&(Z.streaming=!0),this.currentMessageIndex=q),this.streamingMessage=!0,this.taskInProgress=!0,!T&&!Z&&((c=this.ensureRunningAssistantPlaceholder)==null||c.call(this,d,"restore:no-visible-content-yet")),this.$forceUpdate(),u.lastEventIndex=0,Be("[TaskPolling] 重置偏移量为 0,从头开始轮询"),this._rebuildingFromScratch=!0,this._rebuildingEventCount=g.length,window.__taskEventHandler=V=>{this.handleTaskEvent(V)},u.startPolling(V=>{this.handleTaskEvent(V)}),qn("restore:rebuild-polling-started",{lastEventIndex:u.lastEventIndex,currentConversationId:this.currentConversationId}),setTimeout(()=>{Be("[TaskPolling] 历史事件处理完毕,清除重建标记"),this._rebuildingFromScratch=!1,this._rebuildingEventCount=0},2e3);return}if(v.actions){const O=v.actions.filter(q=>q.type==="thinking");if(_&&O.length>0){const q=O[O.length-1];q.streaming&&q.blockId&&this.$nextTick(()=>{this.chatSetThinkingLock(q.blockId,!0)})}for(const q of O)q.blockId&&(q.collapsed=!0);const G=v.actions.filter(q=>q.type==="text");if(b&&G.length>0){const q=G[G.length-1];q.streaming=!0}const Z=v.actions.filter(q=>q.type==="tool");for(const q of Z)q.tool&&q.tool.id&&(this.toolRegisterAction(q,q.tool.id),q.tool.executionId&&this.toolRegisterAction(q,q.tool.executionId),q.tool.name&&this.toolTrackAction(q.tool.name,q))}this.streamingMessage=!0,this.taskInProgress=!0;const N=this.messages.length-1;v&&v.role==="assistant"&&(this.currentMessageIndex=N),this.$forceUpdate(),this.$nextTick(()=>{this.conditionalScrollToBottom()}),window.__taskEventHandler=O=>{this.handleTaskEvent(O)},Be("[TaskPolling] 启动轮询,起始偏移量:",u.lastEventIndex),u.startPolling(O=>{this.handleTaskEvent(O)}),qn("restore:polling-started-follow",{lastEventIndex:u.lastEventIndex,currentConversationId:this.currentConversationId}),this.uiPushToast({title:S("appTasks.taskRestoredTitle"),message:S("appTasks.taskRestoredMessage"),type:"info",duration:3e3})}catch(l){qn("restore:error",{message:(l==null?void 0:l.message)||String(l)}),console.error("[TaskPolling] 恢复任务状态失败:",l)}}},Goe={...Loe,...Noe,...$oe,...Boe,...Foe,...Hoe,...Uoe,...Woe,...zoe,...joe,...Voe},Koe={async handleEasterEggPayload(s){await lv().handlePayload(s,this)},async startEasterEggEffect(s,e={}){await lv().startEffect(s,e,this)},destroyEasterEggEffect(s=!1){return lv().destroyEffect(s)},finishEasterEggCleanup(){lv().finishCleanup()}},qoe=s=>String(s||"").toLowerCase()==="conversation_only"?"conversation_only":"workspace_and_conversation",Qoe={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)||S("appMessages.versioningFetchStatusFailed"));return null}const o=r.data||{};return this.versioningHostMode=!!o.host_mode,M1(!!o.host_mode),this.versioningEnabled=!!o.enabled,this.versioningMode="overwrite",this.versioningRestoreMode="overwrite",o}catch(i){return n||this.uiPushToast({title:S("common.versioning"),message:(i==null?void 0:i.message)||S("appMessages.versioningFetchStatusFailed"),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)||S("appMessages.versioningLoadCheckpointsFailed"));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:S("common.versioning"),message:(n==null?void 0:n.message)||S("appMessages.versioningLoadCheckpointsFailed"),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:S("common.versioning"),message:s?S("appMessages.versioningEnabledForNext"):S("appMessages.versioningDisabledForNext"),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)||S("appMessages.versioningToggleFailed"));this.versioningEnabled=!!((e=n==null?void 0:n.data)!=null&&e.enabled),this.versioningMode="overwrite",this.versioningRestoreMode="overwrite",this.uiPushToast({title:S("common.versioning"),message:this.versioningEnabled?S("appMessages.versioningOn"):S("appMessages.versioningOff"),type:"success"}),this.versioningEnabled?await this.fetchVersioningCheckpoints(this.currentConversationId):(this.versioningCheckpoints=[],this.versioningSelectedSeq=null,this.versioningSelectedDetail=null)}catch(t){this.uiPushToast({title:S("common.versioning"),message:(t==null?void 0:t.message)||S("appMessages.versioningSwitchFailed"),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(`${S("appMessages.versioningDetailParseFailed")}: ${(r==null?void 0:r.message)||S("common.unknownError")}`)}if(!t.ok||!(i!=null&&i.success))throw new Error((i==null?void 0:i.error)||S("appMessages.versioningLoadDetailFailed"));this.versioningSelectedDetail=i.data||null}catch(t){console.error("[VersioningDetail] error:",t),this.uiPushToast({title:S("common.versioning"),message:(t==null?void 0:t.message)||S("appMessages.versioningLoadDetailFailed"),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=qoe(this.versioningTrackingMode),t=e==="conversation_only"?S("appMessages.versioningScopeConversationOnly"):S("appMessages.versioningScopeConversationAndWorkspace"),n=s==="copy"?S("appMessages.versioningModeCopy"):S("appMessages.versioningModeOverwrite");if(await this.confirmAction({title:S("appMessages.versioningRestoreConfirmTitle"),message:S("appMessages.versioningRestoreConfirmMessage",{scope:t,mode:n,seq:this.versioningSelectedSeq}),confirmText:S("appMessages.versioningRestoreConfirmText"),cancelText:S("common.cancel")})){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)||S("appMessages.versioningRestoreFailed"));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:S("appMessages.versioningRestoreConversationTitle"),updated_at:new Date().toISOString(),total_messages:0,total_tools:0},...this.conversations.filter(l=>l&&l.id!==c)),this.uiPushToast({title:S("common.versioning"),message:s==="copy"?S("appMessages.versioningRestoreCopyDone"):S("appMessages.versioningRestoreDone"),type:"success"})}catch(o){this.uiPushToast({title:S("common.versioning"),message:(o==null?void 0:o.message)||S("appMessages.versioningRestoreFailed"),type:"error"})}finally{this.versioningRestoring=!1}}}},zB={data:Fee,created:Nie,mounted:$ie,beforeUnmount:Bie,computed:jee,watch:Gee,methods:{...zie,...Jie,...are,...ire,...mre,...Cre,...zre,...Toe,...Qoe,...Koe,...Goe,...Pr(Is,{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"}),...Pr(er,{modelSet:"setModel"}),...Pr(TE,{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",chatClearStreamingResidualState:"clearStreamingResidualState",chatResetStreamingAttemptActions:"resetStreamingAttemptActions"}),...Pr(lk,{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"}),...Pr(eL,{toolRegisterAction:"registerToolAction",toolUnregisterAction:"unregisterToolAction",toolFindAction:"findToolAction",toolTrackAction:"trackToolAction",toolReleaseAction:"releaseToolAction",toolGetLatestAction:"getLatestActiveToolAction",toolResetTracking:"resetToolTracking",toolSetSettings:"setToolSettings",toolSetSettingsLoading:"setToolSettingsLoading"}),...Pr(tL,{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"}),...Pr(rL,{uploadHandleSelected:"handleSelectedFiles",uploadBatchFiles:"uploadFiles"}),...Pr(Pc,{fileFetchTree:"fetchFileTree",fileSetTreeFromResponse:"setFileTreeFromResponse",fileFetchTodoList:"fetchTodoList",fileSetTodoList:"setTodoList",fileHideContextMenu:"hideContextMenu",fileMarkTreeUnavailable:"markFileTreeUnavailable"}),...Pr(pL,{monitorSyncDesktop:"syncDesktopFromTree",monitorResetVisual:"resetVisualState",monitorResetSpeech:"resetSpeechBuffer",monitorShowSpeech:"enqueueModelSpeech",monitorShowThinking:"enqueueModelThinking",monitorEndModelOutput:"endModelOutput",monitorShowPendingReply:"showPendingReply",monitorPreviewTool:"previewToolIntent",monitorQueueTool:"enqueueToolEvent",monitorResolveTool:"resolveToolResult",forceUnlockMonitor:"resetVisualState"}),...Pr(dd,{subAgentFetch:"fetchSubAgents"}),...Pr(vg,{backgroundCommandFetch:"fetchCommands"}),...Pr(oL,{focusFetchFiles:"fetchFocusedFiles",focusSetFiles:"setFocusedFiles"}),...Pr(Js,{personalizationOpenDrawer:"openDrawer",personalizationFetch:"fetchPersonalization"})}};zB.components=Dee;const Xoe={class:"image-picker-panel"},Yoe={class:"header"},Joe={class:"header-left"},Zoe={class:"title"},eae=["disabled"],tae={class:"body"},sae={key:0,class:"loading"},nae={key:1,class:"empty"},iae={key:2,class:"grid"},rae=["onClick","title"],oae={class:"video-thumb"},aae={class:"ext"},lae={class:"name"},cae={class:"footer"},uae={class:"count"},dae={class:"actions"},hae=["disabled"],fae=ct({__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=ge(new Set(t.initialSelected||[])),r=ge(null);let o=0;Ke(()=>t.initialSelected,g=>{i.value=new Set(g||[])});const a=be(()=>t.entries||[]),c=g=>{if(!g)return;const v=new Set(i.value);v.has(g)?v.delete(g):(v.clear(),v.add(g)),i.value=v},l=()=>{Date.now()<o||n("close")},u=()=>n("confirm",Array.from(i.value)),d=()=>{var g;t.uploading||(o=Date.now()+1500,(g=r.value)==null||g.click())},h=g=>{const v=g.target,m=v==null?void 0:v.files,y=m&&m.length?Array.from(m):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=g=>{var v;return!g||!g.includes(".")?"":(v=g.split(".").pop())==null?void 0:v.toLowerCase()};return dn(()=>{i.value=new Set(t.initialSelected||[])}),(g,v)=>(F(),Ft(gs,{name:"overlay-fade"},{default:Gt(()=>[s.open?(F(),U("div",{key:0,class:"image-picker-backdrop",onClick:De(l,["self"])},[M("div",Xoe,[M("div",Yoe,[M("div",Joe,[M("div",Zoe,Q(g.$t("overlay.videoPickerTitle")),1),M("button",{type:"button",class:"local-btn",disabled:s.uploading,onClick:d},Q(s.uploading?g.$t("overlay.uploading"):g.$t("overlay.sendFromLocal")),9,eae),M("input",{ref_key:"localInput",ref:r,type:"file",class:"file-input-hidden",accept:"video/*",onChange:h},null,544)]),We(ml,{label:g.$t("common.close"),onClick:l},null,8,["label"])]),M("div",tae,[s.loading?(F(),U("div",sae,Q(g.$t("common.loading")),1)):a.value.length?(F(),U("div",iae,[(F(!0),U(Ie,null,Ze(a.value,m=>(F(),U("div",{key:m.path,class:Ce(["card",{selected:i.value.has(m.path)}]),onClick:y=>c(m.path),title:m.path},[M("div",oae,[v[0]||(v[0]=M("span",{class:"icon icon-sm"},"🎞️",-1)),M("span",aae,Q(p(m.name)),1)]),M("div",lae,Q(m.name),1)],10,rae))),128))])):(F(),U("div",nae,Q(g.$t("overlay.noVideos")),1))]),M("div",cae,[M("div",uae,Q(g.$t("overlay.videoSelectedCount",{n:i.value.size})),1),M("div",dae,[M("button",{type:"button",class:"btn secondary",onClick:l},Q(g.$t("common.cancel")),1),M("button",{type:"button",class:"btn primary",disabled:!i.value.size,onClick:u},Q(g.$t("common.confirm")),9,hae)])])])])):me("",!0)]),_:1}))}}),pae=qt(fae,[["__scopeId","data-v-aaf97637"]]),mae=["aria-label"],gae=["src","alt"],vae={key:0,class:"image-lightbox__caption"},yae=ct({__name:"ImageLightbox",setup(s){const e=Is(),t=be(()=>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 Ke(t,o=>r(!!o),{immediate:!0}),Rn(()=>r(!1)),(o,a)=>(F(),Ft(Tf,{to:"body"},[We(gs,{name:"lightbox-fade"},{default:Gt(()=>[t.value?(F(),U("div",{key:0,class:"image-lightbox",role:"dialog","aria-modal":"true","aria-label":t.value.name||o.$t("overlay.imagePreview"),onClick:De(n,["self"])},[We(ml,{variant:"bare",class:"image-lightbox__close",label:o.$t("overlay.closePreview"),onClick:n},null,8,["label"]),M("div",{class:"image-lightbox__stage",onClick:De(n,["self"])},[M("img",{class:"image-lightbox__img",src:t.value.url,alt:t.value.name||o.$t("overlay.imagePreview"),draggable:"false"},null,8,gae),t.value.name?(F(),U("div",vae,Q(t.value.name),1)):me("",!0)])],8,mae)):me("",!0)]),_:1})]))}}),bae=qt(yae,[["__scopeId","data-v-ebc698c5"]]),_ae={class:"qd-window__header"},wae={class:"qd-window__title"},Sae={class:"qd-window__counter"},kae={class:"qd-todo-text"},PP=60,LP=45,Cae=260,Tae=ct({__name:"TodoWindow",setup(s){const e=Pc(),t=be(()=>e.todoList),n=ge([]),i=ge(!1),r=ge(!1),o=ge(!1),a=ge(null);let c=0;const l=be(()=>n.value.filter(b=>b.done).length),u=b=>new Promise(k=>setTimeout(k,b));function d(b){return Array.isArray(b==null?void 0:b.tasks)?b.tasks:[]}function h(b){return b.map(k=>`${k.index}:${k.title}`).join("|")}function p(b){return b==="done"||b==="completed"}function g(b){if(b.entering&&b.enterDelay)return{animationDelay:`${b.enterDelay}ms`};if(b.leaving&&b.leaveDelay)return{animationDelay:`${b.leaveDelay}ms`}}async function v(){const b=n.value;b.length&&(b.forEach((k,w)=>{k.leaveDelay=w*LP,k.leaving=!0}),await u(b.length*LP+Cae+20))}function m(b,k=0){n.value=b.map((A,C)=>({key:`${A.index}:${A.title}`,title:A.title,done:p(A.status),entering:!0,leaving:!1,justDone:!1,enterDelay:k+C*PP,leaveDelay:0}));const w=k+b.length*PP+340+30,T=c;setTimeout(()=>{T===c&&n.value.forEach(A=>{A.entering=!1,A.enterDelay=0})},w)}function y(b){return new Promise(k=>{ft(()=>{const w=a.value,T=w==null?void 0:w.children[b];if(!w||!T){k();return}const A=w.getBoundingClientRect(),C=T.getBoundingClientRect();if(C.top>=A.top&&C.bottom<=A.bottom){k();return}let x=!1,D;const N=()=>{x||(x=!0,D&&clearTimeout(D),w.removeEventListener("scroll",O),k())},O=()=>{D&&clearTimeout(D),D=setTimeout(N,90)};w.addEventListener("scroll",O),T.scrollIntoView({behavior:"smooth",block:"nearest"}),D=setTimeout(N,800)})})}function _(b){n.value=b.map(k=>({key:`${k.index}:${k.title}`,title:k.title,done:p(k.status),entering:!1,leaving:!1,justDone:!1,enterDelay:0,leaveDelay:0}))}return Ke(t,async(b,k)=>{const w=++c,T=d(b),A=d(k),C=e.todoListLive;if(!T.length){if(n.value.length&&C){if(o.value=!0,await v(),w!==c)return;o.value=!1}n.value=[],i.value=!1;return}if(!n.value.length){i.value=!0,C?(r.value=!0,setTimeout(()=>{r.value=!1},320),m(T,300)):_(T);return}if(h(A)===h(T)){if(!C){T.forEach((E,x)=>{const D=n.value[x];D&&(D.done=p(E.status))});return}for(let E=0;E<T.length;E+=1){const x=n.value[E];if(!x)continue;const D=p(T[E].status);if(x.done!==D){for(;o.value;)if(await u(50),w!==c)return;if(D&&(await y(E),w!==c))return;if(x.done=D,D){x.justDone=!0;const N=x;setTimeout(()=>{N.justDone=!1},400)}}}return}if(!C){_(T);return}o.value=!0,await v(),w===c&&(m(T),o.value=!1)},{flush:"sync",immediate:!0}),(b,k)=>i.value?(F(),U("section",{key:0,class:Ce(["qd-window",{"qd-window-enter":r.value}])},[M("header",_ae,[k[0]||(k[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>',1)),M("span",wae,Q(b.$t("quickdock.todoWindowTitle")),1),M("span",Sae,Q(l.value)+"/"+Q(n.value.length),1)]),M("ul",{ref_key:"listRef",ref:a,class:"qd-list"},[(F(!0),U(Ie,null,Ze(n.value,w=>(F(),U("li",{key:w.key,class:Ce(["qd-todo-item",{"is-done":w.done,"just-done":w.justDone,"qd-row-enter":w.entering,"qd-row-leave":w.leaving}]),style:qe(g(w))},[k[1]||(k[1]=M("span",{class:"qd-todo-dot"},null,-1)),M("span",kae,Q(w.title),1)],6))),128))],512)],2)):me("",!0)}}),Aae={class:"qd-window__header"},Eae={class:"qd-window__title"},Mae={ref:"listRef",class:"wf-list"},xae={class:"wf-row__name"},Rae={key:0,class:"wf-row__meta"},Iae={key:1,class:"wf-row__meta"},Pae={class:"wf-footnote__text"},Lae=420,Oae=660,Dae=240,Nae=240,$ae=1600,Bae=ct({__name:"WorkflowWindow",setup(s){const e=yg(),{snapshot:t}=xi(e),n=ge([]),i=ge(!1),r=ge(!1),o=ge(!1),a=ge(null),c=ge(!1),l=ge(null);let u=0,d=0;const h=C=>new Promise(E=>setTimeout(E,C));function p(C){return{"is-done":C.kind==="done","is-current":C.kind==="current","is-next":C.kind==="next","is-just-done":C.justDone,"is-reviving":C.reviving,"is-leaving":C.leaving,"is-entering":C.entering,"is-reject-flash":C.rejectFlash,"is-reviewing":C.reviewing}}function g(C,E,x){return d+=1,{key:`${E}-${C}-${d}`,name:C,kind:E,rounds:x,reviewing:!1,justDone:!1,reviving:!1,leaving:!1,entering:!1,rejectFlash:!1}}function v(C){const E=C.history.map(x=>g(x.name,"done",x.rounds));if(C.current){const x=g(C.current.name,"current",C.current.rounds);x.reviewing=C.reviewing,E.push(x),C.next&&E.push(g(C.next,"next",null))}else C.status==="completed"&&E.push(g(S("quickdock.workflowEndRow"),"done",null));return E}function m(C){return ft(()=>{const E=l.value;if(!E)return;const x=E.scrollHeight;if(!C){E.scrollTop=x;return}return y(E,x,Lae)})}function y(C,E,x){return new Promise(D=>{const N=C.scrollTop,O=E-N;if(Math.abs(O)<1){C.scrollTop=E,D();return}const G=performance.now(),Z=q=>{const V=Math.min(1,(q-G)/x),I=1-Math.pow(1-V,3);C.scrollTop=N+O*I,V<1?requestAnimationFrame(Z):D()};requestAnimationFrame(Z)})}function _(C){n.value=v(C),m(!1)}function b(C,E){var N,O,G;const x=C.history.map(Z=>Z.name),D=E.history.map(Z=>Z.name);return D.length===x.length+1&&D[D.length-1]===((N=C.current)==null?void 0:N.name)?"advance":D.length<x.length&&x.slice(0,D.length).every((Z,q)=>Z===D[q])?"reject":D.join("|")===x.join("|")&&((O=E.current)==null?void 0:O.name)===((G=C.current)==null?void 0:G.name)&&E.next===C.next?"update":"replace"}async function k(C,E){if(await m(!0),E!==u)return;const x=n.value.find(N=>N.kind==="current"),D=n.value.find(N=>N.kind==="next");if(x&&(x.kind="done",x.reviewing=!1,x.justDone=!0),D&&(D.kind=C.current?"current":"done"),C.current&&C.next){const N=g(C.next,"next",null);N.entering=!0,n.value.push(N)}await m(!0),E===u&&_(C)}async function w(C,E,x){var G;const D=n.value.find(Z=>Z.kind==="current");if(D&&(D.rejectFlash=!0),await h(Oae),x!==u)return;const N=E.history.length,O=n.value[N];n.value.forEach((Z,q)=>{q>N&&Z.kind!=="current"&&(Z.leaving=!0)}),O&&O.kind==="done"&&(O.kind="current",O.reviving=!0,O.rounds=((G=E.current)==null?void 0:G.rounds)??null),D&&(D.rejectFlash=!1,D.kind="next",D.rounds=null,D.reviewing=!1),await h(Dae),x===u&&(n.value=n.value.filter(Z=>!Z.leaving),await m(!0),x===u&&_(E))}function T(C){const E=n.value.find(x=>x.kind==="current");E&&C.current&&(E.reviewing=C.reviewing,E.rounds=C.current.rounds)}async function A(C){o.value=!0,await h(Nae),C===u&&(o.value=!1)}return Ke(t,async(C,E)=>{const x=++u,D=e.live;if(!C.active){if(E!=null&&E.active&&D&&n.value.length&&(await A(x),x!==u))return;n.value=[],a.value=null,i.value=!1;return}if(a.value=C.footnote,!(E!=null&&E.active)||!n.value.length){i.value=!0,_(C),D&&(r.value=!0,setTimeout(()=>{r.value=!1},320));return}if(!D){_(C);return}const N=b(E,C);if(N==="advance"?await k(C,x):N==="reject"?await w(E,C,x):N==="update"?T(C):_(C),C.status==="completed"&&x===u){if(await h($ae),x!==u||(await A(x),x!==u))return;n.value=[],a.value=null,i.value=!1,e.reset()}},{flush:"sync",immediate:!0}),Ke(()=>e.exiting,async C=>{if(!C)return;const E=++u;if(await A(E),E!==u){o.value=!1;return}o.value=!1,n.value=[],a.value=null,i.value=!1,e.finishExit()},{flush:"sync"}),Ke(()=>t.value.footnote,(C,E)=>{C&&C!==E&&(c.value=!0,setTimeout(()=>{c.value=!1},260))}),(C,E)=>i.value?(F(),U("section",{key:0,class:Ce(["qd-window",{"qd-window-enter":r.value,"qd-window-exit":o.value}])},[M("header",Aae,[E[0]||(E[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)),M("span",Eae,Q(Ne(t).name),1)]),M("div",{ref_key:"viewportRef",ref:l,class:"wf-viewport"},[M("ul",Mae,[(F(!0),U(Ie,null,Ze(n.value,x=>(F(),U("li",{key:x.key,class:Ce(["wf-row",p(x)])},[E[2]||(E[2]=M("span",{class:"wf-row__dot"},null,-1)),M("span",xae,Q(x.name),1),x.kind==="current"&&x.reviewing?(F(),U("span",Rae,[E[1]||(E[1]=M("span",{class:"wf-spinner"},null,-1)),cn(Q(C.$t("quickdock.reviewing")),1)])):x.rounds!=null&&x.kind!=="next"?(F(),U("span",Iae,Q(C.$t("quickdock.roundsLabel",{n:x.rounds})),1)):me("",!0)],2))),128))],512)],512),a.value?(F(),U("div",{key:0,class:Ce(["wf-footnote",[`wf-footnote--${a.value.kind}`,{"is-entering":c.value}]])},[E[3]||(E[3]=M("span",{class:"wf-footnote__dot"},null,-1)),M("span",Pae,Q(a.value.text),1)],2)):me("",!0)],2)):me("",!0)}}),Fae={class:"qd-window__header"},Hae={key:0,class:"qd-window__icon",viewBox:"0 0 16 16",fill:"none"},Uae={key:1,class:"qd-window__icon",viewBox:"0 0 16 16",fill:"none"},Wae={class:"qd-window__title"},zae={class:"qd-window__counter"},jae=["data-kind","onClick"],Vae=["title"],Gae=["title","onClick"],OP=ct({__name:"RunnerWindow",props:{kind:{}},setup(s){function e(_){return _==="idle"?"idle":_==="completed"?"done":_==="failed"||_==="timeout"||_==="terminated"||_==="cancelled"?"ended":"running"}function t(_){return _==="completed"?"done":_==="failed"||_==="timeout"||_==="cancelled"?"ended":"running"}const n=s,i=dd(),r=vg(),o=oo(),{detail:a}=xi(o),c=ge([]),l=ge(!1),u=ge(null);let d=!1;const h=be(()=>(lt.value,n.kind==="agent"?i.subAgents.map(_=>{const b=(_.task_id||"").toString();if(!b)return null;const k=(_.status||"").toString().toLowerCase();return{id:b,name:_.display_name||_.summary||S("quickdock.agentNamed",{id:_.agent_id??b}),state:e(k)}}).filter(_=>_!==null):r.commands.map(_=>{const b=(_.command_id||"").toString();if(!b)return null;const k=(_.status||"").toString().toLowerCase();return{id:b,name:_.command||b,state:t(k)}}).filter(_=>_!==null)));function p(_){var b,k;return((b=a.value)==null?void 0:b.kind)===n.kind&&((k=a.value)==null?void 0:k.id)===_.id}function g(_){o.closeMenu(),o.openDetail(n.kind,_.id)}function v(_,b){const w=_.currentTarget.getBoundingClientRect();o.openMenu({type:"runner",kind:n.kind,key:b.id,left:w.right,top:w.bottom+6,alignRight:!0})}function m(_){return new Promise(b=>{const k=u.value;if(!k){b();return}const w=k.getBoundingClientRect(),T=_.getBoundingClientRect();if(T.top>=w.top&&T.bottom<=w.bottom){b();return}let C=!1,E;const x=()=>{C||(C=!0,E&&clearTimeout(E),k.removeEventListener("scroll",D),b())},D=()=>{E&&clearTimeout(E),E=setTimeout(x,90)};k.addEventListener("scroll",D),_.scrollIntoView({behavior:"smooth",block:"nearest"}),E=setTimeout(x,800)})}async function y(_,b=0){b>0&&await new Promise(A=>setTimeout(A,b)),await ft();const k=u.value,w=c.value.indexOf(_),T=k==null?void 0:k.children[w];if(!T){_.pendingEnter=!1,_.entering=!0,setTimeout(()=>{_.entering=!1},380);return}await m(T),_.pendingEnter=!1,_.entering=!0,setTimeout(()=>{_.entering=!1},380)}return Ke(h,_=>{const b=new Map(_.map(A=>[A.id,A]));c.value=c.value.filter(A=>b.has(A.id)),c.value.forEach(A=>{const C=b.get(A.id);C&&(A.name=C.name,A.state=C.state)});const k=new Set(c.value.map(A=>A.id)),w=_.filter(A=>!k.has(A.id)),T=w.some(A=>A.state==="running");if(w.length){const A=T&&!d&&!c.value.length;A&&(d=!0,l.value=!0,setTimeout(()=>{l.value=!1},320)),w.forEach((C,E)=>{const x={id:C.id,name:C.name,state:C.state,entering:!1,pendingEnter:T};if(c.value.push(x),T){const D=(A?300:0)+E*60;y(c.value[c.value.length-1],D)}})}},{immediate:!0}),(_,b)=>c.value.length?(F(),U("section",{key:0,class:Ce(["qd-window",{"qd-window-enter":l.value}])},[M("header",Fae,[s.kind==="agent"?(F(),U("svg",Hae,[...b[0]||(b[0]=[M("circle",{cx:"8",cy:"5.5",r:"2.5",stroke:"currentColor","stroke-width":"1.4"},null,-1),M("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(),U("svg",Uae,[...b[1]||(b[1]=[M("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),M("path",{d:"M8 12h5.5",stroke:"currentColor","stroke-width":"1.4","stroke-linecap":"round"},null,-1)])])),M("span",Wae,Q(s.kind==="agent"?_.$t("quickdock.subAgent"):_.$t("quickdock.backgroundCommand")),1),M("span",zae,Q(c.value.length),1)]),M("ul",{ref_key:"listRef",ref:u,class:"qd-list"},[(F(!0),U(Ie,null,Ze(c.value,k=>(F(),U("li",{key:k.id,class:Ce(["qd-run-item",[`is-${k.state}`,{"is-active":p(k),"qd-row-enter":k.entering}]]),"data-kind":s.kind,style:qe(k.pendingEnter?{opacity:"0"}:void 0),onClick:w=>g(k)},[b[3]||(b[3]=M("span",{class:"qd-run-status"},null,-1)),M("span",{class:"qd-run-name",title:k.name},Q(k.name),9,Vae),M("button",{class:"qd-row-menu-btn",title:_.$t("quickdock.more"),onClick:De(w=>v(w,k),["stop"])},[...b[2]||(b[2]=[M("svg",{viewBox:"0 0 16 16"},[M("circle",{cx:"3.5",cy:"8",r:"1.3",fill:"currentColor"}),M("circle",{cx:"8",cy:"8",r:"1.3",fill:"currentColor"}),M("circle",{cx:"12.5",cy:"8",r:"1.3",fill:"currentColor"})],-1)])],8,Gae)],14,jae))),128))],512)],2)):me("",!0)}}),Kae={class:"qd-detail__header"},qae=["title"],Qae=["title"],Xae={class:"qd-detail__close"},Yae={key:0,class:"qd-detail__empty"},Jae={class:"tool-name"},Zae=["title"],ele={key:0,class:"qd-tool-spinner"},tle={key:1,class:"qd-tool-done"},sle={key:1,class:"feed-compressed__label"},nle={key:0,class:"qd-detail__empty"},ile=ct({__name:"RunnerDetailPanel",setup(s){const e=new Set(["completed","failed","timeout","terminated"]),t=new Set(["completed","failed","timeout","cancelled"]),n=oo(),i=dd(),r=vg(),{detail:o}=xi(n),{activityEntries:a,activityLoading:c}=xi(i),{activeDetail:l,detailLoading:u}=xi(r),d=ge(null);Ke(o,P=>{P&&(d.value={kind:P.kind,id:P.id})},{immediate:!0});const h=be(()=>o.value||d.value),p=ge(""),g=be(()=>{var ne,ce;const P=h.value;if(!P)return"";if(P.kind==="agent"){const _e=i.subAgents.find(it=>it.task_id===P.id),Pe=((ne=i.activeAgent)==null?void 0:ne.task_id)===P.id?i.activeAgent:null;return String((Pe==null?void 0:Pe.status)||(_e==null?void 0:_e.status)||"")}const X=r.commands.find(_e=>_e.command_id===P.id),J=((ce=r.activeCommand)==null?void 0:ce.command_id)===P.id?r.activeCommand:null;return String((J==null?void 0:J.status)||(X==null?void 0:X.status)||"")});Ke(g,P=>{P&&(p.value=P)},{immediate:!0});const v=ge(!1),m=ge(!1),y=ge(!1),_=ge(!1),b=ge(null),k=be(()=>g.value||p.value||""),w=be(()=>{const P=k.value.toLowerCase();return!h.value||!P||P==="idle"?!1:!(h.value.kind==="agent"?e:t).has(P)}),T=be(()=>{const P=k.value.toLowerCase();return P==="idle"?"idle":w.value?"running":P==="completed"?"done":"ended"}),A=be(()=>{var X,J;if(lt.value,!h.value)return"";if(h.value.kind==="agent"){const ne=i.subAgents.find(ce=>{var _e;return ce.task_id===((_e=h.value)==null?void 0:_e.id)});return(ne==null?void 0:ne.display_name)||(ne==null?void 0:ne.summary)||((X=i.activeAgent)==null?void 0:X.display_name)||S("quickdock.subAgent")}const P=r.commands.find(ne=>{var ce;return ne.command_id===((ce=h.value)==null?void 0:ce.id)});return(P==null?void 0:P.command)||((J=r.activeCommand)==null?void 0:J.command)||S("quickdock.backgroundCommand")}),C=be(()=>{lt.value;const P=k.value.toLowerCase();return P==="idle"?S("quickdock.statusIdle"):w.value?S("common.running"):P==="completed"?S("quickdock.statusCompleted"):P==="failed"?S("quickdock.statusFailed"):P==="timeout"?S("quickdock.statusTimeout"):P==="terminated"||P==="cancelled"?S("quickdock.statusTerminated"):S("quickdock.statusEnded")}),E=be(()=>{const P=h.value;if(!P||P.kind!=="agent")return 0;const X=i.subAgents.find(ne=>ne.task_id===P.id),J=Number(X==null?void 0:X.current_context_tokens);return Number.isFinite(J)&&J>0?J:0}),x=ge(0);Ke(E,P=>{P>0&&(x.value=P)},{immediate:!0});const D=be(()=>E.value||x.value);function N(P){return!P||P<=0?"":P>=1e3?`${(P/1e3).toFixed(1)}k Tokens`:`${P} Tokens`}const O=be(()=>{var P;return((P=h.value)==null?void 0:P.kind)!=="agent"?"":N(D.value)}),G=be(()=>(lt.value,S("quickdock.contextTokensTitle",{tokens:D.value.toLocaleString()})));function Z(P){return P==="running"||P==="in_progress"?"running":P==="calling"?"calling":P==="completed"||P==="done"||P==="success"?"completed":P==="failed"||P==="error"?"failed":P||"running"}function q(P){const X=(P||"").toString().toLowerCase();return["completed","failed","timeout","terminated","cancelled","done","success","error"].includes(X)}function V(P){const X=P.tool||"",J=P.args||{};return X==="read_file"?S("quickdock.toolReadFile",{path:J.path||J.file_path||""}):X==="write_file"?S("quickdock.toolWriteFile",{path:J.file_path||J.path||""}):X==="read_skill"?S("quickdock.toolReadSkill",{name:J.skill_name||""}):X==="web_search"?S("quickdock.toolSearch",{query:J.query||J.q||""}):X==="extract_webpage"?S("quickdock.toolExtract",{url:J.url||""}):X==="run_command"?S("quickdock.toolRunCommand",{command:J.command||""}):X==="edit_file"?S("quickdock.toolEditFile",{path:J.path||J.file_path||""}):X==="read_mediafile"?S("quickdock.toolReadMedia",{path:J.path||J.file_path||""}):X||S("common.tool")}const I=be(()=>{lt.value;const P=a.value||[],X=[];let J=null;const ne=()=>{J&&(X.push(J),J=null)};return P.forEach((ce,_e)=>{var rt;if((ce==null?void 0:ce.type)==="progress"&&(ce==null?void 0:ce.subtype)==="output"&&typeof ce.content=="string"){ne();const Oe={kind:"output",key:`output-${ce.ts||_e}`,content:ce.content};let xe=X.length;for(;xe>0;){const pe=X[xe-1];if(pe.kind==="tool"&&!q((rt=pe.entry)==null?void 0:rt.status))xe-=1;else break}X.splice(xe,0,Oe);return}if((ce==null?void 0:ce.type)==="progress"&&(ce==null?void 0:ce.subtype)==="compression"){ne(),X.push({kind:"compression",key:`compression-${ce.ts||_e}`,round:Number(ce.round)||0});return}if(!ce||ce.type!=="progress"||!ce.tool)return;const Pe=ce.id||`${ce.tool}-${ce.ts||_e}`;if(J&&(J.entry.id===ce.id||J.key===Pe)&&!q(J.entry.status)){J.entry={...J.entry,...ce};return}if(ce.id){const Oe=X.find(xe=>xe.kind==="tool"&&xe.entry.id===ce.id&&!q(xe.entry.status));if(Oe&&Oe.kind==="tool"){Oe.entry={...Oe.entry,...ce};return}}ne();let it=Pe,at=0;for(;X.some(Oe=>Oe.kind==="tool"&&Oe.key===it);)at+=1,it=`${Pe}--${at}`;J={kind:"tool",key:it,entry:{...ce}}}),ne(),X.map(ce=>{if(ce.kind==="output"||ce.kind==="compression")return ce;const _e=Z(ce.entry.status);return{kind:"tool",key:ce.key,state:_e,toolName:ce.entry.tool||S("common.tool"),text:V(ce.entry)}})}),$=be(()=>{var X,J;if(((X=h.value)==null?void 0:X.kind)!=="cmd")return[];const P=(J=l.value)==null?void 0:J.output;return typeof P!="string"?[]:P.split(`
|
||
`)}),L=ge(new Set);let K=new Set,se=!1;function oe(){K=new Set,se=!1,L.value=new Set}Ke([I,$],()=>{var J;const P=((J=h.value)==null?void 0:J.kind)==="agent"?I.value.map(ne=>ne.key):$.value.map((ne,ce)=>`term-${ce}`);if(!se){if(!P.length)return;se=!0,P.forEach(ne=>K.add(ne)),ft(()=>ve(!1));return}const X=P.filter(ne=>!K.has(ne));X.length&&(X.forEach(ne=>K.add(ne)),L.value=new Set(X),setTimeout(()=>{L.value=new Set},400))},{flush:"post"}),Ke(o,(P,X)=>{if(!P){const J=()=>{(X==null?void 0:X.kind)==="agent"&&i.closeSubAgent(),(X==null?void 0:X.kind)==="cmd"&&r.closeCommand()};v.value?(m.value=!1,y.value=!0,setTimeout(()=>{y.value=!1,v.value=!1,J()},190)):J();return}if((X==null?void 0:X.kind)==="agent"&&i.closeSubAgent(),(X==null?void 0:X.kind)==="cmd"&&r.closeCommand(),oe(),P.kind==="agent"){const J=i.subAgents.find(ne=>ne.task_id===P.id);J&&i.openSubAgent(J,{silent:!0})}else{const J=r.commands.find(ne=>ne.command_id===P.id);J&&r.openCommand(J,{silent:!0})}v.value?(_.value=!1,ft(()=>{_.value=!0,ve(!1),setTimeout(()=>{_.value=!1},200)})):(v.value=!0,m.value=!0,setTimeout(()=>{m.value=!1},260),ft(()=>{ve(!1)}))},{immediate:!0});function ve(P){const X=b.value;X&&X.scrollTo({top:X.scrollHeight,behavior:P?"smooth":"auto"})}function le(){const P=b.value;if(!P||!se)return;P.scrollHeight-P.scrollTop-P.clientHeight<80&&ft(()=>ve(!0))}Ke(()=>[I.value.length,$.value.length],()=>{le()});function ue(){n.closeDetail()}return(P,X)=>{var ne;const J=Hs("CloseButton");return v.value?(F(),U("section",{key:0,class:Ce(["qd-detail",{"panel-enter":m.value,"panel-leave":y.value}])},[M("header",Kae,[M("span",{class:Ce(["qd-detail__dot",`is-${T.value}`])},null,2),M("span",{class:"qd-detail__title",title:A.value},Q(A.value),9,qae),M("span",{class:Ce(["qd-detail__badge",`is-${T.value}`])},Q(C.value),3),O.value?(F(),U("span",{key:0,class:"qd-detail__tokens",title:G.value},Q(O.value),9,Qae)):me("",!0),M("span",Xae,[We(J,{label:P.$t("common.close"),title:P.$t("common.close"),onClick:ue},null,8,["label","title"])])]),M("div",{ref_key:"bodyRef",ref:b,class:Ce(["qd-detail__body",{"body-fade":_.value}])},[((ne=h.value)==null?void 0:ne.kind)==="agent"?(F(),U(Ie,{key:0},[I.value.length?me("",!0):(F(),U("div",Yae,Q(Ne(c)?P.$t("common.loading"):P.$t("quickdock.noProgress")),1)),(F(!0),U(Ie,null,Ze(I.value,ce=>(F(),U("div",{key:ce.key,class:Ce(["qd-feed-row",[ce.kind==="tool"?"feed-tool":ce.kind==="compression"?"feed-compressed":"feed-text",{"is-new":L.value.has(ce.key)}]])},[ce.kind==="tool"?(F(),U(Ie,{key:0},[M("span",Jae,Q(ce.toolName),1),M("span",{class:"tool-param",title:ce.text},Q(ce.text),9,Zae),M("span",{class:Ce(["tool-status",{"is-error":ce.state==="failed"}])},[ce.state==="running"||ce.state==="calling"?(F(),U("span",ele)):(F(),U("span",tle,Q(ce.state==="failed"?"✕":"✓"),1))],2)],64)):ce.kind==="compression"?(F(),U("span",sle,[X[0]||(X[0]=M("svg",{class:"feed-compressed__icon",viewBox:"0 0 16 16",fill:"none","aria-hidden":"true"},[M("path",{d:"M8 1.5 13.5 4v4.5c0 3-2.2 5-5.5 6-3.3-1-5.5-3-5.5-6V4L8 1.5Z",stroke:"currentColor","stroke-width":"1.3","stroke-linejoin":"round"}),M("path",{d:"M5.5 8.2 7.2 9.9 11 5.8",stroke:"currentColor","stroke-width":"1.3","stroke-linecap":"round","stroke-linejoin":"round"})],-1)),cn(" "+Q(Ne(S)("quickdock.contextCompressed",{round:ce.round})),1)])):(F(),U(Ie,{key:2},[cn(Q(ce.content),1)],64))],2))),128))],64)):(F(),U(Ie,{key:1},[$.value.length?me("",!0):(F(),U("div",nle,Q(Ne(u)?P.$t("common.loading"):P.$t("quickdock.noOutput")),1)),(F(!0),U(Ie,null,Ze($.value,(ce,_e)=>(F(),U("div",{key:_e,class:Ce(["qd-feed-row feed-term",{"is-new":L.value.has(`term-${_e}`)}])},Q(ce),3))),128))],64))],2)],2)):me("",!0)}}}),rle={class:"qd-window__header"},ole={class:"qd-window__title"},ale={class:"qd-window__counter"},lle=["title","onClick"],cle=["title","onClick"],ule={class:"qd-file-name"},dle=ct({__name:"FileWindow",setup(s){const e=oo(),{editedFiles:t,previewPath:n}=xi(e),i=ge([]),r=ge(!1),o=ge(null);let a=!1;function c(g){return g.split("/").pop()||g}function l(g){e.closeMenu(),e.openPreview(g.path)}function u(g,v){const y=g.currentTarget.getBoundingClientRect();e.openMenu({type:"file",key:v.path,left:y.left,top:y.bottom+6,alignRight:!1})}function d(g){return new Promise(v=>{const m=o.value;if(!m){v();return}const y=m.getBoundingClientRect(),_=g.getBoundingClientRect();if(_.top>=y.top&&_.bottom<=y.bottom){v();return}let k=!1,w;const T=()=>{k||(k=!0,w&&clearTimeout(w),m.removeEventListener("scroll",A),v())},A=()=>{w&&clearTimeout(w),w=setTimeout(T,90)};m.addEventListener("scroll",A),g.scrollIntoView({behavior:"smooth",block:"nearest"}),w=setTimeout(T,800)})}async function h(g,v=0){v>0&&await new Promise(b=>setTimeout(b,v)),await ft();const m=o.value,y=i.value.indexOf(g),_=m==null?void 0:m.children[y];if(!_){g.pendingEnter=!1,g.entering=!0,setTimeout(()=>{g.entering=!1},380);return}await d(_),g.pendingEnter=!1,g.entering=!0,setTimeout(()=>{g.entering=!1},380)}let p=!1;return Ke(t,g=>{const v=e.editedFilesLive&&p;p=!0;const m=new Map(g.map(b=>[b.path,b]));i.value=i.value.filter(b=>m.has(b.path));const y=new Set(i.value.map(b=>b.path)),_=g.filter(b=>!y.has(b.path));if(_.length){const b=v&&!a&&!i.value.length;b&&(a=!0,r.value=!0,setTimeout(()=>{r.value=!1},320)),_.forEach((k,w)=>{const T={path:k.path,entering:!1,pendingEnter:v};if(i.value.push(T),v){const A=(b?300:0)+w*60;h(i.value[i.value.length-1],A)}})}},{immediate:!0}),(g,v)=>i.value.length?(F(),U("section",{key:0,class:Ce(["qd-window",{"qd-window-enter":r.value}])},[M("header",rle,[v[0]||(v[0]=M("svg",{class:"qd-window__icon",viewBox:"0 0 16 16",fill:"none"},[M("path",{d:"M4 2.5h5.5L12 5v8.5H4V2.5z",stroke:"currentColor","stroke-width":"1.3","stroke-linejoin":"round"}),M("path",{d:"M9.5 2.5V5H12",stroke:"currentColor","stroke-width":"1.3","stroke-linejoin":"round"})],-1)),M("span",ole,Q(g.$t("quickdock.fileWindowTitle")),1),M("span",ale,Q(i.value.length),1)]),M("ul",{ref_key:"listRef",ref:o,class:"qd-list"},[(F(!0),U(Ie,null,Ze(i.value,m=>(F(),U("li",{key:m.path,class:Ce(["qd-file-item",{"is-active":Ne(n)===m.path,"qd-row-enter":m.entering}]),style:qe(m.pendingEnter?{opacity:"0"}:void 0),title:m.path,onClick:y=>l(m)},[M("button",{class:"qd-row-menu-btn",title:g.$t("quickdock.more"),onClick:De(y=>u(y,m),["stop"])},[...v[1]||(v[1]=[M("svg",{viewBox:"0 0 16 16"},[M("circle",{cx:"3.5",cy:"8",r:"1.3",fill:"currentColor"}),M("circle",{cx:"8",cy:"8",r:"1.3",fill:"currentColor"}),M("circle",{cx:"12.5",cy:"8",r:"1.3",fill:"currentColor"})],-1)])],8,cle),M("span",ule,Q(c(m.path)),1)],14,lle))),128))],512)],2)):me("",!0)}}),hle=["disabled"],fle=300,ple=3e3,mle=128,gle=ct({__name:"QuickDock",props:{hostMode:{type:Boolean}},setup(s){const e=oo(),t=dd(),n=vg(),i=kr(),r=Is(),o=Pc(),a=yg(),c=Js(),{menu:l,hasContent:u,userCollapsed:d}=xi(e),h=ge(null);Ke(d,le=>{le&&e.resetTransient()});const p=be(()=>c.form.quick_dock_auto_expand!==!1),g=be(()=>hL()||c.loaded||!!c.error),v=ge(!0);let m=0,y=null,_=null,b=null,k=null,w=!0;function T(){return w?!1:y?e.filesSyncSeq>y.filesSeq&&o.todoSyncSeq>y.todoSeq:!0}function A(){b!==null&&(clearTimeout(b),b=null),k!==null&&(clearTimeout(k),k=null)}function C(){m+=1,v.value=!0,y={filesSeq:e.filesSyncSeq,todoSeq:o.todoSyncSeq},A(),_||(_=Ke(()=>[e.filesSyncSeq,o.todoSyncSeq],()=>{E()})),E(),k=setTimeout(()=>{x(!0)},ple)}function E(){!v.value||!T()||(b!==null&&clearTimeout(b),b=setTimeout(()=>{b=null,x()},fle))}function x(le=!1){if(!v.value||!le&&!T())return;A(),_&&(_(),_=null),y=null,e.settleInitialContent();const ue=m;requestAnimationFrame(()=>{requestAnimationFrame(()=>{ue===m&&(v.value=!1)})})}Ke(u,le=>{e.userCollapsed=!p.value},{immediate:!0}),Ke(p,le=>{e.userCollapsed=!le}),Ke(u,le=>{if(!e.assumedActive){S6(le);const ue=i.currentConversationId;ue&&C6(ue,le)}});const D=new Set(["completed","failed","timeout","terminated"]),N=new Set(["completed","failed","timeout","cancelled"]),O=be(()=>{const le=l.value;if(!le)return{};const ue=Math.min(le.top,window.innerHeight-mle-8);return le.alignRight?{right:`${window.innerWidth-le.left}px`,top:`${ue}px`}:{left:`${le.left}px`,top:`${ue}px`}}),G=be(()=>{const le=l.value;if(!le||le.type!=="runner")return!1;if(le.kind==="agent"){const X=t.subAgents.find(ne=>ne.task_id===le.key),J=((X==null?void 0:X.status)||"").toString().toLowerCase();return!!X&&!D.has(J)}const ue=n.commands.find(X=>X.command_id===le.key),P=((ue==null?void 0:ue.status)||"").toString().toLowerCase();return!!ue&&!N.has(P)});async function Z(){const le=l.value;if(!le||le.type!=="runner")return;e.closeMenu();const ue=le.kind==="agent"?await t.terminateSubAgent(le.key):await n.cancelCommand(le.key);ue!=null&&ue.success||r.pushToast({message:(ue==null?void 0:ue.error)||S("quickdock.killForceStopFailed"),type:"error"})}function q(le){return le.split("/").pop()||le}function V(){const le=l.value;if(!le||le.type!=="file")return;e.closeMenu();const ue=document.createElement("a");ue.href=`/api/download/file?path=${encodeURIComponent(le.key)}`,ue.download=q(le.key),document.body.appendChild(ue),ue.click(),ue.remove()}async function I(){var P;const le=l.value;if(!le||le.type!=="file")return;const ue=le.key;e.closeMenu();try{const X=await fetch(`/api/project/file-open-apps?path=${encodeURIComponent(ue)}`),J=await X.json().catch(()=>({}));if(!X.ok||!(J!=null&&J.success))throw new Error((J==null?void 0:J.error)||S("quickdock.revealDetectAppsFailed"));const ne=Array.isArray((P=J==null?void 0:J.data)==null?void 0:P.apps)?J.data.apps:[];if(!ne.length)throw new Error(S("quickdock.revealNoAppsFound"));const ce=await fetch("/api/project/open-file-with-app",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:ue,app_id:ne[0].id})}),_e=await ce.json().catch(()=>({}));if(!ce.ok||!(_e!=null&&_e.success))throw new Error((_e==null?void 0:_e.error)||S("quickdock.revealOpenFileFailed"))}catch(X){r.pushToast({message:(X==null?void 0:X.message)||S("quickdock.revealOpenFileFailed"),type:"error"})}}async function $(){var J;const le=l.value;if(!le||le.type!=="file")return;const ue=le.key;e.closeMenu();const P=(ne,ce="info")=>r.pushToast({message:ne,type:ce,duration:2e3});if((J=navigator.clipboard)!=null&&J.writeText)try{await navigator.clipboard.writeText(ue),P(S("quickdock.copiedRelativePath"),"success");return}catch{}const X=document.createElement("textarea");X.value=ue,X.style.position="fixed",X.style.opacity="0",document.body.appendChild(X),X.select();try{document.execCommand("copy"),P(S("quickdock.copiedRelativePath"),"success")}catch{P(S("common.copyFailed"),"error")}X.remove()}function L(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 K(le){if(!l.value)return;const ue=le.target;ue!=null&&ue.closest(".qd-menu")||ue!=null&&ue.closest(".qd-row-menu-btn")||e.closeMenu()}function se(){l.value&&e.closeMenu()}let oe=null;function ve(){t.fetchSubAgents(),n.fetchCommands()}return dn(()=>{const le=Promise.allSettled([t.fetchSubAgents(),n.fetchCommands()]);oe=setInterval(ve,5e3),document.addEventListener("keydown",L),document.addEventListener("click",K),C(),le.then(()=>{w=!1,E()})}),Rn(()=>{oe&&(clearInterval(oe),oe=null),A(),document.removeEventListener("keydown",L),document.removeEventListener("click",K),e.resetTransient()}),Ke(()=>i.currentConversationId,()=>{e.resetTransient();const le=i.currentConversationId;le?a.fetchStatus(le):a.reset(),ve(),C(),e.assumeContentForConversation(i.currentConversationId)},{flush:"sync"}),(le,ue)=>(F(),U("aside",{class:Ce(["quick-dock",{"quick-dock--empty":!g.value||!Ne(u)||Ne(d),"quick-dock--no-anim":v.value}])},[M("div",{ref_key:"scrollRef",ref:h,class:"quick-dock__scroll",onScrollPassive:se},[We(Bae),We(Tae),We(OP,{kind:"agent"}),We(OP,{kind:"cmd"}),We(dle)],544),We(ile),Ne(l)?(F(),U("div",{key:0,class:"qd-menu menu-enter",style:qe(O.value),onClick:ue[0]||(ue[0]=De(()=>{},["stop"]))},[Ne(l).type==="runner"?(F(),U("button",{key:0,class:"qd-menu__item qd-menu__item--danger",disabled:!G.value,onClick:Z},Q(le.$t("quickdock.menuForceStop")),9,hle)):(F(),U(Ie,{key:1},[M("button",{class:"qd-menu__item",onClick:V},Q(le.$t("common.download")),1),s.hostMode?(F(),U("button",{key:0,class:"qd-menu__item",onClick:I},Q(le.$t("quickdock.menuRevealInManager")),1)):me("",!0),M("button",{class:"qd-menu__item",onClick:$},Q(le.$t("quickdock.menuCopyPath")),1)],64))],4)):me("",!0)],2))}}),vle=["title"],yle={class:"qd-preview__panel"},ble={class:"qd-preview__header"},_le=["title"],wle=["title"],Sle={class:"qd-preview__body"},kle={key:0,class:"qd-preview__loading"},Cle={key:1,class:"qd-preview__error"},Tle={key:0,class:"qd-code qd-code--wrap"},Ale={class:"qd-code-line-no","aria-hidden":"true"},Ele=["innerHTML"],Mle={class:"qd-code-gutter","aria-hidden":"true"},xle={class:"qd-code-pre"},Rle=["innerHTML"],DP=21,Ile=100*1024,NP="agents_qd_preview_width",$P=320,BP=860,IT=452,Ple=ct({__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=oo(),{previewPath:n}=xi(t),r=ge((()=>{if(typeof window>"u"||!window.localStorage)return IT;try{const A=Number(window.localStorage.getItem(NP));return!Number.isFinite(A)||A<=0?IT:Math.max($P,Math.min(BP,A))}catch{return IT}})());function o(A){A.preventDefault();const C=A.clientX,E=r.value,x=N=>{const O=E+(C-N.clientX);r.value=Math.max($P,Math.min(BP,O))},D=()=>{document.removeEventListener("mousemove",x),document.removeEventListener("mouseup",D),document.body.style.cursor="",document.body.style.userSelect="";try{window.localStorage.setItem(NP,String(r.value))}catch{}};document.addEventListener("mousemove",x),document.addEventListener("mouseup",D),document.body.style.cursor="col-resize",document.body.style.userSelect="none"}const a=ge(""),c=ge(!1),l=ge(""),u=ge(-1),d=be(()=>a.value.length>Ile?null:ZD(n.value||"")),h=be(()=>{const A=O1(a.value,d.value);return a.value.endsWith(`
|
||
`)?A+`
|
||
`:A}),p=be(()=>a.value?a.value.split(`
|
||
`).length:0),g=Js(),v=be(()=>g.form.file_preview_auto_wrap===!0),m=be(()=>a.value?a.value.split(`
|
||
`).map(A=>O1(A,d.value)):[]),y=be(()=>{const A=n.value||"";return A.split("/").pop()||A}),_=be(()=>{const C=(n.value||"").split("/");return C.length>1?`${C.slice(0,-1).join("/")}/`:""});function b(A){const C=A.split("/").pop()||"",E=C.lastIndexOf(".");return E>=0?C.slice(E).toLowerCase():""}let k=0;Ke(n,async A=>{const C=++k;if(a.value="",l.value="",u.value=-1,!!A){if(!e.has(b(A))){l.value=S("quickdock.previewTypeUnsupported");return}c.value=!0;try{const E=await fetch(`/api/file/content?path=${encodeURIComponent(A)}`);if(!E.ok){const D=await E.json().catch(()=>({}));throw new Error((D==null?void 0:D.error)||S("quickdock.loadFailedHttp",{status:E.status}))}const x=await E.text();if(C!==k)return;a.value=x}catch(E){if(C!==k)return;l.value=(E==null?void 0:E.message)||S("common.loadFailed")}finally{C===k&&(c.value=!1)}}},{immediate:!0});function w(A){const E=A.currentTarget.getBoundingClientRect(),x=Math.floor((A.clientY-E.top)/DP);u.value=x>=0&&x<p.value?x:-1}function T(){t.closePreview()}return(A,C)=>(F(),Ft(gs,{name:"qd-preview-slide"},{default:Gt(()=>[Ne(n)?(F(),U("aside",{key:0,class:"qd-preview",style:qe({width:r.value+"px"})},[M("div",{class:"qd-preview__resize",title:A.$t("quickdock.resizeWidthHint"),onMousedown:o},null,40,vle),M("section",yle,[M("header",ble,[C[1]||(C[1]=M("svg",{viewBox:"0 0 16 16",fill:"none"},[M("path",{d:"M4 2.5h5.5L12 5v8.5H4V2.5z",stroke:"currentColor","stroke-width":"1.3","stroke-linejoin":"round"}),M("path",{d:"M9.5 2.5V5H12",stroke:"currentColor","stroke-width":"1.3","stroke-linejoin":"round"})],-1)),M("span",{class:"qd-preview__name",title:Ne(n)},Q(y.value),9,_le),M("span",{class:"qd-preview__path",title:Ne(n)},Q(_.value),9,wle),We(ml,{label:A.$t("common.close"),title:A.$t("common.close"),onClick:T},null,8,["label","title"])]),M("div",Sle,[c.value?(F(),U("div",kle,Q(A.$t("common.loading")),1)):l.value?(F(),U("div",Cle,Q(l.value),1)):(F(),U(Ie,{key:2},[v.value?(F(),U("div",Tle,[(F(!0),U(Ie,null,Ze(m.value,(E,x)=>(F(),U("div",{key:x,class:"qd-code-line"},[M("span",Ale,Q(x+1),1),M("span",{class:"qd-code-line-text",innerHTML:E},null,8,Ele)]))),128))])):(F(),U("div",{key:1,class:"qd-code",onMousemove:w,onMouseleave:C[0]||(C[0]=E=>u.value=-1)},[u.value>=0?(F(),U("div",{key:0,class:"qd-code-hoverline",style:qe({top:`${u.value*DP}px`})},null,4)):me("",!0),M("div",Mle,[(F(!0),U(Ie,null,Ze(p.value,E=>(F(),U("span",{key:E},Q(E),1))),128))]),M("pre",xle,[M("code",{innerHTML:h.value},null,8,Rle)])],32))],64))])])],4)):me("",!0)]),_:1}))}}),Lle=["innerHTML"],Ole={class:"pop-domain"},Dle={class:"pop-scroll"},Nle={class:"pop-body"},$le={class:"pop-title-row"},Ble={class:"pop-title"},Fle={key:0,class:"pop-locator"},Hle={key:0,class:"pop-url"},Ule={key:1,class:"pop-image"},Wle=["src","alt"],zle={key:2,class:"pop-snippet"},jle={key:0,class:"pop-footer"},Vle=["href"],Gle=["innerHTML"],Kle={class:"pop-domain"},qle={class:"pop-pager"},Qle=["disabled","aria-label"],Xle={class:"pop-pager-count"},Yle=["disabled","aria-label"],Jle={class:"pop-scroll"},Zle={class:"pop-body"},ece={class:"pop-title-row"},tce={class:"pop-title"},sce={key:0,class:"pop-locator"},nce={key:0,class:"pop-url"},ice={key:1,class:"pop-image"},rce=["src","alt"],oce={key:2,class:"pop-snippet"},ace={key:0,class:"pop-footer"},lce=["href"],cce='<svg class="chip-file-icon" viewBox="0 0 16 16" fill="none"><path d="M4 1.5h5.5L13 5v9.5H4z" stroke="currentColor" stroke-width="1.2" stroke-linejoin="round"/><path d="M9.5 1.5V5H13" stroke="currentColor" stroke-width="1.2" stroke-linejoin="round"/></svg>',uce=ct({name:"CitationPopover",__name:"CitationPopover",props:{hostMode:{type:Boolean}},setup(s){const e=s,t=oo(),n=Is(),i=be(()=>ts.annotations.length===1?ts.annotations[0]:null),r=ge(0),o=be(()=>{const I=ts.annotations;return I.length?I[Math.min(r.value,I.length-1)]??null:null});function a(I){const $=ts.annotations;if($.length<2)return;const L=Math.min(Math.max(r.value+I,0),$.length-1);L!==r.value&&(r.value=L,ft(()=>{O(),l.value&&FT(l.value)}))}const c=be(()=>{const I=o.value;return I?h(I)?!!e.hostMode:!!I.url:!1}),l=ge(null),u=ge({}),d=be(()=>!n.isMobileViewport);function h(I){return I.type==="file_citation"}const p=new Set([".png",".jpg",".jpeg",".gif",".webp",".svg",".bmp",".ico",".avif"]);function g(I){if(!h(I))return!1;const $=(I.file_path||I.file_name||"").toLowerCase(),L=$.lastIndexOf(".");return L>=0&&p.has($.slice(L))}function v(I){return`/api/file/content?path=${encodeURIComponent(I.file_path||"")}`}function m(I){n.openImagePreview({url:v(I),name:I.file_name||""})}function y(I){return(I||"").replace(/^www\./,"")}function _(I){return h(I)?cce:_L(I.domain||"")}function b(I){return h(I)?I.file_path||I.file_name||"":y(I.domain)}function k(I){const $=[];return I.page!=null&&$.push(`p.${I.page}`),I.line_start!=null&&$.push(I.line_end!=null&&I.line_end!==I.line_start?`L${I.line_start}–${I.line_end}`:`L${I.line_start}`),$.join(" · ")}function w(I){!I.file_path||!d.value||(t.openPreview(I.file_path),Nl())}const T=ge({}),A=new Set;function C(I){return I.snippet||T.value[I.id]||""}async function E(I){if(!h(I)||g(I)||I.snippet||!I.file_path||T.value[I.id]||A.has(I.id))return;A.add(I.id);const $=I.file_path;try{const L=await fetch(`/api/file/content?path=${encodeURIComponent($)}`);if(!L.ok)return;let K=await L.text();if(K.includes("\0")||(K.match(/\uFFFD/g)||[]).length>Math.max(4,K.length*.005))return;if(I.line_start!=null){const oe=K.split(`
|
||
`),ve=Math.max(1,I.line_start),le=Math.min(oe.length,I.line_end??ve);K=oe.slice(ve-1,le).join(`
|
||
`)}K=K.split(`
|
||
`).map(oe=>oe.trim()).filter(Boolean).join(`
|
||
`).slice(0,300),K&&(T.value={...T.value,[I.id]:K})}catch{}finally{A.delete(I.id)}}function x(){for(const I of ts.annotations)E(I)}Ke(()=>{var I;return[ts.visible,(I=o.value)==null?void 0:I.id]},([I])=>{I&&o.value&&E(o.value)});function D(I){h(I)&&w(I)}async function N(I){var L;const $=I.file_path;if($){try{const K=await fetch(`/api/project/file-open-apps?path=${encodeURIComponent($)}`),se=await K.json().catch(()=>({}));if(!K.ok||!(se!=null&&se.success))throw new Error((se==null?void 0:se.error)||S("quickdock.revealDetectAppsFailed"));const oe=Array.isArray((L=se==null?void 0:se.data)==null?void 0:L.apps)?se.data.apps:[];if(!oe.length)throw new Error(S("quickdock.revealNoAppsFound"));const ve=await fetch("/api/project/open-file-with-app",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:$,app_id:oe[0].id})}),le=await ve.json().catch(()=>({}));if(!ve.ok||!(le!=null&&le.success))throw new Error((le==null?void 0:le.error)||S("quickdock.revealOpenFileFailed"))}catch(K){n.pushToast({message:(K==null?void 0:K.message)||S("quickdock.revealOpenFileFailed"),type:"error"});return}Nl()}}function O(){const I=ts.anchor,$=l.value;if(!I||!$)return;const L=I.getBoundingClientRect(),K=320,oe=Math.min($.offsetHeight||200,300);let ve=Math.min(Math.max(8,L.left),window.innerWidth-K-8),le=L.bottom+6;le+oe>window.innerHeight-8&&(le=Math.max(8,L.top-oe-6)),u.value={left:`${ve}px`,top:`${le}px`}}Ke(()=>ts.visible,async I=>{I&&(r.value=0,x(),await ft(),O(),l.value&&FT(l.value))});const G=I=>{l.value&&!l.value.contains(I.target)&&Nl()},Z=I=>{I.key==="Escape"&&Nl()},q=()=>Nl(),V=()=>Nl();return dn(()=>{document.addEventListener("click",G,!0),document.addEventListener("keydown",Z),window.addEventListener("scroll",q,!0),window.addEventListener("resize",V)}),Rn(()=>{document.removeEventListener("click",G,!0),document.removeEventListener("keydown",Z),window.removeEventListener("scroll",q,!0),window.removeEventListener("resize",V)}),(I,$)=>(F(),Ft(Tf,{to:"body"},[Ne(ts).visible?(F(),U("div",{key:0,ref_key:"popoverEl",ref:l,class:"citation-popover",style:qe(u.value),onMouseenter:$[8]||($[8]=(...L)=>Ne(px)&&Ne(px)(...L)),onMouseleave:$[9]||($[9]=(...L)=>Ne(mx)&&Ne(mx)(...L)),onClick:$[10]||($[10]=De(()=>{},["stop"]))},[i.value?(F(),U(Ie,{key:0},[M("div",{class:Ce(["pop-header",{clickable:h(i.value)&&d.value}]),onClick:$[0]||($[0]=L=>D(i.value))},[M("span",{class:"pop-icon",innerHTML:_(i.value)},null,8,Lle),M("span",Ole,Q(b(i.value)),1)],2),M("div",Dle,[M("div",Nle,[M("div",$le,[M("div",Ble,Q(i.value.title||i.value.file_name||""),1),k(i.value)?(F(),U("span",Fle,Q(k(i.value)),1)):me("",!0)]),i.value.url?(F(),U("div",Hle,Q(i.value.url),1)):me("",!0),g(i.value)?(F(),U("div",Ule,[M("img",{src:v(i.value),alt:i.value.file_name||"",loading:"lazy",onClick:$[1]||($[1]=De(L=>m(i.value),["stop"]))},null,8,Wle)])):C(i.value)?(F(),U("div",zle,"“"+Q(C(i.value))+"”",1)):me("",!0)])]),c.value?(F(),U("div",jle,[!h(i.value)&&i.value.url?(F(),U("a",{key:0,class:"pop-open",href:i.value.url,target:"_blank",rel:"noopener"},Q(Ne(S)("chat.citationOpenSource"))+" ↗",9,Vle)):h(i.value)&&s.hostMode?(F(),U("span",{key:1,class:"pop-open",onClick:$[2]||($[2]=L=>N(i.value))},Q(Ne(S)("quickdock.menuRevealInManager")),1)):me("",!0)])):me("",!0)],64)):(F(),U(Ie,{key:1},[M("div",{class:Ce(["pop-header",{clickable:o.value&&h(o.value)&&d.value}]),onClick:$[5]||($[5]=L=>D(o.value))},[M("span",{class:"pop-icon",innerHTML:_(o.value)},null,8,Gle),M("span",Kle,Q(b(o.value)),1),M("span",qle,[M("button",{type:"button",class:"pop-pager-btn",disabled:r.value<=0,"aria-label":Ne(S)("chat.citationPrev"),onClick:$[3]||($[3]=De(L=>a(-1),["stop"]))},[...$[11]||($[11]=[M("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true"},[M("path",{d:"m15 6-6 6 6 6"})],-1)])],8,Qle),M("span",Xle,Q(r.value+1)+"/"+Q(Ne(ts).annotations.length),1),M("button",{type:"button",class:"pop-pager-btn",disabled:r.value>=Ne(ts).annotations.length-1,"aria-label":Ne(S)("chat.citationNext"),onClick:$[4]||($[4]=De(L=>a(1),["stop"]))},[...$[12]||($[12]=[M("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round","aria-hidden":"true"},[M("path",{d:"m9 6 6 6-6 6"})],-1)])],8,Yle)])],2),M("div",Jle,[M("div",Zle,[M("div",ece,[M("div",tce,Q(o.value.title||o.value.file_name||""),1),k(o.value)?(F(),U("span",sce,Q(k(o.value)),1)):me("",!0)]),o.value.url?(F(),U("div",nce,Q(o.value.url),1)):me("",!0),g(o.value)?(F(),U("div",ice,[M("img",{src:v(o.value),alt:o.value.file_name||"",loading:"lazy",onClick:$[6]||($[6]=De(L=>m(o.value),["stop"]))},null,8,rce)])):C(o.value)?(F(),U("div",oce,"“"+Q(C(o.value))+"”",1)):me("",!0)])]),c.value?(F(),U("div",ace,[!h(o.value)&&o.value.url?(F(),U("a",{key:0,class:"pop-open",href:o.value.url,target:"_blank",rel:"noopener"},Q(Ne(S)("chat.citationOpenSource"))+" ↗",9,lce)):h(o.value)&&s.hostMode?(F(),U("span",{key:1,class:"pop-open",onClick:$[7]||($[7]=L=>N(o.value))},Q(Ne(S)("quickdock.menuRevealInManager")),1)):me("",!0)])):me("",!0)],64))],36)):me("",!0)]))}}),dce=qt(uce,[["__scopeId","data-v-0a060838"]]),hce={key:0,class:"drag-upload-overlay"},fce={class:"drag-upload-content"},pce={class:"drag-upload-text"},mce={class:"drag-upload-hint"},gce={key:0,class:"app-loading-state"},vce={class:"loading-copy"},yce={class:"main-container"},bce={key:0,class:"conversation-ribbon",ref:"titleRibbon"},_ce=["disabled"],wce={class:"selector-label"},Sce={class:"selector-model"},kce={class:"selector-mode"},Cce={class:"conversation-ribbon__text"},Tce={key:0,class:"model-mode-dropdown",ref:"headerMenu"},Ace={class:"dropdown-column","data-tutorial":"header-model-options"},Ece={class:"dropdown-title"},Mce={class:"dropdown-list dropdown-list--models"},xce=["onClick","disabled"],Rce={class:"item-label"},Ice={class:"item-desc"},Pce={key:0,class:"item-check"},Lce={class:"dropdown-column","data-tutorial":"header-runmode-options"},Oce={class:"dropdown-title"},Dce=["onClick","disabled"],Nce={class:"item-label"},$ce={class:"item-desc"},Bce={key:0,class:"item-check"},Fce={key:0,class:"dropdown-effort"},Hce={key:2,class:"blank-hero-overlay"},Uce={class:"blank-hero-text"},Wce={key:0,class:"scroll-lock-toggle"},zce={key:2,class:"qd-toggle-anchor"},jce=["aria-label","aria-pressed"],Vce={class:"right-panels__slot"},Gce={class:"right-panels__slot"},Kce={key:0,class:"desktop-approval-overlay"},qce={class:"mobile-panel-topbar"},Qce=["aria-label"],Xce=["src"],Yce=["disabled"],Jce={class:"mobile-selector-label"},Zce={class:"mobile-selector-model"},eue={class:"mobile-selector-mode"},tue=["title"],sue={key:0,class:"mobile-panel-menu mobile-panel-menu--dropdown"},nue=["aria-label"],iue={class:"item-label"},rue=["aria-label"],oue=["src"],aue={class:"item-label"},lue=["aria-label"],cue=["src"],uue={class:"item-label"},due=["aria-label"],hue=["src"],fue={class:"item-label"},pue={key:0,class:"model-mode-dropdown model-mode-dropdown--mobile",ref:"headerMenu"},mue={class:"dropdown-column","data-tutorial":"header-model-options"},gue={class:"dropdown-title"},vue={class:"dropdown-list dropdown-list--models"},yue=["onClick","disabled"],bue={class:"item-label"},_ue={key:0,class:"item-check"},wue={class:"dropdown-column","data-tutorial":"header-runmode-options"},Sue={class:"dropdown-title"},kue=["onClick","disabled"],Cue={class:"item-label"},Tue={key:0,class:"item-check"},Aue={key:0,class:"dropdown-effort"},Eue={class:"mobile-panel-sheet mobile-panel-sheet--conversation"},Mue={class:"mobile-panel-sheet mobile-panel-sheet--approval"},xue=ct({...zB,__name:"App",setup(s){const e=rr(()=>St(()=>import("./VirtualMonitorSurface.js"),__vite__mapDeps([29,1,3,5,2,4]))),t=rr(()=>St(()=>import("./PathAuthorizationDialog.js"),__vite__mapDeps([30,1,2,3,4,31]))),n=_E(),i=Js(),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 d;if(typeof window>"u")return!1;const l=new URLSearchParams(window.location.search),u=((d=window.navigator)==null?void 0:d.userAgent)||"";return l.has("app_shell")||!!(window!=null&&window.AndroidThemeBridge)||/;\s*wv\)/i.test(u)},a=ge(o());dn(()=>{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 d=Hs("ConversationSidebar"),h=Hs("TokenDrawer"),p=Hs("EffortSlider"),g=Hs("ChatArea"),v=Hs("StatusAvatar"),m=Hs("InputComposer"),y=Hs("TerminalPanel"),_=Hs("GitChangesPanel"),b=Hs("ToolApprovalPanel"),k=Hs("PersonalizationDrawer"),w=Hs("ImagePicker"),T=Hs("ConversationReviewDialog"),A=Hs("SubAgentActivityDialog"),C=Hs("BackgroundCommandDialog"),E=Hs("GoalProgressDialog"),x=Hs("UserQuestionDialog"),D=Hs("PlanApprovalDialog"),N=Hs("SandboxSetupDialog"),O=Hs("VersioningDialog"),G=Hs("TutorialOverlay"),Z=Hs("NewUserTutorialPrompt"),q=Hs("WorkflowDemoShell"),V=Hs("AppShell");return F(),Ft(V,{"download-file":l.downloadFile,"download-folder":l.downloadFolder},{default:Gt(()=>{var I,$;return[We(gs,{name:"drag-overlay-fade"},{default:Gt(()=>[l.dragOverActive?(F(),U("div",hce,[M("div",fce,[u[27]||(u[27]=M("div",{class:"drag-upload-icon"},[M("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor","stroke-width":"1.5"},[M("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),M("polyline",{points:"17 8 12 3 7 8"}),M("line",{x1:"12",y1:"3",x2:"12",y2:"15"})])],-1)),M("div",pce,Q(l.$t("appCore.dragUploadText")),1),M("div",mce,Q(l.$t("appCore.dragUploadHint")),1)])])):me("",!0)]),_:1}),!l.isConnected&&l.messages.length===0?(F(),U("div",gce,[u[28]||(u[28]=M("div",{class:"loading-animation","aria-hidden":"true"},[M("div",{class:"boxes"},[M("div",{class:"box"},[M("div"),M("div"),M("div"),M("div")]),M("div",{class:"box"},[M("div"),M("div"),M("div"),M("div")]),M("div",{class:"box"},[M("div"),M("div"),M("div"),M("div")]),M("div",{class:"box"},[M("div"),M("div"),M("div"),M("div")])])],-1)),M("div",vce,[M("h2",null,Q(l.$t("common.loading")),1),M("p",null,Q(l.$t("appCore.connectingServer")),1),M("button",{type:"button",class:"loading-refresh-btn",onClick:u[0]||(u[0]=(...L)=>l.refreshCurrentPage&&l.refreshCurrentPage(...L))},Q(l.$t("appCore.refreshPage")),1)])])):(F(),U(Ie,{key:1},[M("div",yce,[l.isMobileViewport?me("",!0):(F(),Ft(d,{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":($=(I=Ne(i))==null?void 0:I.form)==null?void 0:$.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"])),M("main",{class:Ce(["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:qe(l.chatContainerStyle)},[We(h,{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(),U("div",bce,[u[31]||(u[31]=M("div",{class:"conversation-ribbon__blur","aria-hidden":"true"},null,-1)),M("button",{type:"button",class:Ce(["conversation-ribbon__selector",{open:l.headerMenuOpen}]),"data-tutorial":"header-model-selector",onClick:u[1]||(u[1]=De((...L)=>l.toggleHeaderMenu&&l.toggleHeaderMenu(...L),["stop"])),disabled:!l.isConnected},[M("span",wce,[M("span",Sce,Q(l.currentModelLabel),1),u[29]||(u[29]=M("span",{class:"selector-sep"},"·",-1)),M("span",kce,Q(l.headerRunModeLabel),1)]),u[30]||(u[30]=M("svg",{viewBox:"0 0 24 24","aria-hidden":"true",class:"selector-caret"},[M("path",{d:"M7 10l5 5 5-5",fill:"none",stroke:"currentColor","stroke-width":"1.8","stroke-linecap":"round","stroke-linejoin":"round"})],-1))],10,_ce),M("span",Cce,Q(l.titleTypingText||l.currentConversationTitle),1),We(gs,{name:"header-menu"},{default:Gt(()=>[l.headerMenuOpen?(F(),U("div",Tce,[M("div",Ace,[M("div",Ece,Q(l.$t("appCore.model")),1),M("div",Mce,[(F(!0),U(Ie,null,Ze(l.modelOptions,L=>(F(),U("button",{key:L.key,type:"button",class:Ce(["dropdown-item",{active:L.key===l.currentModelKey,disabled:L.disabled}]),onClick:De(K=>l.handleHeaderModelSelect(L.key,L.disabled),["stop"]),disabled:l.streamingMessage||!l.isConnected||L.disabled},[M("div",Rce,Q(L.label),1),M("div",Ice,Q(L.description),1),L.key===l.currentModelKey?(F(),U("span",Pce,"✓")):me("",!0)],10,xce))),128))])]),M("div",Lce,[M("div",Oce,Q(l.$t("appCore.runMode")),1),(F(!0),U(Ie,null,Ze(l.headerRunModeOptions,L=>(F(),U("button",{key:L.value,type:"button",class:Ce(["dropdown-item",{active:L.value===l.resolvedRunMode}]),onClick:De(K=>l.handleHeaderRunModeSelect(L.value),["stop"]),disabled:l.streamingMessage||!l.isConnected},[M("div",Nce,Q(L.label),1),M("div",$ce,Q(L.desc),1),L.value===l.resolvedRunMode?(F(),U("span",Bce,"✓")):me("",!0)],10,Dce))),128)),l.showEffortSlider?(F(),U("div",Fce,[We(p,{"model-value":l.reasoningEffort,"onUpdate:modelValue":l.setReasoningEffort},null,8,["model-value","onUpdate:modelValue"])])):me("",!0)])],512)):me("",!0)]),_:1})],512)):me("",!0),Ov(We(g,{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"]),[[cF,l.chatDisplayMode==="chat"]]),l.chatDisplayMode==="monitor"?(F(),Ft(Ne(e),{key:1})):me("",!0),l.blankHeroActive?(F(),U("div",Hce,[l.showStatusAvatar?(F(),Ft(v,{key:0,mode:"idle",size:58,tracking:""})):me("",!0),M("p",Uce,Q(l.blankWelcomeText),1)])):me("",!0),We(gs,{name:"scroll-to-bottom-fade"},{default:Gt(()=>[l.showScrollToBottomButton?(F(),U("div",Wce,[M("button",{onClick:u[2]||(u[2]=(...L)=>l.toggleScrollLock&&l.toggleScrollLock(...L)),class:"scroll-lock-btn"},[...u[32]||(u[32]=[M("svg",{viewBox:"0 0 24 24","aria-hidden":"true","stroke-linecap":"round","stroke-linejoin":"round"},[M("path",{d:"M12 5v12"}),M("path",{d:"M7 13l5 5 5-5"})],-1)])])])):me("",!0)]),_:1}),M("div",{class:Ce(["composer-container",{"blank-hero-mode":l.composerHeroActive}])},[We(m,{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,"plan-approval-minimized":l.planApprovalMinimized,"pending-plan-approval-count":l.pendingPlanApprovals.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,onRestorePlanApproval:l.restorePlanApprovalDialog,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]=L=>l.handleTokenPanelToggleClick(L)),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]=L=>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","plan-approval-minimized","pending-plan-approval-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","onRestorePlanApproval","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?me("",!0):(F(),Ft(gle,{key:1,"host-mode":l.versioningHostMode},null,8,["host-mode"])),l.isMobileViewport?me("",!0):(F(),U("div",zce,[M("button",{type:"button",class:"qd-toggle","aria-label":l.qdExpanded?l.$t("appCore.collapseQuickDock"):l.$t("appCore.expandQuickDock"),"aria-pressed":l.qdExpanded,onClick:u[5]||(u[5]=L=>l.qdUserCollapsed=!l.qdUserCollapsed)},[...u[33]||(u[33]=[M("svg",{viewBox:"0 0 18 18",width:"16",height:"16","aria-hidden":"true"},[M("line",{x1:"2",y1:"3.5",x2:"16",y2:"3.5"}),M("line",{x1:"2",y1:"7.5",x2:"10",y2:"7.5"}),M("line",{x1:"2",y1:"11.5",x2:"14",y2:"11.5"}),M("line",{x1:"2",y1:"15.5",x2:"7",y2:"15.5"})],-1)])],8,jce)])),l.isMobileViewport?me("",!0):(F(),Ft(Ple,{key:3})),We(dce,{"host-mode":l.versioningHostMode},null,8,["host-mode"]),!l.isMobileViewport&&(l.terminalPanelOpen||l.gitChangesPanelOpen)?(F(),U("div",{key:4,class:"resize-handle resize-handle--right-panels",onMousedown:u[6]||(u[6]=L=>l.startResize("right",L))},null,32)):me("",!0),We(gs,{name:"right-panels-slide"},{default:Gt(()=>[!l.isMobileViewport&&(l.terminalPanelOpen||l.gitChangesPanelOpen)?(F(),U("div",{key:0,class:"right-panels",style:qe(l.rightPanelsStyle)},[M("div",Vce,[We(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(),U("div",{key:0,class:"right-panels__split-handle",onMousedown:u[7]||(u[7]=(...L)=>l.startRightSplitResize&&l.startRightSplitResize(...L))},null,32)):me("",!0),M("div",Gce,[We(_,{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)):me("",!0)]),_:1})]),We(gs,{name:"desktop-approval-fade"},{default:Gt(()=>[!l.isMobileViewport&&!l.rightCollapsed?(F(),U("div",Kce,[M("div",{class:"desktop-approval-sheet",style:qe({width:Math.min(l.rightWidth||420,520)+"px"})},[We(b,{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]=L=>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)])):me("",!0)]),_:1}),We(k),We(Ne(t),{open:l.pathAuthorizationDialogOpen,value:l.pathAuthorizationDraft,mode:l.pathAuthorizationMode,saving:l.pathAuthorizationSaving,"onUpdate:value":u[9]||(u[9]=L=>l.pathAuthorizationDraft=L),"onUpdate:mode":l.setPathAuthorizationMode,onClose:l.closePathAuthorizationDialog,onSave:l.savePathAuthorization},null,8,["open","value","mode","saving","onUpdate:mode","onClose","onSave"]),We(gs,{name:"overlay-fade"},{default:Gt(()=>[l.imagePickerOpen?(F(),Ft(w,{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"])):me("",!0)]),_:1}),We(gs,{name:"overlay-fade"},{default:Gt(()=>[l.videoPickerOpen?(F(),Ft(pae,{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"])):me("",!0)]),_:1}),We(bae),We(gs,{name:"overlay-fade"},{default:Gt(()=>[l.reviewDialogOpen?(F(),Ft(T,{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]=L=>l.reviewDialogOpen=!1),onSelect:l.handleReviewSelect,onLoadMore:l.loadMoreReviewConversations,onToggleSend:u[11]||(u[11]=L=>l.reviewSendToModel=L),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"])):me("",!0)]),_:1}),We(A),We(C),We(E,{open:l.goalDialogOpen,progress:l.goalProgress,onClose:u[12]||(u[12]=L=>l.goalDialogOpen=!1)},null,8,["open","progress"]),We(x,{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]=L=>l.userQuestionActiveIndex=L),onSubmit:l.submitUserQuestionAnswers,onDismiss:l.dismissUserQuestions},null,8,["visible","questions","active-index","submitting-ids","onMinimize","onSubmit","onDismiss"]),We(D,{visible:l.pendingPlanApprovals.length>0&&!l.planApprovalMinimized,approvals:l.pendingPlanApprovals,"submitting-ids":l.answeringPlanApprovalIds,onSubmit:l.submitPlanApproval,onMinimize:l.minimizePlanApprovalDialog},null,8,["visible","approvals","submitting-ids","onSubmit","onMinimize"]),We(N),We(gs,{name:"overlay-fade"},{default:Gt(()=>[l.versioningDialogOpen?(F(),Ft(O,{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]=L=>l.versioningDialogOpen=!1),onRefresh:l.refreshVersioningDialog,onToggleEnabled:l.toggleConversationVersioning,onSelect:l.selectVersioningCheckpoint,"onUpdate:restoreMode":u[15]||(u[15]=L=>l.versioningRestoreMode=L),"onUpdate:trackingMode":u[16]||(u[16]=L=>l.versioningTrackingMode=L),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"])):me("",!0)]),_:1}),Ne(n).running?(F(),Ft(G,{key:0})):me("",!0),We(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(),U("div",{key:1,class:Ce(["mobile-panel-trigger",{"is-hidden":!!l.activeMobileOverlay}]),ref:"mobilePanelTrigger"},[M("div",qce,[u[35]||(u[35]=M("div",{class:"mobile-panel-topbar__blur","aria-hidden":"true"},null,-1)),M("button",{type:"button",class:"mobile-panel-fab","data-tutorial":"mobile-menu-trigger","aria-label":l.$t("appCore.switchWorkspace"),onClick:u[17]||(u[17]=(...L)=>l.toggleMobileOverlayMenu&&l.toggleMobileOverlayMenu(...L))},[M("img",{src:Ne(r),alt:"","aria-hidden":"true"},null,8,Xce)],8,Qce),M("button",{type:"button",class:Ce(["mobile-topbar-selector",{open:l.headerMenuOpen}]),"data-tutorial":"header-model-selector-mobile",onClick:u[18]||(u[18]=De((...L)=>l.toggleHeaderMenu&&l.toggleHeaderMenu(...L),["stop"])),disabled:!l.isConnected},[M("span",Jce,[M("span",Zce,Q(l.currentModelLabel),1),u[34]||(u[34]=M("span",{class:"mobile-selector-sep"},"·",-1)),M("span",eue,Q(l.headerRunModeLabel),1)])],10,Yce),M("div",{class:"mobile-topbar-title",title:l.currentConversationTitle||l.$t("overlay.unnamedConversation")},Q(l.currentConversationTitle||l.$t("overlay.unnamedConversation")),9,tue)]),We(gs,{name:"mobile-panel-menu"},{default:Gt(()=>[l.mobileOverlayMenuOpen?(F(),U("div",sue,[M("button",{type:"button",class:"dropdown-item mobile-menu-item","data-tutorial":"mobile-menu-conversation","aria-label":l.$t("appCore.conversationHistory"),onClick:u[19]||(u[19]=L=>l.openMobileOverlay("conversation"))},[u[36]||(u[36]=M("svg",{class:"mobile-menu-icon",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true"},[M("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"}),M("path",{d:"M8 8.5h8",stroke:"currentColor","stroke-width":"1.7","stroke-linecap":"round"}),M("path",{d:"M8 11.5h5",stroke:"currentColor","stroke-width":"1.7","stroke-linecap":"round"})],-1)),M("div",iue,Q(l.$t("appCore.conversationHistory")),1)],8,nue),M("button",{type:"button",class:"dropdown-item mobile-menu-item mobile-menu-item--personal","data-tutorial":"mobile-menu-personal","aria-label":l.$t("appCore.personalSpace"),onClick:u[20]||(u[20]=(...L)=>l.handleMobilePersonalClick&&l.handleMobilePersonalClick(...L))},[M("img",{class:"mobile-menu-icon",src:c.personal,alt:"","aria-hidden":"true"},null,8,oue),M("div",aue,Q(l.$t("appCore.personalSpace")),1)],8,rue),M("button",{type:"button",class:"dropdown-item mobile-menu-item","data-tutorial":"mobile-menu-new-chat","aria-label":l.$t("common.newConversation"),onClick:u[21]||(u[21]=(...L)=>l.createNewConversation&&l.createNewConversation(...L))},[M("img",{class:"mobile-menu-icon",src:c.newChat,alt:"","aria-hidden":"true"},null,8,cue),M("div",uue,Q(l.$t("common.newConversation")),1)],8,lue),a.value?(F(),U("button",{key:0,type:"button",class:"dropdown-item mobile-menu-item mobile-menu-item--refresh","aria-label":l.$t("appCore.refreshPage"),onClick:u[22]||(u[22]=(...L)=>l.handleMobileRefreshClick&&l.handleMobileRefreshClick(...L))},[M("img",{class:"mobile-menu-icon",src:c.refresh,alt:"","aria-hidden":"true"},null,8,hue),M("div",fue,Q(l.$t("appCore.refreshPage")),1)],8,due)):me("",!0)])):me("",!0)]),_:1}),We(gs,{name:"header-menu"},{default:Gt(()=>[l.headerMenuOpen&&l.isMobileViewport?(F(),U("div",pue,[M("div",mue,[M("div",gue,Q(l.$t("appCore.model")),1),M("div",vue,[(F(!0),U(Ie,null,Ze(l.modelOptions,L=>(F(),U("button",{key:L.key,type:"button",class:Ce(["dropdown-item",{active:L.key===l.currentModelKey,disabled:L.disabled}]),onClick:De(K=>l.handleHeaderModelSelect(L.key,L.disabled),["stop"]),disabled:l.streamingMessage||!l.isConnected||L.disabled},[M("div",bue,Q(L.label),1),L.key===l.currentModelKey?(F(),U("span",_ue,"✓")):me("",!0)],10,yue))),128))])]),M("div",wue,[M("div",Sue,Q(l.$t("appCore.runMode")),1),(F(!0),U(Ie,null,Ze(l.headerRunModeOptions,L=>(F(),U("button",{key:L.value,type:"button",class:Ce(["dropdown-item",{active:L.value===l.resolvedRunMode}]),onClick:De(K=>l.handleHeaderRunModeSelect(L.value),["stop"]),disabled:l.streamingMessage||!l.isConnected},[M("div",Cue,Q(L.label),1),L.value===l.resolvedRunMode?(F(),U("span",Tue,"✓")):me("",!0)],10,kue))),128)),l.showEffortSlider?(F(),U("div",Aue,[We(p,{"model-value":l.reasoningEffort,"onUpdate:modelValue":l.setReasoningEffort},null,8,["model-value","onUpdate:modelValue"])])):me("",!0)])],512)):me("",!0)]),_:1})],2)):me("",!0),We(gs,{name:"mobile-panel-overlay"},{default:Gt(()=>{var L,K;return[l.isMobileViewport&&l.activeMobileOverlay==="conversation"?(F(),U("div",{key:0,class:"mobile-panel-overlay mobile-panel-overlay--left",onClick:u[24]||(u[24]=De((...se)=>l.closeMobileOverlay&&l.closeMobileOverlay(...se),["self"]))},[M("div",Eue,[We(d,{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":(K=(L=Ne(i))==null?void 0:L.form)==null?void 0:K.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]=se=>l.handleMobileOverlaySelect(se)),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"])])])):me("",!0)]}),_:1}),We(gs,{name:"mobile-panel-overlay"},{default:Gt(()=>[l.isMobileViewport&&l.activeMobileOverlay==="approval"?(F(),U("div",{key:0,class:"mobile-panel-overlay mobile-panel-overlay--right mobile-approval-overlay",onClick:u[26]||(u[26]=De(L=>l.closeMobileOverlay("backdrop-click"),["self"]))},[M("div",Mue,[We(b,{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]=L=>l.closeMobileOverlay("approval-panel-close-btn"))},null,8,["width","approvals","deciding-approval-ids","auto-approval-feed-lines","auto-approval-final-message","onSwitchUnrestricted","onApprove","onReject"])])])):me("",!0)]),_:1}),l.workflowDemoRoute?(F(),Ft(q,{key:2,"route-path":l.workflowDemoRoute},null,8,["route-path"])):me("",!0)],64))]}),_:1},8,["download-file","download-folder"])}}}),jB="agents_ui_theme",wE=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)},SE=()=>{if(typeof window>"u")return"classic";const s=window.localStorage.getItem(jB);return s==="light"||s==="dark"||s==="classic"?s:"classic"},Rue=s=>{typeof window>"u"||window.localStorage.setItem(jB,s)},Iue=()=>{const s=SE();wE(s)},Que=()=>{const s=t=>{wE(t),Rue(t)},e=()=>wE(SE());return dn(()=>{e()}),{setTheme:s,restore:e,loadTheme:SE}},HM=GP(xue),Pue=bF();HM.use(Pue);uF(HM);Iue();HM.mount("#app");export{zg as M,ete as a,Js as b,tL as c,Is as d,_E as e,zo as f,ix as g,er as h,Que as i,gre as j,dd as k,vg as l,xi as s,pL as u};
|