@reviseio/engine 0.0.0-stage → 3.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +21 -0
- package/FONT-LICENSE-HAN-EXT-B.txt +91 -0
- package/FONT-LICENSE-KATEX.txt +95 -0
- package/FONT-LICENSE-LIBERATION.txt +102 -0
- package/FONT-LICENSE-NOTO-MULTILINGUAL.txt +93 -0
- package/FONT-LICENSE-NOTO-SANS-SC.txt +93 -0
- package/FONT-LICENSE-NOTO.txt +94 -0
- package/FONT-LICENSE-SOURCE-CODE-PRO.txt +94 -0
- package/FONT-LICENSE-SOURCE-SERIF-4.txt +93 -0
- package/LICENSE +141 -0
- package/README.md +11 -2
- package/THIRD-PARTY-NOTICES.md +3376 -0
- package/assets/historyMaterializeWorker-Kl0syEbc.js +618 -0
- package/chunks/AgentHtmlConverter-CnnB8-WI.js +379 -0
- package/chunks/AgentPageRenderViews-BTLjPZJQ.js +2 -0
- package/chunks/AgentPageRenderer-DLgUGrGy.js +180 -0
- package/chunks/BidiText-Bkp4Y90s.js +160 -0
- package/chunks/BlockDiff-B6-aJxHo.js +42 -0
- package/chunks/CanvasRenderer-C1Vegx9Y.js +110 -0
- package/chunks/ColorParserFull-BKH72fK8.js +446 -0
- package/chunks/DocumentCompare-C8295s35.js +6 -0
- package/chunks/DocumentLayout-CsU5MR-3.js +12 -0
- package/chunks/DocumentLayoutEngine-C62pyGVf.js +218 -0
- package/chunks/DocumentMutator-Bat_oLBQ.js +13 -0
- package/chunks/DocumentScrubber-BZQn_z92.js +21 -0
- package/chunks/DocumentSession-BDcazSEv.js +1 -0
- package/chunks/DocumentStylesheet-CEEt18sr.js +7 -0
- package/chunks/DocxConverter-BC31uYIL.js +1236 -0
- package/chunks/DocxGraft-L10HXM3U.js +8 -0
- package/chunks/HorizontalRuleOrnaments-gmUZ3R7Q.js +3 -0
- package/chunks/HtmlConverter-C5ihhZ6G.js +267 -0
- package/chunks/ListNumbering-Qlu6AuRZ.js +23 -0
- package/chunks/MarkdownConverter-DofaSeC4.js +57 -0
- package/chunks/MathRenderer-Bz9WEVvF.js +68 -0
- package/chunks/OdtConverter-c1fTWoAt.js +125 -0
- package/chunks/OfficeImportShared-CrOpHpJ-.js +30 -0
- package/chunks/PageNumeralFonts-BWzI061X.js +5 -0
- package/chunks/ParagraphDiffAnalysis-DrmStvmz.js +36 -0
- package/chunks/PdfConverter-DX7fsRH5.js +457 -0
- package/chunks/RtfConverter-hbJ2529G.js +186 -0
- package/chunks/TableBorders-DVhdvo6f.js +32 -0
- package/chunks/TableGrid-DbroRucl.js +12 -0
- package/chunks/TextDecoding-IPbuUqcC.js +2 -0
- package/chunks/TextFileDecoder-BZBBejlR.js +10 -0
- package/chunks/TxtConverter-YHv5FXWb.js +14 -0
- package/chunks/Typography-B4gndEdB.js +28 -0
- package/chunks/UnicodeUtils-CXtusU4g.js +10 -0
- package/chunks/XmlConverter-BRRluy9k.js +55 -0
- package/chunks/_commonjsHelpers-DaMA6jEr.js +2 -0
- package/chunks/_revise-sdk-lazy-harfbuzz-CDWdjF9f.js +1 -0
- package/chunks/base64-Di1bxoXD.js +1 -0
- package/chunks/browser-module-CFmqfGkE.js +1791 -0
- package/chunks/bundle.min-DRpfgV69.js +782 -0
- package/chunks/capture-i_dPkQIS.js +11 -0
- package/chunks/carrier-pYM9xf6x.js +6 -0
- package/chunks/chromeImageLayout-BiQ3Iz1-.js +18 -0
- package/chunks/engine-LMUnxdm2.js +520 -0
- package/chunks/footnoteFlatten-EE85Hjre.js +6 -0
- package/chunks/graftExport-G-dG7Vcc.js +104 -0
- package/chunks/html2canvas.esm-CntiHiYW.js +997 -0
- package/chunks/index-BLb10wQt.js +1002 -0
- package/chunks/index-BWdRWxoH.js +1807 -0
- package/chunks/index.es-CI0QPo8w.js +780 -0
- package/chunks/jspdf.es.min-DU74zN8b.js +1792 -0
- package/chunks/jszip.min-CPW0h1Kx.js +476 -0
- package/chunks/katex-DWj8TvwO.js +1462 -0
- package/chunks/pdf-BLWDCiFF.js +1828 -0
- package/chunks/purify.es-BwLardii.js +107 -0
- package/chunks/serverDocumentSession-DGDU5Lh3.js +1011 -0
- package/chunks/signatures-DTNDS2PH.js +21 -0
- package/chunks/suggestionAuthorship-B-IuLQlE.js +1 -0
- package/chunks/web-tree-sitter-BXGZGnNj.js +2 -0
- package/chunks/xmlScan-DXjt2cTS.js +8 -0
- package/engine.d.ts +179 -0
- package/engine.js +3 -0
- package/package.json +64 -4
- package/serverToolContract.d.ts +420 -0
- package/serverToolInputs.generated.d.ts +264 -0
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import{n as hl,q as us,r as Ae,P as Gt,s as Po,u as In,v as hs,w as fl,y as mt,x as It,D as fs,z as pl,A as et,a as G,B as ml,C as rt,E as ot,F as st,G as lt,H as de,I as Z,J as We,K as at,L as ct,M as ps,N as Jt,O as Ht,Q as bl,R as ms,e as bs,S as yl,T as ys,U as qt,V as Je,W as ks,X as kl,Y as Sl,Z as Il,_ as vn,$ as xn,a0 as vl,a1 as xl,a2 as wl,a3 as Qt,a4 as Al,a5 as Ss,a6 as Is,a7 as vs,a8 as xs,a9 as Tl,aa as ws,ab as Cl,ac as Pl,ad as As,g as gt,ae as Mo,af as ge,ag as Te,ah as wn,ai as Ce,aj as Bo,ak as An,al as Tn,am as Ml,an as Zt,ao as Bl,b as El,d as Eo,ap as Ts,aq as Cs,f as Ps,ar as Ms,as as Nl,i as Ll,at as Fl,au as Ol,av as No,aw as Rl,ax as Dl,ay as $l,az as jl,aA as Yt,aB as _l,aC as Lo,aD as Xl,aE as Ul,aF as zl,aG as Bs,aH as Wl,aI as Jl,aJ as Hl,aK as ql,aL as Yl,aM as Kl,aN as Es}from"./engine-LMUnxdm2.js";import{f as W,h as Cn,t as He,k as Ct,a as xt,i as Xt,l as Ns,m as Fo,n as Oo,g as ue,o as Ls,c as Pe,p as Ro,q as Vl,r as Gl,s as Ql}from"./CanvasRenderer-C1Vegx9Y.js";import{d as Do,S as St,f as Pn,b as Fs,c as qe,A as it,e as Zl,m as $o,g as tc,h as Me,i as ec,n as nc,j as Be,s as Os,k as jo,l as oc,o as rc}from"./AgentHtmlConverter-CnnB8-WI.js";import*as I from"yjs";import{b as Mn}from"./TableGrid-DbroRucl.js";import{j as Pt,i as Bn}from"./signatures-DTNDS2PH.js";import{w as sc,r as ic,a as En}from"./ParagraphDiffAnalysis-DrmStvmz.js";import{MarkdownConverter as Nn}from"./MarkdownConverter-DofaSeC4.js";import{s as Ye,a as _o,b as Xo,c as Rs}from"./DocumentStylesheet-CEEt18sr.js";import{a as Ds,g as ac}from"./BidiText-Bkp4Y90s.js";import{C as $s,a as js,b as _s,H as Ln,h as Ke,n as lc}from"./Typography-B4gndEdB.js";import{a as Xs,s as Us,b as cc,n as zs}from"./TableBorders-DVhdvo6f.js";import{d as dc,a as te}from"./index-BLb10wQt.js";import{R as Nt,A as Ws}from"./suggestionAuthorship-B-IuLQlE.js";import{d as gc,p as uc}from"./chromeImageLayout-BiQ3Iz1-.js";function hc(s){const t=s.children.filter(e=>e.type==="text");return t.length===0?[{type:"text",text:""}]:t}function Fn(s){return hc(s).reduce((t,e)=>t+e.text.length,0)}function fc(s,t){const e=W(s,t);if(!e||!e.id)return null;if(e.type==="paragraph"){let n=0;for(const o of e.children)o.type==="text"&&(n+=o.text.length);return{block:e.id,offset:n}}if(e.type==="list"){const n=e;let o=0;for(let r=0;r<n.children.length;r++)o+=Fn(n.children[r]),r<n.children.length-1&&(o+=1);return{block:e.id,offset:o}}return{block:e.id,offset:0}}function kt(s){if(!s||typeof s!="object")return"";const t=s;if(t.type==="text"&&typeof t.text=="string")return t.text;if((t.type==="code"||t.type==="math")&&typeof t.content=="string")return t.content;if(Array.isArray(t.children)){const e=t.type==="list"?" ":"";return t.children.map(n=>kt(n)).join(e)}return""}const Js={P:"paragraph",LI:"list-item",TD:"table-cell",TH:"table-cell",TR:"table-row",TABLE:"table",UL:"list",OL:"list",H1:"paragraph",H2:"paragraph",H3:"paragraph",H4:"paragraph",H5:"paragraph",H6:"paragraph"};function Hs(s,t){if(!/<[^>]+\bid\s*=/i.test(t))return null;const e=kt(s);if(e.includes(t)||e.includes(Do(t)))return null;const n=document.createElement("template");n.innerHTML=t;const o=[...n.content.querySelectorAll("[id]")].filter(c=>Js[c.tagName]);if(!o.length)return null;const r=new Map,i=(c,d=null)=>{if(!c||typeof c!="object")return;const g=c;g.id&&(d?d.add(g.id):r.set(g.id,[...r.get(g.id)??[],g])),g.children?.forEach(u=>i(u,d))};i(s);const a=new Set,l=new Set;for(const c of o){const d=r.get(c.id)??[];if(a.has(c.id)||d.length!==1||d[0].type!==Js[c.tagName])throw new St("target_stale",`HTML matcher id '${c.id}' is missing, contradictory, or outside the authorized target. Read the target again.`,"target_resolution");a.add(c.id);const g=d[0],u=kt(g),f=c.textContent??"",h=Pn(u,f,"prefer-exact");if(u!==f&&!h.some(y=>y.start===0&&y.end===u.length))throw new St("target_stale",`HTML matcher text for '${c.id}' no longer matches that block. Read it again before editing.`,"matching");const p=new Set;i(g,p);const m=o.filter(y=>y!==c&&c.contains(y));if(m.some(y=>!p.has(y.id)))throw new St("target_stale",`HTML matcher ids contradict the document hierarchy inside '${c.id}'.`,"target_resolution");m.length||p.forEach(y=>l.add(y))}return l}function Ee(s,t){const e=W(s,t);return e?.type==="list"&&e.id!==t?e.children.find(n=>n.id===t)??null:e}function Uo(s){if(!(!s||s.type!=="paragraph"&&s.type!=="list-item"))return it.toAgentHtml({type:"doc",children:[{...s,type:"paragraph"}]})}function On(s,t,e="prefer-exact"){const n=Hs(s,t),o=Fs(kt(s),t,e,qe(t)?Uo(s):void 0);if(!n)return o;const r=qs(s);return o.filter(i=>{const a=r.filter(l=>l.start<i.end&&i.start<l.end);return a.length>0&&a.every(l=>n.has(l.blockId))})}function qs(s){const t=[];let e=0;const n=o=>{if(!o||typeof o!="object")return;const r=o,i=Array.isArray(r.children)?r.children:[],a=r.type==="list"||r.type==="table"||r.type==="table-row"||r.type==="table-cell"||r.type==="container";if(r.id&&!a){const l=kt(o);if(l.length>0){t.push({blockId:r.id,start:e,end:e+l.length,text:l}),e+=l.length;return}}i.forEach((l,c)=>{r.type==="list"&&c>0&&(e+=1),n(l)})};return n(s),t}function pc(s,t,e){const n=[];for(const o of s){const r=Math.max(t,o.start),i=Math.min(e,o.end);i<=r||n.push({blockId:o.blockId,start:r-o.start,end:i-o.start})}return n}function Ys(s){const t=new Map;let e=0;const n=o=>{if(!o||typeof o!="object")return;const r=o;if(r.type==="text"&&typeof r.text=="string"){const i=e;e+=r.text.length;for(const a of r.marks?.comment?.split(",")??[]){const l=a.trim();if(!l)continue;const c=t.get(l);t.set(l,{start:c?Math.min(c.start,i):i,end:c?Math.max(c.end,e):e})}return}if((r.type==="code"||r.type==="math")&&typeof r.content=="string"){e+=r.content.length;return}if(Array.isArray(r.children)){const i=r.type==="list"?1:0;r.children.forEach((a,l)=>{i&&l>0&&(e+=i),n(a)})}};return n(s),t}const Ks=300;function zo(s,t,e,n,o){const r=Ys(t);return(s.comments??[]).filter(i=>!i.parentId&&i.resolved!==!0).filter(i=>!o.has(i.id)).filter(i=>{if(i.anchorBlockId===e)return!0;const a=r.get(i.id);return a?n?n.start<a.end&&a.start<n.end:!0:!1}).map(i=>({id:i.id,author:i.agentName??i.author,bodyMd:i.bodyMd.length>Ks?`${i.bodyMd.slice(0,Ks)}…`:i.bodyMd}))}function Vs(s,t){const e=t.length===1?"thread":"threads";return{success:!1,overlappingThreadIds:t.map(n=>n.id),errorCode:"comment_overlap",error:`That text in block ${s} already carries ${t.length} unresolved comment ${e}: ${t.map(n=>`${n.id} (${n.author}): "${n.bodyMd}"`).join("; ")}. If your point is already covered there, do not repeat it: reply with reply_to_comment_id="${t[0].id}". If you are raising a genuinely different point, retry with acknowledge_existing_thread_ids=[${t.map(n=>`"${n.id}"`).join(", ")}].`}}function mc(s,t,e,n,o,r,i,a){const l=r&&typeof r=="object"?["text"in r,"start_text"in r||"end_text"in r,"whole_block"in r]:[],c=l.length>0&&("text"in r?typeof r.text=="string"&&r.text.length>0:"whole_block"in r?r.whole_block===!0:typeof r.start_text=="string"&&r.start_text.length>0&&typeof r.end_text=="string"&&r.end_text.length>0);if(l.filter(Boolean).length!==1||!c)return{success:!1,error:"Anchor must contain exactly one of: text, start_text/end_text, or whole_block=true.",errorCode:"invalid_anchor"};const d=new Set((a??[]).map(w=>w.trim()).filter(Boolean)),g=Ee(s,n);if(!g)return{success:!1,error:`Block ${n} not found`,errorCode:"target_missing"};if("whole_block"in r){const w=zo(s,g,n,null,d);if(w.length>0)return Vs(n,w);const A=e.addBlockComment(n,o,i);return A?{success:!0,commentId:A}:{success:!1,error:`Could not attach a comment to block ${n}`}}const u=Ee(t,n),f=kt(u??g);let h=-1,p=-1;const m="text"in r?On(u??g,r.text):Zl(f,r.start_text,r.end_text,Uo(u??g),(w,A)=>On(u??g,w,A));if(m.length!==1)return{success:!1,error:m.length?`Anchor text matched ${m.length} locations in block '${n}'. Provide unique text or an HTML fragment that identifies the formatting, such as <b>claim</b> for bold or <i>claim</i> for italic. Start/end boundary text is included in the comment range; do not use surrounding separators unless they should also be commented on.`:`Anchor text was not found in block '${n}'.`,errorCode:m.length?"anchor_ambiguous":"anchor_not_found"};({start:h,end:p}=m[0]);const y=qs(u??g),b=pc(y,h,p);if(b.length===0)return{success:!1,error:`The anchor range in block ${n} does not map to commentable text`};const k=[];for(const w of b){const A=Ee(t,w.blockId),P=Ee(s,w.blockId);if(!A||!P)return{success:!1,error:`The anchor range in block ${n} could not be mapped to its live text; read the block again and retry`};let T={start:w.start,end:w.end};if(kt(P)!==kt(A)){const E=e.mapAcceptedSuggestionRangeToLiveRange(w.blockId,w.start,w.end);if(!E)return{success:!1,error:`The anchor range in block ${n} could not be mapped across pending suggestions; read the block again and retry`};T=E}k.push({blockId:w.blockId,...T})}const S=new Map;for(const w of zo(s,g,n,{start:h,end:p},d))s.comments?.some(A=>A.id===w.id&&A.anchorBlockId===n)&&S.set(w.id,w);for(const w of k){const A=Ee(s,w.blockId);if(A)for(const P of zo(s,A,w.blockId,{start:w.start,end:w.end},d))S.set(P.id,P)}const v=Array.from(S.values());if(v.length>0)return Vs(n,v);const x=e.addCommentToRanges(k,o,i);return x?{success:!0,commentId:x,range:{start:h,end:p}}:{success:!1,error:`Could not attach a comment to block ${n}`}}function Gs(s,t){const e=s.comments??[];let n=e.find(r=>r.id===t);if(!n)return null;const o=new Set([n.id]);for(;n.parentId&&!o.has(n.parentId);){o.add(n.parentId);const r=e.find(i=>i.id===n.parentId);if(!r)break;n=r}return n}function bc(s,t,e,n,o){const r=Gs(s,e);if(!r)return{success:!1,error:`Comment ${e} not found`,errorCode:"target_not_found"};if(r.resolved)return{success:!1,error:`Comment thread ${r.id} is resolved; leave a new comment instead`,errorCode:"already_resolved"};const i=t.replyToComment(r.id,n,o);return i?{success:!0,commentId:i,threadId:r.id}:{success:!1,error:`Could not reply to comment ${e}`,errorCode:"comment_mutation_failed"}}function yc(s,t,e){const n=W(s.getDocument(),t),o=W(s.getDocumentWithAcceptedSuggestions(),t);if(!n||!o)throw new St("target_missing",`Footnote target '${t}' no longer exists. Read the document again.`,"target_resolution");if(n.type!=="paragraph"||o.type!=="paragraph")throw new St("target_unsupported","Footnote references require a paragraph target. Read the paragraph inside this block and use its id.","target_resolution");const r=e?On(o,e):[];if(e&&r.length!==1)throw new St(r.length?"anchor_ambiguous":"anchor_not_found",r.length?`Anchor text matched ${r.length} locations in block ${t}; include unique surrounding text.`:`Anchor text ${JSON.stringify(e)} not found in block ${t}. Read it again.`,"matching");let i=e?r[0].end:kt(o).length;if(kt(n)!==kt(o)){const a=kc(n,kt(o),i);if(a===null)throw new St("target_stale","Anchor could not be mapped across pending suggestions. Read the block again.","target_resolution");i=a}return{block:t,offset:i}}function kc(s,t,e){let n="",o=0,r=e===0?0:null;for(const i of s.children){if(i.type!=="text")return null;const a=i.text.length;i.marks?.deletion||(r===null&&n.length+a>=e&&(r=o+(e-n.length)),n+=i.text),o+=a}return n===t?r:null}function Wo(s,t){return{indentStepPx:Ae(t).indentStepPx,storedAsUnits:s.get(Gt.paragraphIndentStorageVersion)===Po}}const Qs=new WeakMap;function Jo(s){return s.getXmlFragment("content")}function Zs(s,t){let e=t,n=null;for(;e;){if(n=e.parent,n===s)return e instanceof I.XmlElement&&e.getAttribute("id")||null;e=n}return null}function Sc(s){const t=Jo(s),e={nestedBlocks:new WeakMap,doc:null,blockCache:new Map,elementByBlockId:new Map,dirtyBlockIds:new Set,structuralChange:!1,observer:()=>{}},n=o=>{for(const r of o){let i=r.target;for(;i&&i!==t;)i instanceof I.XmlElement&&e.nestedBlocks.delete(i),i=i.parent;if(r.target===t&&r instanceof I.YXmlEvent&&r.childListChanged){e.structuralChange=!0;continue}if(r instanceof I.YXmlEvent&&r.childListChanged){const l=Zs(t,r.target);l!==null&&e.dirtyBlockIds.add(l);continue}const a=Zs(t,r.target);a!==null&&e.dirtyBlockIds.add(a)}};return e.observer=n,t.observeDeep(n),e}function ti(s){let t=Qs.get(s);return t||(t=Sc(s),Qs.set(s,t)),t}function Rn(s,t){const e=ti(s);e.nestedBlocks=new WeakMap,e.doc=t,e.blockCache.clear(),e.elementByBlockId.clear();const n=Jo(s).toArray();for(const o of t.children)o.id&&e.blockCache.set(o.id,o);for(const o of n)if(o instanceof I.XmlElement){const r=o.getAttribute("id");r&&e.elementByBlockId.set(r,o)}e.dirtyBlockIds.clear(),e.structuralChange=!1}function Dn(s,t,e){const n=e.nestedBlocks.get(s);if(n)return n;const o=In(s,t,void 0,r=>Dn(r,t,e));return o&&e.nestedBlocks.set(s,o),o}const $n=new WeakMap;function Ic(s){let t=$n.get(s);t||(t={blocks:[],dirty:!0,observing:!1},$n.set(s,t));const e=s.getXmlFragment("chrome");if(t.observing||(t.observing=!0,e.observeDeep(()=>{const n=$n.get(s);n&&(n.dirty=!0)})),t.dirty){const n=[];for(const o of e.toArray())if(o instanceof I.XmlElement||o?.constructor?.name==="YXmlElement"){const r=In(o,Wo(s.getMap("metadata"),void 0));r&&r.type==="header-footer"&&n.push(r)}t.blocks=n,t.dirty=!1}return t.blocks}const jn=new WeakMap;function vc(s){let t=jn.get(s);t||(t={blocks:[],dirty:!0,observing:!1},jn.set(s,t));const e=s.getXmlFragment("notes");if(t.observing||(t.observing=!0,e.observeDeep(()=>{const n=jn.get(s);n&&(n.dirty=!0)})),t.dirty){const n=[];for(const o of e.toArray())if(o instanceof I.XmlElement||o?.constructor?.name==="YXmlElement"){const r=In(o,Wo(s.getMap("metadata"),void 0));r&&r.type==="footnote"&&n.push(r)}t.blocks=n,t.dirty=!1}return t.blocks}function xc(s){return!!($n.get(s)?.dirty||jn.get(s)?.dirty)}function _n(s,t){const e=vc(t);e.length>0?(s.notes=e,fl(s)):delete s.notes}function Xn(s,t){const e=t.getMap("comments"),n=[];e.forEach(o=>{o&&typeof o=="object"&&n.push(o)}),n.length>0?(n.sort((o,r)=>(o.createdAt??"").localeCompare(r.createdAt??"")),s.comments=n):delete s.comments}function Ho(s,t){const e=t.getMap("oxml-ranges"),n=[];e.forEach(o=>{o&&typeof o=="object"&&n.push(o)}),n.length>0?(n.sort((o,r)=>o.id.localeCompare(r.id)),s.oxmlRanges=n):delete s.oxmlRanges}function Un(s,t){const e=t.getMap("sdt-wrappers"),n=[];if(e.forEach(o=>{o&&typeof o=="object"&&n.push(o)}),n.length>0){const o=new Map;s.children.forEach((i,a)=>{i.id&&o.set(i.id,a)});const r=i=>i.blockIds?.[0]??i.startBlockId??"";n.sort((i,a)=>(o.get(r(i))??Number.MAX_SAFE_INTEGER)-(o.get(r(a))??Number.MAX_SAFE_INTEGER)||i.id.localeCompare(a.id)),s.sdtWrappers=n}else delete s.sdtWrappers}function zn(s,t){const e=Ic(t);e.length>0?s.chrome=e:delete s.chrome;const n=hs(e);n.headers?s.headers=n.headers:delete s.headers,n.footers?s.footers=n.footers:delete s.footers}function Kt(s){const t=ti(s),e=Jo(s),n=s.getMap("metadata"),o=n?.get("title"),r=n?.get("pageless"),i=n?.get("watermark"),a=typeof i=="string"&&i.trim()!==""?i:void 0,l=hl(s),c=n?.get("stylesheet"),d=c&&typeof c=="object"&&Array.isArray(c.paragraphStyles)&&c.paragraphStyles.length>0?c:void 0,g=n?.get("stylesXml"),u=typeof g=="string"&&g.length>0?g:void 0,f=n?.get("docxSource"),h=f&&typeof f=="object"&&Array.isArray(f.spans)?f:void 0,p=n?.get("coreProperties"),m=p&&typeof p=="object"&&Object.keys(p).length>0?p:void 0,y=n?.get("fontSubstitutes"),b=y&&typeof y=="object"&&Object.keys(y).length>0?y:void 0,k=us(n),S=Wo(n,k);if(t.indentContext&&(t.indentContext.indentStepPx!==S.indentStepPx||t.indentContext.storedAsUnits!==S.storedAsUnits)&&(t.nestedBlocks=new WeakMap,t.doc=null,t.blockCache.clear(),t.elementByBlockId.clear()),t.indentContext=S,!t.doc){const v=[],x=e.toArray();for(let w=0;w<x.length;w++){const A=x[w];if(A instanceof I.XmlElement){const P=Dn(A,S,t);P&&(v.push(P),t.blockCache.set(P.id,P),t.elementByBlockId.set(P.id,A))}}return t.doc={type:"doc",children:v},o&&(t.doc.title=o),r!==void 0&&(t.doc.pageless=r),k&&(t.doc.pageLayout=k),a&&(t.doc.watermark=a),l&&(t.doc.chromeImages=l),d&&(t.doc.stylesheet=d),u&&(t.doc.stylesXml=u),h&&(t.doc.docxSource=h),m&&(t.doc.coreProperties=m),b&&(t.doc.fontSubstitutes=b),zn(t.doc,s),_n(t.doc,s),Xn(t.doc,s),Un(t.doc,s),Ho(t.doc,s),t.dirtyBlockIds.clear(),t.structuralChange=!1,t.doc}if(e.length!==t.doc.children.length&&(t.structuralChange=!0),t.structuralChange){const v=[],x=new Map,w=new Map,A=e.toArray();for(let P=0;P<A.length;P++){const T=A[P];if(T instanceof I.XmlElement){const E=T.getAttribute("id"),B=E?t.dirtyBlockIds.has(E):!0,N=E?t.blockCache.get(E):void 0,R=E!==null&&t.elementByBlockId.get(E)===T;if(E&&!B&&N&&R)v.push(N),x.set(E,N),w.set(E,T);else{const M=Dn(T,S,t);M&&(v.push(M),x.set(M.id,M),w.set(M.id,T))}}}return t.doc={type:"doc",children:v},o&&(t.doc.title=o),r!==void 0&&(t.doc.pageless=r),k&&(t.doc.pageLayout=k),a&&(t.doc.watermark=a),l&&(t.doc.chromeImages=l),d&&(t.doc.stylesheet=d),u&&(t.doc.stylesXml=u),h&&(t.doc.docxSource=h),m&&(t.doc.coreProperties=m),b&&(t.doc.fontSubstitutes=b),zn(t.doc,s),_n(t.doc,s),Xn(t.doc,s),Un(t.doc,s),Ho(t.doc,s),t.blockCache=x,t.elementByBlockId=w,t.dirtyBlockIds.clear(),t.structuralChange=!1,t.doc}if(t.dirtyBlockIds.size>0){const v=[...t.doc.children],x=e.toArray();for(let w=0;w<v.length;w++){const A=v[w];if(A?.id&&t.dirtyBlockIds.has(A.id)&&w<x.length){const P=x[w];if(P instanceof I.XmlElement){const T=Dn(P,S,t);T&&(t.blockCache.delete(A.id),v[w]=T,t.blockCache.set(T.id,T),t.elementByBlockId.set(T.id,P))}}}t.doc={type:"doc",children:v},o&&(t.doc.title=o),r!==void 0&&(t.doc.pageless=r),k&&(t.doc.pageLayout=k),a&&(t.doc.watermark=a),l&&(t.doc.chromeImages=l),d&&(t.doc.stylesheet=d),u&&(t.doc.stylesXml=u),h&&(t.doc.docxSource=h),m&&(t.doc.coreProperties=m),b&&(t.doc.fontSubstitutes=b),zn(t.doc,s),_n(t.doc,s),Xn(t.doc,s),Un(t.doc,s),Ho(t.doc,s),t.dirtyBlockIds.clear()}return o!==void 0?t.doc.title=o:delete t.doc.title,r!==void 0?t.doc.pageless=r:delete t.doc.pageless,k?t.doc.pageLayout=k:delete t.doc.pageLayout,u?t.doc.stylesXml=u:delete t.doc.stylesXml,h?t.doc.docxSource=h:delete t.doc.docxSource,m?t.doc.coreProperties=m:delete t.doc.coreProperties,b?t.doc.fontSubstitutes=b:delete t.doc.fontSubstitutes,t.doc.chromeImages!==l&&(t.doc={...t.doc},l?t.doc.chromeImages=l:delete t.doc.chromeImages),t.doc.watermark!==a&&(t.doc={...t.doc},a!==void 0?t.doc.watermark=a:delete t.doc.watermark),t.doc.stylesheet!==d&&(t.doc={...t.doc},d!==void 0?t.doc.stylesheet=d:delete t.doc.stylesheet),xc(s)&&(t.doc={...t.doc}),zn(t.doc,s),_n(t.doc,s),Xn(t.doc,s),Un(t.doc,s),t.doc}const qo=new WeakMap,Ve="__revise_end_of_document__";function wt(s,t){qo.set(s,{...qo.get(s),...t})}function Rt(s){return qo.get(s)}function Wn(s){if(s.name==="insert_block")return Rt(s)?.stableId}function wc(s){return!!Rt(s)?.allowNoopContinuation}function Ac(s){if(s.name==="replace_block")return Rt(s)?.multiBlockReplace}const Jn=/\\+u[0-9a-fA-F]{4}/;function ei(s){let t="";const e=[],n=[];for(let o=0;o<s.length;){const r=s.slice(o).match(/^(\\+u)([0-9a-fA-F]{4})/),i=r?o+r[0].length:o+1,a=r?String.fromCharCode(Number.parseInt(r[2],16)):s[o],l=Me(a);t+=l;for(let c=0;c<l.length;c++)e.push(o),n.push(i);o=i}return{text:t,sourceStarts:e,sourceEnds:n}}function Yo(s,t){return s.flatMap(e=>{if(e.length<=0)return[];const n=t.sourceStarts[e.offset],o=t.sourceEnds[e.offset+e.length-1];return n===void 0||o===void 0||o<n?[]:[{offset:n,length:o-n}]})}function Ko(s){return s.replace(/^(?:#{1,6}|>|[-*+]|\d+[.)])[ \t]+/,"")}function Tc(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ni(s,t){const e=t.split(/(\s+)/),n=[];for(const l of e)/^\s+$/.test(l)?n.push("\\s+"):l.length>0&&n.push(Tc(l));if(n.length===0)return[];const o=n.join(""),r=new RegExp(o,"g"),i=[];let a;for(;(a=r.exec(s))!==null;)i.push({offset:a.index,length:a[0].length});return i}function Cc(s,t,e,n,o){const r=[];let i=s.indexOf(t);for(;i!==-1;){const a=i+n-e.length,l=Math.min(i+o-e.length+1,s.length);for(let c=a;c<l;c++)if(s.substring(c,c+e.length)===e){const d=c+e.length-i;d>=n&&d<=o&&r.push({offset:i,length:d})}i=s.indexOf(t,i+1)}return r}function Hn(s,t){const e=$o(t);if(e.length>1)for(const n of e){const o=Pn(s,n);if(o.length)return o.map(({start:r,end:i})=>({offset:r,length:i-r}))}for(const n of e){if(qe(n))continue;const o=Pc(s,n);if(o.length)return o}return[]}function Pc(s,t){if(!t)return[];if(/^\s*$/.test(t))return Vo(s,t);if(Jn.test(s)||Jn.test(t))return oi(s,t);const e=sc();return e!==null?e:oi(s,t)}function oi(s,t){const e=Pn(s,t);if(e.length)return e.map(({start:d,end:g})=>({offset:d,length:g-d}));const n=Me(s),o=Me(t),r=Vo(n,o);if(r.length>0)return r;const i=ni(n,o);if(i.length>0)return i;let a,l;if(Jn.test(s)||Jn.test(t)){a=ei(s),l=ei(t).text;const d=Vo(a.text,l);if(d.length>0)return Yo(d,a);const g=ni(a.text,l);if(g.length>0)return Yo(g,a)}const c=8;if(o.length>=c*2){const d=ri(n,o,c);if(d!==null)return[d]}if(a&&l&&l.length>=c*2){const d=ri(a.text,l,c);if(d!==null)return Yo([d],a)}return[]}function Mc(s,t){let e="";for(const n of s.children)n.type==="text"&&(e+=n.text);return Hn(e,t)}function Vo(s,t){const e=[];let n=s.indexOf(t);for(;n!==-1;)e.push({offset:n,length:t.length}),n=s.indexOf(t,n+t.length);return e}function ri(s,t,e){const n=Math.floor(t.length/2);for(let o=n;o>=e;o--){const r=t.substring(0,o),i=t.substring(t.length-o),a=Math.max(5,Math.floor(t.length*.2)),l=Math.max(o*2,t.length-a),c=t.length+a,d=Cc(s,r,i,l,c);if(d.length===1)return d[0]}return null}function si(s,t){const e=Do(s);return t.code||t.latex?e:tc(e)}function Go(s,t){const e=W(s,t);if(!e)return null;if(e.id===t)return{block:e,container:e};if(e.type==="list"){const n=e,o=n.children.find(r=>r.id===t);return o?{block:o,container:{...n,children:[o]}}:null}return null}function Bc(s){return s instanceof St&&s.code==="text_not_found"}class Ec{constructor(t){this.doc=t,this.forks=new Map,this.texts=new Map,this.dirty=new Set}text(t,e){if(this.dirty.delete(t)){const n=this.forks.get(t),o=n?Go(mt(n),t):null;this.texts.set(t,o?kt(o.block):null)}if(!this.texts.has(t)){if(e!==void 0)return e;const n=Go(this.doc,t);this.texts.set(t,n?kt(n.block):null)}return this.texts.get(t)}apply(t,e,n,o){const r=this.forkOf(t);if(!r)return!1;try{Wt(r,{name:o?"replace_all":"replace",arguments:{id:t,find:e,replace:n}})}catch(i){if(Bc(i))return!1;throw i}return this.dirty.add(t),!0}get forkCount(){return this.forks.size}forkOf(t){if(!this.forks.has(t)){const e=Go(this.doc,t);let n=null;e&&(n=new I.Doc,n.getXmlFragment("content").insert(0,[It(e.container)])),this.forks.set(t,n)}return this.forks.get(t)}}function Qo(s,t){if(qe(t)){let e=null;for(const n of s){const o=n.html?ec(n.text,n.html,t):[];if(o.length){if(o.length>1||e!==null)return null;e=n.blockId}}if(e!==null)return e}for(const e of["exact","normalized"]){let n=null;for(const o of s){const r=Fs(o.text,t,e);if(r.length){if(r.length>1||n!==null)return null;n=o.blockId}}if(n!==null)return n}return null}function ee(s){const t=$o(s).at(-1);return nc(Me(t)).text}function ii(s){return s?.type==="paragraph"||s?.type==="list-item"||s?.type==="code"||s?.type==="math"}function Ge(s){const t=[],e=(n,o)=>{if(!(!n||typeof n!="object")&&(typeof n.id=="string"&&n.id.trim().length>0&&ii(n)&&t.push({blockId:n.id,topLevelBlockId:o,text:kt(n)}),Array.isArray(n.children)))for(const r of n.children)e(r,o)};for(const n of s.children)e(n,n.id??null);for(const n of s.notes??[])e(n,n.id);return t}function Zo(s,t){const e=n=>!n||typeof n!="object"?!1:n.id===t?!0:Array.isArray(n.children)&&n.children.some(e);for(const n of s.notes??[])if(e(n))return n.id;return null}function ai(s,t){const e=Zo(s,t);if(!e)return null;if(t!==e)return t;const n=s.notes?.find(i=>i.id===e);if(!n)return t;const o=[],r=i=>{!i||typeof i!="object"||(typeof i.id=="string"&&(i.type==="paragraph"||i.type==="list-item"||i.type==="code"||i.type==="math")&&o.push(i.id),Array.isArray(i.children)&&i.children.forEach(r))};return n.children.forEach(r),o.length===1?o[0]:t}function qn(s,t){return t.has(s.blockId)||s.topLevelBlockId!==null&&t.has(s.topLevelBlockId)}class tr{constructor(t){this.doc=t,this.normalized=new Map,this.candidates=null,this.simulation=new Ec(t)}contains(t,e){return this.qualifies(t,e)}qualifies(t,e,n){const o=this.simulation.text(t,n);if(o===null)return!1;const r=ee(e);if(!r||/^\s*$/.test(r))return!1;let i=this.normalized.get(o);if(i===void 0&&(i=ee(o),this.normalized.size>4096&&this.normalized.clear(),this.normalized.set(o,i)),!i.includes(r))return!1;if(Hn(o,e).length>0)return!0;const a=Ko(e);return a!==e&&a.trim()!==""&&Hn(o,a).length>0}apply(t,e,n,o){return this.simulation.apply(t,e,n,o)}loadedTargets(t,e){if(!e||e.size===0)return[];const n=ee(t);return!n||/^\s*$/.test(n)?[]:(this.candidates??(this.candidates=Ge(this.doc)),this.candidates.filter(o=>qn(o,e)&&this.qualifies(o.blockId,t,o.text)).map(o=>o.blockId))}}function Nc(s){if(!s.loadedBlockIds||s.loadedBlockIds.size===0)return[];const t=ee(s.find);return!t||/^\s*$/.test(t)?[]:Ge(s.doc).filter(e=>qn(e,s.loadedBlockIds)&&ee(e.text).includes(t)).map(e=>e.blockId)}function li(s){if(!s.loadedBlockIds||s.loadedBlockIds.size===0)return null;const t=ee(s.find);if(!t||/^\s*$/.test(t))return null;const e=W(s.doc,s.requestedBlockId);if(e&&ee(kt(e)).includes(t))return null;const n=$o(s.find).at(-1),o=Ge(s.doc).filter(i=>i.blockId!==s.requestedBlockId&&qn(i,s.loadedBlockIds));if(o.some(i=>Pn(i.text,n).length>0))return Qo(o,n);let r=null;for(const i of o)if(ee(i.text).includes(t)){if(r!==null)return null;r=i.blockId}return r}function Lc(s,t,e){const n=W(s,t);if(!n||n.id!==t||!["table","table-row","table-cell"].includes(n.type))return null;const o=Ge({children:[n]});return Qo(o,e)}const ci=new WeakSet;function er(s){ci.add(s)}function Fc(s){if(s.action.name!=="replace"&&s.action.name!=="replace_all"){const d=s.action.arguments?.id;return typeof d=="string"&&d&&s.opaqueBlockIds.add(d),{action:s.action}}if(!s.action.arguments||typeof s.action.arguments!="object")return{action:s.action};const t=s.action.arguments,e=typeof t.id=="string"?t.id.trim():"",n=typeof t.find=="string"?t.find:"";if(!e||!n)return{action:s.action};const o=typeof t.replace=="string"?t.replace:"",r=s.action.name==="replace_all",i=d=>{try{s.plannedTexts.apply(d,n,o,r)}catch{s.opaqueBlockIds.add(d)}};if(ci.has(s.action)||s.opaqueBlockIds.has(e))return i(e),{action:s.action};const a=Lc(s.doc,e,n)??(s.plannedTexts.contains(e,n)?null:li({doc:s.doc,requestedBlockId:e,find:n,loadedBlockIds:s.loadedBlockIds}));if(i(a??e),!a)return{action:s.action};const l={...s.action,arguments:{...t,id:a}},c=Rt(s.action);return c&&wt(l,c),{action:l,retarget:{fromBlockId:e,toBlockId:a}}}function Oc(s){const t=[],e=[],n=new tr(s.doc),o=new Set;for(const r of s.actions){const i=Fc({action:r,doc:s.doc,loadedBlockIds:s.loadedBlockIds,plannedTexts:n,opaqueBlockIds:o});t.push(i.action),i.retarget&&e.push(i.retarget)}return{actions:t,retargets:e}}function nr(s){return s.children.map(t=>{const e={type:"doc",children:[t]};return it.toInternalHtml(e).trim()})}function Rc(s,t=0){const e=Nn.fromMarkdown(s);if(t){for(const n of e.children)if(n.type==="list")for(const o of n.children)o.indentLevel=Math.min(8,t+(o.indentLevel??0))}return nr(e)}function Dc(s){return s.replace(/<span\b([^>]*?)\sdir\s*=\s*["']?(ltr|rtl|auto)["']?([^>]*)>([\s\S]*?)<\/span>/gi,(t,e,n,o,r)=>{const i=n.toLowerCase(),a=i==="ltr"?"":i==="rtl"?"":"",l=`${e}${o}`.trim(),c=l?`<span ${l}>${r}</span>`:r;return`${a}${c}`})}function $c(s,t,e,n){return nr(it.fromAgentHtml(Dc(s),{existingDocument:t,replacementBlock:e,listItemBaseIndent:n,preserveImageReferenceIds:!0}))}const he=/<\/?[a-z][^>]*>/i;function Ne(s){return s.replace(/\s+/g," ").trim()}function di(s){return Ne(s).replace(/^>\s+/,"")}function jc(s,t){if(s.replace==="")return null;const e=s.format==="html"||he.test(s.replace),n=e?it.fromAgentHtml(s.replace,{replacementBlock:W(t,s.id)??void 0,existingDocument:t,preserveImageReferenceIds:!0}):Nn.fromMarkdown(s.replace);if(n.children.length!==1||n.children[0].type!=="list")return null;const o=n.children[0].children;if(o.length===0)return null;const r=W(t,s.id);if(!r||r.type!=="list")return null;const i=r,a=he.test(s.find)?it.fromAgentHtml(s.find,{existingDocument:t,preserveImageReferenceIds:!0}):Nn.fromMarkdown(s.find),l=a.children.length===1&&a.children[0].type==="list"?a.children[0].children.map(y=>Ne(kt(y))):[Ne(kt(a))];if(l.length===0||l.some(y=>y===""))return null;const c=i.children.map(y=>Ne(kt(y))),d=[];for(let y=0;y+l.length<=c.length;y++)l.every((b,k)=>c[y+k]===b)&&(d.push(y),y+=l.length-1);if(d.length===0)throw new Error(`replace: the replacement contains ${o.length} list items, so "find" must match complete list item(s) in block '${s.id}' — it did not. Include each full item's text in "find" (or use insert_markdown to add items).`);if(d.length>1&&!s.all)throw new Error(`replace: "find" matches ${d.length} runs of list items in block '${s.id}'. Include more items in "find" so it matches exactly one location, or set all: true.`);const g=s.all?d:[d[0]],u=[];let f=0;for(const y of g)u.push(...i.children.slice(f,y)),u.push(...o),f=y+l.length;u.push(...i.children.slice(f));const h=g.length===1&&g[0]===0&&l.length===i.children.length,p=h?{...n.children[0],id:i.id}:{...i,children:u},m=h&&e?s.replace:nr({children:[p]})[0];return{name:"replace_block",arguments:{id:i.id,content:[m]}}}function _c(s,t){if(s.replace===""||s.all)return null;const e=W(t,s.id);if(!e)return null;const n=s.format==="html"||!s.format&&he.test(s.find)?kt(it.fromAgentHtml(s.find,{existingDocument:t,preserveImageReferenceIds:!0})):kt(Nn.fromMarkdown(s.find)),o=kt(e);if(di(n)!==di(o))return null;const r=s.format==="html"||!s.format&&he.test(s.replace)?$c(s.replace,t,e):Rc(s.replace),i=r.length===1&&/^<p\b[^>]*>[\s\S]*<\/p>$/i.test(r[0]),a=(s.format==="html"||!s.format&&he.test(s.replace))&&/^<p\s+[^>]+>/i.test(s.replace.trim()),l=e.type==="footnote"?ai(t,s.id):null,c=l!==null&&l!==s.id&&W(t,l)?.type==="paragraph",d=s.format!=="markdown"&&he.test(s.find)&&!he.test(s.find.replace(/<\/?(?:b|strong|i|em|u|s|strike|sup|sub|code|mark|span|a|br)\b[^>]*>/gi,""));return i&&!a&&(e.type==="table-cell"||c||e.type==="paragraph"&&(d||Ne(s.find)===Ne(o)))?null:{name:"replace_block",arguments:{id:s.id,content:r}}}function Xc(s,t){return jc(s,t)??_c(s,t)}function or(s,t){const e=W(s,t);return e?hi(e):null}const Yn=s=>s===void 0||typeof s=="function";function Ut(s,t){if(s===t)return!0;if(typeof s!="object"||typeof t!="object"||!s||!t)return typeof s=="number"&&typeof t=="number"?!Number.isFinite(s)&&!Number.isFinite(t):!1;const e=s.toJSON,n=t.toJSON;if(typeof e=="function"||typeof n=="function")return Ut(typeof e=="function"?e.call(s):s,typeof n=="function"?n.call(t):t);if(Array.isArray(s)||Array.isArray(t)){if(!Array.isArray(s)||!Array.isArray(t)||s.length!==t.length)return!1;for(let l=0;l<s.length;l++)if(!Ut(s[l],t[l]))return!1;return!0}const o=s,r=t,i=Object.keys(o).filter(l=>!Yn(o[l])),a=Object.keys(r).filter(l=>!Yn(r[l]));if(i.length!==a.length)return!1;for(const l of i)if(Yn(r[l])||!Object.prototype.hasOwnProperty.call(r,l)||!Ut(o[l],r[l]))return!1;return!0}const gi=16777619,Uc=1114113,zc=1114114,Wc=1114115,Jc=1114116,rr=1114117,Hc=1114118,ui=1114119;function Kn(s,t){switch(typeof t){case"string":return sr(_t(_t(s,Uc),t.length),t);case"number":return Number.isFinite(t)?sr(_t(s,zc),String(t)):_t(s,rr);case"boolean":return _t(s,t?Wc:Jc);case"object":break;default:return _t(s,rr)}if(t===null)return _t(s,rr);const e=t;if(typeof e.toJSON=="function")return Kn(s,e.toJSON());if(Array.isArray(t)){s=_t(_t(s,Hc),t.length);for(const r of t)s=Kn(s,r);return s}const n=t;let o=Object.keys(n);for(let r=1;r<o.length;r++)if(o[r-1]>o[r]){o=[...o].sort();break}s=_t(s,ui);for(const r of o){const i=n[r];Yn(i)||(s=sr(_t(s,r.length),r),s=Kn(s,i))}return _t(s,ui)}function _t(s,t){return Math.imul(s^t,gi)}function sr(s,t){for(let e=0;e<t.length;e++)s=Math.imul(s^t.charCodeAt(e),gi);return s}function hi(s){return(Kn(2166136261,s)>>>0).toString(36)}function qc(s,t){const e=new Map;for(const n of t){if(e.has(n))continue;const o=or(s,n);o!==null&&e.set(n,o)}return e}const fi=50,pi="document_state_changed",Yc=new Set(["replace","replace_block","style_blocks","remove_block","remove_blocks"]);function ir(s,t){const e=s.name==="replace"&&!!s.arguments&&typeof s.arguments=="object"&&Object.prototype.hasOwnProperty.call(s.arguments,"replacements"),n=s.name==="replace_many";if(!e&&!n)return{actions:[s]};const o=n?"replace_many":"replace";if(!s.arguments||typeof s.arguments!="object")return{actions:[],error:`${o} requires object arguments`};const r=s.arguments.id,i=s.arguments.replacements;if(!Array.isArray(i)||i.length===0)return{actions:[],error:`${o} requires a non-empty replacements array`};if(i.length>fi)return{actions:[],error:`${o} supports at most ${fi} replacements per call`};const a=[],l=t?new tr(t.doc):null;for(let d=0;d<i.length;d++){const g=i[d];if(!g||typeof g!="object")return{actions:[],error:`${o} replacement #${d+1} must be an object`};if(typeof g.find!="string")return{actions:[],error:`${o} replacement #${d+1} is missing "find"`};if(g.find.length===0&&(n||typeof r!="string"||r.trim().length===0))return{actions:[],error:n?`${o} replacement #${d+1} has an empty "find"`:`${o} replacement #${d+1} has an empty "find" and therefore requires a direct block id`};if(typeof g.replace!="string")return{actions:[],error:`${o} replacement #${d+1} is missing "replace"`};if(g.occurrence!==void 0&&g.occurrence!==null&&g.occurrence!=="unique"&&g.occurrence!=="all")return{actions:[],error:`${o} replacement #${d+1} has invalid "occurrence"; use "unique" or "all"`};if(g.comment!==void 0&&g.comment!==null&&(typeof g.comment!="string"||g.comment.trim().length===0))return{actions:[],error:`${o} replacement #${d+1} comment must be a non-empty string when provided`};let u=typeof r=="string"&&r.trim()?[r.trim()]:[];const f=u.length===0;if(u.length===0&&g.find.length>0&&t){const h=l?l.loadedTargets(g.find,t.loadedBlockIds):[];if(g.occurrence==="all")u=h;else if(l)u=h.length===1?h:[];else{const p=li({doc:t.doc,requestedBlockId:"",find:g.find,loadedBlockIds:t.loadedBlockIds});u=p?[p]:[]}}if(u.length===0){const h=t&&g.find.length>0?l?l.loadedTargets(g.find,t.loadedBlockIds):Nc({doc:t.doc,find:g.find,loadedBlockIds:t.loadedBlockIds}):[];return{actions:[],error:t?.loadedBlockIds?.size&&g.find.length>0?h.length===0?`${o} replacement #${d+1}: find text was not found in any loaded block. Check the exact text, or read the block that contains it.`:`${o} replacement #${d+1}: find text appears in ${h.length} loaded blocks (${h.slice(0,10).join(", ")}). Pass a block id, or use occurrence "all" to replace it in every one.`:`${o} replacement #${d+1} requires a block id unless its find text uniquely identifies one loaded block`}}for(const h of u){try{l?.apply(h,g.find,g.replace,g.occurrence==="all")}catch{}const p=u.length===1?`${s.id||o}-${d+1}`:`${s.id||o}-${d+1}-${h}`;if(t&&!g.comment)try{const y=Xc({type:"replace",id:h,find:g.find,replace:g.replace,format:"html",all:g.occurrence==="all"},t.doc);if(y){const b={...y,id:p};f&&er(b),a.push(b);continue}}catch(y){return{actions:[],error:y instanceof Error?y.message:String(y),failure:Be(y)}}const m={id:p,name:g.occurrence==="all"?"replace_all":"replace",arguments:{id:h,find:g.find,replace:g.replace,...typeof g.comment=="string"?{comment:g.comment.trim()}:{}}};f&&er(m),a.push(m)}}const c=Array.from(new Set(a.map(d=>d.arguments?.id).filter(d=>typeof d=="string"&&d.length>0)));return{actions:a,blockId:c.length===1?c[0]:void 0}}function Kc(s){const{toolCall:t,docBefore:e,resultSets:n}=s,o=t.arguments;if(!o||typeof o!="object")return null;const r=o.search_result_id;if(r==null)return null;if(typeof r!="string"||r.trim().length===0)return{actions:[],targetBlockIds:[],error:"search_result_id must be a non-empty string"};const i=r.trim();if(!Yc.has(t.name))return{actions:[],targetBlockIds:[],error:`${t.name} does not support search_result_id`};if(typeof o.id=="string"&&String(o.id).trim().length>0||Array.isArray(o.ids))return{actions:[],targetBlockIds:[],error:`${t.name} accepts either search_result_id or direct id/ids targets, not both.`};const a=n.get(i);if(!a)return{actions:[],targetBlockIds:[],error:`Search result '${i}' is unavailable. Search result references are request-scoped; rerun search_document in this request, then retry.`,errorCode:pi};for(const u of a.blockIds){if(Zo(e,u))return{actions:[],targetBlockIds:[],error:"Bulk search-result mutations cannot include footnote or endnote bodies. Target those note blocks individually."};const f=or(e,u);if(f===null||f!==a.blockHashes.get(u))return{actions:[],targetBlockIds:[],error:`Search result '${i}' is stale because block '${u}' changed or disappeared. Rerun search_document, then retry; no partial mutation was applied.`,errorCode:pi}}const{search_result_id:l,...c}=o,d=[];let g=[...a.blockIds];if(t.name==="replace"){const u=c.replacements,f=(Array.isArray(u)?u:[c]).map(k=>k&&typeof k=="object"?k:{}),h=new tr(e),p=f.map(()=>!1),m=(k,S,v,x)=>{try{return h.apply(k,S,v,x)}catch{return!0}},y=a.blockIds.map(k=>f.flatMap((S,v)=>{const{find:x,replace:w}=S;return typeof x!="string"||x.length===0||h.contains(k,x)&&m(k,x,typeof w=="string"?w:"",S.occurrence==="all"||!Array.isArray(u))?(p[v]=!0,[v]):[]})),b=p.flatMap((k,S)=>k?[]:[S]);if(b.length>0)return{actions:[],targetBlockIds:[],error:`Search result '${i}' has no block containing the find text of ${Array.isArray(u)?`replacement ${b.map(k=>`#${k+1}`).join(", ")}`:"this replacement"}. Check the exact text; no replacement was applied.`};g=[];for(let k=0;k<a.blockIds.length;k++){const S=a.blockIds[k],v=y[k];if(v.length===0)continue;const x=Array.isArray(u)?v.map(A=>u[A]):null,w=ir({...t,id:`${t.id||"replace"}-search-${k+1}`,arguments:{...c,...x?{replacements:x}:{},id:S}});if(w.error)return{actions:[],targetBlockIds:[],error:w.error};for(const A of w.actions)er(A),d.push(A);g.push(S)}}else if(t.name==="replace_block"){const u=o.count;if(u!=null&&u!==1)return{actions:[],targetBlockIds:[],error:"replace_block with search_result_id applies independently to each matched block, so count must be omitted or 1."};for(let f=0;f<a.blockIds.length;f++)d.push({...t,id:`${t.id||"replace_block"}-search-${f+1}`,arguments:{...c,id:a.blockIds[f],count:1}})}else if(t.name==="remove_block")for(let u=0;u<a.blockIds.length;u++)d.push({...t,id:`${t.id||"remove_block"}-search-${u+1}`,arguments:{id:a.blockIds[u],count:1}});else{const u=o.selectors,f=(Array.isArray(u)?u:typeof u=="string"?[u]:[]).flatMap(p=>typeof p=="string"?p.split(",").map(m=>m.trim()):[p]);if(f.length===0||f.some(p=>typeof p!="string"||p.trim().length===0))return{actions:[],targetBlockIds:[],error:"style_blocks requires one or more non-empty selectors"};const h=a.blockIds.flatMap(p=>f.map(m=>{const y=String(m).trim();return/^(?:\*|all|document|:root)$/i.test(y)?`#${p}`:`#${p} ${y}`}));d.push({...t,arguments:{...c,selectors:h}})}return{actions:d,targetBlockIds:g,resultSet:a}}function mi(s,t){const e={...t};for(const n of["lang","oxmlRPr","oxmlRange","sdtInline","field","aiGenerated","__htmlClassName"])e[n]===void 0&&s?.[n]!==void 0&&Object.assign(e,{[n]:s[n]});for(const n of fs)e[n]===void 0&&s?.[n]===!1&&(e[n]=!1);if(e.docxRunPropertyResets===void 0){const n=pl(s?.docxRunPropertyResets)?.split(",").filter(o=>o==="color"?e.color===void 0:e.backgroundColor===void 0);n?.length&&(e.docxRunPropertyResets=n.join(","))}return e}function Vn(s,t){const e=s.map(i=>i.text).join("");if(!e||e!==t.map(i=>i.text).join("")){const i=new Set(s.filter(l=>l.text.length>0).map(l=>l.marks?.lang)),a=i.size===1?[...i][0]:void 0;return a===void 0?t:t.map(l=>({...l,marks:{lang:a,...l.marks}}))}const n=[];let o=0,r=0;for(const i of t){if(i.text.length===0){n.push({...i,marks:i.marks?{...i.marks}:void 0});continue}let a=0;for(;a<i.text.length;){for(;r===s[o].text.length;)o++,r=0;const l=s[o],c=Math.min(i.text.length-a,l.text.length-r);n.push({...i,text:i.text.slice(a,a+c),marks:mi(l.marks,i.marks)}),a+=c,r+=c}}return n}function Vc(s,t){const e=Mn(s),n=Array.from({length:e.cols},(l,c)=>Math.max(.001,s.columnWidths[c]||100/e.cols)),o=new Map;for(const l of t){const c=e.byId.get(l.cellId);if(!c)throw new St("target_stale","The requested table cell no longer exists. Read the table again.","target_resolution");if(!Number.isFinite(l.percent)||l.percent<=0||l.percent>100)throw new St("attribute_value_unsupported","Cell width must be greater than 0 and at most 100 percent.");const d=n.slice(c.col,c.col+c.colSpan).reduce((g,u)=>g+u,0);for(let g=c.col;g<c.col+c.colSpan;g++){const u=l.percent*n[g]/d;if(o.has(g)&&Math.abs(o.get(g)-u)>.001)throw new St("attribute_conflict","Conflicting cell widths constrain the same table column. Set each column once, using one unmerged row.");o.set(g,u)}}const r=[...o.values()].reduce((l,c)=>l+c,0),i=n.map((l,c)=>c).filter(l=>!o.has(l));if(r>100.001||!i.length&&Math.abs(r-100)>.001||i.length&&r>=100)throw new St("attribute_conflict","Requested column widths conflict: they must leave space for other columns and sum to 100 percent when all columns are specified.");const a=i.reduce((l,c)=>l+n[c],0);return n.map((l,c)=>o.get(c)??(100-r)*l/a)}function bi(s,t,e,n){if(!n?.length)return;const o=t==="row"?s.cols:s.rows;if(n.length>o)return{success:!1,error:`content[${o}] is outside the table's ${o} ${t==="row"?"columns":"rows"}. Supply at most ${o} entries for this insertion.`};for(const r of s.cells){const i=t==="row"?r.row:r.col,a=t==="row"?r.rowSpan:r.colSpan;if(i>=e||i+a<=e)continue;const l=t==="row"?r.col:r.row,c=t==="row"?r.colSpan:r.rowSpan;for(let d=l;d<l+c;d++)if(n[d]?.length)return{success:!1,error:`content[${d}] targets a position covered by a merged cell. Leave that slot empty or insert outside the merged span; the table was not changed.`}}}function Gc(s,t){return{type:"paragraph",id:G(),...s?{direction:s}:{},children:[{type:"text",text:"",...t?{marks:t}:{}}]}}function yi(s){const t=s?.children.find(n=>n.type==="paragraph")?.children.find(n=>n.type==="text")?.marks;if(!t)return;const e={};return t.fontFamily&&t.fontFamily!==ml&&(e.fontFamily=t.fontFamily),typeof t.fontSize=="number"&&(e.fontSize=t.fontSize),typeof t.color=="string"&&t.color&&(e.color=t.color),Object.keys(e).length>0?e:void 0}function ki(s){const t=s?.children.find(n=>n.type==="paragraph");if(!t)return;let e="";for(const n of t.children)e+=n.text??"";return Ds(t.direction,e)==="rtl"?"rtl":void 0}function Qc(s,t){return{type:"table-cell",id:G(),children:[Gc(s,t)]}}function Si(s,t,e){return!s||s.length===0?Qc(t,e):{type:"table-cell",id:G(),children:s}}function Gn(s,t){const e=s.get("content",I.XmlFragment);function n(o){for(let r=0;r<o.length;r++){const i=o.get(r);if(i instanceof I.XmlElement){if(i.nodeName==="table"&&i.getAttribute("id")===t)return i;if(i.nodeName==="container"||i.nodeName==="footnote"||i.nodeName==="table"||i.nodeName==="table-row"||i.nodeName==="table-cell"){const a=n(i);if(a)return a}}}return null}return n(e)??n(s.getXmlFragment("notes"))}function ar(s,t){const e=Number(rt(s,t));return Number.isFinite(e)&&e>1?Math.floor(e):1}function Ii(s){if(!s)return;const t=In(s.el,{indentStepPx:48,storedAsUnits:!1});return t?.type==="table-cell"?t:void 0}function Qn(s){const t=[];for(let a=0;a<s.length;a++){const l=s.get(a);l instanceof I.XmlElement&&l.nodeName==="table-row"&&t.push(l)}const e=s.getAttribute("columnWidths");let n=0;try{const a=e?JSON.parse(e):[];n=Array.isArray(a)?a.length:0}catch{n=0}for(const a of t){let l=0;for(let c=0;c<a.length;c++){const d=a.get(c);d instanceof I.XmlElement&&d.nodeName==="table-cell"&&(l+=ar(d,"colSpan"))}n=Math.max(n,l)}n=Math.max(n,1);const o=t.length,r=Array.from({length:o},()=>new Array(n).fill(void 0)),i=[];for(let a=0;a<o;a++){const l=t[a];let c=0,d=0;for(let g=0;g<l.length;g++){const u=l.get(g);if(!(u instanceof I.XmlElement)||u.nodeName!=="table-cell")continue;for(;c<n&&r[a][c]!==void 0;)c++;if(c>=n)break;const f=Math.min(ar(u,"colSpan"),n-c),h=Math.min(ar(u,"rowSpan"),o-a),p={el:u,row:a,col:c,rowSpan:h,colSpan:f,physicalIndex:d};i.push(p);for(let m=a;m<a+h;m++)for(let y=c;y<c+f;y++)r[m][y]===void 0&&(r[m][y]=p);c+=f,d++}}return{rows:o,cols:n,cells:i,occupancy:r,rowEls:t}}function Qe(s,t,e){e>1?s.setAttribute(t,String(e)):et(s,t)}function vi(s){return It(s)}function Zc(s){const t=new I.XmlElement("table-row");t.setAttribute("id",s.id);let e=0;for(const n of s.children){const o=vi(n);t.insert(e++,[o])}return t}function td(s,t,e){const n=Gn(s,t);if(!n)return{success:!1,error:`Table with ID "${t}" not found.`};const o=Qn(n);return o.rows===0?{success:!1,error:"Table has no rows."}:e<0||e>=o.cols?{success:!1,error:`Invalid column index ${e}. Table has ${o.cols} columns.`}:o.cols<=1?{success:!1,error:"Cannot remove the last column from a table."}:(s.transact(()=>{for(const i of o.cells)i.col<=e&&e<i.col+i.colSpan&&(i.colSpan>1?Qe(i.el,"colSpan",i.colSpan-1):o.rowEls[i.row].delete(i.physicalIndex,1));const r=n.getAttribute("columnWidths");if(r){const i=JSON.parse(r);if(e<i.length){const a=i[e];i.splice(e,1);const l=i.reduce((d,g)=>d+g,0),c=l>0?i.map(d=>d+a*d/l):i;n.setAttribute("columnWidths",JSON.stringify(c))}}}),{success:!0})}function ed(s,t){const e=Qn(s);if(t<0||t>=e.rows)return;for(const r of e.cells)r.row<t&&r.row+r.rowSpan>t&&Qe(r.el,"rowSpan",r.rowSpan-1);const n=e.cells.filter(r=>r.row===t&&r.rowSpan>1).sort((r,i)=>r.col-i.col);if(n.length>0&&t+1<e.rows){const r=e.rowEls[t+1],i=e.cells.filter(l=>l.row===t+1);let a=0;for(const l of n){const c=l.el.clone();Qe(c,"rowSpan",l.rowSpan-1);const d=i.filter(g=>g.col<l.col).length+a;r.insert(d,[c]),a++}}const o=e.rowEls[t];for(let r=0;r<s.length;r++)if(s.get(r)===o){s.delete(r,1);break}}function nd(s,t,e){const n=Gn(s,t);if(!n)return{success:!1,error:`Table with ID "${t}" not found.`};const o=[...new Set(e)],r=o.find(i=>!Number.isInteger(i)||i<0||i>=n.length);return r!==void 0?{success:!1,error:`Invalid row index ${r}. Table has ${n.length} rows.`}:o.length===0?{success:!1,error:"No rows to remove."}:o.length>=n.length?{success:!1,error:"Cannot remove the last row from a table. To delete every row, remove the table block instead."}:(s.transact(()=>{for(const i of o.sort((a,l)=>l-a))ed(n,i)}),{success:!0})}const Zn=s=>s==null?void 0:Array.isArray(s)?s:[s];function xi(s,t){const e=[...Zn(t.rowIds)??[],...Zn(t.rowId)??[]],n=[...Zn(t.rowIndices)??[],...Zn(t.rowIndex)??[]];if(e.length&&n.length)return{error:"Pass rowIds or rowIndices, not both. Prefer rowIds: the stable <tr id> values from the table you read."};if(!e.length&&!n.length)return{error:"Pass rowIds: the stable <tr id> of each row to remove (one string or an array)."};const o=e.length>0,r=[],i=[];for(const l of o?e:n)if(o){const c=typeof l=="string"?s.children.findIndex(d=>d.id===l):-1;c<0?i.push(`Row ${JSON.stringify(l)} not found`):r.push(c)}else!Number.isInteger(l)||Number(l)<0||Number(l)>=s.children.length?i.push(`Invalid row index ${JSON.stringify(l)} (table has ${s.children.length} rows)`):r.push(Number(l));if(i.length)return{error:`${i.join("; ")} in table ${s.id}. No rows were removed. Read the table and use current row IDs.`};if(new Set(r).size!==r.length)return{error:`Each row may be listed once. No rows were removed from table ${s.id}.`};if(r.length>=s.children.length)return{error:`Cannot remove the last row from table ${s.id}. To delete every row, remove the table block instead.`};const a=[...r].sort((l,c)=>l-c);return{rowIndices:a,rowIds:a.map(l=>s.children[l].id),byId:o}}function od(s,t,e,n,o){const r=Gn(s,t);if(!r)return{success:!1,error:`Table with ID "${t}" not found.`};const i=Qn(r);if(i.rows===0)return{success:!1,error:"Table has no rows."};const a=i.cols;if(n<0||n>=a)return{success:!1,error:`Invalid reference column index ${n}. Table has ${a} columns.`};const l=e==="before"?n:n+1;return bi(i,"column",l,o)||(s.transact(()=>{for(let g=0;g<i.rows;g++){const u=l>0&&l<a&&i.occupancy[g][l-1]===i.occupancy[g][l]?i.occupancy[g][l]:void 0;if(u){u.row===g&&Qe(u.el,"colSpan",u.colSpan+1);continue}const f=o?.[g],h=Ii(i.occupancy[g]?.[n]),p=Si(f,ki(h),yi(h)),m=vi(p),y=i.cells.filter(b=>b.row===g&&b.col<l).length;i.rowEls[g].insert(y,[m])}const d=r.getAttribute("columnWidths");if(d){const g=JSON.parse(d),u=100/(a+1),f=(100-u)/100,h=g.map(p=>p*f);h.splice(l,0,u),r.setAttribute("columnWidths",JSON.stringify(h))}}),{success:!0})}function rd(s,t,e,n){const o=Qn(t);return bi(o,"row",e,n)||(s.transact(()=>{const i=o.cells.filter(u=>u.row<e&&u.row+u.rowSpan>e),a=new Set;for(const u of i){Qe(u.el,"rowSpan",u.rowSpan+1);for(let f=u.col;f<u.col+u.colSpan;f++)a.add(f)}const l=[];for(let u=0;u<o.cols;u++){if(a.has(u))continue;const f=Ii(o.occupancy[e-1]?.[u]??o.occupancy[e]?.[u]);l.push(Si(n?.[u],ki(f),yi(f)))}const c={id:G(),children:l},d=Zc(c);let g=t.length;if(e<o.rows){const u=o.rowEls[e];for(let f=0;f<t.length;f++)if(t.get(f)===u){g=f;break}}t.insert(g,[d])}),{success:!0})}function sd(s,t,e,n,o){const r=Gn(s,t);if(!r)return{success:!1,error:`Table with ID "${t}" not found.`};if(n<0||n>=r.length)return{success:!1,error:`Invalid reference row index ${n}. Table has ${r.length} rows.`};const i=r.get(0);if(!(i instanceof I.XmlElement)||i.nodeName!=="table-row")return{success:!1,error:"Table has no rows."};const a=e==="before"?n:n+1;return rd(s,r,a,o)}const wi=new Set(["com","org","net","edu","gov","mil","int","io","co","ai","app","dev","tech","cloud","software","digital","online","site","website","web","blog","biz","info","pro","company","agency","studio","media","news","shop","store","uk","de","fr","es","it","nl","be","at","ch","cx","pl","ru","cn","jp","kr","in","au","nz","ca","us","mx","br","ar","za","ie","se","no","dk","fi","pt","cz","gr","hu","ro","ua","il","ae","sg","hk","tw","id","my","ph","th","vn","tr","me","tv","cc","gg","fm","ly","to","is","im","ws","la","ac","sh","vc","xyz","top","live","space"]),Ai=/^(?:mailto|tel):\S+$/i,Ti=/^[^\s@/?#:]+@[^\s@/?#:]+\.[a-z]{2,}$/i;function id(s){if(!s||s.length<4)return!1;if(Ai.test(s)||Ti.test(s))return!0;if(/^https?:\/\//i.test(s))try{return new URL(s),!0}catch{return!1}if(s.split(/[/?#]/,1)[0].includes("@"))return!1;if(/^www\./i.test(s))try{return new URL(`https://${s}`),!0}catch{return!1}if(!s.includes(".")||!/^[a-zA-Z0-9]/.test(s))return!1;try{const t=new URL(`https://${s}`).hostname.split(".").filter(n=>n.length>0);if(t.length<2)return!1;const e=t[t.length-1].toLowerCase();if(wi.has(e))return!0;if(t.length>=3){const n=t[t.length-2].toLowerCase();if(wi.has(n))return!0}return!1}catch{return!1}}function ad(s){return/^https?:\/\//i.test(s)||Ai.test(s)?s:Ti.test(s)?`mailto:${s}`:`https://${s}`}function Ci(s){return s===" "||s===" "||s===`
|
|
2
|
+
`||s==="\r"}function Pi(s){if(!s||s.length<4)return[];const t=[];let e=0;for(;e<s.length;){if(Ci(s[e])){e++;continue}let n=e,o=e;for(;o<s.length&&!Ci(s[o]);)o++;const r=s.slice(n,o);id(r)&&t.push({url:ad(r),originalText:r,start:n,end:o}),e=o}return t}function bt(s){for(const t of s.toArray())if(t instanceof I.XmlText)return t;return null}function lr(s){const t=String(s.getAttribute("id")??"");throw new St("target_type_mismatch",`Target '${t}' is a ${s.nodeName}, not a directly editable text block. Read its contents and target a paragraph ID instead${s.nodeName==="table-cell"?", or use the table-cell editing tool":""}. No change was made.`,"target_resolution",!0,"unchanged",{targetId:t,targetType:s.nodeName})}function Le(s){return s instanceof I.XmlElement&&s.nodeName==="header-footer"}function Fe(){throw new Error("Headers and footers have fixed left, center, and right paragraph slots. Edit or replace one existing paragraph; do not insert, remove, split, join, or change the block type of a slot.")}function ld(s,t){const e=bt(s),n=s.parent instanceof I.XmlElement&&s.parent.nodeName==="list"?s.parent.getAttribute("variant")??void 0:void 0;if(e)return[{blockId:t,yBlock:s,yText:e,blockText:fe(e),listVariant:s.nodeName==="list-item"?n:void 0}];if(s.nodeName==="list"){const i=[];for(const a of s.toArray()){if(!(a instanceof I.XmlElement)||a.nodeName!=="list-item")continue;const l=bt(a);if(!l)continue;const c=a.getAttribute("id")||t;i.push({blockId:c,yBlock:a,yText:l,blockText:fe(l),listVariant:s.getAttribute("variant")??void 0})}return i}const o=[],r=i=>{for(const a of i.toArray()){if(!(a instanceof I.XmlElement))continue;const l=bt(a);l?o.push({blockId:a.getAttribute("id")??t,yBlock:a,yText:l,blockText:fe(l)}):r(a)}};return r(s),o}function cd(s,t){const e=new Set,n=r=>{const i=r.getAttribute("id"),a=typeof i=="string"?i:"",l=bt(r);if(a&&l&&!e.has(a)){const c=t({blockId:a,yBlock:r,yText:l,blockText:fe(l)});if(e.add(a),c===!0)return!0}for(const c of r.toArray())if(c instanceof I.XmlElement&&n(c))return!0;return!1},o=We(s);for(const r of o.toArray())if(r instanceof I.XmlElement&&n(r))return}function dd(s,t,e,n=3){const o=qe(e)?rc(e):Do(e);if(!o||/^\s*$/.test(o))return null;const r=Me(o);if(!r||/^\s*$/.test(r))return null;const i=[];let a=0,l=!1;return cd(s,c=>{if(!(c.blockId===t||!Me(c.blockText).includes(r))&&(a++,i.length<n&&i.push(c.blockId),a>n))return l=!0,!0}),a===0?null:{blockIds:i,totalMatches:a,truncated:l}}function gd(s,t,e){const n=dd(s,t,e);if(!n||n.blockIds.length===0)return"";if(n.totalMatches===1)return` Did you mean block '${n.blockIds[0]}'?`;const o=n.blockIds.map(a=>`'${a}'`).join(", "),r=n.totalMatches-n.blockIds.length,i=r>0?n.truncated?` and at least ${r} more`:` and ${r} more`:"";return` This text appears in other blocks: ${o}${i}. Did you mean one of those block IDs?`}function ud(s,t){if(t.length<=20)return"";const e=s.indexOf(t.slice(0,20));if(e<0)return"";let n=20;for(;n<t.length&&s[e+n]===t[n];)n++;if(n>=t.length)return"";const o=Math.max(0,n-20),r=t.slice(o,n+40),i=s.slice(e+o,e+n+40);return` The first ${n} characters of find match the block, then they differ: find has ${JSON.stringify(r)} where the block reads ${JSON.stringify(i)}.`}const cr=new WeakMap;function dr(s){return cr.get(s)}const pt=s=>({kind:"block",...s}),Mt=s=>({kind:"textMark",...s}),hd=new Set(["bold","italic","underline","strikethrough","doubleStrikethrough","smallCaps","allCaps","code","superscript","subscript"]),Mi={fontSize:{integer:!0,min:1,max:512},letterSpacing:{min:-20,max:100}},fd=[pt({attr:"align",nodeNames:["paragraph","image","math","table","toc"],valueType:"string",enumValues:["left","center","right","justify"],aliases:["textAlign","text-align"]}),pt({attr:"heading",nodeNames:["paragraph"],valueType:"number",integer:!0,min:1,max:6}),pt({attr:"lineSpacing",nodeNames:["paragraph","list","list-item"],valueType:"number",min:.5,max:4,aliases:["lineHeight","line-height"]}),pt({attr:"leftIndent",nodeNames:["paragraph"],valueType:"number",integer:!0,min:0,max:20,aliases:["marginLeft","margin-left","left-indent","indent","indents"]}),pt({attr:"direction",nodeNames:["paragraph","list-item","toc"],valueType:"string",enumValues:["ltr","rtl"],aliases:["dir"]}),pt({attr:"firstLineIndent",nodeNames:["paragraph"],valueType:"number",integer:!0,min:-1,max:1,aliases:["textIndent","text-indent","first-line-indent"]}),pt({attr:"spaceBefore",nodeNames:["paragraph","list","list-item"],valueType:"number",min:0,aliases:["marginTop","margin-top"]}),pt({attr:"spaceAfter",nodeNames:["paragraph","list","list-item"],valueType:"number",min:0,aliases:["marginBottom","margin-bottom"]}),pt({attr:"width",nodeNames:["image"],valueType:"number",integer:!0,min:1}),pt({attr:"height",nodeNames:["image"],valueType:"number",integer:!0,min:1}),pt({attr:"alt",nodeNames:["image"],valueType:"string"}),pt({attr:"language",nodeNames:["code"],valueType:"string"}),pt({attr:"renderDiagram",nodeNames:["code"],valueType:"boolean"}),pt({attr:"showDiagramSource",nodeNames:["code"],valueType:"boolean"}),pt({attr:"displayMode",nodeNames:["math"],valueType:"string",enumValues:["inline","block"]}),pt({attr:"variant",nodeNames:["list"],valueType:"string",enumValues:["ordered","unordered","todo"],aliases:["listStyleType","list-style-type"]}),pt({attr:"startNumber",nodeNames:["list"],valueType:"number",integer:!0,min:1}),pt({attr:"numberingChainId",nodeNames:["list"],valueType:"string"}),pt({attr:"checked",nodeNames:["list-item"],valueType:"boolean"}),pt({attr:"indentLevel",nodeNames:["list-item"],valueType:"number",integer:!0,min:0,max:10}),pt({attr:"tableWidth",nodeNames:["table"],valueType:"number",integer:!0,min:1,aliases:["width"]}),pt({attr:"borderColor",nodeNames:["table","table-cell","container"],valueType:"string",aliases:["border-color"]}),pt({attr:"borderWidth",nodeNames:["table","table-cell"],valueType:"number",integer:!0,min:0,aliases:["border-width"]}),pt({attr:"borders",nodeNames:["table","table-cell"],valueType:"string",aliases:["border"]}),pt({attr:"cellPadding",nodeNames:["table"],valueType:"number",integer:!0,min:0,aliases:["cell-padding","padding"]}),pt({attr:"hasHeader",nodeNames:["table"],valueType:"boolean"}),pt({attr:"verticalAlign",nodeNames:["table-cell"],valueType:"string",enumValues:["top","middle","bottom"],aliases:["vertical-align"]}),pt({attr:"backgroundColor",nodeNames:["table-cell"],valueType:"string",aliases:["background-color","background","highlightColor","highlight-color"]}),pt({attr:"padding",nodeNames:["container","table-cell"],valueType:"number",integer:!0,min:0}),Mt({attr:"bold",valueType:"boolean",aliases:["fontWeight","font-weight"]}),Mt({attr:"italic",valueType:"boolean",aliases:["fontStyle","font-style"]}),Mt({attr:"underline",valueType:"boolean",aliases:["textDecoration","text-decoration"]}),Mt({attr:"strikethrough",valueType:"boolean",aliases:["strike","line-through"]}),Mt({attr:"doubleStrikethrough",valueType:"boolean",aliases:["double-strikethrough","double-strike","dstrike"]}),Mt({attr:"smallCaps",valueType:"boolean",aliases:["small-caps","fontVariant","font-variant"]}),Mt({attr:"allCaps",valueType:"boolean",aliases:["all-caps","caps"]}),Mt({attr:"letterSpacing",valueType:"number",min:-20,max:100,aliases:["letter-spacing","characterSpacing","character-spacing"]}),Mt({attr:"code",valueType:"boolean"}),Mt({attr:"superscript",valueType:"boolean"}),Mt({attr:"subscript",valueType:"boolean"}),Mt({attr:"fontSize",valueType:"number",integer:!0,min:1,max:512,aliases:["font-size"]}),Mt({attr:"fontFamily",valueType:"string",aliases:["font-family"]}),Mt({attr:"backgroundColor",valueType:"string",aliases:["background-color","background","highlightColor","highlight-color"]}),Mt({attr:"color",valueType:"string"}),Mt({attr:"link",valueType:"string",aliases:["href"]})],gr=new Map,Bi=(s,t)=>{const e=s.toLowerCase(),n=gr.get(e)??[];n.push(t),gr.set(e,n)};for(const s of fd){Bi(s.attr,s);for(const t of s.aliases??[])Bi(t,s)}const Ei={align:{nodeNames:["paragraph","image","math","table","toc"],valueType:"string",enumValues:["left","center","right","justify"]},heading:{nodeNames:["paragraph"],valueType:"number",integer:!0,min:1,max:6},lineSpacing:{nodeNames:["paragraph","list","list-item"],valueType:"number",min:.5,max:4},leftIndent:{nodeNames:["paragraph"],valueType:"number",integer:!0,min:0,max:20},direction:{nodeNames:["paragraph","list-item","toc"],valueType:"string",enumValues:["ltr","rtl"]},firstLineIndent:{nodeNames:["paragraph"],valueType:"number",integer:!0,min:-1,max:1},spaceBefore:{nodeNames:["paragraph","list","list-item"],valueType:"number",min:0},spaceAfter:{nodeNames:["paragraph","list","list-item"],valueType:"number",min:0},width:{nodeNames:["image"],valueType:"number",integer:!0,min:1},height:{nodeNames:["image"],valueType:"number",integer:!0,min:1},alt:{nodeNames:["image"],valueType:"string"},src:{nodeNames:["image"],valueType:"string"},language:{nodeNames:["code"],valueType:"string"},renderDiagram:{nodeNames:["code"],valueType:"boolean"},showDiagramSource:{nodeNames:["code"],valueType:"boolean"},displayMode:{nodeNames:["math"],valueType:"string",enumValues:["inline","block"]},variant:{nodeNames:["list"],valueType:"string",enumValues:["ordered","unordered","todo"]},startNumber:{nodeNames:["list"],valueType:"number",integer:!0,min:1},numberingChainId:{nodeNames:["list"],valueType:"string"},checked:{nodeNames:["list-item"],valueType:"boolean"},indentLevel:{nodeNames:["list-item"],valueType:"number",integer:!0,min:0,max:10},tableWidth:{nodeNames:["table"],valueType:"number",integer:!0,min:1},borderColor:{nodeNames:["table","table-cell","container"],valueType:"string"},borderWidth:{nodeNames:["table","table-cell"],valueType:"number",integer:!0,min:0},borders:{nodeNames:["table","table-cell"],valueType:"string"},cellPadding:{nodeNames:["table"],valueType:"number",integer:!0,min:0},hasHeader:{nodeNames:["table"],valueType:"boolean"},verticalAlign:{nodeNames:["table-cell"],valueType:"string",enumValues:["top","middle","bottom"]},backgroundColor:{nodeNames:["table-cell"],valueType:"string"},padding:{nodeNames:["container","table-cell"],valueType:"number",integer:!0,min:0}};function fe(s){const t=st(s);let e="";for(const n of t)n.insert&&typeof n.insert=="string"&&(e+=n.insert);return e}function Ni(s,t,e){if(fe(t).length===0)return!!ye(s.getAttribute("_emptyTextMarks"))[e];const n=st(t);for(const o of n)if(!(!o.insert||typeof o.insert!="string"||o.insert.length===0)&&(o.attributes||{})[e]!==!0)return!1;return!0}function pd(s,t,e){const n=ye(s.getAttribute("_emptyTextMarks"));e?n[t]=!0:delete n[t],Object.keys(n).length===0?s.removeAttribute("_emptyTextMarks"):s.setAttribute("_emptyTextMarks",JSON.stringify(n))}function to(s,t,e){if(e>0)return;const n=t.children.find(o=>o.type==="text"&&o.text===""&&Object.keys(o.marks??{}).length>0);n?.marks&&s.setAttribute("_emptyTextMarks",JSON.stringify(n.marks))}function ur(s,t,e){const n=ye(s.getAttribute("_emptyTextMarks"));e==null?delete n[t]:n[t]=e,Object.keys(n).length===0?s.removeAttribute("_emptyTextMarks"):s.setAttribute("_emptyTextMarks",JSON.stringify(n))}function md(s,t,e){const n=Oe(s,t);if(!Number.isFinite(n))throw new Error(`set_block_attribute "${s}" expects a number.`);if(e.integer&&!Number.isInteger(n))throw new Error(`set_block_attribute "${s}" expects an integer value.`);if(e.min!==void 0&&n<e.min)throw new Error(`set_block_attribute "${s}" must be >= ${e.min}.`);if(e.max!==void 0&&n>e.max)throw new Error(`set_block_attribute "${s}" must be <= ${e.max}.`);return n}function bd(s){if(s==null)return"set";if(s==="set"||s==="toggle"||s==="remove")return s;throw new Error('set_block_attribute operation must be one of "set", "toggle", or "remove".')}function Li(s,t){let e=Array.isArray(t)?t:[t];if(typeof t=="string"){const r=t.trim();if(r.startsWith("[")&&r.endsWith("]"))try{const i=JSON.parse(r);Array.isArray(i)&&(e=i)}catch{}}const n=[],o=new Set;for(const r of e){if(typeof r!="string"||r.trim().length===0)throw new Error(`${s} requires a valid block ID or a non-empty list of block IDs.`);const i=r.trim();o.has(i)||(o.add(i),n.push(i))}if(n.length===0)throw new Error(`${s} requires a valid block ID or a non-empty list of block IDs.`);return n}function Fi(s){if(s===!0||s===!1)return s;if(typeof s=="string"){const t=s.trim().toLowerCase();if(t==="true")return!0;if(t==="false")return!1}return!1}function Oi(s,t,e){if(e.valueType==="string"){if(typeof t!="string")throw new Error(`set_block_attribute "${s}" expects a string value.`);if(e.enumValues&&!e.enumValues.includes(t))throw new Error(`set_block_attribute "${s}" must be one of: ${e.enumValues.join(", ")}.`);return t}if(e.valueType==="boolean"){if(typeof t!="boolean")throw new Error(`set_block_attribute "${s}" expects a boolean value.`);return String(t)}const n=Oe(s,t);if(!Number.isFinite(n))throw new Error(`set_block_attribute "${s}" expects a number.`);if(e.integer&&!Number.isInteger(n))throw new Error(`set_block_attribute "${s}" expects an integer value.`);if(e.min!==void 0&&n<e.min)throw new Error(`set_block_attribute "${s}" must be >= ${e.min}.`);if(e.max!==void 0&&n>e.max)throw new Error(`set_block_attribute "${s}" must be <= ${e.max}.`);return String(n)}function hr(s,t,e){if(e===void 0){et(s,t);return}s.setAttribute(t,String(e))}function Ri(s,t,e){if(t==="toggle")throw new Error('set_block_attribute "indentLevel" does not support toggle. Use operation "set" with a numeric value or "remove".');const n=t==="remove"?0:Number(Oi("indentLevel",e,{valueType:"number",integer:!0,min:0,max:20})),o=n>0?Jt(1):void 0,r=n>1?Ht(n-1):void 0;hr(s,"firstLineIndent",o),hr(s,"leftIndent",r)}function fr(s,t,e){if(e===null){et(s,t);return}const n=t==="leftIndent"?Ht(e):Jt(e);hr(s,t,n)}function Oe(s,t){if(typeof t=="number")return t;if(typeof t!="string")return Number.NaN;const e=t.trim();if(!e)return Number.NaN;const n=e.toLowerCase();if(s==="leftIndent"||s==="firstLineIndent"){const i=bl(e,{firstLine:s==="firstLineIndent"});if(i!==void 0)return i}const o=n.match(/^(-?\d+(?:\.\d+)?)(px|pt|in|cm|mm)$/);if(o){const i=Number(o[1]),a=o[2],l={px:1,pt:4/3,in:96,cm:96/2.54,mm:96/25.4};return i*l[a]}if(s==="heading"){const i=n.match(/^h([1-6])$/);if(i)return Number(i[1])}if(s==="lineSpacing"){const i={single:1,"1x":1,"1.0x":1,one:1,double:2,"2x":2,"2.0x":2,onehalf:1.5,"one-half":1.5,"one and a half":1.5,"one-and-a-half":1.5,"1.5x":1.5};if(i[n]!==void 0)return i[n]}const r=Number(e);return Number.isFinite(r)?r:Number.NaN}function ne(s,t,e){const n=fe(e);s.push({kind:"replace",paragraphId:t,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(e,0,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(e,n.length,0)),text:n,oldText:n})}function Bt(s){const t=s.getAttribute("id");return typeof t=="string"&&t.length>0?t:s.nodeName}function eo(s){return gr.get(s.trim().toLowerCase())??[]}function pe(s,t,e,n){if(typeof e!="string")throw new Error(`${s} "${t}" expects a string value.`);const o=e.trim();if(o.length===0)throw new Error(`${s} "${t}" expects a non-empty string.`);if(/[<>;]/.test(o))throw new Error(`${s} "${t}" contains unsupported characters.`);if(t==="fontFamily"&&yd(o))throw new Error(`${s} "fontFamily" does not support CSS-wide values like "inherit"; use a concrete font family such as "Arial, sans-serif".`);const r=o.toLowerCase();if(n&&!n.includes(r))throw new Error(`${s} "${t}" must be one of: ${n.join(", ")}.`);return n?r:o}function yd(s){const t=s.trim().replace(/\s*!important\s*$/i,"").trim().toLowerCase();return["inherit","initial","unset","revert","revert-layer"].includes(t)}function pr(s,t,e){if(typeof e=="boolean")return e;if(typeof e=="string"){const n=e.trim().toLowerCase();if(["true","yes","on","1"].includes(n))return!0;if(["false","no","off","0","none"].includes(n))return!1}if(e===1)return!0;if(e===0)return!1;throw new Error(`${s} "${t}" expects a boolean value.`)}function Di(s,t,e){if(typeof e!="string"&&typeof e!="number")return e;const n=s.trim().toLowerCase(),o=typeof e=="number"?String(e):e.trim().toLowerCase();if(n==="fontstyle"||n==="font-style"){if(t==="italic"){if(o==="italic"||o==="oblique")return!0;if(o==="normal")return!1}return e}if(n==="fontweight"||n==="font-weight"){if(t==="bold"){if(o==="bold"||o==="bolder")return!0;if(o==="normal"||o==="lighter")return!1;const r=Number(o);if(Number.isFinite(r))return r>=600}return e}if(n==="textdecoration"||n==="text-decoration"){if(t==="underline"){if(o.includes("underline"))return!0;if(o==="none")return!1}return e}return(n==="line-through"||n==="strike")&&t==="strikethrough"?o!=="false"&&o!=="none":e}function Re(s,t,e,n){const o=Oe(t,e);if(!Number.isFinite(o))throw new Error(`${s} "${t}" expects a number.`);const r=n.integer?Math.round(o):o;if(n.min!==void 0&&r<n.min)throw new Error(`${s} "${t}" must be >= ${n.min}.`);if(n.max!==void 0&&r>n.max)throw new Error(`${s} "${t}" must be <= ${n.max}.`);return r}function Ft(s,t,e,n){const o=Bt(t);if(e){ne(s,o,e);return}const r=`Updated ${n} on ${t.nodeName} block.`;s.push({kind:"replace",paragraphId:o,text:r,oldText:r})}function no(s,t){const e=s.parent;if(s.nodeName!=="paragraph"||!(e instanceof I.XmlElement)||e.nodeName!=="footnote"||!s.doc)return null;const n=Kt(s.doc).notes?.find(o=>o.id===e.getAttribute("id"))?.children.find(o=>o.id===s.getAttribute("id"));return!n||n.type!=="paragraph"||typeof t=="string"&&n.children.length>0&&n.children.every(o=>o.marks?.fontFamily===t)?null:"Note-body fontFamily is inherited from its reference numeral. Style the reference paragraph to change the note font."}function $i(s){const{toolName:t,yBlock:e,yText:n,attribute:o,operation:r,value:i,config:a,anchors:l}=s;if(!n||e.nodeName!=="paragraph"&&e.nodeName!=="list-item")throw new Error(`${t} "${o}" only supports paragraph or list-item text blocks.`);if(r==="toggle"&&a.valueType!=="boolean")throw new Error(`${t} "${o}" does not support toggle. Use operation "set" with a value or "remove".`);let c;if(r==="remove"||i===null)c=null;else if(r==="toggle")c=!Ni(e,n,o);else if(a.valueType==="boolean")c=i===void 0?!0:pr(t,o,i);else{if(i===void 0)throw new Error(`${t} "${o}" requires a value.`);a.valueType==="number"?c=Re(t,o,i,a):c=pe(t,o,i)}if(o==="fontFamily"){const d=no(e,c);if(d)throw new Error(d)}if(n.length>0)at(n,0,n.length,{[o]:c===null?null:c}),ne(l,Bt(e),n);else{ur(e,o,c);const d=`Text mark "${o}" ${c===null?"removed":"set"}.`;l.push({kind:"replace",paragraphId:Bt(e),text:d,oldText:d})}}const ji=new Set(["fontSize","fontFamily","color"]);function _i(s){const{toolName:t,yBlock:e,attribute:n,operation:o,value:r,config:i,anchors:a}=s;if(!ji.has(n))throw new Error(`${t} "${n}" cannot style a table of contents: its entries are generated from the document's headings. A table of contents supports fontSize, fontFamily, color; style the headings themselves for other text formatting.`);if(o==="toggle")throw new Error(`${t} "${n}" does not support toggle. Use operation "set" with a value or "remove".`);if(o==="remove"||r===null)e.removeAttribute(n);else{if(r===void 0)throw new Error(`${t} "${n}" requires a value.`);if(n==="fontSize"){const l=Re(t,n,r,i);if(!kl(l))throw new Error(`${t} "fontSize" on a table of contents must be between ${Sl} and ${Il} px.`);e.setAttribute(n,String(l))}else if(n==="color"){const l=typeof r=="string"?ks(r):void 0;if(!l)throw new Error(`${t} "color" expects a CSS color string or null.`);e.setAttribute(n,l)}else e.setAttribute(n,pe(t,n,r))}Ft(a,e,null,n)}function kd(s){const{yBlock:t}=s;if(t.nodeName==="paragraph"||t.nodeName==="list-item"){$i({...s,yText:bt(t)});return}if(t.nodeName==="toc"){_i(s);return}const e=[],n=[],o=l=>{for(let c=0;c<l.length;c++){const d=l.get(c);if(d instanceof I.XmlElement&&!s.independentlySelectedTargets?.has(d)){if(d.nodeName==="paragraph"||d.nodeName==="list-item"){e.push(d);continue}if(d.nodeName==="toc"){ji.has(s.attribute)&&n.push(d);continue}o(d)}}};if(o(t),s.attribute==="fontFamily"&&s.operation!=="toggle"){const l=s.operation==="remove"||s.value===null?null:pe(s.toolName,s.attribute,s.value);for(const c of e){const d=no(c,l);if(d)throw new Error(d)}}let r=0;const i=[],a=l=>{try{$i({...s,yBlock:l,yText:bt(l)}),r++}catch(c){i.push(c instanceof Error?c.message:String(c))}};for(const l of e)a(l);for(const l of n)try{_i({...s,yBlock:l}),r++}catch(c){i.push(c instanceof Error?c.message:String(c))}if(r===0)throw new Error(i[0]??`${s.toolName} "${s.attribute}" found no descendant text blocks to style.`)}function Sd(s){const{toolName:t,yBlock:e,ranges:n,attribute:o,operation:r,value:i,config:a,anchors:l}=s,c=bt(e);if(!c)throw new Error(`${t} inline selector matched a block without text content.`);let d;if(r==="remove"||i===null?d=null:a.valueType==="boolean"?d=pr(t,o,i):a.valueType==="number"?d=Re(t,o,i,a):d=pe(t,o,i),o==="fontFamily"){const g=no(e,d);if(g)throw new Error(g)}for(const g of n)at(c,g.start,g.length,{[o]:d===null?null:d});ne(l,Bt(e),c)}function oo(s){const{toolName:t,yBlock:e,attribute:n,operation:o,value:r,config:i,anchors:a}=s;if(!i.nodeNames.includes(e.nodeName))throw new Error(`${t} "${n}" is not valid for ${e.nodeName} blocks.`);const l=n==="heading"&&e.nodeName==="paragraph"?{heading:rt(e,"heading"),styleId:rt(e,"styleId")}:void 0;if(n==="indentLevel"&&e.nodeName==="paragraph"){Ri(e,o,r),Ft(a,e,bt(e),n);return}if(n==="padding"&&e.nodeName==="table-cell"){if(o==="remove"||r===null)et(e,n);else{const c=Re(t,n,r,i);e.setAttribute(n,JSON.stringify({top:c,right:c,bottom:c,left:c}))}Ft(a,e,null,n);return}if(n==="borders"&&(e.nodeName==="table"||e.nodeName==="table-cell")){if(o==="remove"||r===null)et(e,"borders");else{const c=pe(t,n,r),d=Xs(c);if(!d)throw new Error(`${t} "border" expects a CSS border shorthand like "1px solid #cccccc" or "none".`);const g={top:d,right:d,bottom:d,left:d};e.nodeName==="table"&&(g.insideH=d,g.insideV=d);const u=Us(g);u&&e.setAttribute("borders",u)}Ft(a,e,null,"borders");return}if(e.nodeName==="table-cell"&&(n==="borderColor"||n==="borderWidth")){if(o==="remove"||r===null)et(e,"borders");else{const c=cc(rt(e,"borders")),d=n==="borderColor"?pe(t,n,r):Re(t,n,r,i),g=["top","right","bottom","left"],u={};for(const h of g){const p=c?.[h]??{style:"single",width:1,color:"#cccccc"};u[h]={...p,...n==="borderColor"?{color:d}:{width:d}}}const f=Us(u);f&&e.setAttribute("borders",f)}Ft(a,e,null,"borders");return}if(o==="remove"||r===null)et(e,n);else if(o==="toggle"){if(i.valueType!=="boolean")throw new Error(`${t} "${n}" only supports toggle for boolean attributes.`);const c=Fi(rt(e,n));e.setAttribute(n,String(!c))}else{if(r===void 0)throw new Error(`${t} "${n}" requires "value" when operation is "set".`);let c;i.valueType==="string"?c=pe(t,n,r,i.enumValues):i.valueType==="boolean"?c=String(pr(t,n,r)):c=String(Re(t,n,r,i)),e.nodeName==="paragraph"&&(n==="leftIndent"||n==="firstLineIndent")?fr(e,n,Number(c)):e.setAttribute(n,c)}l&&Id(e,l),Ft(a,e,bt(e),n)}function Xi(s){const t=Number(s);return Number.isInteger(t)&&t>=1&&t<=6?t:void 0}function Id(s,t){const e=s.doc?.getMap("metadata").get("stylesheet"),n=Xi(rt(s,"heading")),o=Ye(e,n);if(!e||!o)return;const r=(typeof t.styleId=="string"?_o(e,t.styleId):void 0)??Ye(e,Xi(t.heading));n!==void 0&&o.styleId.toLowerCase()!=="normal"?s.setAttribute("styleId",o.styleId):et(s,"styleId");const i=r?.paragraphAttrs??{},a=o.paragraphAttrs??{},l=(f,h)=>Object.prototype.hasOwnProperty.call(f,h),c=["align","lineSpacing","spaceBefore","spaceAfter","contextualSpacing","leftIndent","firstLineIndent","direction","borders","shading","tabStops"];for(const f of c){if(!l(i,f)&&!l(a,f))continue;const h=a[f];h===void 0||h===!1?et(s,f):f==="leftIndent"||f==="firstLineIndent"?fr(s,f,Number(h)):s.setAttribute(f,String(h))}const d=["keepNext","keepLines","widowControl"];if(d.some(f=>l(i,f)||l(a,f))){const f={};vn(f,rt(s,"pagination"));for(const p of d)!l(i,p)&&!l(a,p)||(a[p]===void 0?delete f[p]:f[p]=a[p]);const h=qt(f);h===void 0?et(s,"pagination"):s.setAttribute("pagination",h)}const g=Xo(r?.runMarks,o.runMarks),u=bt(s);if(u&&u.length>0)at(u,0,u.length,g);else for(const[f,h]of Object.entries(g))ur(s,f,h===!1?null:h)}function vd(s){if(s.config.nodeNames.includes(s.yBlock.nodeName)){oo(s);return}if(!(s.config.nodeNames.includes("paragraph")||s.config.nodeNames.includes("list-item"))){oo(s);return}let t=0;const e=[],n=o=>{for(let r=0;r<o.length;r++){const i=o.get(r);if(i instanceof I.XmlElement&&!s.independentlySelectedTargets.has(i)){if(i.nodeName==="paragraph"||i.nodeName==="list-item"){try{oo({...s,yBlock:i}),t++}catch(a){e.push(a instanceof Error?a.message:String(a))}continue}n(i)}}};if(n(s.yBlock),t===0)throw new Error(e[0]??`${s.toolName} "${s.attribute}" found no descendant text blocks to style.`)}function xd(s){const t=[],e=n=>{n.nodeName!=="footnote"&&n.nodeName!=="header-footer"&&t.push(n);for(let o=0;o<n.length;o++){const r=n.get(o);r instanceof I.XmlElement&&e(r)}};for(const n of[We(s),s.getXmlFragment("notes")])for(const o of n.toArray())o instanceof I.XmlElement&&e(o);return t}function mr(s){switch(s.nodeName){case"paragraph":{const t=s.getAttribute("heading");return typeof t=="string"&&/^[1-6]$/.test(t)?[`h${t}`]:["p"]}case"list":return s.getAttribute("variant")==="ordered"?["ol"]:["ul"];case"list-item":return["li"];case"code":return["pre"];case"math":return["latex"];case"image":return["img"];case"table":return["table"];case"table-row":return["tr"];case"table-cell":return["td"];case"container":return["div"];default:return[s.nodeName]}}function wd(s,t){const e=[],n=o=>{for(let r=0;r<o.length;r++){const i=o.get(r);i instanceof I.XmlElement&&(mr(i).includes(t)&&e.push(i),n(i))}};return n(s),e}function Ad(s){const t=s.match(/^#([A-Za-z0-9_-]+)\s+([a-zA-Z][a-zA-Z0-9-]*)$/);return t?{id:t[1],tag:t[2].toLowerCase()}:null}function Ze(s){return s.toLowerCase()==="th"?"td":s.toLowerCase()}function br(s){const t=s.match(/^(\*|[a-zA-Z][a-zA-Z0-9-]*)(?::(?:(first-child)|(last-child)|nth-child\(\s*(\d+|odd|even)\s*\)))?$/);if(!t)return null;const e=t[2]?1:t[3]?"last":t[4]==="odd"||t[4]==="even"?t[4]:t[4]?Number(t[4]):void 0;return typeof e=="number"&&e<1?null:{tag:Ze(t[1]),nthChild:e}}function tn(s,t){if(t.tag!=="*"&&!mr(s).includes(t.tag))return!1;if(t.nthChild===void 0)return!0;const e=s.parent;if(!(e instanceof I.XmlElement)&&!(e instanceof I.XmlFragment))return!1;const n=e.toArray().filter(r=>r instanceof I.XmlElement),o=n.indexOf(s)+1;return o===0?!1:t.nthChild==="last"?o===n.length:t.nthChild==="odd"?o%2===1:t.nthChild==="even"?o%2===0:o===t.nthChild}function Ui(s,t){if(!tn(s,t[t.length-1]))return!1;let e=s.parent;for(let n=t.length-2;n>=0;n--){for(;e instanceof I.XmlElement&&!tn(e,t[n]);)e=e.parent;if(!(e instanceof I.XmlElement))return!1;e=e.parent}return!0}const yr={span:"*",b:"bold",strong:"bold",i:"italic",em:"italic",u:"underline",s:"strikethrough",strike:"strikethrough",del:"strikethrough",code:"code",sup:"superscript",sub:"subscript",mark:"backgroundColor",a:"link"};function Td(s){const t=s.split(/\s+/).filter(Boolean),e=t.findIndex(o=>yr[o.toLowerCase()]!==void 0);if(e<0)return null;const n=t.slice(e).map(o=>o.toLowerCase());return n.some(o=>!yr[o])?null:{scopeSelector:e===0?"*":t.slice(0,e).join(" "),markAttributes:Array.from(new Set(n.map(o=>yr[o])))}}function Cd(s){if(s.nodeName==="paragraph"||s.nodeName==="list-item")return[s];const t=[],e=n=>{for(let o=0;o<n.length;o++){const r=n.get(o);r instanceof I.XmlElement&&(r.nodeName==="paragraph"||r.nodeName==="list-item"?t.push(r):e(r))}};return e(s),t}function Pd(s,t){if(t==="*")return!0;const e=s?.[t];return t==="link"||t==="backgroundColor"?typeof e=="string"&&e.length>0:e===!0}function Md(s,t){const e=[];let n=0;for(const o of st(s)){if(typeof o.insert!="string")continue;const r=o.insert.length,i=o.attributes;if(r>0&&t.every(a=>Pd(i,a))){const a=e[e.length-1];a&&a.start+a.length===n?a.length+=r:e.push({start:n,length:r})}n+=r}return e}function Bd(s,t){const e=[...s,...t].sort((o,r)=>o.start-r.start),n=[];for(const o of e){const r=n[n.length-1];r&&o.start<=r.start+r.length?r.length=Math.max(r.length,o.start+o.length-r.start):n.push({...o})}return n}function Ed(s){const t=Array.isArray(s)?s:[s],e=[],n=new Set;for(const o of t){if(typeof o!="string")throw new Error("style_blocks selectors must be strings.");for(const r of o.split(",")){const i=r.trim(),a=["all","document",":root"].includes(i.toLowerCase())?"*":i.replace(/\s*>\s*/g," ");a&&(n.has(a)||(n.add(a),e.push(a)))}}if(e.length===0)throw new Error("style_blocks requires at least one selector.");return e}function zi(s,t){const e=xd(s),n=[],o=new Set,r=[],i=[],a=l=>{const c=Bt(l),d=`${l.nodeName}:${c}`;o.has(d)||(o.add(d),n.push(l))};for(const l of t){if(l==="*"){for(const m of e)a(m);continue}const c=l.match(/^(p|h[1-6]|li)\[data-style-id=(?:"([^"]+)"|'([^']+)'|([^\]]+))\]$/i);if(c){const m=Ze(c[1]),y=(c[2]??c[3]??c[4]).trim(),b=e.filter(k=>tn(k,{tag:m})&&k.getAttribute("styleId")===y);b.length===0&&r.push(l);for(const k of b)a(k);continue}const d=l.match(/^#([A-Za-z0-9_-]+)\s*~\s*(\*|[a-zA-Z][a-zA-Z0-9-]*)$/);if(d){const m=Z(s,d[1]),y=m?.parent;if(!m||!(y instanceof I.XmlElement)&&!(y instanceof I.XmlFragment)){r.push(l);continue}const b=y.toArray(),k=b.indexOf(m),S=Ze(d[2]),v=e.filter(x=>x.parent===y&&b.indexOf(x)>k&&tn(x,{tag:S}));v.length===0&&r.push(l);for(const x of v)a(x);continue}const g=l.match(/^#([A-Za-z0-9_-]+)\s+(.+)$/);if(g){const m=Z(s,g[1]);if(!m){r.push(l);continue}const y=g[2].split(/\s+/).filter(Boolean).map(br);if(y.some(v=>v===null)){i.push(`selector "${l}" is not supported; descendants may use block tags, :first-child, and :nth-child(n).`);continue}const b=y,k=v=>{let x=v;for(;x;){if(x===m)return!0;x=x.parent}return!1},S=e.filter(v=>k(v)&&(b.length!==1||b[0].tag!=="*"||v!==m)&&Ui(v,b));S.length===0&&r.push(l);for(const v of S)a(v);continue}const u=Ad(l);if(u){if(u.tag==="span"){i.push('selector "span" is inline, not a block selector; target containing blocks with p, li, h1-h6, or #blockId.');continue}const m=Z(s,u.id);if(!m){r.push(l);continue}const y=wd(m,Ze(u.tag));if(y.length===0){r.push(l);continue}for(const b of y)a(b);continue}if(l.includes(" ")&&!l.startsWith("#")){const m=l.split(/\s+/).filter(Boolean).map(br);if(m.some(k=>k===null)){i.push(`selector "${l}" is not supported; descendant selectors may use block tags, :first-child, and :nth-child(n).`);continue}const y=m;if(y.some(k=>k.tag==="span")){i.push(`selector "${l}" contains an inline selector; target its containing block instead.`);continue}const b=e.filter(k=>Ui(k,y));b.length===0&&r.push(l);for(const k of b)a(k);continue}if(l.startsWith("#")){const m=l.slice(1).trim();if(!m||/[\s.#:[\]>+~]/.test(m)){i.push(`selector "${l}" is not supported; use #blockId with a plain block ID.`);continue}const y=Z(s,m);y?a(y):r.push(l);continue}const f=br(l);if(f){let m=0;for(const y of e)tn(y,f)&&(a(y),m+=1);m===0&&r.push(l);continue}if(!/^[a-zA-Z][a-zA-Z0-9-]*$/.test(l)){i.push(`selector "${l}" is not supported; use *, #id, or tag selectors like p, h2, li, table.`);continue}const h=Ze(l);if(h==="span"){i.push('selector "span" is inline, not a block selector; target containing blocks with p, li, h1-h6, or #blockId.');continue}let p=0;for(const m of e)mr(m).includes(h)&&(a(m),p++);p===0&&r.push(l)}return{targets:n,unmatchedSelectors:r,invalidSelectorErrors:i}}function Nd(s,t){const e=Ed(t),n=[],o=[];for(const c of e){const d=Td(c);d?o.push({selector:c,parsed:d}):n.push(c)}const r=n.length>0?zi(s,n):{targets:[],unmatchedSelectors:[],invalidSelectorErrors:[]},i=new Map,a=[...r.unmatchedSelectors],l=[...r.invalidSelectorErrors];for(const{selector:c,parsed:d}of o){const g=zi(s,[d.scopeSelector]);if(g.invalidSelectorErrors.length>0){l.push(...g.invalidSelectorErrors.map(h=>`selector "${c}": ${h}`));continue}let u=0;const f=new Set;for(const h of g.targets)for(const p of Cd(h)){const m=Bt(p);if(f.has(m))continue;f.add(m);const y=bt(p);if(!y)continue;const b=Md(y,d.markAttributes);if(b.length===0)continue;u+=b.length;const k=i.get(m);k?k.ranges=Bd(k.ranges,b):i.set(m,{yBlock:p,ranges:b})}u===0&&a.push(c)}return{targets:r.targets,inlineTargets:Array.from(i.values()),unmatchedSelectors:a,invalidSelectorErrors:l}}function me(s){return s.trim().toLowerCase().replace(/[-_\s]/g,"")}function Ld(s){let t;if(Array.isArray(s))t=s.map((e,n)=>{if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`style_blocks attrs[${n}] must be an object.`);const o=e;if(typeof o.name!="string"||o.name.trim().length===0)throw new Error(`style_blocks attrs[${n}].name must be a string.`);return[o.name,o.value]});else if(s&&typeof s=="object")t=Object.entries(s);else throw new Error("style_blocks requires an attrs array or object.");if(t.length===0)throw new Error("style_blocks requires at least one attr.");return t.map(([e,n])=>({rawName:e,canonicalName:me(e),value:n}))}function Fd(s){const t=[],e=[],n=new Set,o=(r,i,a)=>{const l=`${i.kind}:${i.attr}`;let c=a;if(i.kind==="textMark"&&i.attr==="color"||i.kind==="block"&&(i.attr==="borderColor"||i.attr==="backgroundColor")){if(a!==null&&typeof a!="string")throw new Error(`style_blocks "${i.attr}" expects a CSS color string or null.`);if(typeof a=="string"&&(c=ks(a),!c))throw new Error(`style_blocks "${i.attr}" does not support ${JSON.stringify(a)}. Use a CSS named color, hex color, or CSS color function.`)}if(i.attr==="variant"&&typeof a=="string"){const g=a.trim().toLowerCase();["decimal","number","numbered","numeric","ol"].includes(g)?c="ordered":["disc","circle","square","bullet","bulleted","ul"].includes(g)?c="unordered":["check","checklist","checkbox","task"].includes(g)&&(c="todo")}const d={rawName:r,entry:i,value:c};if(n.has(l)){const g=t.findIndex(u=>`${u.entry.kind}:${u.entry.attr}`===l);g>=0&&(t[g]=d);return}n.add(l),t.push(d)};for(const{rawName:r,value:i}of s){if(r.trim().toLowerCase()==="border"){if(typeof i=="string"&&Xs(i)){for(const d of eo("borders"))o(r,d,i);continue}const l=eo("borderWidth"),c=eo("borderColor");if(i===null||typeof i=="number"){for(const d of l)o(r,d,i);if(i===null)for(const d of c)o(r,d,null);continue}if(typeof i=="string"){const d=i.match(/(?:^|\s)(\d+(?:\.\d+)?)(?:px|pt)?(?:\s|$)/i),g=Array.from(i.matchAll(/(?:^|\s)(#[0-9a-f]{3,8}|rgba?\([^)]*\)|hsla?\([^)]*\)|[a-z]+)(?=\s|$)/gi)).find(u=>!["solid","dashed","dotted","double","none"].includes(u[1].toLowerCase()));if(d)for(const u of l)o(r,u,d[1]);if(g)for(const u of c)o(r,u,g[1]);if(d||g)continue}e.push(r);continue}const a=eo(r);if(a.length===0){e.push(r);continue}for(const l of a)o(r,l,i)}return Object.assign(t,{unsupportedAttrs:e})}function Wi(s,t,e){const n=new Map;for(const r of s){const i=me(r.rawName),a=n.get(i)??[];a.push(r),n.set(i,a)}const o=[];for(const r of n.values()){const i=r.filter(c=>c.entry.kind==="textMark"),a=r.filter(c=>c.entry.kind==="block");if(i.length===0&&a.length>1){const c=a.filter(d=>d.entry.kind==="block"&&d.entry.nodeNames.some(g=>g===t.nodeName));o.push(...c.length?c:r);continue}if(i.length===0||a.length===0){o.push(...r);continue}if(e){o.push(...i);continue}const l=a.filter(c=>c.entry.kind==="block"&&c.entry.nodeNames.some(d=>d===t.nodeName));o.push(...l.length>0?l:i)}return o}function Ji(s){const t=[];for(const e of s){if(e.entry.kind!=="textMark"||e.entry.attr!=="backgroundColor"||e.value===null)continue;if(typeof e.value!="string")throw new Error(`style_blocks "backgroundColor" expects one of: ${Ln.join(", ")}.`);const n=e.value.trim(),o=Ke(n);if(!o)throw new Error(`style_blocks "backgroundColor" does not support ${JSON.stringify(n)} as a text highlight. Use one of: ${Ln.join(", ")}.`);e.value=o,n.toLowerCase()!==o&&t.push(`${e.rawName}: ${n} -> ${o}`)}return t}function De(s,t,e,n){s[e].push(n);const o=s.issuesByRawName.get(t.canonicalName)??[];o.push(n),s.issuesByRawName.set(t.canonicalName,o)}function ro(s,t){for(let e=s.length-1;e>=0;e--)if(s[e].canonicalName===t)return s[e]}function zt(s){return typeof s=="string"?s.trim().toLowerCase():void 0}function en(s){if(typeof s!="string")return;const t=s.trim().match(/^(-?\d+(?:\.\d+)?)%$/);if(!t)return;const e=Number(t[1]);return Number.isFinite(e)&&e>0?e:void 0}function so(s){return s===0?!0:typeof s=="string"&&/^[-+]?0+(?:\.0+)?(?:px|pt|in|cm|mm|%)?$/i.test(s.trim())}function Od(s){let t=s;for(;t.parent instanceof I.XmlElement;)t=t.parent;return t}function kr(s,t){const e=Bt(Od(t)),n=s.children.findIndex(c=>c.id===e),o=n>=0?s.children.slice(n).find(c=>c.type==="section-break"):void 0,r=ms(s.pageLayout,o?.type==="section-break"?o.layout:void 0),{pageWidth:i}=bs(r),a=Math.max(1,i-r.marginLeftPx-r.marginRightPx),l=r.columnGapTwips/15;return Math.max(1,Math.round(dc(a,r.columnCount,l)))}function Rd(s){if(s===null)return{remove:!0};if(typeof s=="number")return!Number.isFinite(s)||s<0?null:s===0?{remove:!0}:{remove:!1,style:"single",width:s};if(typeof s!="string")return null;const t=s.trim(),e=t.toLowerCase();if(e==="none"||so(e))return{remove:!0};const n=t.match(/(?:^|\s)(\d+(?:\.\d+)?)(px|pt)?(?=\s|$)/i),o=e.match(/(?:^|\s)(solid|double|dashed|dotted|none)(?=\s|$)/),r=Array.from(t.matchAll(/(?:^|\s)(#[0-9a-f]{3,8}|rgba?\([^)]*\)|hsla?\([^)]*\)|[a-z]+)(?=\s|$)/gi)).find(c=>!["solid","double","dashed","dotted","none"].includes(c[1].toLowerCase()));if(!n&&!o&&!r)return null;if(o?.[1]==="none")return{remove:!0};const i=n?Number(n[1]):void 0,a=i===void 0?void 0:n?.[2]?.toLowerCase()==="pt"?i*(4/3):i,l=o?.[1];return{remove:!1,style:l==="double"||l==="dashed"||l==="dotted"?l:"single",...a!==void 0?{width:a}:{},...r?{color:r[1]}:{}}}function Dd(s){if(s.yBlock.nodeName!=="paragraph")return;const t={bordertop:"top",borderright:"right",borderbottom:"bottom",borderleft:"left"};for(const e of s.rawAttrs){const n=t[e.canonicalName];if(e.canonicalName!=="border"&&!n)continue;s.result.handledRawNames.add(e.canonicalName);const o=Rd(e.value);if(!o){De(s.result,e,"errors",`${Bt(s.yBlock)}.borders: style_blocks "${e.rawName}" expects CSS border syntax such as "1px solid #cccccc".`);continue}let r={};try{const a=JSON.parse(String(rt(s.yBlock,"borders")??"{}"));a&&typeof a=="object"&&!Array.isArray(a)&&(r=a)}catch{r={}}const i=n?[n]:["top","right","bottom","left"];if(o.remove)for(const a of i)delete r[a];else for(const a of i){const l=r[a]??{style:"single",width:1,color:"#000000"};r[a]={style:o.style??l.style,width:o.width??l.width,color:o.color??l.color}}Object.keys(r).length>0?s.yBlock.setAttribute("borders",JSON.stringify(r)):et(s.yBlock,"borders"),Ft(s.anchors,s.yBlock,bt(s.yBlock),"borders"),s.result.appliedAttrs.push(`${e.rawName} -> paragraph borders`),s.result.exactMappings.push(`${e.rawName} -> paragraph borders`)}}function $d(s){if(s.yBlock.nodeName!=="image")return;const t=x=>ro(s.rawAttrs,x),e=t("display");e&&zt(e.value)==="block"&&(s.result.handledRawNames.add(e.canonicalName),De(s.result,e,"ignoredAttrs",`${e.rawName}: block`));const n=t("float"),o=zt(n?.value);n&&(o==="left"||o==="right")&&(s.result.handledRawNames.add(n.canonicalName),s.yBlock.setAttribute("align",o),Ft(s.anchors,s.yBlock,null,"align"),s.result.appliedAttrs.push(`${n.rawName} -> align`),s.result.approximateMappings.push(`${n.rawName}: ${o} -> align: ${o} without text wrapping`));const r=t("marginleft"),i=t("marginright"),a=zt(r?.value),l=zt(i?.value);let c;a==="auto"&&l==="auto"?c="center":a==="auto"&&(!i||so(i.value))?c="right":l==="auto"&&(!r||so(r.value))&&(c="left"),c&&(r&&s.result.handledRawNames.add(r.canonicalName),i&&s.result.handledRawNames.add(i.canonicalName),s.yBlock.setAttribute("align",c),Ft(s.anchors,s.yBlock,null,"align"),s.result.appliedAttrs.push("auto margins -> align"),s.result.exactMappings.push(`margin-left/margin-right auto -> align: ${c}`));for(const x of["margintop","marginright","marginbottom","marginleft"]){const w=t(x);!w||s.result.handledRawNames.has(w.canonicalName)||(s.result.handledRawNames.add(w.canonicalName),so(w.value)?De(s.result,w,"ignoredAttrs",`${w.rawName}: ${String(w.value)}`):De(s.result,w,"unsupportedImageSpacing",`${w.rawName}: ${String(w.value)}`))}const d=t("width"),g=t("maxwidth"),u=t("height"),f=zt(u?.value)==="auto",h=en(d?.value),p=en(g?.value),m=kr(s.doc,s.yBlock),y=Math.max(1,Number(s.yBlock.getAttribute("width"))||1),b=Math.max(1,Number(s.yBlock.getAttribute("height"))||1);let k=y,S=!1,v=!1;if(h!==void 0&&d)k=Math.max(1,Math.round(m*h/100)),s.result.handledRawNames.add(d.canonicalName),S=!0,v=!0;else if(f&&d){const x=Oe("width",d.value);Number.isFinite(x)&&x>0&&(k=Math.max(1,Math.round(x)),s.result.handledRawNames.add(d.canonicalName),S=!0,v=!0)}if(p!==void 0&&g){const x=Math.max(1,Math.round(m*p/100));k=Math.min(k,x),s.result.handledRawNames.add(g.canonicalName),S=!0,s.result.approximateMappings.push(`${g.rawName}: ${String(g.value)} -> fixed ${k}px snapshot`)}if(S){s.yBlock.setAttribute("width",String(k));const x=u&&!f?Oe("height",u.value):Number.NaN,w=f||!Number.isFinite(x);if(w){const A=Math.max(1,Math.round(b*k/y));s.yBlock.setAttribute("height",String(A))}f&&u&&s.result.handledRawNames.add(u.canonicalName),Ft(s.anchors,s.yBlock,null,"width/height"),s.result.appliedAttrs.push("responsive image size -> fixed snapshot"),v&&d&&s.result.approximateMappings.push(`${d.rawName}: ${String(d.value)} -> fixed ${k}px snapshot${w?" with auto height":""}`)}else f&&u&&(s.result.handledRawNames.add(u.canonicalName),De(s.result,u,"ignoredAttrs",`${u.rawName}: auto`))}function jd(s){if(s.yBlock.nodeName!=="table")return;const t=i=>ro(s.rawAttrs,i),e=t("width"),n=en(e?.value);if(e&&n!==void 0){const i=kr(s.doc,s.yBlock),a=Math.max(1,Math.round(i*n/100));s.result.handledRawNames.add(e.canonicalName),s.yBlock.setAttribute("tableWidth",String(a)),Ft(s.anchors,s.yBlock,null,"tableWidth"),s.result.appliedAttrs.push("responsive table width -> fixed snapshot"),s.result.approximateMappings.push(`${e.rawName}: ${String(e.value)} -> fixed ${a}px snapshot`)}const o=t("marginleft"),r=t("marginright");zt(o?.value)==="auto"&&zt(r?.value)==="auto"&&(s.result.handledRawNames.add(o.canonicalName),s.result.handledRawNames.add(r.canonicalName),s.yBlock.setAttribute("align","center"),Ft(s.anchors,s.yBlock,null,"align"),s.result.appliedAttrs.push("auto margins -> align"),s.result.exactMappings.push("margin-left/margin-right auto -> align: center"))}function _d(s){if(s.yBlock.nodeName!=="paragraph")return;const t=a=>ro(s.rawAttrs,a),e=t("breakafter"),n=t("breakbefore"),o=t("breakinside");if(!e&&!n&&!o)return;const r=new Set(String(rt(s.yBlock,"pagination")??"").split(",").filter(Boolean));e&&(s.result.handledRawNames.add(e.canonicalName),e.value===null||zt(e.value)==="auto"?r.delete("keepNext"):["avoid","avoid-page"].includes(zt(e.value)??"")&&r.add("keepNext"),s.result.appliedAttrs.push(`${e.rawName} -> keepNext`)),o&&(s.result.handledRawNames.add(o.canonicalName),o.value===null||zt(o.value)==="auto"?r.delete("keepLines"):["avoid","avoid-page"].includes(zt(o.value)??"")&&r.add("keepLines"),s.result.appliedAttrs.push(`${o.rawName} -> keepLines`)),n&&(s.result.handledRawNames.add(n.canonicalName),De(s.result,n,"ignoredAttrs",`${n.rawName}: ${String(n.value)}`));const i=Array.from(r).join(",");i?s.yBlock.setAttribute("pagination",i):et(s.yBlock,"pagination"),Ft(s.anchors,s.yBlock,bt(s.yBlock),"pagination")}function Xd(s){const t={issuesByRawName:new Map,handledRawNames:new Set,appliedAttrs:[],exactMappings:[],approximateMappings:[],ignoredAttrs:[],unsupportedImageSpacing:[],errors:[]};return Dd({yBlock:s.yBlock,rawAttrs:s.rawAttrs,anchors:s.anchors,result:t}),_d({...s,result:t}),$d({...s,result:t}),jd({...s,result:t}),t}function Ud(s){const{inlineRangeCount:t,unsupportedAttrs:e,unmatchedSelectors:n,invalidSelectorErrors:o,skippedTargetErrors:r,exactCompatibilityMappings:i,approximateCompatibilityMappings:a,ignoredCompatibilityAttrs:l,unsupportedImageSpacing:c}=s,d=s.styleEffects,g=[`style_blocks ${d.outcome==="partial"?"partially applied requested styling":d.outcome==="unchanged"?"verified requested styling unchanged":"applied requested styling"}. Matched ${d.targetBlockIds.length} blocks${t?` and ${t} inline ranges`:""}; changed ${d.changedBlockIds.length} blocks.`,...d.attributes.map(u=>`${u.name}: applied to ${u.appliedBlockIds.length} targets (including already-equal values), skipped on ${new Set(u.skipped.map(f=>f.blockId)).size}.`)];if(i.length>0&&g.push(`Compatibility mappings: ${Array.from(new Set(i)).join("; ")}.`),a.length>0&&g.push(`Approximate compatibility mappings: ${Array.from(new Set(a)).join("; ")}.`),l.length>0&&g.push(`Ignored compatibility attrs: ${Array.from(new Set(l)).join(", ")}.`),c.length>0&&g.push(`Unsupported image spacing ignored: ${Array.from(new Set(c)).join(", ")}.`),n.length>0&&g.push(`Unmatched selectors: ${n.join(", ")}.`),o.length>0&&g.push(`Invalid selectors ignored: ${o.join("; ")}.`),e.length>0&&g.push(`Unsupported attrs ignored: ${e.join(", ")}.`),r.length>0){const u=Array.from(new Set(r)),f=u.slice(0,12),h=u.length-f.length;g.push(`Skipped invalid target/style pairs: ${f.join("; ")}${h>0?`; and ${h} more`:""}.`)}return g.join(" ")}function zd(s){const t=ye(s.getAttribute("_emptyTextMarks"));for(const e of _s)delete t[e];Object.keys(t).length===0?s.removeAttribute("_emptyTextMarks"):s.setAttribute("_emptyTextMarks",JSON.stringify(t))}function Wd(s,t=1){if(typeof s!="number"||!Number.isFinite(s))return t;const e=Math.floor(s);return e>=1?e:t}function Jd(s){const t=bt(s);if(t){const n=st(t);let o="";for(const r of n)r.insert&&typeof r.insert=="string"&&(o+=r.insert);return o}const e=s.nodeName;return e==="list"?"List removed":e==="table"?"Table removed":e==="code"?"Code block removed":e==="math"?"Math block removed":e==="image"?"Image removed":"Block removed"}function Hi(s,t,e){const n=Jd(s),o=bt(s),r=t&&t.length>0?t:void 0;if(o&&n.length>0){e.push({kind:"delete",paragraphId:r,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(o,0,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(o,n.length,0)),text:n});return}e.push({kind:"delete",paragraphId:r,text:n})}function Hd(s,t){const e=s.parent;if(!(e instanceof I.XmlElement)&&!(e instanceof I.XmlFragment)||s.nodeName!=="list")return null;const n=e.toArray().indexOf(s);if(n<0)return null;const o=[];for(const r of s.toArray()){if(!(r instanceof I.XmlElement)||r.nodeName!=="list-item")continue;const i=new I.XmlElement("paragraph");i.setAttribute("id",r.getAttribute("id")||G());const a=rt(r,"direction");(a==="ltr"||a==="rtl")&&i.setAttribute("direction",a);for(const g of["lineSpacing","spaceBefore","spaceAfter","contextualSpacing"]){const u=rt(r,g)??rt(s,g);u!==void 0&&i.setAttribute(g,String(u))}const l=r.getAttribute("_emptyTextMarks");l&&i.setAttribute("_emptyTextMarks",l);const c=bt(r),d=new I.XmlText;c&&yl(d,st(c)),i.insert(0,[d]),o.push(i)}if(o.length===0)return null;Hi(s,s.getAttribute("id"),t),e.delete(n,1),e.insert(n,o);for(const r of o){const i=bt(r);if(!i)continue;const a=fe(i);t.push({kind:"insert",paragraphId:r.getAttribute("id"),from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(i,0,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(i,a.length,0)),text:a})}return o}function qi(s,t){if(t.link)return[{text:s,marks:t}];const e=Pi(s);if(e.length===0)return[{text:s,marks:t}];const n=[];let o=0;for(const r of e)r.start>o&&n.push({text:s.slice(o,r.start),marks:t}),n.push({text:r.originalText,marks:{...t,link:r.url}}),o=r.end;return o<s.length&&n.push({text:s.slice(o),marks:t}),n}function io(s){return It(ys(s,t=>!t.text||t.marks?.link?t:qi(t.text,t.marks||{}).map(e=>({type:"text",text:e.text,marks:e.marks}))))}function Yi(s,t){return Pt(Bn(t==="todo"?{...s,checked:s.checked??!1}:s))}function Ki(s,t,e,n=!1){return s.flatMap(o=>{if(o.type==="list")return o.children.map(r=>({...r,indentLevel:(n?0:t)+(r.indentLevel??0)}));if(o.type==="paragraph")return[{type:"list-item",id:o.id,children:o.children,direction:o.direction,lineSpacing:o.lineSpacing,spaceBefore:o.spaceBefore,spaceAfter:o.spaceAfter,indentLevel:t}];throw new Error(`Cannot put a ${o.type} inside a list item. Insert it before or after the containing list instead.`)}).map((o,r)=>({...o,id:r===0?e:o.id||G()}))}function oe(s,t,e,n){const o=qi(e,n);let r=t;for(const i of o)lt(s,r,i.text,i.marks),r+=i.text.length;return r}function Vi(s,t,e){const n=s.toString(),o=e??n.length,r=n.slice(t,o),i=Pi(r);for(const a of i){const l=t+a.start;at(s,l,a.end-a.start,{link:a.url})}}function Sr(s,t){if(!Je(s,t)||s.children.length!==t.children.length)return!1;for(let e=0;e<s.children.length;e++){const n=s.children[e],o=t.children[e];if(n.type!==o.type||n.type!=="text"||o.type!=="text"||n.text!==o.text||JSON.stringify(n.marks||{})!==JSON.stringify(o.marks||{}))return!1}return!0}function ao(s,t){const e=["heading","align","leftIndent","firstLineIndent","spaceBefore","spaceAfter","lineSpacing","styleId","direction","borders","shading","tabStops"];for(const o of e){const r=t[o];r===void 0?et(s,o):s.setAttribute(o,String(r))}const n=qt(t);n===void 0?et(s,"pagination"):s.setAttribute("pagination",n)}function qd(s,t){if(s.length!==t.length)return!1;for(let e=0;e<s.length;e++){const n=s[e],o=t[e];if(n.type!==o.type||n.text!==o.text||JSON.stringify(n.marks||{})!==JSON.stringify(o.marks||{}))return!1}return!0}function Yd(s,t){return s.type!==t.type?!1:s.type==="paragraph"&&t.type==="paragraph"?Sr(s,t):qd(s.children,t.children)}function Gi(s){return s.map(t=>({...t,marks:t.marks?{...t.marks}:void 0}))}function Qi(s,t){const e=n=>{for(const o of n){if(o.type==="paragraph"&&o.id===t)return o;if(o.type==="list"){for(const r of o.children)if(r.id===t)return r;continue}if(o.type==="container"||o.type==="table-cell"){const r=e(o.children);if(r)return r;continue}if(o.type==="table")for(const r of o.children)for(const i of r.children){const a=e(i.children);if(a)return a}}return null};return e(s.children)}function Zi(s){return s.replace(/�?39;|'/g,"'").trim()}function Kd(s,t,e){const n=s.indexOf(t);return n===-1?s:s.slice(0,n)+e+s.slice(n+t.length)}function Vd(s,t){if(t.type==="paragraph")return Zi(it.toAgentHtml({type:"doc",children:[{...t,children:Gi(t.children)}]}));if(s.listVariant==="todo")return null;const e={type:"list",id:"__agent_html_replace__",variant:s.listVariant==="ordered"?"ordered":"unordered",children:[{...t,children:Gi(t.children),indentLevel:void 0}]},n=Zi(it.toAgentHtml({type:"doc",children:[e]})).match(/^<(?:ul|ol)(?:\s[^>]*)?>([\s\S]*)<\/(?:ul|ol)>$/);return n?n[1].trim():null}function Gd(s,t,e,n){try{if(e.type==="paragraph"){const i=it.fromAgentHtml(t,{existingDocument:n,replacementBlock:e});return i.children.length!==1||i.children[0].type!=="paragraph"?null:i.children[0]}if(s.listVariant==="todo")return null;const o=s.listVariant==="ordered"?"ol":"ul",r=it.fromAgentHtml(`<${o}>${t}</${o}>`,{existingDocument:n});return r.children.length!==1||r.children[0].type!=="list"||r.children[0].children.length!==1?null:r.children[0].children[0]}catch{return null}}function Qd(s,t){const e=/<mark\b[^>]*\bcolor=(?:"([^"]+)"|'([^']+)')[^>]*>/i,n=s.match(e),o=t.match(e),r=n?.[1]??n?.[2],i=o?.[1]??o?.[2];if(!r||!i||r===i)return null;const a=Ke(r),l=Ke(i);return!a||a!==l?null:`Highlight colors ${JSON.stringify(r)} and ${JSON.stringify(i)} both resolve to ${JSON.stringify(a)}, so this replacement is a no-op. Use a different canonical highlight color: ${Ln.join(", ")}.`}function Zd(s){const t=/<mark\b[^>]*\bcolor=(?:"([^"]+)"|'([^']+)')[^>]*>/gi;for(const e of s.matchAll(t)){const n=e[1]??e[2];if(n&&!Ke(n))throw new Error(`Unsupported highlight color ${JSON.stringify(n)}. Use one of: ${Ln.join(", ")}.`)}}function ta(s){const t=s?.comment;return typeof t!="string"||t.length===0?[]:Array.from(new Set(t.split(",").map(e=>e.trim()).filter(Boolean))).sort()}function re(s,t={}){const e=Object.entries(s??{}).filter(([n,o])=>o!==void 0&&(n!=="comment"||!t.ignoreComment)).map(([n,o])=>n==="comment"?[n,ta(s).join(",")]:[n,o]).filter(([,n])=>n!=="").sort(([n],[o])=>n<o?-1:n>o?1:0);return JSON.stringify(e)}function tg(s){return Object.fromEntries(Object.entries(s).sort(([t],[e])=>t<e?-1:t>e?1:0))}function lo(s){return s.flatMap(t=>{const{comment:e,...n}=t.marks??{},o=ta(t.marks);return Array.from({length:t.text.length},(r,i)=>({value:t.text[i],marks:n,comment:o}))})}function eg(s){return s.length===0?[]:s.reduce((t,e)=>t.filter(n=>e.includes(n)))}const be=-1,Ir=0,nn=1;function ng(s){const t=[];for(let e=0;e<s.length;e++){const[n,o]=s[e],r=s[e+1];if(!(r!==void 0&&(n===be&&r[0]===nn||n===nn&&r[0]===be))){t.push([n,o]);continue}const i=n===be?o:r[1],a=n===nn?o:r[1];let l=0;const c=Math.min(i.length,a.length);for(;l<c&&i[l]===a[l];)l++;let d=0;const g=c-l;for(;d<g&&i[i.length-1-d]===a[a.length-1-d];)d++;l>0&&t.push([Ir,i.slice(0,l)]);const u=i.slice(l,i.length-d),f=a.slice(l,a.length-d);u.length>0&&t.push([be,u]),f.length>0&&t.push([nn,f]),d>0&&t.push([Ir,i.slice(i.length-d)]),e++}return t}function og(s,t){const e=lo(s),n=lo(t),o=ng(ic([],e.map(d=>d.value).join(""),n.map(d=>d.value).join(""))),r=new Array(n.length),i=new Array(n.length);let a=0,l=0;for(let d=0;d<o.length;d++){const[g,u]=o[d];if(g===Ir){for(let S=0;S<u.length;S++)r[l+S]=e[a+S].comment,i[l+S]=e[a+S].marks.lang;a+=u.length,l+=u.length;continue}if(g===be){a+=u.length;continue}if(g!==nn)continue;const f=o[d-1],h=o[d+1],p=[];f?.[0]===be&&p.push(...e.slice(a-f[1].length,a)),h?.[0]===be&&p.push(...e.slice(a,a+h[1].length));const m=p.length>0?p:[e[a-1],e[a]].filter(S=>!!S),y=eg(m.map(S=>S.comment)),b=m[0]?.marks.lang,k=typeof b=="string"&&m.every(S=>S.marks.lang===b)?b:void 0;for(let S=0;S<u.length;S++)r[l+S]=y,i[l+S]=k;l+=u.length}const c=[];return n.forEach((d,g)=>{const u=r[g]??[],f=tg({...d.marks,...d.marks.lang===void 0&&i[g]!==void 0?{lang:i[g]}:{},...u.length>0?{comment:u.join(",")}:{}}),h=c[c.length-1];h&&re(h.marks)===re(f)?h.text+=d.value:c.push({type:"text",text:d.value,...Object.keys(f).length>0?{marks:f}:{}})}),c}function rg(s,t){const e=lo(s),n=lo(t);return e.length===n.length&&e.every((o,r)=>o.value===n[r].value&&re(o.marks)===re(n[r].marks)&&o.comment.join(",")===n[r].comment.join(","))}function ea(s,t,e,n,o){if(e=jo(e),n=jo(n),e.length===0)return null;const r=Qi(t,s.blockId);if(!r)return null;const i=Vd(s,r),a=i?jo(i):null;if(!a||!a.includes(e))return null;const l=oc(a,e).length;if(!o&&l>1)throw new Error(`Found ${l} matches for ${JSON.stringify(e)} in block '${s.blockId}' once comment-thread tags are ignored (threads don't distinguish text). Include more surrounding text so it matches exactly one location, or use replace_all.`);Zd(n);const c=o?a.split(e).join(n):Kd(a,e,n);if(c===a)return null;const d=Gd(s,c,r,t);if(!d)throw new Error(`Matched AgentHtml in block '${s.blockId}', but the replacement is not a supported single-block text update.`);if(d.type!==r.type)throw new Error(`Matched AgentHtml in block '${s.blockId}', but the replacement changes the block structure. Keep replace() within a single compatible text block.`);const g={...d,children:og(r.children,Vn(r.children,d.children))};if(Yd(r,g)||rg(r.children,g.children)&&(r.type!=="paragraph"||g.type!=="paragraph"||Je(r,g)))throw new Error(Qd(e,n)??`Matched AgentHtml in block '${s.blockId}', but the replacement would not change any supported text or formatting.`);return{blockId:s.blockId,yBlock:s.yBlock,currentBlock:r,replacementBlock:g}}function co(s,t){const e=bt(s.yBlock);if(!e)throw new Error(`Target block '${s.blockId}' has no text content to replace.`);const n=h=>h.flatMap(p=>Array.from({length:p.text.length},(m,y)=>({value:p.text[y],marks:p.marks||{}}))),o=(h,p)=>h.value===p.value&&re(h.marks)===re(p.marks),r=n(s.currentBlock.children),i=n(s.replacementBlock.children);let a=0;for(;a<r.length&&a<i.length&&o(r[a],i[a]);)a++;let l=0;for(;l<r.length-a&&l<i.length-a&&o(r[r.length-l-1],i[i.length-l-1]);)l++;const c=r.length-a-l,d=i.slice(a,i.length-l),g=I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(e,a,-1));c>0&&e.delete(a,c);let u=a;const f=[];for(let h=0;h<d.length;){const p=d[h].marks;let m=d[h].value;for(h++;h<d.length&&re(d[h].marks)===re(p);)m+=d[h].value,h++;f.push({type:"text",text:m,marks:p}),u=oe(e,u,m,p)}s.currentBlock.type==="paragraph"&&s.replacementBlock.type==="paragraph"&&(s.replacementBlock.heading?s.yBlock.setAttribute("heading",String(s.replacementBlock.heading)):s.yBlock.removeAttribute("heading"),s.replacementBlock.align?s.yBlock.setAttribute("align",s.replacementBlock.align):et(s.yBlock,"align")),t.push({kind:"replace",paragraphId:s.blockId,previewStartOffset:a,sourceFrom:g,previewTextNodes:f,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(e,a,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(e,u,0)),text:d.map(h=>h.value).join(""),oldText:r.slice(a,r.length-l).map(h=>h.value).join("")})}function Wt(s,t,e,n){const o=[];wt(t,{verifiedUnchanged:!1,styleEffects:void 0}),cr.delete(t);const r=t.name;n&&r!=="insert_block"&&(n.lastInsertedBlock=void 0);const i=t.arguments;if(r==="replace_many"||r==="replace"&&Array.isArray(i?.replacements)){const a=ir({...t,id:e??"replacement-batch"},{doc:Kt(s),loadedBlockIds:null});if(a.error){const d=a.failure;throw new St(d?.code??"invalid_arguments",a.error,d?.phase??"validation",d?.retryable,d?.mutationOutcome,d?.details)}let l=n,c=!0;for(const d of a.actions){const g=d,u=Wt(s,g,e,l);if(c=c&&!!Rt(g)?.verifiedUnchanged,o.push(...u),!l){const f=Kt(s);l={document:f,htmlParsingContext:it.createParsingContext(f),refreshDocumentIncrementally:!0}}}return wt(t,{verifiedUnchanged:c}),o}switch(t.name){case"move_blocks":throw new St("move_requires_live_session","move_blocks must execute through the tracked-move session operation, not the generic replacement planner.");case"insert_block":{const{referenceId:a,position:l,content:c}=t.arguments;if(typeof a!="string"||!a.trim())throw new Error("insert_block referenceId is required. Resolve blank-document anchors before applying the action.");const d=Wn(t),g=n?.document??mt(s);if(!Array.isArray(c))throw new Error("insert_block content must be an array");if(c.length!==1)throw new Error("insert_block should only receive a single block after preprocessing. Got array with "+c.length+" items");const u=c[0];let f,h;if(a===Ve)f=We(s),h=f.length;else if(n?.lastInsertedBlock&&n.lastInsertedBlock.id===a)f=n.lastInsertedBlock.yParent,h=l==="before"?n.lastInsertedBlock.index:n.lastInsertedBlock.index+1;else{const S=ot(s,a);if(!S)throw new Error(`Reference block '${a}' not found in the current document. Read the document again and use a current block ID.`);f=S.yParent,h=l==="before"?S.index:S.index+1}if((Le(f)||f===s.getXmlFragment("chrome"))&&Fe(),f instanceof I.XmlElement&&(f.nodeName==="table"||f.nodeName==="table-row"))throw new Error("insert_block cannot insert beside a table row or cell. Use a paragraph ID inside the cell to insert cell content, the table ID to insert beside the table, or insert_table_row / insert_table_column to change the table structure.");let p,m;const y=n?.lastInsertedBlock;if(y?.yParent===f&&y.index===h-1)p=y.block,m=y.insertionFont;else if(h>0){const S=f.get(h-1);if(S instanceof I.XmlElement){const v=S.getAttribute("id");v&&(p=n?.lastInsertedBlock?.id===v?n.lastInsertedBlock.block:W(g,v)??void 0)}}m??(m=it.insertionFontFor(p));let b;if(u.includes("<")&&u.includes(">")?b=it.fromAgentHtml(u,{previousBlock:p,insertionFont:m,existingDocument:g,parsingContext:n?.htmlParsingContext,listItemBaseIndent:f instanceof I.XmlElement&&f.nodeName==="list"?Number(Z(s,a)?.getAttribute("indentLevel")??0):void 0}):b=it.fromAgentHtml(`<p>${u}</p>`,{previousBlock:p,insertionFont:m,existingDocument:g,parsingContext:n?.htmlParsingContext,listItemBaseIndent:f instanceof I.XmlElement&&f.nodeName==="list"?Number(Z(s,a)?.getAttribute("indentLevel")??0):void 0}),b.children.length!==1)throw new Error(`insert_block should produce exactly one block. Got ${b.children.length} blocks from content: ${u}`);const k=b.children[0];if(!d)throw new Error("insert_block must have stableId set by preprocessor");if(k.id=d,f instanceof I.XmlElement&&f.nodeName==="list"){const S=Z(s,a),v=Ki([k],Number(S?.getAttribute("indentLevel")??0),d,!0);f.insert(h,v.map(x=>It(x))),o.push({kind:"insert",paragraphId:f.getAttribute("id"),text:v.map(x=>x.children.map(w=>w.text).join("")).join(`
|
|
3
|
+
`)});break}if(k.type==="paragraph"){const S=k,v=new I.XmlElement("paragraph");v.setAttribute("id",d),ao(v,S);const x=new I.XmlText;let w=0;S.children.forEach(P=>{if(P.type==="text"){const T=P;w=oe(x,w,T.text,T.marks||{})}}),to(v,S,w),v.insert(0,[x]),f.insert(h,[v]);const A=S.children.filter(P=>P.type==="text").map(P=>P.text).join("");o.push({kind:"insert",paragraphId:d,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(x,0,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(x,A.length,0)),text:A})}else if(k.type==="list"){const S=io(k);f.insert(h,[S]);const v=[];for(const x of S.toArray()){if(!(x instanceof I.XmlElement))continue;const w=ct(x);if(!w)continue;const A=st(w).map(P=>typeof P.insert=="string"?P.insert:"").join("");A.length&&v.push({yText:w,plainText:A})}v.forEach(({yText:x,plainText:w})=>{o.push({kind:"insert",paragraphId:d,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(x,0,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(x,w.length,0)),text:w})})}else if(k.type==="table"){const S=io({...k,id:d});f.insert(h,[S]),o.push({kind:"insert",paragraphId:d,text:"Table inserted"})}else if(k.type==="code"){const S=k,v=new I.XmlElement("code");v.setAttribute("id",d),S.language&&v.setAttribute("language",S.language),S.renderDiagram!==void 0&&v.setAttribute("renderDiagram",String(S.renderDiagram)),S.showDiagramSource!==void 0&&v.setAttribute("showDiagramSource",String(S.showDiagramSource));const x=new I.XmlText;v.insert(0,[x]),lt(x,0,S.content||""),f.insert(h,[v]),o.push({kind:"insert",paragraphId:d,text:"Code block inserted"})}else if(k.type==="math"){const S=k,v=new I.XmlElement("math");v.setAttribute("id",d),S.displayMode&&v.setAttribute("displayMode",S.displayMode),S.align&&v.setAttribute("align",S.align);const x=new I.XmlText;v.insert(0,[x]),lt(x,0,S.content||""),f.insert(h,[v]),o.push({kind:"insert",paragraphId:d,text:"Math block inserted"})}else if(k.type==="page-break"){const S=new I.XmlElement("page-break");S.setAttribute("id",d),f.insert(h,[S]),o.push({kind:"insert",paragraphId:d,text:"Page break inserted"})}else if(k.type==="toc"){const S=It({...k,id:d});f.insert(h,[S]),o.push({kind:"insert",paragraphId:d,text:"Table of contents inserted"})}else if(k.type==="image"){const S=k,v=new I.XmlElement("image");v.setAttribute("id",d),v.setAttribute("src",S.src),S.sourceUrl&&v.setAttribute("sourceUrl",S.sourceUrl),v.setAttribute("width",String(S.width)),v.setAttribute("height",String(S.height)),S.alt&&v.setAttribute("alt",S.alt),S.align&&v.setAttribute("align",S.align),f.insert(h,[v]),o.push({kind:"insert",paragraphId:d,text:"Image inserted"})}else throw new Error(`insert_block expected a paragraph, list, table, code, math, image, table-of-contents, or page-break block but got ${k.type}`);n&&(n.lastInsertedBlock={id:d,yParent:f,index:h,block:k,insertionFont:m},f===s.getXmlFragment("content")?n.document.children.splice(h,0,k):(n.document=mt(s),n.htmlParsingContext=it.createParsingContext(n.document)));break}case"replace":case"replace_all":{const{id:a}=t.arguments;let{find:l,replace:c}=t.arguments;const d=n?.document??mt(s),g=Z(s,a);if(!g)throw new Error(`Target block '${a}' not found in the document. Please only reference IDs you see inside <document_content>.`);let u=ld(g,a);const f=Hs(Qi(d,a)??W(d,a),l);if(f&&(u=u.filter(y=>f.has(y.blockId))),f&&u.length===0)throw new St("target_stale","HTML matcher identities no longer resolve to editable text within this target. Read the target again.","target_resolution");if(u.length===0)break;if(l.length===0){if(u.length!==1||u[0].blockText.length!==0)throw new Error(`An empty find may only fill one truly empty text block; block '${a}' is not an unambiguous empty target.`);const y=u[0];xr(y.yText,0,0,l,c,y.blockId,o,ye(y.yBlock.getAttribute("_emptyTextMarks")));break}const h=y=>u.map(b=>({...b,matches:Hn(b.blockText,y)})).filter(b=>b.matches.length>0);if(qe(l)){const y=u.map(b=>ea(b,d,l,c,t.name==="replace_all")).filter(b=>b!==null);if(y.length>0){if(t.name==="replace"&&y.length>1)throw new Error(`Found ${y.length} exact AgentHtml matches for "${l}" in block '${a}'. Include more surrounding AgentHtml so it matches exactly one location, or use replace_all.`);if(t.name==="replace")co(y[0],o);else for(const b of y)co(b,o);break}}let p=h(l);if(p.length===0){const y=Ko(l);if(y!==l&&y.trim()!==""){const b=h(y);b.length>0&&(l=y,c=Ko(c),p=b)}}if(p.length===0){const y=u.map(A=>ea(A,d,l,c,t.name==="replace_all")).filter(A=>A!==null);if(y.length>0){if(t.name==="replace")co(y[0],o);else for(const A of y)co(A,o);break}const b=u.map(A=>A.blockText).join(`
|
|
4
|
+
`),k=Os(b.length>100?b.slice(0,100)+"...":b),S=gd(s,a,l),v=/(?:\*\*|__|^>|^#{1,6}\s|^[-*+]\s|^\d+[.)]\s|\|)/m.test(l)?" The requested find contains Markdown syntax, while this preview is stored plain text; formatting markers are not literal characters.":"";if(l.includes("<")&&l.includes(">"))throw new St("text_not_found",`No match found for "${l}" in block '${a}'. The block's stored plain text begins ${JSON.stringify(k)}. If you're matching AgentHtml from the document context, the snippet must match the exact block HTML.${S}`,"matching");const x=u.map(A=>ud(A.blockText,l)).find(Boolean)??"",w=typeof c=="string"&&c.trim().length>=4&&!c.includes(l)&&b.includes(c)?` The block already contains the replacement text ${JSON.stringify(c)}, so this edit may already be applied; check the current block before retrying.`:"";throw new St("text_not_found",`No match found for "${l}" in block '${a}'. The block's stored plain text begins ${JSON.stringify(k)}.${w}${x}${v} Make sure the text you're searching for exists exactly as written (case-sensitive, including punctuation and spaces).${S}`,"matching")}const m=p.reduce((y,b)=>y+b.matches.length,0);if((t.name==="replace_all"||m===1)&&p.every(y=>y.matches.every(b=>na(y.yText,b.offset,b.length,l,c)))){wt(t,{verifiedUnchanged:!0});break}if(t.name==="replace"){const y=p.reduce((S,v)=>S+v.matches.length,0);if(y>1)throw new Error(`Found ${y} matches for "${l}" in block '${a}'. Include more surrounding context in "find" so it matches exactly one location, or use replace_all to change every occurrence.`);const b=p[0],k=b.matches[0];xr(b.yText,k.offset,k.length,l,c,b.blockId,o)}else for(const y of p){let b=-1;y.matches=y.matches.filter(k=>k.offset<b?!1:(b=k.offset+k.length,!0));for(let k=y.matches.length-1;k>=0;k--){const S=y.matches[k];xr(y.yText,S.offset,S.length,l,c,y.blockId,o)}}break}case"replace_block":{const{id:a,content:l,count:c}=t.arguments;if(c!==void 0&&(!Number.isFinite(c)||Math.floor(c)<1))throw new Error("replace_block count must be a positive integer.");const d=Wd(c,1),g=n?.document??mt(s),u=W(g,a);if(!u){const S=g.children.map(v=>v.id).filter(v=>v).slice(0,10);throw console.error(`[ForkActionApplicator] Block with id '${a}' not found. Available IDs:`,S),new Error(`Target block '${a}' not found in the document. Please only reference IDs you see inside <document_content>.`)}const f=ot(s,a);if(!f)throw new Error(`Y.js block not found for id: ${a}`);const{yBlock:h,yParent:p,index:m}=f,y=Le(p);if((h.nodeName==="header-footer"||y&&d!==1)&&Fe(),d>1){const S=Math.max(0,p.length-(m+1)),v=Math.min(d-1,S);for(let x=0;x<v;x++){const w=p.get(m+1);if(!(w instanceof I.XmlElement))break;const A=w.getAttribute("id");Hi(w,A??void 0,o),p.delete(m+1,1)}}const b=Cn(g,a),k=b>0?g.children[b-1]:void 0;{const S=(Array.isArray(l)?l:[l]).join(""),v=it.fromAgentHtml(S,{previousBlock:k,replacementBlock:u,existingDocument:g,listItemBaseIndent:h.nodeName==="list-item"?Number(h.getAttribute("indentLevel")??0):void 0});if(y&&(v.children.length!==1||v.children[0].type!=="paragraph")&&Fe(),h.nodeName==="list-item"&&p instanceof I.XmlElement&&p.nodeName==="list"){const x=Ki(v.children,Number(h.getAttribute("indentLevel")??0),a,!0);if(d===1&&x.length===1&&u.type==="list"){const w=u.children.find(A=>A.id===a);if(u.variant==="todo"&&x[0].checked===void 0&&w?.checked!==void 0&&(x[0].checked=w.checked),x[0].children=Vn(w?.children??[],x[0].children),w&&Yi(w,u.variant)===Yi(x[0],u.variant)){wt(t,{verifiedUnchanged:!0});break}}p.delete(m,1),p.insert(m,x.map(w=>It(w))),o.push({kind:"replace",paragraphId:p.getAttribute("id"),oldText:"List item",text:x.map(w=>w.children.map(A=>A.text).join("")).join(`
|
|
5
|
+
`)});break}if(u.type==="paragraph"){const x=A=>A.children.filter(P=>!P.marks?.footnoteRef),w=it.extractUniformTextFontFamily(x(u));if(w){for(const A of v.children)if(A.type==="paragraph"&&it.extractUniformTextFontFamily(x(A)))for(const P of x(A))P.marks={...P.marks,fontFamily:w}}}if(v.children.length>0)if(v.children.length===1){const x=v.children[0];if(d===1&&(u.type==="paragraph"||u.type==="list")&&x.type===u.type){if(u.type==="paragraph"&&x.type==="paragraph")x.children=Vn(u.children,x.children);else if(u.type==="list"&&x.type==="list"){const O=new Map(u.children.map(L=>[L.id,L])),$=u.children.length===x.children.length&&x.children.every((L,D)=>L.children.map(H=>H.text).join("")===u.children[D].children.map(H=>H.text).join(""));x.children=x.children.map((L,D)=>({...L,children:Vn((O.get(L.id)??($?u.children[D]:void 0))?.children??[],L.children)}))}const N=O=>Array.isArray(O)?O.map(N):O&&typeof O=="object"?Object.fromEntries(Object.entries(O).filter(([$,L])=>$!=="id"&&L!==void 0&&!($==="marks"&&Object.keys(L).length===0)).sort(([$],[L])=>$.localeCompare(L)).map(([$,L])=>[$,N(L)])):O,R=O=>JSON.stringify(N(O)),M=O=>it.toInternalHtml({type:"doc",children:[N(O)]});if(R(u)===R(x)||M(u)===M(x)){wt(t,{verifiedUnchanged:!0});break}}if(!(h instanceof I.XmlElement))break;if(x.type==="list"){p.delete(m,1);const N=io({...x,id:a});p.insert(m,[N]);const R=u.type==="list"?"List":"Paragraph";o.push({kind:"replace",paragraphId:a,text:"List replaced",oldText:R});break}if(x.type==="table"){const N=x;p.delete(m,1);const R=io({...N,id:a});p.insert(m,[R]);const M=u.type==="table"?"Table":u.type==="list"?"List":"Paragraph";o.push({kind:"replace",paragraphId:a,text:"Table replaced",oldText:M});break}if(x.type==="code"){const N=x;p.delete(m,1);const R=new I.XmlElement("code");R.setAttribute("id",a),N.language&&R.setAttribute("language",N.language),N.renderDiagram!==void 0&&R.setAttribute("renderDiagram",String(N.renderDiagram)),N.showDiagramSource!==void 0&&R.setAttribute("showDiagramSource",String(N.showDiagramSource));const M=new I.XmlText;R.insert(0,[M]),lt(M,0,N.content||""),p.insert(m,[R]);const O=u.type==="code"?"Code block":u.type==="table"?"Table":u.type==="list"?"List":"Paragraph";o.push({kind:"replace",paragraphId:a,text:"Code block replaced",oldText:O});break}if(x.type==="math"){const N=x;p.delete(m,1);const R=new I.XmlElement("math");R.setAttribute("id",a),N.displayMode&&R.setAttribute("displayMode",N.displayMode),N.align&&R.setAttribute("align",N.align);const M=new I.XmlText;R.insert(0,[M]),lt(M,0,N.content||""),p.insert(m,[R]);const O=u.type==="math"?"Math block":u.type==="code"?"Code block":u.type==="table"?"Table":u.type==="list"?"List":"Paragraph";o.push({kind:"replace",paragraphId:a,text:"Math block replaced",oldText:O});break}if(x.type==="page-break"){p.delete(m,1);const N=new I.XmlElement("page-break");N.setAttribute("id",a),p.insert(m,[N]);const R=u.type==="image"?"Image":u.type==="math"?"Math block":u.type==="code"?"Code block":u.type==="table"?"Table":u.type==="list"?"List":"Paragraph";o.push({kind:"replace",paragraphId:a,text:"Page break replaced",oldText:R});break}if(x.type==="toc"){p.delete(m,1);const N=It({...x,id:a});p.insert(m,[N]),o.push({kind:"replace",paragraphId:a,text:"Table of contents replaced",oldText:"Block"});break}if(x.type==="image"){const N=x;p.delete(m,1);const R=new I.XmlElement("image");R.setAttribute("id",a),R.setAttribute("src",N.src),N.sourceUrl&&R.setAttribute("sourceUrl",N.sourceUrl),R.setAttribute("width",String(N.width)),R.setAttribute("height",String(N.height)),N.alt&&R.setAttribute("alt",N.alt),N.align&&R.setAttribute("align",N.align),p.insert(m,[R]);const M=u.type==="image"?"Image":u.type==="math"?"Math block":u.type==="code"?"Code block":u.type==="table"?"Table":u.type==="list"?"List":"Paragraph";o.push({kind:"replace",paragraphId:a,text:"Image replaced",oldText:M});break}if((u.type==="math"||u.type==="code")&&x.type==="paragraph"){p.delete(m,1);const N=new I.XmlElement("paragraph");N.setAttribute("id",a),ao(N,x);const R=new I.XmlText;let M=0;for(const O of x.children)O.type==="text"&&(M=oe(R,M,O.text,O.marks||{}));to(N,x,M),N.insert(0,[R]),p.insert(m,[N]),o.push({kind:"replace",paragraphId:a,text:x.children.filter(O=>O.type==="text").map(O=>O.text).join(""),oldText:u.type==="code"?"Code block":"Math block"});break}if((u.type==="list"||u.type==="table")&&x.type==="paragraph"){p.delete(m,1);const N=new I.XmlElement("paragraph");N.setAttribute("id",a),ao(N,x);const R=new I.XmlText;let M=0;for(const O of x.children)O.type==="text"&&(M=oe(R,M,O.text,O.marks||{}));to(N,x,M),N.insert(0,[R]),p.insert(m,[N]),o.push({kind:"replace",paragraphId:a,text:x.children.filter(O=>O.type==="text").map(O=>O.text).join(""),oldText:u.type==="table"?"Table":"List"});break}const w=bt(h);w||lr(h);const A=u.type==="paragraph"?u:null,P=w.length,T=v.children[0],E=A!==null&&Sr(A,T);let B=0;if(!E){if(P>0&&w.delete(0,P),T.children.length>0){for(const N of T.children)if(N.type==="text"){const R=N;B=oe(w,B,R.text,R.marks||{})}}ao(h,T)}if(!E){const N=u.type==="paragraph"?u.children.filter(R=>R.type==="text").map(R=>R.text).join(""):"";o.push({kind:"replace",paragraphId:a,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(w,0,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(w,B,0)),text:T.children.filter(R=>R.type==="text").map(R=>R.text).join(""),oldText:N})}}else{if(!(h instanceof I.XmlElement))throw new St("target_type_mismatch","Target is not an editable block. Read the current document and target a paragraph ID.","target_resolution");const x=bt(h);x||lr(h);const w=u.type==="paragraph"?u:null,A=x.length,P=u.type==="paragraph"?u.children.filter(R=>R.type==="text").map(R=>R.text).join(""):"",T=v.children[0],E=w!==null&&Sr(w,T);let B=0;if(!E){if(A>0&&x.delete(0,A),T.children.length>0){for(const R of T.children)if(R.type==="text"){const M=R;B=oe(x,B,M.text,M.marks||{})}}T.heading&&h.setAttribute("heading",String(T.heading)),T.align&&h.setAttribute("align",T.align)}E||o.push({kind:"replace",paragraphId:a,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(x,0,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(x,B,0)),text:T.children.filter(R=>R.type==="text").map(R=>R.text).join(""),oldText:P});let N=m+1;for(let R=1;R<v.children.length;R++){const M=v.children[R],O=new I.XmlElement("paragraph"),$=M.id||G();O.setAttribute("id",$),M.heading&&O.setAttribute("heading",String(M.heading)),M.align&&O.setAttribute("align",M.align);const L=new I.XmlText;let D=0;M.children.forEach(F=>{if(F.type==="text"){const X=F;D=oe(L,D,X.text,X.marks||{})}}),to(O,M,D),O.insert(0,[L]),p.insert(N,[O]),N++;const H=M.children.filter(F=>F.type==="text").map(F=>F.text).join("");o.push({kind:"insert",paragraphId:$,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(L,0,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(L,H.length,0)),text:H})}}}break}case"style_blocks":{const{selectors:a,attrs:l}=t.arguments,{targets:c,inlineTargets:d,unmatchedSelectors:g,invalidSelectorErrors:u}=Nd(s,a),f=Ld(l),h=Fd(f);if(c.length===0&&d.length===0)throw new Error(`style_blocks matched no blocks. Unmatched selectors: ${g.length>0?g.join(", "):"all"}. ${u.length>0?`Invalid selectors: ${u.join("; ")}.`:""}`);const p=[],m=new Map,y=(J,K,q)=>{const Q=me(J);let ut=m.get(Q);ut||(ut={name:J,applied:new Set,skipped:new Map},m.set(Q,ut)),q?ut.skipped.set(`${K}\0${q}`,{blockId:K,reason:q}):ut.applied.add(K)},b=o.length,k=new Set,S=new Set,v=new Set(c),x=new Set,w=[],A=[],P=[],T=[],E=Kt(s),B=new Set([...c,...d.map(J=>J.yBlock)].map(Bt)),N=J=>"id"in J&&B.has(String(J.id))||"children"in J&&J.children.some(K=>N(K)),R=J=>[...J.children,...J.notes??[],...J.chrome??[]],M=new Set(R(E).filter(N).map(J=>J.id)),O=J=>Pt({order:J.children.map(K=>K.id),noteOrder:(J.notes??[]).map(K=>K.id),chromeOrder:(J.chrome??[]).map(K=>K.id),targets:R(J).filter(K=>M.has(K.id))}),$=O(E),L=new Set,D=new Set,H=ro(f,"width");if(H&&!(c.some(J=>J.nodeName==="image")&&en(H.value)===void 0)){const J=new Map;for(const q of c){if(q.nodeName!=="table-cell")continue;let Q=q.parent;for(;Q instanceof I.XmlElement&&Q.nodeName!=="table";)Q=Q.parent;if(!(Q instanceof I.XmlElement))continue;const ut=W(E,Bt(Q));if(!ut||ut.type!=="table")continue;const yt=en(H.value),Lt=Oe("width",H.value),dt=ut.tableWidth??kr(E,Q),ht=yt??(typeof Lt=="number"&&Number.isFinite(Lt)?Lt/dt*100:NaN);J.has(Q)||J.set(Q,[]),J.get(Q).push({cellId:Bt(q),percent:ht}),L.add(q)}const K=[...J].map(([q,Q])=>({table:q,requests:Q,widths:Vc(W(E,Bt(q)),Q)}));for(const q of K){const Q=String(q.table.getAttribute("columnWidths")??""),ut=JSON.stringify(q.widths),yt=W(E,Bt(q.table)),Lt=Mn(yt);for(const dt of q.requests){const ht=Lt.byId.get(dt.cellId),vt=Tt=>Tt.slice(ht.col,ht.col+ht.colSpan).reduce((ce,Sn)=>ce+Sn,0);Math.abs(vt(yt.columnWidths)-vt(q.widths))>.001&&D.add(dt.cellId)}Q!==ut&&(q.table.setAttribute("columnWidths",ut),Ft(o,q.table,null,"columnWidths"),k.add(Bt(q.table))),x.add(H.canonicalName),S.add("columnWidths")}}for(const J of c){const K=Bt(J);let q=!1;const Q=Xd({doc:E,yBlock:J,rawAttrs:f,anchors:o});L.has(J)&&H&&(Q.handledRawNames.add(H.canonicalName),Q.appliedAttrs.push("cell width -> table columns"));for(const dt of Q.handledRawNames){const ht=f.find(Tt=>Tt.canonicalName===dt),vt=Q.issuesByRawName.get(dt)??[];y(ht?.rawName??dt,K,vt.length?vt.join("; "):void 0),x.add(dt)}for(const dt of Q.appliedAttrs)S.add(dt),k.add(K);w.push(...Q.exactMappings),A.push(...Q.approximateMappings),P.push(...Q.ignoredAttrs),T.push(...Q.unsupportedImageSpacing),p.push(...Q.errors);const ut=Wi(h,J,!1);A.push(...Ji(ut));const yt=ut.some(({rawName:dt,value:ht})=>["liststyletype","list-style-type"].includes(dt.toLowerCase())&&typeof ht=="string"&&ht.toLowerCase()==="none"),Lt=[];for(const{rawName:dt,entry:ht,value:vt}of ut){if(yt&&J.nodeName==="list"&&ht.kind!=="textMark"&&ht.nodeNames.includes("paragraph")&&!ht.nodeNames.includes("list-item")){Lt.push({rawName:dt,entry:ht,value:vt});continue}if(!Q.handledRawNames.has(me(dt)))try{if(ht.attr==="variant"&&typeof vt=="string"&&vt.trim().toLowerCase()==="none"&&["liststyletype","list-style-type"].includes(dt.trim().toLowerCase())){if(J.nodeName!=="list")throw new Error('style_blocks "listStyleType: none" only applies to list blocks.');q=!0;continue}if(ht.kind==="textMark"){const Tt=Di(dt,ht.attr,vt);kd({toolName:"style_blocks",yBlock:J,attribute:ht.attr,operation:Tt===null?"remove":"set",value:Tt,config:ht,anchors:o,independentlySelectedTargets:v}),k.add(K),S.add(`${dt} -> ${ht.attr}`),y(dt,K);continue}vd({toolName:"style_blocks",yBlock:J,attribute:ht.attr,operation:vt===null?"remove":"set",value:vt,config:{nodeNames:ht.nodeNames,valueType:ht.valueType,integer:ht.integer,min:ht.min,max:ht.max,enumValues:ht.enumValues},anchors:o,independentlySelectedTargets:v}),k.add(K),S.add(`${dt} -> ${ht.attr}`),y(dt,K)}catch(Tt){y(dt,K,Tt instanceof Error?Tt.message:String(Tt)),p.push(`${K}.${ht.attr}: ${Tt instanceof Error?Tt.message:String(Tt)}`)}}if(q){const dt=Hd(J,o);if(dt){for(const{rawName:ht,entry:vt,value:Tt}of Lt)if(vt.kind!=="textMark")try{for(const ce of dt)oo({toolName:"style_blocks",yBlock:ce,attribute:vt.attr,operation:Tt===null?"remove":"set",value:Tt,config:vt,anchors:o});S.add(`${ht} -> ${vt.attr}`),y(ht,K)}catch(ce){const Sn=ce instanceof Error?ce.message:String(ce);y(ht,K,Sn),p.push(`${K}.${vt.attr}: ${Sn}`)}k.add(K),S.add("listStyleType -> plain paragraphs"),y("listStyleType",K)}else p.push(`${K}.variant: could not convert the list to plain paragraphs.`)}}for(const{yBlock:J,ranges:K}of d){const q=Bt(J),Q=Wi(h,J,!0);A.push(...Ji(Q));for(const{rawName:ut,entry:yt,value:Lt}of Q){if(yt.kind!=="textMark"){const dt="Block attributes cannot apply to an inline range; select its block instead.";y(ut,q,dt),p.push(`${q}.${yt.attr}: ${dt}`);continue}try{const dt=Di(ut,yt.attr,Lt);Sd({toolName:"style_blocks",yBlock:J,ranges:K,attribute:yt.attr,operation:dt===null?"remove":"set",value:dt,config:yt,anchors:o}),k.add(q),S.add(`${ut} -> ${yt.attr}`),y(ut,q)}catch(dt){y(ut,q,dt instanceof Error?dt.message:String(dt)),p.push(`${q}.${yt.attr}: ${dt instanceof Error?dt.message:String(dt)}`)}}}for(const J of h.unsupportedAttrs??[]){const K=m.get(me(J)),q=new Set([...K?.skipped.values()??[]].map(Q=>Q.blockId));for(const Q of B)!K?.applied.has(Q)&&!q.has(Q)&&y(J,Q,"Unsupported attribute for this target.")}const F=Kt(s),X=J=>{const K=new Map,q=Q=>{"id"in Q&&Q.id&&K.set(Q.id,Q),"children"in Q&&Q.children.forEach(ut=>q(ut))};return R(J).forEach(q),K},C=X(E),j=X(F),U=J=>Pt(C.get(J)??null)!==Pt(j.get(J)??null),z=[...new Set([...B,...o.slice(b).map(J=>J.paragraphId).filter(J=>!!J)])].filter(U),tt=[...B].filter(J=>U(J)||D.has(J)),_=[...m.values()].map(J=>({name:J.name,appliedBlockIds:[...J.applied],skipped:[...J.skipped.values()]})),V=_.every(J=>J.skipped.length===0)&&S.size>0&&p.length===0&&g.length===0&&u.length===0&&P.length===0&&T.length===0&&(h.unsupportedAttrs??[]).every(J=>x.has(me(J))),nt={outcome:V?tt.length?"complete":"unchanged":"partial",targetBlockIds:[...B],changedBlockIds:tt,affectedBlockIds:z,attributes:_};if(wt(t,{styleEffects:nt}),V&&$===O(F)&&wt(t,{verifiedUnchanged:!0}),o.length===b&&!Rt(t)?.verifiedUnchanged){if(T.length||P.length)throw new St("attribute_unsupported","These image layout attributes cannot be represented. Use width/height or align for image sizing/placement, and document blockGap or surrounding paragraph spacing for separation.","validation");if(h.length===0){const J=h.unsupportedAttrs??[];throw new Error(J.length>0?`style_blocks has no supported attrs. Unsupported attrs: ${J.join(", ")}.`:"style_blocks requires at least one attr.")}throw new Error(`style_blocks could not apply to any target. ${p.length>0?`Skipped target attrs: ${p.join("; ")}`:"No matching supported attributes."}`)}cr.set(t,Ud({styleEffects:nt,matchedTargetCount:c.length+d.reduce((J,K)=>J+K.ranges.length,0),inlineRangeCount:d.reduce((J,K)=>J+K.ranges.length,0),unsupportedAttrs:(h.unsupportedAttrs??[]).filter(J=>!x.has(me(J))),unmatchedSelectors:g,invalidSelectorErrors:u,skippedTargetErrors:p,exactCompatibilityMappings:w,approximateCompatibilityMappings:A,ignoredCompatibilityAttrs:P,unsupportedImageSpacing:T}));break}case"set_block_attribute":{const{id:a,attribute:l,operation:c,value:d}=t.arguments,g=Li("set_block_attribute",a),u=()=>{const b=Kt(s);return g.map(k=>W(b,k))},f=JSON.stringify(u());if(typeof l!="string"||l.trim().length===0)throw new Error("set_block_attribute requires a non-empty attribute name.");const h=l.trim();if(h==="id")throw new Error("set_block_attribute cannot modify the reserved 'id' attribute.");const p=bd(c),m=[],y=(b,k)=>{if(g.length<=1)throw new Error(k);return m.push(`${b}: ${k}`),!0};for(const b of g){const k=ot(s,b);if(!k){y(b,`Target block '${b}' not found in the document. Please only reference IDs you see inside <document_content>.`);continue}const{yBlock:S}=k,v=bt(S);if(h==="fontFamily"){const w=no(S);if(w){y(b,w);continue}}if(hd.has(h)){if(!v||S.nodeName!=="paragraph"&&S.nodeName!=="list-item"){y(b,`set_block_attribute "${h}" only supports paragraph or list-item text blocks.`);continue}let w;if(p==="remove")w=!1;else if(p==="toggle")w=!Ni(S,v,h);else if(d===void 0)w=!0;else if(typeof d=="boolean")w=d;else throw new Error(`set_block_attribute "${h}" expects a boolean value when operation is "set".`);if(v.length>0)at(v,0,v.length,{[h]:w?!0:null}),ne(o,b,v);else{pd(S,h,w);const A=`Text mark "${h}" ${w?"enabled":"removed"}.`;o.push({kind:"replace",paragraphId:b,text:A,oldText:A})}continue}if(h in Mi){if(!v||S.nodeName!=="paragraph"&&S.nodeName!=="list-item"){y(b,`set_block_attribute "${h}" only supports paragraph or list-item text blocks.`);continue}if(p==="toggle")throw new Error(`set_block_attribute "${h}" does not support toggle. Use operation "set" with a numeric value or "remove".`);const w=Mi[h],A=p==="remove"?null:md(h,d,w);if(v.length>0)at(v,0,v.length,{[h]:A===null?null:A}),ne(o,b,v);else{ur(S,h,A);const P=`Text mark "${h}" ${A===null?"removed":"set"}.`;o.push({kind:"replace",paragraphId:b,text:P,oldText:P})}continue}if(h==="indentLevel"&&S.nodeName==="paragraph"){Ri(S,p,d),v&&ne(o,b,v);continue}const x=Ei[h];if(!x){const w=Object.keys(Ei).sort().join(", ");throw new Error(`set_block_attribute "${h}" is not supported. Supported block attributes: ${w}.`)}if(!x.nodeNames.includes(S.nodeName)){y(b,`set_block_attribute "${h}" is not valid for ${S.nodeName} blocks.`);continue}if(p==="remove")et(S,h);else if(p==="toggle"){if(x.valueType!=="boolean")throw new Error(`set_block_attribute "${h}" only supports toggle for boolean attributes.`);const w=Fi(rt(S,h));S.setAttribute(h,String(!w))}else{if(d===void 0)throw new Error(`set_block_attribute "${h}" requires "value" when operation is "set".`);const w=Oi(h,d,x);S.nodeName==="paragraph"&&(h==="leftIndent"||h==="firstLineIndent")?fr(S,h,Number(w)):S.setAttribute(h,w)}if(v)ne(o,b,v);else{const w=`Updated ${h} on ${S.nodeName} block.`;o.push({kind:"replace",paragraphId:b,text:w,oldText:w})}}if(o.length===0&&m.length>0)throw new Error(`set_block_attribute could not apply to any target. Skipped targets: ${m.join("; ")}`);m.length===0&&f===JSON.stringify(u())&&wt(t,{verifiedUnchanged:!0});break}case"clear_formatting":{const{id:a}=t.arguments,l=Li("clear_formatting",a),c=()=>{const g=Kt(s);return l.map(u=>W(g,u))},d=JSON.stringify(c());for(const g of l){const u=ot(s,g);if(!u)throw new Error(`Target block '${g}' not found in the document. Please only reference IDs you see inside <document_content>.`);const f=[];if(u.yBlock.nodeName==="list"){for(let h=0;h<u.yBlock.length;h++){const p=u.yBlock.get(h);if(p instanceof I.XmlElement&&p.nodeName==="list-item"){const m=p.getAttribute("id")||g;f.push({id:m,yBlock:p})}}if(f.length===0){const h=`Cleared formatting on list block ${g}.`;o.push({kind:"replace",paragraphId:g,text:h,oldText:h});continue}}else f.push({id:g,yBlock:u.yBlock});for(const h of f){if(h.yBlock.nodeName!=="paragraph"&&h.yBlock.nodeName!=="list-item")throw new Error("clear_formatting only supports paragraph, list, or list-item blocks.");const p=bt(h.yBlock);if(!p)throw new Error("clear_formatting only supports paragraph, list, or list-item text blocks.");if(h.yBlock.nodeName==="paragraph")for(const m of $s)et(h.yBlock,m);if(zd(h.yBlock),p.length>0){let m=0;for(const y of st(p)){const b=typeof y.insert=="string"?y.insert.length:1,k={...js};typeof y.attributes?.footnoteRef=="string"&&y.attributes.footnoteRef.length>0&&delete k.superscript,at(p,m,b,k),m+=b}ne(o,h.id,p)}else{const m="Formatting cleared.";o.push({kind:"replace",paragraphId:h.id,text:m,oldText:m})}}}d===JSON.stringify(c())&&wt(t,{verifiedUnchanged:!0});break}case"remove_block":{const{id:a,count:l=1}=t.arguments,c=ot(s,a);if(!c)throw new Error(`Target block '${a}' not found in the document. Please only reference IDs you see inside <document_content>.`);const{yParent:d,index:g}=c;Le(d)&&Fe();const u=We(s),f=d===u;for(let h=0;h<l;h++){const p=g;if(p>=d.length)break;const m=d.get(p);if(!(m instanceof I.XmlElement))break;const y=m.getAttribute("id"),b=m.nodeName;if(f&&d.length===1){if(b==="paragraph"){const k=bt(m);if(k&&k.length>0){const S=st(k);let v="";for(const x of S)x.insert&&typeof x.insert=="string"&&(v+=x.insert);o.push({kind:"delete",paragraphId:y,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(k,0,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(k,v.length,0)),text:v}),k.delete(0,k.length)}}else{o.push({kind:"delete",paragraphId:y,text:b==="list"?"List removed":"Block removed"});const k=new I.XmlElement("paragraph");k.setAttribute("id",y);const S=new I.XmlText;k.insert(0,[S]),d.delete(p,1),d.insert(p,[k])}break}if(b==="list")o.push({kind:"delete",paragraphId:y,text:"List removed"});else{const k=bt(m);if(k){const S=st(k);let v="";for(const x of S)x.insert&&typeof x.insert=="string"&&(v+=x.insert);o.push({kind:"delete",paragraphId:y,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(k,0,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(k,v.length,0)),text:v})}else o.push({kind:"delete",paragraphId:y,text:"Block removed"})}d.delete(p,1)}break}case"append_to_paragraph":{const{id:a,content:l}=t.arguments,c=Z(s,a);if(!c)throw new Error(`Target block '${a}' not found in the document. Please only reference IDs you see inside <document_content>.`);const d=bt(c);d||lr(c);const g=d.length,u=de(g>0?go(d,g-1,1):ye(c.getAttribute("_emptyTextMarks"))),f=it.fromAgentHtml(l);if(f.children.length>0){const h=[];for(const y of f.children)y.type==="paragraph"&&y.children.forEach(b=>{b.type==="text"&&h.push(b)});let p=g,m="";for(const y of h)if(y.text){const b=oe(d,p,y.text,{...u||{},...y.marks||{}});m+=y.text,p=b}m&&o.push({kind:"insert",paragraphId:a,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(d,g,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(d,p,0)),text:m})}break}case"break_paragraph":{const{id:a,substring:l}=t.arguments,c=typeof l=="string"?l:String(l??"");if(c.trim().length===0)throw new Error("break_paragraph requires a non-empty substring to split on.");const d=n?.document??mt(s),g=W(d,a);if(!g)throw new Error(`Target block '${a}' not found in the document. Please only reference IDs you see inside <document_content>.`);if(g.type!=="paragraph")throw new Error(`break_paragraph only works on paragraphs. Block '${a}' is type '${g.type}'.`);const u=Mc(g,c);if(u.length===0){const j=g.children.filter(z=>z.type==="text").map(z=>z.text).join(""),U=Os(j.length>100?j.slice(0,100)+"...":j);throw new Error(`No match found for "${c}" in block '${a}'. The block contains: "${U}".`)}const f=u[0].offset,h=ot(s,a);if(!h)throw new Error(`Y.js block not found for id: ${a}`);const{yBlock:p,yParent:m,index:y}=h;if(Le(m)&&Fe(),!(p instanceof I.XmlElement))throw new Error(`Target block '${a}' is not a valid Y.XmlElement.`);const b=bt(p);if(!b)throw new Error(`break_paragraph only works on text paragraphs. Block '${a}' has no text content.`);const{beforeOps:k,afterOps:S,formatAtSplit:v,originalText:x,beforeText:w,afterText:A}=sg(b,f);b.delete(0,b.length);let P=0;for(const j of k)lt(b,P,j.insert,j.attributes??{}),P+=j.insert.length;const T=G(),E=new I.XmlElement("paragraph");E.setAttribute("id",T);const B=p.getAttribute("heading");B&&E.setAttribute("heading",B);const N=rt(p,"align");N&&E.setAttribute("align",N);const R=rt(p,"lineSpacing");R!=null&&E.setAttribute("lineSpacing",R);const M=rt(p,"pagination");M!=null&&E.setAttribute("pagination",M);const O=p.getAttribute("styleId");O!=null&&E.setAttribute("styleId",O);const $=rt(p,"direction");$!=null&&E.setAttribute("direction",$);const L=rt(p,"borders");L!=null&&E.setAttribute("borders",L);const D=rt(p,"shading");D!=null&&E.setAttribute("shading",D);const H=rt(p,"tabStops");H!=null&&E.setAttribute("tabStops",H);const F=p.getAttribute("oxmlPPr");F!=null&&E.setAttribute("oxmlPPr",F);const X=new I.XmlText;let C=0;for(const j of S)X.insert(C,j.insert,j.attributes??{}),C+=j.insert.length;if(S.length===0){const j=ye(p.getAttribute("_emptyTextMarks")),U=de({...j,...v??{}});U&&Object.keys(U).length>0&&E.setAttribute("_emptyTextMarks",JSON.stringify(U))}E.insert(0,[X]),m.insert(y+1,[E]),w!==x&&o.push({kind:"replace",paragraphId:a,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(b,0,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(b,P,0)),text:w,oldText:x}),o.push({kind:"insert",paragraphId:T,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(X,0,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(X,C,0)),text:A||"Paragraph split"});break}case"join_paragraphs":{const{firstId:a,secondId:l,separator:c}=t.arguments;if(!a||!l||a===l)throw new Error("join_paragraphs requires two different paragraph IDs: firstId and secondId.");const d=ot(s,a),g=ot(s,l);if(!d)throw new Error(`Target block '${a}' not found in the document.`);if(!g)throw new Error(`Target block '${l}' not found in the document.`);if((Le(d.yParent)||Le(g.yParent))&&Fe(),d.yBlock.nodeName!=="paragraph"||g.yBlock.nodeName!=="paragraph")throw new Error("join_paragraphs only works on two paragraph blocks.");if(d.yParent!==g.yParent||g.index!==d.index+1)throw new Error(`join_paragraphs requires adjacent sibling paragraphs with secondId immediately after firstId. '${l}' does not immediately follow '${a}'.`);const u=bt(d.yBlock),f=bt(g.yBlock);if(!u||!f)throw new Error("join_paragraphs only works on text paragraph blocks.");const h=u.toString(),p=f.toString(),m=c!==void 0?String(c):/\S/.test(h)&&/\S/.test(p)?" ":"",y=h.match(/\s+$/)?.[0].length??0,b=p.match(/^\s+/)?.[0].length??0,k=m.length>0,S=k?h.slice(0,h.length-y):h,v=k?p.slice(b):p;k&&y>0&&u.delete(u.length-y,y);const x=st(u),w=st(f),A=x.length>0?x[x.length-1].attributes??{}:{},P=w.length>0?w[0].attributes??{}:{};let T=u.length;m.length>0&&(lt(u,T,m,Object.keys(A).length>0?A:P),T+=m.length);let E=k?b:0;for(const N of w){if(typeof N.insert!="string"||N.insert.length===0)continue;const R=N.insert.slice(E);E=Math.max(0,E-N.insert.length),R.length!==0&&(lt(u,T,R,N.attributes??{}),T+=R.length)}const B=`${S}${m}${v}`;o.push({kind:"replace",paragraphId:a,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(u,0,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(u,u.length,0)),text:B||"Paragraphs joined",oldText:h}),o.push({kind:"delete",paragraphId:l,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(f,0,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(f,f.length,0)),text:p||"Empty paragraph removed"}),g.yParent.delete(g.index,1);break}case"insert_table_row":{const a=mt(s),l=it.createParsingContext(a),{tableId:c,referenceIndex:d,referenceRowId:g,position:u,content:f}=t.arguments,h=W(a,c);if(h?.type!=="table")throw new Error(`Table ${c} not found`);let p=d;if(g!==void 0){if(p=h.children.findIndex(k=>k.id===g),p<0)throw new Error(`Row ${g} not found in table ${c}. Read the table and use a current row ID.`);if(d!==void 0&&d!==p)throw new Error(`Row ${g} is at index ${p}, not ${d}. Use referenceRowId alone or reread the table.`)}if(p===void 0||!Number.isInteger(p)||p<0||p>=h.children.length)throw new Error("Invalid reference row index. Supply a current referenceRowId or a valid 0-based referenceIndex.");const m=h.children[p],y=f?.map(k=>{if(k==="")return;const S=it.fromAgentHtml(k,{existingDocument:a,parsingContext:l});return S.children.length>0?S.children:void 0}),b=sd(s,c,u,p,y);if(!b.success)throw new Error(b.error||"Failed to insert table row");o.push({kind:"insert",paragraphId:c,text:`Row inserted ${u} row ${m.id} (reference index ${p}; new row index ${p+(u==="after"?1:0)})`});break}case"remove_table_row":{const a=t.arguments,l=String(a.tableId??""),c=W(mt(s),l);if(c?.type!=="table"||c.id!==l)throw new Error(`Table ${l} not found`);const d=xi(c,a);if("error"in d)throw new Error(d.error);const{rowIndices:g,rowIds:u}=d,f=nd(s,l,g);if(!f.success)throw new Error(f.error||"Failed to remove table rows");g.forEach((h,p)=>o.push({kind:"delete",paragraphId:l,text:`Row ${u[p]} (index ${h}) removed`}));break}case"insert_table_column":{const a=mt(s),l=it.createParsingContext(a),{tableId:c,referenceIndex:d,position:g,content:u}=t.arguments,f=u?.map(p=>{if(p==="")return;const m=it.fromAgentHtml(p,{existingDocument:a,parsingContext:l});return m.children.length>0?m.children:void 0}),h=od(s,c,g,d,f);if(!h.success)throw new Error(h.error||"Failed to insert table column");o.push({kind:"insert",paragraphId:c,text:`Column inserted ${g} column ${d}`});break}case"remove_table_column":{const{tableId:a,columnIndex:l}=t.arguments,c=td(s,a,l);if(!c.success)throw new Error(c.error||"Failed to remove table column");o.push({kind:"delete",paragraphId:a,text:`Column ${l} removed`});break}}return n?.refreshDocumentIncrementally&&(n.document=Kt(s)),o}function ye(s){if(!s)return{};try{const t=JSON.parse(s);if(t&&typeof t=="object")return t}catch{}return{}}function sg(s,t){const e=[],n=[];let o={},r="",i="",a="",l=0;const c=st(s);for(const d of c){if(!d.insert||typeof d.insert!="string")continue;const g=d.insert,u=d.attributes||{},f=l+g.length;if(r+=g,f<=t)e.push({insert:g,attributes:u}),i+=g,f===t&&(o=u);else if(l>=t)n.push({insert:g,attributes:u}),a+=g;else{const h=t-l,p=g.slice(0,h),m=g.slice(h);p.length>0&&(e.push({insert:p,attributes:u}),i+=p),m.length>0&&(n.push({insert:m,attributes:u}),a+=m),o=u}l=f}return{beforeOps:e,afterOps:n,formatAtSplit:o,originalText:r,beforeText:i,afterText:a}}function go(s,t,e){const n=t+e;let o=0,r=null;for(const i of st(s)){if(typeof i.insert!="string")continue;const a=o+i.insert.length;if(a>t&&o<n){const l=i.attributes||{},c={};for(const d of ps){const g=l[d];g!=null&&g!==!1&&(c[d]=g)}if(r===null)r=c;else for(const d of Object.keys(r))r[d]!==c[d]&&delete r[d]}if(o=a,o>=n)break}return r??{}}function vr(s){const t=new Set;if(!s.includes("<")||!s.includes(">"))return t;try{const e=it.fromAgentHtml(s),n=o=>{if(o.type==="text"){for(const r of xn)o.marks?.[r]!==void 0&&t.add(r);return}if("children"in o&&Array.isArray(o.children))for(const r of o.children)n(r)};for(const o of e.children)n(o)}catch{}return t}function na(s,t,e,n,o){if(o.includes("<")&&o.includes(">")||vr(n).size>0)return!1;const r=go(s,t,e),i=si(o,r);return s.toString().slice(t,t+e)===i}function xr(s,t,e,n,o,r,i,a={}){if(!na(s,t,e,n,o))if(o.includes("<")&&o.includes(">")){const l={...a,...go(s,t,e)};for(const f of vr(n))delete l[f];const c=o.trim(),d=/^<\s*(?:p|h[1-6])(?:\s|>|\/)/i.test(c)?c:`<p>${o}</p>`,g=it.fromAgentHtml(d,{preserveExplicitMarkResets:!0}),u=g.children.length>0?g.children[0]:null;if(u&&u.type==="paragraph"&&u.children.length>0){s.delete(t,e);const f=[];for(const b of u.children)if(b.type==="text"){const k=b,S={...l,...k.marks||{}};f.push({text:k.text,marks:S})}const h=s.doc;let p=t;const m=[];for(const b of f){const k=m[m.length-1],S=JSON.stringify(b.marks||{}),v=k?JSON.stringify(k.marks||{}):null;k&&S===v?k.text+=b.text:m.push({text:b.text,marks:b.marks||{}})}const y=m.map(b=>b.text).join("");h.transact(()=>{lt(s,t,y);let b=t;for(const k of m)k.marks&&Object.keys(k.marks).length>0&&at(s,b,k.text.length,k.marks),b+=k.text.length;p=t+y.length},"performReplacement"),Vi(s,t,p),i.push({kind:"replace",paragraphId:r,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(s,t,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(s,p,0)),text:o.replace(/<[^>]*>/g,""),oldText:n.replace(/<[^>]*>/g,"")})}}else{const l={...a,...go(s,t,e)},c=si(o,l);for(const d of vr(n))delete l[d];s.delete(t,e),c.length>0&<(s,t,c,l),Vi(s,t,t+c.length),i.push({kind:"replace",paragraphId:r,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(s,t,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(s,t+c.length,0)),text:c,oldText:n.replace(/<[^>]*>/g,"")})}}function ig(s,t,e,n,o={}){if(!t.length)return{anchorsByAction:[],failures:[],alreadySatisfied:!1};const r=t.every(h=>h.name==="insert_block"),i=r?n:o.canonicalDocument?.()??n;r||Rn(s,i);let a;const l={document:r?{...n,children:[...n.children]}:i,get htmlParsingContext(){return a??(a=it.createParsingContext(n))},set htmlParsingContext(h){a=h},refreshDocumentIncrementally:!r},c=[],d=[],g=new Set,u=[],f=(h,p,m,y)=>{const b=Rt(h);d.push({actionIndex:p,actionName:h.name,error:m,failure:y,sourceEditIndex:b?.sourceEditIndex,sourceEditType:b?.sourceEditType})};for(let h=0;h<t.length;h++){const p=t[h];try{const m=()=>Wt(s,p,`${e}_${h}`,!o.skipContextForFirstAction||r||h>0?l:void 0),y=o.measure?o.measure(m):m();o.skipContextForFirstAction&&!r&&h===0&&t.length>1&&(l.document=Kt(s)),c.push(y);const b=Rt(p);if(y.length&&b?.splitReplacementGroup&&g.add(b.splitReplacementGroup),!y.length&&o.rejectUnchangedAction&&!b?.verifiedUnchanged)if(wc(p)&&b?.splitReplacementGroup)u.push({action:p,index:h,group:b.splitReplacementGroup});else{f(p,h,dr(p)??`${JSON.stringify(p.arguments)} - no change made`);break}}catch(m){if(o.throwOnError)throw m;if(f(p,h,String(m),Be(m)),!o.continueAfterError)break}}for(const{action:h,index:p,group:m}of u)g.has(m)||f(h,p,"Split replacement made no verified change");return{anchorsByAction:c,failures:d,alreadySatisfied:d.length===0&&t.every(h=>Rt(h)?.verifiedUnchanged)}}const wr=()=>{},ag={count:wr,gauge:wr,distribution:wr},oa=new WeakSet;function Ar(s,t){try{ag.count("frontend.editor.yjs_observer_failure",1,{event:t})}catch{}console.error(`Yjs ${t} observer failed`,s)}function ra(s,t=Ar){if(oa.has(s))return;oa.add(s);const e=s.emit;let n=Number.NEGATIVE_INFINITY;s.emit=function(o,r){if(!["update","updateV2","afterTransactionCleanup"].includes(o))return e.call(this,o,r);const i=Array.from(this._observers.get(o)??[]);for(const a of i)try{a(...r)}catch(l){const c=Date.now();if(c-n>=3e4){n=c;try{t(l,o)}catch{}}}}}const sa="suggestion-id-repair";function lg(s){if(s.deleteSet.clients.size>0)return!0;for(const[t,e]of s.afterState){const n=s.beforeState.get(t)??0;if(n===e)continue;const o=s.doc.store.clients.get(t);for(let r=I.findIndexSS(o,n);r<o.length&&o[r].id.clock<e;r++){const i=o[r];if(i instanceof I.Item&&i.content instanceof I.ContentFormat&&["insertion","deletion","suggestionId","proposalId"].includes(i.content.key))return!0}}return!1}function cg(s,t,e="recover"){const n=new Set(["content","chrome","notes"].filter(l=>s.share.has(l)).map(l=>s.getXmlFragment(l))),o=new Set,r=l=>{l._item?.deleted||(l instanceof I.XmlText?o.add(l):l instanceof I.XmlFragment&&l.toArray().forEach(r))};if(t){const l=lg(t);for(const[c,d]of t.changed)c instanceof I.XmlText?l&&o.add(c):c instanceof I.XmlFragment&&(d.has("structuralSuggestionId")||d.has("suggestionId"))&&r(c);vl(t,c=>{c.deleted||c.content instanceof I.ContentType&&r(c.content.type)})}else n.forEach(r);const i=l=>typeof l=="string"&&l.trim().length>0,a=[];for(const l of o){if(l._item?.deleted)continue;let c=l,d=!1;for(;c.parent;){c=c.parent;const h=c;if(h instanceof I.XmlElement&&["structuralSuggestionId","suggestionId","proposalId"].some(p=>i(h.getAttribute(p)))){d=!0;break}}if(d||!n.has(c))continue;let g=0,u,f;for(const h of st(l)){const p=typeof h.insert=="string"?h.insert.length:1,m=h.attributes??{};if(typeof h.insert!="string"||p===0||!(m.insertion||m.deletion)||i(m.suggestionId)||i(m.proposalId)){u=void 0,f=void 0,g+=p;continue}const y=JSON.stringify(Object.entries(m).filter(([b])=>b==="insertion"||b==="deletion"||b==="layeredInsertion"||b.startsWith("suggestion")).sort(([b],[k])=>b.localeCompare(k)));if(f&&u===y)f.length+=p;else{const b=I.createRelativePositionFromTypeIndex(l,g).item;if(!b){g+=p;continue}f={text:l,start:g,length:p,id:`recovered-inline-${b.client.toString(36)}-${b.clock.toString(36)}`},u=y,a.push(f)}g+=p}}return a.length&&s.transact(()=>{for(const l of a)at(l.text,l.start,l.length,e==="strip"?{insertion:null,deletion:null,layeredInsertion:null,formatChange:null}:{suggestionId:l.id})},sa),a.length}function uo(s,t){if(Array.isArray(s))return s.map(o=>uo(o,t));if(!s||typeof s!="object")return s;const e={};for(const[o,r]of Object.entries(s))if(!(t.regenerateIds&&o==="id")){if(t.regenerateIds&&o==="marks"&&r&&typeof r=="object"&&!Array.isArray(r)&&"comment"in r){const{comment:i,...a}=r;Object.keys(a).length>0&&(e[o]=uo(a,t));continue}e[o]=uo(r,t)}const n=e.type;return t.regenerateIds&&typeof n=="string"&&n!=="doc"&&n!=="text"&&(e.id=G()),e}function dg(s){return s.map(t=>uo(t,{regenerateIds:!0}))}const gg=["borders","align","styleId","direction","_emptyTextMarks"],ug=["id","heading","oxmlAttrs",...wl],hg=["pagination"],fg=[...xl("paragraph"),...hg].filter(s=>!gg.includes(s)&&!ug.includes(s));function ia(s,t){for(const e of fg){const n=rt(s,e);n!=null&&t.setAttribute(e,n)}}const ho=new Set(["aiGenerated","insertion","deletion","formatChange","suggestionId","suggestionSource","suggestionAuthorType","suggestionCreatedAt","suggestionLabel","suggestionCommentThreadId","suggestionAuthorName","suggestionAgentModel","suggestionAgentConversationId","suggestionAgentRequestId","suggestionAgentTurn","suggestionPriorAttributes","layeredInsertion","docxMove","proposalId","toolCallId","toolType","diffSegmentIndex","__htmlClassName"]),pg=["insertion","deletion","formatChange","suggestionId","suggestionSource","suggestionAuthorType","suggestionCreatedAt","suggestionLabel","suggestionCommentThreadId","suggestionAuthorName","suggestionAgentModel","suggestionAgentConversationId","suggestionAgentRequestId","suggestionAgentTurn","suggestionPriorAttributes","layeredInsertion","docxMove"];function aa(s,t){if(!s)return[];const e=!!s.footnoteRef,n=[];for(const[o,r]of Object.entries(s))r===void 0||r===!1||r===null||ho.has(o)||o==="link"&&t.excludeLink||o==="comment"&&t.excludeComment||o!=="footnoteRef"&&(o==="superscript"&&e||n.push([o,r]));return n}function Tr(s){const{explicitMarks:t,inheritedMarks:e,emptyParagraphMarks:n,exitingLink:o=!1,exitingComment:r=!1,noteBodyFontSize:i,suggestionMarks:a}=s,l={},c=[],d=f=>{c.includes(f)||c.push(f)},g=f=>l[f]!==void 0,u=f=>c.includes(f);if(t){for(const[f,h]of Object.entries(t))h===!1?d(f):h!=null&&(l[f]=h);l.footnoteRef&&(delete l.footnoteRef,e?.footnoteRef&&delete l.superscript)}for(const[f,h]of aa(e,{excludeLink:o,excludeComment:r}))!g(f)&&!u(f)&&(l[f]=h);e?.footnoteRef&&!l.footnoteRef&&(d("footnoteRef"),l.superscript||d("superscript"));for(const[f,h]of aa(n,{excludeLink:o,excludeComment:r}))!g(f)&&!u(f)&&(l[f]=h);if(i!=null&&l.fontSize===void 0&&!u("fontSize")&&(l.fontSize=i),o&&!l.link&&d("link"),r&&!l.comment&&d("comment"),a)Object.assign(l,a);else if(e){const f=e;for(const h of pg)f[h]!==void 0&&f[h]!==null&&d(h)}return{marksToApply:l,marksToRemove:c}}function la(s,t,e,n){if(lt(s,t,e),Object.keys(n.marksToApply).length>0&&at(s,t,e.length,n.marksToApply),n.marksToRemove.length>0){const o={};for(const r of n.marksToRemove)o[r]=null;at(s,t,e.length,o)}}function Cr(s,t,e){const n=vs(t,e,Qt(s.getDocument().children));s.transact(()=>{const o=s.getYChromeFragment();Pr(o,i=>i.getAttribute("sectionIndex")===void 0);for(const i of n)o.push([s.blockToYjsElement(i)]);const r=s.ydoc.getMap("metadata");r.delete("headers"),r.delete("footers")})}function ca(s){return hs(s.getDocument().chrome??[])}function Pr(s,t){for(let e=s.length-1;e>=0;e--){const n=s.get(e);n instanceof I.XmlElement&&t(n)&&s.delete(e,1)}}function mg(s,t,e,n){const o=Qt(s.getDocument().children),r=vs(e,n,o).map(i=>({...i,sectionIndex:t}));s.transact(()=>{const i=s.getYChromeFragment();Pr(i,a=>a.getAttribute("sectionIndex")===String(t));for(const a of r)i.push([s.blockToYjsElement(a)])})}function bg(s,t){return Tl(s.getDocument().chrome??[],t)}function Mr(s,t,e,n){const o=(s.getDocument().chrome??[]).find(i=>i.type==="header-footer"&&i.side===t&&i.slot===e&&i.sectionIndex===n);if(o)return o;const r=xs(t,e,void 0,Qt(s.getDocument().children),n);return s.transact(()=>{s.getYChromeFragment().push([s.blockToYjsElement(r)])}),r}function yg(s){const t=s.getYContentFragment(),e=[];for(const r of t.toArray())r instanceof I.XmlElement&&r.nodeName==="header-footer"&&e.push(r);const n=s.getYChromeFragment();if(e.length===0&&n.length<=3){da(s);return}const o=s.getYChromeFragment();s.transact(()=>{for(const i of e){const a=s.getDocument().children.find(l=>l.type==="header-footer"&&l.id===i.getAttribute("id"));a&&o.push([s.blockToYjsElement(a)])}const r=t.toArray();for(let i=r.length-1;i>=0;i--){const a=r[i];a instanceof I.XmlElement&&a.nodeName==="header-footer"&&t.delete(i,1)}}),da(s)}function da(s){const t=s.getYChromeFragment(),e=new Map,n=[],o=t.toArray(),r=s.getDocument().chrome??[],i=a=>{const l=r.find(c=>c.id===a);return!!(l&&As(l))};o.forEach((a,l)=>{if(!(a instanceof I.XmlElement)||a.nodeName!=="header-footer")return;const c=`${a.getAttribute("side")}:${a.getAttribute("slot")}:${a.getAttribute("sectionIndex")??""}`,d=e.get(c);if(d===void 0){e.set(c,l);return}const g=o[d];!i(g.getAttribute("id"))&&i(a.getAttribute("id"))?(n.push(d),e.set(c,l)):n.push(l)}),n.length!==0&&s.transact(()=>{for(const a of n.sort((l,c)=>c-l))t.delete(a,1)})}function kg(s){const t=s.ydoc.getMap("metadata"),e=t.get("headers"),n=t.get("footers");!e&&!n||((s.getDocument().chrome?.length??0)>0?s.transact(()=>{t.delete("headers"),t.delete("footers")}):Cr(s,e,n))}function Sg(s,t,e="bottom-right"){const n=(s.getDocument().chrome??[]).filter(c=>c.type==="header-footer"&&c.slot==="default"&&c.sectionIndex===void 0),o=c=>{const d=Pl(c);return!d||d.children.every(g=>g.type==="text"&&(g.marks?.field==="page"||g.text.trim()===""))},r=new Set(n.filter(o).map(c=>c.side)),i=t?ws(e):void 0,a=i?.side==="headers"?"header":"footer",l=!!i&&!n.some(c=>c.side===a&&!o(c));!r.size&&!l||s.transact(()=>{const c=s.getYChromeFragment();Pr(c,d=>d.nodeName==="header-footer"&&d.getAttribute("slot")==="default"&&Br(d)===void 0&&r.has(d.getAttribute("side"))),i&&l&&c.push([s.blockToYjsElement(xs(a,"default",Cl([i.paragraph]),Qt(s.getDocument().children)))])})}function Ig(s){const t=s.ydoc.getMap("metadata");if(t.get(Gt.showPageNumbers)!==!0)return;const e=t.get(Gt.pageNumberPosition)??"bottom-right",{headers:n={},footers:o={}}=ca(s),r=ws(e),i=r.side==="headers"?n:o;if(s.transact(()=>{t.set(Gt.showPageNumbers,!1)}),!i.default){const a={...i,default:[r.paragraph]};Cr(s,r.side==="headers"?a:n,r.side==="footers"?a:o)}}function vg(s,t){const e=t?{fontFamily:t}:{},n=[];for(const o of s.split(/(\{PAGE\}|\{PAGES\})/))o&&(o==="{PAGE}"?n.push({type:"text",text:"1",marks:{field:"page",...e}}):o==="{PAGES}"?n.push({type:"text",text:"1",marks:{field:"numPages",...e}}):n.push({type:"text",text:o,...t?{marks:{...e}}:{}}));return n.length===0&&n.push({type:"text",text:"",...t?{marks:{...e}}:{}}),n}function xg(s){return s.toArray().every(t=>t instanceof I.XmlText?t.length===0:t instanceof I.XmlElement?t.toArray().every(e=>e instanceof I.XmlText?e.toDelta().every(n=>typeof n.insert=="string"&&n.insert.length===0):!1):!0)}function Br(s){const t=s.getAttribute("sectionIndex");if(t==null||t==="")return;const e=Number(t);return Number.isFinite(e)?e:void 0}function ga(s){return JSON.stringify((s.getDocument().chrome??[]).map(t=>t.type==="header-footer"?{side:t.side,slot:t.slot,sectionIndex:t.sectionIndex,children:t.children.map(e=>({align:e.align,children:e.children}))}:t.type))}function wg(s,t){const{side:e,sectionIndex:n}=t,o=s.getYChromeFragment();if(t.clear){const h=[];o.toArray().forEach((m,y)=>{m instanceof I.XmlElement&&m.nodeName==="header-footer"&&m.getAttribute("side")===e&&(t.slot===void 0||m.getAttribute("slot")===t.slot)&&(n===void 0||Br(m)===n)&&h.push(y)});const p=(t.slot!==void 0&&t.slot!=="default"||n!==void 0)&&o.toArray().some((m,y)=>m instanceof I.XmlElement&&m.nodeName==="header-footer"&&m.getAttribute("side")===e&&!h.includes(y));return p&&h.length>0&&h.every(m=>{const y=o.get(m);return y instanceof I.XmlElement&&xg(y)})?{changed:!1,removedCount:0}:h.length===0?p?(Mr(s,e,t.slot??"default",n),{changed:!0,removedCount:0,createdEmpty:!0}):{changed:!1,removedCount:0}:(s.transact(()=>{for(const m of h.reverse())o.delete(m,1)}),{changed:!0,removedCount:h.length})}const r=t.slot??"default",i=t.zones??{},a=[];if(typeof i.left=="string"&&a.push([0,i.left]),typeof i.center=="string"&&a.push([1,i.center]),typeof i.right=="string"&&a.push([2,i.right]),a.length===0)return{changed:!1,removedCount:0};const l=ga(s),c=()=>{for(const h of o.toArray())if(h instanceof I.XmlElement&&h.nodeName==="header-footer"&&h.getAttribute("side")===e&&h.getAttribute("slot")===r&&Br(h)===n)return h;return null},d=a.every(([,h])=>h==="");let g=!1;if(!c()&&d){if(!((r!=="default"||n!==void 0)&&o.toArray().some(h=>h instanceof I.XmlElement&&h.nodeName==="header-footer"&&h.getAttribute("side")===e)))return{changed:!1,removedCount:0};g=!0}Mr(s,e,r,n);const u=c();if(!u)return{changed:!1,removedCount:0};if(g)return{changed:!0,removedCount:0,createdEmpty:g};const f=Qt(s.getDocument().children);return s.transact(()=>{for(const[h,p]of a){const m=(s.getDocument().chrome??[]).find(k=>k.type==="header-footer"&&k.side===e&&k.slot===r&&k.sectionIndex===n)?.children[h],y=Al[h],b={type:"paragraph",id:m?.id??G(),children:vg(p,f),...m?.align??y?{align:m?.align??y}:{}};u.get(h)&&u.delete(h,1),u.insert(h,[s.blockToYjsElement(b)])}}),{changed:ga(s)!==l,removedCount:0}}function Ag(s,t,e){const n=e!==void 0?[e]:["default","first","even"];let o=0;return s.transact(()=>{for(const r of n){const i=Ss(s.ydoc,t,r);i.length!==0&&(o+=i.length,Is(s.ydoc,t,r,[]))}}),o}function Tg(s,t){const e=Ss(s.ydoc,t.side,t.slot);return JSON.stringify(e)===JSON.stringify([t])?!1:(s.transact(()=>{Is(s.ydoc,t.side,t.slot,[t])}),!0)}function se(s){return s.ydoc?s.ydoc.getMap("comments"):null}function Cg(s){const t=se(s);if(!t)return[];const e=[];return t.forEach(n=>{n&&typeof n=="object"&&e.push(n)}),e.sort((n,o)=>(n.createdAt??"").localeCompare(o.createdAt??"")),e}function ua(s){const t=s.getAttribute("structuralSuggestionKind")==="insert"?s.getAttribute("structuralSuggestionId"):s.getAttribute("diffState")==="insert"?s.getAttribute("suggestionId"):void 0;return typeof t=="string"?t:void 0}function Pg(s,t){if(!s.ydoc||t.length===0)return[];const e=new Set(t),n=[],o=(r,i)=>{for(const a of r.toArray()){if(a instanceof I.XmlElement){const g=ua(a);o(a,typeof g=="string"&&e.has(g)?g:i);continue}if(!(a instanceof I.XmlText)||!(r instanceof I.XmlElement))continue;const l=r.getAttribute("id");if(typeof l!="string")continue;let c=0,d=0;for(const g of st(a)){if(typeof g.insert!="string")continue;const u=g.insert.length,f=d+(g.attributes?.deletion?0:u),h=g.attributes?.suggestionId??i,p=!g.attributes?.suggestionId&&!!i;if(u>0&&typeof h=="string"&&e.has(h)){const m=n[n.length-1];m?.blockId===l&&m.suggestionId===h&&!!m.structural===p&&m.end===c?(m.end+=u,m.projectedEnd=f):n.push({blockId:l,suggestionId:h,start:c,end:c+u,projectedStart:d,projectedEnd:f,...p?{structural:!0}:{}})}c+=u,d=f}c===0&&i&&n.push({blockId:l,suggestionId:i,start:0,end:0,projectedStart:0,projectedEnd:0,structural:!0})}};return o(s.getYContentFragment()),o(s.ydoc.getXmlFragment("notes")),o(s.ydoc.getXmlFragment("chrome")),n}function Er(s,t,e,n){return{id:gt(),author:e?.author??"Anonymous",...e?.initials?{initials:e.initials}:{},...e?.authorId?{authorId:e.authorId}:{},...e?.authorImageUrl?{authorImageUrl:e.authorImageUrl}:{},...e?.authorType?{authorType:e.authorType}:{},...e?.agentName?{agentName:e.agentName}:{},...e?.agentModel?{agentModel:e.agentModel}:{},...e?.suggestionId?{suggestionId:e.suggestionId}:{},...e?.mentions?.length?{mentions:e.mentions}:{},...e?.citations?.length?{citations:e.citations.map(o=>({...o}))}:{},...e?.anchorBlockId?{anchorBlockId:e.anchorBlockId}:{},...e?.agentRequestId?{agentRequestId:e.agentRequestId}:{},...e?.agentConversationId?{agentConversationId:e.agentConversationId}:{},...e?.agentTriggerIds?.length?{agentTriggerIds:[...e.agentTriggerIds]}:{},...e?.relatedSuggestionIds?.length?{relatedSuggestionIds:[...e.relatedSuggestionIds]}:{},createdAt:new Date().toISOString(),bodyMd:t,...n?{parentId:n}:{}}}function ha(s,t,e,n){const o=se(s);if(!o||!Z(s.ydoc,t))return null;const r=Er(s,e,{...n,anchorBlockId:t});return s.transact(()=>{o.set(r.id,r)}),r.id}function Mg(s,t,e,n,o){const r=Z(s.ydoc,t),i=r?ct(r):null;if(!i||n<=e||e>=i.length)return!1;const a=Math.min(n,i.length),l=st(i);let c=0,d=!1;for(const g of l){if(typeof g.insert!="string")continue;const u=c,f=c+g.insert.length;c=f;const h=Math.max(u,e),p=Math.min(f,a);if(p<=h)continue;const m=g.attributes?.comment,y=m?m.split(","):[];y.includes(o)||y.push(o),at(i,h,p-h,{comment:y.join(",")}),d=!0}return d}function Bg(s,t,e,n,o,r){return Nr(s,[{blockId:t,start:e,end:n}],o,r)}function Nr(s,t,e,n){const o=se(s);if(!o||t.length===0)return null;const r=Er(s,e,n),i=r.id;let a=!1;return s.transact(()=>{for(const l of t)a=Mg(s,l.blockId,l.start,l.end,i)||a;a&&o.set(i,r)}),a?i:null}function Eg(s,t,e,n){const o=se(s);if(!o||!o.has(t))return null;const r=Er(s,e,n,t);return s.transact(()=>{o.set(r.id,r)}),r.id}function Ng(s,t,e){const n=se(s),o=n?.get(t);return!n||!o?!1:(s.transact(()=>{n.set(t,{...o,resolved:e})}),!0)}function Lg(s,t,e){const n=se(s);if(!n)return 0;const o=new Set(t);if(o.size===0)return 0;const r=[];return n.forEach(i=>{const a=i;if(!a||typeof a!="object"||a.parentId||a.resolved)return;const l=[];typeof a.suggestionId=="string"&&a.suggestionId.length>0&&l.push(a.suggestionId);for(const c of a.relatedSuggestionIds??[])l.includes(c)||l.push(c);l.length!==0&&l.some(c=>o.has(c))&&(l.some(c=>e(c))||r.push(a))}),r.length===0?0:(s.transact(()=>{for(const i of r)n.set(i.id,{...i,resolved:!0})}),r.length)}function Fg(s,t){const e=se(s);if(!e)return 0;const n=[];if(e.forEach(l=>{const c=l;c&&typeof c=="object"&&!c.parentId&&!c.resolved&&typeof c.suggestionId=="string"&&c.suggestionId.length>0&&(!t(c.suggestionId)||c.relatedSuggestionIds?.some(d=>!t(d)))&&n.push(c)}),n.length===0)return 0;const o=new Map,r=(l,c)=>{for(const d of l.toArray()){if(d instanceof I.XmlElement){const g=ua(d);r(d,g&&t(g)?g:c);continue}if(d instanceof I.XmlText)for(const g of st(d)){const u=g.attributes?.comment,f=g.attributes?.suggestionId??c;if(!(!u||!f))for(const h of u.split(",")){const p=o.get(h)??[];p.includes(f)||p.push(f),o.set(h,p)}}}};try{r(s.getYContentFragment()),r(s.ydoc.getXmlFragment("notes")),r(s.ydoc.getXmlFragment("chrome"))}catch{}const i=l=>{const c=Array.from(new Set([...l.suggestionId?[l.suggestionId]:[],...o.get(l.id)??[],...l.relatedSuggestionIds??[]])).filter(t);if(c.length>0)return c;if(l.anchorBlockId){let d=Z(s.ydoc,l.anchorBlockId)??null;for(;d;){if(d instanceof I.XmlElement){const g=d.getAttribute("structuralSuggestionId");if(typeof g=="string"&&t(g))return[g];for(const u of["structuralSuggestionRecord","structuralSuggestionRecords"]){const f=d.getAttribute(u);if(typeof f=="string")try{const h=JSON.parse(f),p=(Array.isArray(h)?h:[h]).find(m=>typeof m?.id=="string"&&t(m.id));if(p)return[p.id]}catch{}}}d=d.parent}}return[]};let a=0;return s.transact(()=>{for(const l of n){const c=i(l);if(c.length===0)continue;const d={...l,suggestionId:c[0]};c.length>1?d.relatedSuggestionIds=c:delete d.relatedSuggestionIds,e.set(l.id,d),a+=1}}),a}function Og(s,t){const e=se(s);if(!e||!e.has(t))return!1;const n=new Set([t]);let o=!0;for(;o;)o=!1,e.forEach((r,i)=>{const a=r;a?.parentId&&n.has(a.parentId)&&!n.has(i)&&(n.add(i),o=!0)});return s.transact(()=>{for(const i of n)e.delete(i);const r=i=>{for(const a of i.toArray()){if(a instanceof I.XmlElement){r(a);continue}if(!(a instanceof I.XmlText))continue;let l=0;for(const c of st(a)){if(typeof c.insert!="string")continue;const d=c.insert.length,g=c.attributes?.comment;if(g){const u=g.split(",").filter(f=>!n.has(f));u.length!==g.split(",").length&&at(a,l,d,{comment:u.length>0?u.join(","):null})}l+=d}}};try{r(s.getYContentFragment()),r(s.ydoc.getXmlFragment("notes")),r(s.ydoc.getXmlFragment("chrome"))}catch{}}),!0}function fa(s,t){const e=d=>d.replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/&/g,"&");if(!s.includes("<")||!s.includes(">"))return[{type:"text",text:e(s),marks:{...t}}];const n=[],o={},r=d=>{d&&n.push({type:"text",text:e(d),marks:{...o,...t}})},i=/<(\/?)(i|em|b|strong|u|a)((?:\s+[a-zA-Z-]+="[^"]*")*)\s*\/?>/g;let a=0,l;for(;(l=i.exec(s))!==null;){r(s.slice(a,l.index)),a=i.lastIndex;const d=l[1]==="/",g=l[2].toLowerCase();if(g==="i"||g==="em")d?delete o.italic:o.italic=!0;else if(g==="b"||g==="strong")d?delete o.bold:o.bold=!0;else if(g==="u")d?delete o.underline:o.underline=!0;else if(g==="a")if(d)delete o.link;else{const u=/href="([^"]*)"/.exec(l[3]??"");u?.[1]&&(o.link=e(u[1]))}}r(s.slice(a));const c=n.map(d=>({...d,text:d.text.replace(/<[^>]{1,80}>/g,"")})).filter(d=>d.text.length>0);return c.length>0?c:[{type:"text",text:e(s),marks:{...t}}]}function $e(s){const t=[],e=n=>{for(const o of n.toArray()){if(o instanceof I.XmlElement){if(o.nodeName==="footnote")continue;e(o);continue}if(!(o instanceof I.XmlText))continue;let r=0;for(const i of st(o)){if(typeof i.insert!="string")continue;const a=i.attributes??{};typeof a.footnoteRef=="string"&&a.footnoteRef&&t.push({yText:o,start:r,length:i.insert.length,text:i.insert,attributes:a,footnoteId:a.footnoteRef}),r+=i.insert.length}}};try{e(s.getYContentFragment())}catch{}return t}function ke(s){const t=new Map,e=n=>{for(const o of n.toArray())if(o instanceof I.XmlElement&&o.nodeName==="footnote"){const r=o.getAttribute("id");typeof r=="string"&&r&&t.set(r,o)}};try{e(s.getYNotesFragment()),e(s.getYContentFragment())}catch{}return t}function Rg(s,t){const e=[...s.notes??[],...s.children.filter(n=>n.type==="footnote")];for(const n of e)if(n.id===t||W(n,t))return!0;return!1}function Lr(s){const t=new Map;for(const[e,n]of ke(s))t.set(e,n.getAttribute("noteKind")==="endnote"?"endnote":"footnote");return t}function Dg(s){const t=[];for(const a of $e(s))t.includes(a.footnoteId)||t.push(a.footnoteId);const e=Lr(s),n=new Map,o=s.getDocument();for(const a of[...o.notes??[],...o.children.filter(l=>l.type==="footnote")])n.set(a.id,a);const r={footnote:0,endnote:0},i=[];for(const a of t){const l=n.get(a);if(!l)continue;const c=e.get(a)??"footnote";r[c]+=1,i.push({footnote:l,number:r[c],display:Mo(r[c],c),kind:c})}return i}function Se(s){const t=$e(s);if(t.length===0)return!1;const e=Lr(s),n=new Map,o={footnote:0,endnote:0};for(const i of t)if(!n.has(i.footnoteId)){const a=e.get(i.footnoteId)??"footnote";o[a]+=1,n.set(i.footnoteId,Mo(o[a],a))}const r=t.filter(i=>i.text!==n.get(i.footnoteId));return r.length===0?!1:(s.transact(()=>{for(const i of[...r].sort((a,l)=>l.start-a.start)){const a=n.get(i.footnoteId)??"";i.yText.delete(i.start,i.length),lt(i.yText,i.start,a,i.attributes)}}),!0)}function $g(s){pa(s);const t=$e(s),e=ke(s);if(t.length===0&&e.size===0)return;const n=new Set(t.map(o=>o.footnoteId));s.transact(()=>{for(const[o,r]of e)if(!n.has(o)&&!r.getAttribute("structuralSuggestionId")){const i=r.parent;if(i){const a=i.toArray().indexOf(r);a>=0&&i.delete(a,1)}}for(const o of[...t].sort((r,i)=>i.start-r.start))e.has(o.footnoteId)||o.yText.delete(o.start,o.length)}),Se(s)}function pa(s){let t;try{t=s.getYContentFragment()}catch{return!1}const e=[],n=d=>{for(const g of d.toArray()){if(g instanceof I.XmlElement){n(g);continue}if(!(g instanceof I.XmlText))continue;let u=0;for(const f of st(g)){if(typeof f.insert!="string")continue;const h=f.attributes??{};typeof h.footnotePendingBody=="string"&&e.push({yText:g,start:u,length:f.insert.length,footnoteId:typeof h.footnoteRef=="string"&&h.footnoteRef?h.footnoteRef:G(),body:h.footnotePendingBody,kind:h.footnotePendingKind==="endnote"?"endnote":"footnote",fontFamily:typeof h.fontFamily=="string"?h.fontFamily:void 0,suggestionId:typeof h.suggestionId=="string"?h.suggestionId:void 0,suggested:h.insertion===!0}),u+=f.insert.length}}};if(n(t),e.length===0)return!1;const o=ke(s),r=new Set($e(s).map(d=>d.footnoteId)),i=s.getDocument(),a=new Map;for(const d of[...i.notes??[],...i.children.filter(g=>g.type==="footnote")])a.set(d.id,d.children.flatMap(g=>g.type==="paragraph"?g.children:[]).map(g=>g.type==="text"?g.text:"").join(""));const l=new Set;for(const d of e)if(!o.has(d.footnoteId)){for(const[g,u]of a)if(u===d.body&&!r.has(g)&&!l.has(g)&&o.has(g)){d.footnoteId=g,l.add(g);break}}const c=Qt(s.getDocument().children);return s.transact(()=>{for(const d of e){if(at(d.yText,d.start,d.length,{footnotePendingBody:null,footnotePendingKind:null,footnoteRef:d.footnoteId,superscript:!0}),o.has(d.footnoteId)){if(a.get(d.footnoteId)!==d.body){const p=o.get(d.footnoteId);let m=null;for(const b of p.toArray())if(b instanceof I.XmlElement&&b.nodeName==="paragraph"){m=b;break}const y=m?ct(m):null;if(y){const b=d.fontFamily??c;y.length>0&&y.delete(0,y.length);let k=0;for(const S of fa(d.body,{fontSize:ge,...b?{fontFamily:b}:{}}))lt(y,k,S.text,S.marks),k+=S.text.length}}continue}const g=d.fontFamily??c,u={fontSize:ge,...g?{fontFamily:g}:{}},f={type:"footnote",id:d.footnoteId,...d.kind==="endnote"?{noteKind:"endnote"}:{},children:[{type:"paragraph",id:G(),children:fa(d.body,u)}]},h=s.blockToYjsElement(f);h.setAttribute("id",d.footnoteId),d.kind==="endnote"&&h.setAttribute("noteKind","endnote"),d.suggested&&d.suggestionId&&s.suggestions.setElementStructuralSuggestion(h,"insert",void 0,d.suggestionId,"Insert footnote"),s.getYNotesFragment().push([h]),o.set(d.footnoteId,h)}}),Se(s),!0}function jg(s){let t;try{t=s.getYContentFragment()}catch{return}const e=[];for(const i of t.toArray())i instanceof I.XmlElement&&i.nodeName==="footnote"&&e.push(i);if(e.length===0)return;const n=s.getYNotesFragment(),o=s.getDocument(),r=new Map([...o.notes??[],...o.children.filter(i=>i.type==="footnote")].map(i=>[i.id,i]));s.transact(()=>{for(const a of e){const l=a.getAttribute("id"),c=typeof l=="string"?r.get(l):void 0;c&&n.push([s.blockToYjsElement(c)])}const i=t.toArray();for(let a=i.length-1;a>=0;a--){const l=i[a];l instanceof I.XmlElement&&l.nodeName==="footnote"&&t.delete(a,1)}}),Se(s)}function _g(s,t,e,n,o="footnote"){if(!s.ydoc)return null;const r=G(),i=s.suggestions.isSuggesting(),a=i?gt():void 0,l=Lr(s),c=new Set($e(s).map(m=>m.footnoteId).filter(m=>(l.get(m)??"footnote")===o)).size,d=Mo(c+1,o);let g,u;{const m=W(s.getDocument(),t.block);if(m&&m.type==="paragraph"){u=m.direction;let y=0;for(const b of m.children){if(b.type!=="text")continue;const k=y+b.text.length;if(t.offset<=k&&b.marks?.fontFamily){g=b.marks.fontFamily;break}y=k}}}const f={footnoteRef:r,superscript:!0,...g?{fontFamily:g}:{},...i&&a?{insertion:!0,...s.suggestions.buildInlineMetadataMarks(a,"Insert footnote")}:{}};if(!s.insertTextNodes(t,[{type:"text",text:d,marks:f}],n))return null;const h=g??Qt(s.getDocument().children),p={fontSize:ge,...h?{fontFamily:h}:{}};return s.transact(()=>{const m={type:"footnote",id:r,...o==="endnote"?{noteKind:"endnote"}:{},children:[{type:"paragraph",id:G(),...u?{direction:u}:{},children:[{type:"text",text:e||"",marks:p}]}]},y=s.blockToYjsElement(m);if(y.setAttribute("id",r),o==="endnote"&&y.setAttribute("noteKind","endnote"),i&&a&&s.suggestions.setElementStructuralSuggestion(y,"insert",void 0,a,"Insert footnote"),s.getYNotesFragment().push([y]),!e){const b=y.toArray()[0];b instanceof I.XmlElement&&b.setAttribute("_emptyTextMarks",JSON.stringify(p))}}),Se(s),{footnoteId:r,...a?{suggestionId:a}:{}}}function Xg(s,t,e){const n=ke(s).get(t);if(!n)return!1;let o=null;for(const c of n.toArray())if(c instanceof I.XmlElement&&c.nodeName==="paragraph"){o=c;break}if(!o)return!1;const r=ct(o);if(!r)return!1;const i=s.getDocument(),a=[...i.notes??[],...i.children.filter(c=>c.type==="footnote")].find(c=>c.id===t)?.children.flatMap(c=>c.type==="paragraph"?c.children:[]).find(c=>c.type==="text"&&c.marks?.fontFamily)?.marks?.fontFamily??Qt(s.getDocument().children),l={fontSize:ge,...a?{fontFamily:a}:{}};return s.transact(()=>{r.length>0&&r.delete(0,r.length),e.length>0?lt(r,0,e,l):o.setAttribute("_emptyTextMarks",JSON.stringify(l))}),!0}function Ug(s,t,e,n,o=!1){if(!e)return{success:!1,replacements:0,error:"The text to find must not be empty."};let r=null;const i=b=>{if(!r){for(const k of b.toArray())if(k instanceof I.XmlElement){if(k.getAttribute("id")===t){r=k;return}i(k)}}};for(const b of ke(s).values()){if(b.getAttribute("id")===t){r=b;break}if(i(b),r)break}if(!r)return{success:!1,replacements:0,error:`Note block '${t}' was not found.`};const a=ct(r);if(!a)return{success:!1,replacements:0,error:`Note block '${t}' does not contain editable text.`};let l="";const c=[];let d=0;for(const b of st(a))if(typeof b.insert=="string"){if(!b.attributes?.deletion){for(let k=0;k<b.insert.length;k+=1)c.push(d+k);l+=b.insert}d+=b.insert.length}const g=[];let u=0;for(;u<=l.length-e.length;){const b=l.indexOf(e,u);if(b<0)break;const k=c[b];if(c[b+e.length-1]-k!==e.length-1)return{success:!1,replacements:0,error:`${JSON.stringify(e)} in note block '${t}' runs across a pending tracked deletion. Replace a smaller piece that doesn't span it, or settle that change first.`};g.push(k),u=b+e.length}if(g.length===0)return{success:!1,replacements:0,error:`No match found for ${JSON.stringify(e)} in note block '${t}'.`};if(!o&&g.length>1)return{success:!1,replacements:0,error:`Found ${g.length} matches for ${JSON.stringify(e)} in note block '${t}'. Include more surrounding context so it matches exactly one location, or use replace_all.`};const f=o?g:g.slice(0,1),h=s.suggestions.isSuggesting()?gt():null,p=h?s.suggestions.buildInlineMetadataMarks(h,"Replace footnote text"):null,m=b=>{let k=0;for(const S of st(a)){if(typeof S.insert!="string")continue;const v=k+S.insert.length;if(b<v){const x={...S.attributes??{}};return delete x.insertion,delete x.deletion,delete x.suggestionId,delete x.suggestionLabel,delete x.suggestionCreatedAt,x}k=v}return{fontSize:ge}},y=new Map(f.map(b=>[b,m(b)]));return s.transact(()=>{for(const b of[...f].reverse()){const k=y.get(b)??{fontSize:ge};h&&p?(at(a,b,e.length,{deletion:!0,...p}),n&<(a,b,n,{...k,insertion:!0,deletion:null,formatChange:null,...p})):(a.delete(b,e.length),n&<(a,b,n,k))}}),{success:!0,replacements:f.length,...h?{suggestionId:h}:{}}}function zg(s,t){const e=ke(s);return e.size===0?!1:(s.transact(()=>{for(const n of e.values())t==="endnote"?n.setAttribute("noteKind","endnote"):n.removeAttribute("noteKind")}),Se(s),!0)}function Wg(s,t){const e=$e(s).filter(o=>o.footnoteId===t),n=ke(s).get(t);if(e.length===0&&!n)return!1;if(s.suggestions.isSuggesting()){const o=gt();return s.transact(()=>{for(const r of e)at(r.yText,r.start,r.length,{deletion:!0,...s.suggestions.buildInlineMetadataMarks(o,"Delete footnote")});n&&s.suggestions.setElementStructuralSuggestion(n,"delete",void 0,o,"Delete footnote")}),!0}return s.transact(()=>{for(const o of[...e].sort((r,i)=>i.start-r.start))o.yText.delete(o.start,o.length);if(n){const o=n.parent;if(o){const r=o.toArray().indexOf(n);r>=0&&o.delete(r,1)}}}),Se(s),!0}function ma(s,t,e){const n=a=>{const l=new Map;for(const c of a)c.id&&l.set(c.id,(l.get(c.id)??0)+1);return l},o=n(s),r=n(t),i=a=>a.id&&o.get(a.id)===1&&r.get(a.id)===1?`id:${a.id}`:`content:${e(a)}`;return{beforeKeys:s.map(i),afterKeys:t.map(i)}}function Fr(s,t){const e=s.length,n=t.length,o=Array.from({length:e+1},()=>Array(n+1).fill(0));for(let l=1;l<=e;l++)for(let c=1;c<=n;c++)s[l-1]===t[c-1]?o[l][c]=o[l-1][c-1]+1:o[l][c]=Math.max(o[l-1][c],o[l][c-1]);const r=[];let i=e,a=n;for(;i>0&&a>0;)s[i-1]===t[a-1]?(r.unshift(s[i-1]),i-=1,a-=1):o[i-1][a]>o[i][a-1]?i-=1:a-=1;return r}function ba(s){let t=s,e=null;for(;t;){if(t instanceof I.XmlElement){const n=t.nodeName,o=t.getAttribute("id");if(n==="paragraph"&&o)return{blockId:o,offset:0};if(n==="list-item"&&(e=t),n==="list"&&o&&e){let r=0;for(let i=0;i<t.length;i++){const a=t.get(i);if(a===e)return{blockId:o,offset:r};if(a instanceof I.XmlElement&&a.nodeName==="list-item"){for(let l=0;l<a.length;l++){const c=a.get(l);if(c instanceof I.XmlText){r+=c.length;break}}r+=1}}return{blockId:o,offset:0}}}t=t.parent}return null}function Jg(s,t,e,n){const o=s.getArray("paragraphs"),r=o.toArray().findIndex(a=>a?.get("id")===t);if(r<0)return null;const i=o.get(r);if(!i)return null;if(e==="paragraph")return i.get("content");if(e==="list"&&n!==void 0){const a=i.get("items");return!a||n>=a.length?null:a.get(n)?.get("content")}return null}function Hg(s,t,e,n){const o=Z(s,t);if(!o)return null;if(e==="paragraph"||e==="list-item")return ct(o);if(e==="list"&&n!==void 0){let r=0;for(let i=0;i<o.length;i++){const a=o.get(i);if(a instanceof I.XmlElement&&a.nodeName==="list-item"){if(r===n)return ct(a);r++}}}return null}function ya(s,t,e,n){return Hg(s,t,e,n)||(Te(s)?Jg(s,t,e,n):null)}function ie(s,t,e){const n=W(e,s.block);if(!n||!n.id)return null;if(n.type==="paragraph"){const o=n,r=ya(t,n.id,"paragraph");if(!r)return null;const i=o.children.filter(c=>c.type==="text").reduce((c,d)=>c+d.text.length,0),a=Math.max(0,Math.min(s.offset,i)),l=I.createRelativePositionFromTypeIndex(r,a);return{blockId:n.id,textOffset:l}}if(n.type==="list"){const o=n;let r=-1,i=s.offset;if(s.offset,s.block!==n.id){let d=0;for(let g=0;g<o.children.length;g++){if(o.children[g].id===s.block){r=g,d+s.offset;break}d+=Fn(o.children[g]),g<o.children.length-1&&(d+=1)}}if(r===-1){let d=s.offset;for(let g=0;g<o.children.length;g++){const u=Fn(o.children[g]),f=g<o.children.length-1?1:0;if(d<=u){r=g,i=d;break}d-=u+f,g===o.children.length-1&&(r=g,i=u)}}r===-1&&(r=0,i=0);const a=ya(t,n.id,"list",r);if(!a)return null;const l=Math.max(0,Math.min(i,a.length)),c=I.createRelativePositionFromTypeIndex(a,l);return{blockId:n.id,textOffset:c}}return null}function qg(s,t,e){const n=s.getArray("paragraphs");for(let o=0;o<n.length;o++){const r=n.get(o);if(!r)continue;const i=r.get("id");if(!i)continue;const a=r.get("type");if(a==="paragraph"&&r.get("content")===t)return{blockId:i,offset:0,yTextOffset:0};if(a==="list"){const l=r.get("items");if(!l)continue;const c=W(e,i);if(!c||c.type!=="list")continue;const d=c;let g=0;for(let u=0;u<l.length;u++){if(l.get(u)?.get("content")===t)return{blockId:i,offset:g,yTextOffset:0};u<d.children.length&&(g+=Fn(d.children[u]),u<d.children.length-1&&(g+=1))}}}return null}function on(s,t){const e=I.createAbsolutePositionFromRelativePosition(s.textOffset,t);if(!e||!(e.type instanceof I.XmlText))return Z(t,s.blockId)?{block:s.blockId,offset:0}:null;const n=e.index,o=e.type,r=ba(o);if(r)return{block:r.blockId,offset:r.offset+n};if(Te(t)){const i=mt(t),a=qg(t,o,i);if(a)return{block:a.blockId,offset:a.offset+n}}return Z(t,s.blockId)?{block:s.blockId,offset:n}:null}function Y(s,t,e){return{anchor:s.anchor?ie(s.anchor,t,e):null,focus:s.focus?ie(s.focus,t,e):null}}function Or(s,t){return{anchor:s.anchor?on(s.anchor,t):null,focus:s.focus?on(s.focus,t):null}}function Ie(s){if(typeof window>"u")return null;try{return window.localStorage??null}catch(t){return console.warn(`[${s}] localStorage unavailable:`,t),null}}function Yg(s,t){if(s.length!==t.length)return!1;for(let e=0;e<s.length;e++)if(s[e]!==t[e])return!1;return!0}class Rr{constructor(t,e,n=!1,o){this.destroyed=!1,this.handleDocumentUpdate=()=>{this.cachedBaseUpdate=null,this.cachedBaseUpdateV2=null},this.cachedBaseUpdate=null,this.cachedBaseUpdateV2=null,this.proposals=new Map,this.suggestionMeta=new Map,this.paragraphSuggestions=new Map,this.tableCellSuggestions=new Map,this.undoStack=[],this.redoStack=[],this.listeners=new Set,this.conversationId=null,this.ydoc=t,this.ydoc.on("update",this.handleDocumentUpdate),this.documentId=e||"default",this.conversationId=o||null,this.disableLocalStorage=n,this.storageKey=this.computeStorageKey();const r=t.getXmlFragment("content");this.undoManager=new I.UndoManager(r,{trackedOrigins:new Set}),this.documentId,this.conversationId,this.storageKey,n?this.clearDocumentProposalCacheIfRemote():this.loadFromLocalStorage(),Kg(this.documentId,this)}getBaseUpdate(){return this.cachedBaseUpdate||(this.cachedBaseUpdate=I.encodeStateAsUpdate(this.ydoc)),this.cachedBaseUpdate}seedForkFromBase(t){return this.cachedBaseUpdateV2||(this.cachedBaseUpdateV2=I.encodeStateAsUpdateV2(this.ydoc)),I.applyUpdateV2(t,this.cachedBaseUpdateV2),t}computeStorageKey(){return this.conversationId?`proposals_${this.documentId}_${this.conversationId}`:`proposals_${this.documentId}`}clearDocumentProposalCacheIfRemote(){if(!this.isLikelyRemoteDocumentId())return;const t=Ie("DetachedSuggestionStore");if(!t)return;const e=`proposals_${this.documentId}`,n=[];for(let o=0;o<t.length;o++){const r=t.key(o);r&&(r===e||r.startsWith(`${e}_`))&&n.push(r)}for(const o of n)t.removeItem(o)}isLikelyRemoteDocumentId(){const t=this.documentId.replace(/-/g,"");return/^[a-z0-9]{16}$/i.test(t)?!0:/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(this.documentId)}getYDoc(){return this.ydoc}getDocumentId(){return this.documentId}getConversationId(){return this.conversationId}setOnSuggestionsChanged(t){this.onProposalsChanged=t}setConversation(t,e){this.conversationId!==t&&(this.conversationId,this.conversationId=t,this.storageKey=this.computeStorageKey(),this.proposals.clear(),this.suggestionMeta.clear(),this.paragraphSuggestions.clear(),this.tableCellSuggestions.clear(),e&&(Object.keys(e.proposals||{}).length>0||Object.keys(e.metadata||{}).length>0)?(Object.keys(e.proposals||{}).length,this.loadFromServerData(e)):this.disableLocalStorage||this.loadFromLocalStorage(),this.notifyListeners())}serializeForServer(){const t={proposals:{},metadata:{},paragraphSuggestions:{}},e=new Set;for(const[n,o]of this.suggestionMeta)o.status==="pending"&&e.add(n);for(const[n,o]of this.proposals)e.has(n)&&(t.proposals[n]=btoa(String.fromCharCode(...o)));for(const[n,o]of this.suggestionMeta){if(!e.has(n))continue;const r={...o};r.anchors&&(r.anchors=r.anchors.map(i=>({...i,from:i.from?btoa(String.fromCharCode(...i.from)):i.from,to:i.to?btoa(String.fromCharCode(...i.to)):i.to}))),t.metadata[n]=r}for(const[n,o]of this.paragraphSuggestions){const r=o.filter(i=>e.has(i));r.length>0&&(t.paragraphSuggestions[n]=r)}return t}loadFromServerData(t,e){if(this.proposals.clear(),this.suggestionMeta.clear(),this.paragraphSuggestions.clear(),!!t){if(Object.keys(t.proposals||{}).length,Object.keys(t.metadata||{}).length,e?.persistAndNotify,t.proposals)for(const[n,o]of Object.entries(t.proposals)){const r=Uint8Array.from(atob(o),i=>i.charCodeAt(0));this.proposals.set(n,r)}if(t.metadata)for(const[n,o]of Object.entries(t.metadata)){const r={...o};r.anchors&&(r.anchors=r.anchors.map(i=>({...i,from:i.from?Uint8Array.from(atob(i.from),a=>a.charCodeAt(0)):i.from,to:i.to?Uint8Array.from(atob(i.to),a=>a.charCodeAt(0)):i.to}))),this.suggestionMeta.set(n,r)}if(t.paragraphSuggestions)for(const[n,o]of Object.entries(t.paragraphSuggestions))this.paragraphSuggestions.set(n,o);e?.persistAndNotify&&(this.saveToLocalStorage(),this.notifyListeners())}}static getOldFormatProposals(t){const e=Ie("DetachedSuggestionStore");if(!e)return null;const n=`proposals_${t}`;try{const o=e.getItem(n);if(!o)return null;const r=JSON.parse(o);return!r.proposals||Object.keys(r.proposals).length===0?null:{proposals:r.proposals||{},metadata:r.metadata||{},paragraphSuggestions:r.paragraphSuggestions||{}}}catch(o){return console.error("[DetachedSuggestionStore] Failed to read old format proposals:",o),null}}static clearOldFormatProposals(t){const e=Ie("DetachedSuggestionStore");if(!e)return;const n=`proposals_${t}`;try{e.removeItem(n)}catch(o){console.error("[DetachedSuggestionStore] Failed to clear old format proposals:",o)}}static clearAllStoredSuggestions(t){const e=Ie("DetachedSuggestionStore");if(!e)return;const n=`proposals_${t}`,o=[];for(let r=0;r<e.length;r++){const i=e.key(r);i&&(i===n||i.startsWith(`${n}_`))&&o.push(i)}try{for(const r of o)e.removeItem(r)}catch(r){console.error("[DetachedSuggestionStore] Failed to clear stored proposals for document:",t,r)}}loadFromLocalStorage(){const t=Ie("DetachedSuggestionStore");if(t)try{const e=t.getItem(this.storageKey);if(e){const n=JSON.parse(e);if(Object.keys(n.proposals||{}).length,Object.keys(n.metadata||{}).length,n.proposals)for(const[o,r]of Object.entries(n.proposals)){const i=Uint8Array.from(atob(r),a=>a.charCodeAt(0));this.proposals.set(o,i)}if(n.metadata)for(const[o,r]of Object.entries(n.metadata)){const i=r;i.anchors&&(i.anchors=i.anchors.map(a=>({...a,from:a.from?Uint8Array.from(atob(a.from),l=>l.charCodeAt(0)):a.from,to:a.to?Uint8Array.from(atob(a.to),l=>l.charCodeAt(0)):a.to}))),this.suggestionMeta.set(o,i)}if(n.paragraphSuggestions)for(const[o,r]of Object.entries(n.paragraphSuggestions))this.paragraphSuggestions.set(o,r);Array.from(this.proposals.keys()),Array.from(this.suggestionMeta.keys()),Array.from(this.suggestionMeta.values()).filter(o=>o.status==="pending").length,Array.from(this.suggestionMeta.values()).filter(o=>o.status==="accepted").length,Array.from(this.suggestionMeta.values()).filter(o=>o.status==="rejected").length,Array.from(this.suggestionMeta.values()).map(o=>({id:o.id,status:o.status}))}else this.storageKey}catch(e){console.error("[DetachedSuggestionStore] Failed to load from localStorage:",e)}}saveToLocalStorage(){if(this.disableLocalStorage){this.onProposalsChanged&&this.onProposalsChanged();return}const t=Ie("DetachedSuggestionStore");if(!t){this.onProposalsChanged&&this.onProposalsChanged();return}try{const e={proposals:{},metadata:{},paragraphSuggestions:{}};for(const[n,o]of this.proposals)e.proposals[n]=btoa(String.fromCharCode(...o));for(const[n,o]of this.suggestionMeta){const r={...o};r.anchors&&(r.anchors=r.anchors.map(i=>({...i,from:i.from?btoa(String.fromCharCode(...i.from)):i.from,to:i.to?btoa(String.fromCharCode(...i.to)):i.to}))),e.metadata[n]=r}for(const[n,o]of this.paragraphSuggestions)e.paragraphSuggestions[n]=o;t.setItem(this.storageKey,JSON.stringify(e)),this.storageKey,Object.keys(e.proposals).length,Object.keys(e.metadata).length,Object.values(e.metadata).filter(n=>n.status==="pending").length,Object.values(e.metadata).filter(n=>n.status==="accepted").length,Object.values(e.metadata).filter(n=>n.status==="rejected").length,Object.keys(e.metadata),this.onProposalsChanged&&this.onProposalsChanged()}catch(e){console.error("[DetachedSuggestionStore] Failed to save to localStorage:",e)}}cleanupOldProposals(){const t=Date.now(),e=24*60*60*1e3;for(const[n,o]of this.suggestionMeta)t-o.createdAt>e&&(this.proposals.delete(n),this.suggestionMeta.delete(n),this.removeProposalFromParagraphs(n));this.saveToLocalStorage()}createSuggestion(t,e,n={}){const o=this.seedForkFromBase(new I.Doc),r=I.encodeStateVector(o);let i=[];o.transact(()=>{i=e(o)},"proposal-edit");const a=I.encodeStateAsUpdate(o,r);return this.proposals.set(t,a),this.suggestionMeta.set(t,{id:t,authorId:n.authorId||"system",authorType:n.authorType||"ai",createdAt:Date.now(),status:"pending",anchors:i,...n}),this.saveToLocalStorage(),this.notifyListeners(),i.length,t}createSuggestionFromToolCall(t,e){return this.createSuggestion(this.generateId(),n=>e(n,t),{authorType:"ai",toolCallAction:t,description:`AI: ${t.name}`})}createTextDeletion(t,e,n,o,r,i={}){return this.createSuggestion(t,a=>{const l=Z(a,e);if(!l)return console.warn(`Paragraph ${e} not found for text deletion`),[];const c=ct(l);return c?(c.delete(n,o),[{kind:"delete",paragraphId:e,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(c,n,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(c,n+o,0)),text:r}]):(console.warn(`No text content found in paragraph ${e}`),[])},{...i,id:t})}createTextInsertion(t,e,n,o,r={},i={}){const a={...r,proposalId:t};return this.createSuggestion(t,l=>{const c=Z(l,e);if(!c)return console.warn(`Paragraph ${e} not found for text insertion`),[];const d=ct(c);return d?(lt(d,n,o,a),[{kind:"insert",paragraphId:e,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(d,n,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(d,n+o.length,0)),text:o}]):(console.warn(`No text content found in paragraph ${e}`),[])},{...i,id:t})}createTextReplacement(t,e,n,o,r,i={},a,l={}){const c={...i,proposalId:t};return this.createSuggestion(t,d=>{const g=Z(d,e);if(!g)return console.warn(`Paragraph ${e} not found for text replacement`),[];const u=ct(g);return u?(u.delete(n,o),lt(u,n,r,c),[{kind:"replace",paragraphId:e,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(u,n,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(u,n+r.length,0)),text:r,oldText:a}]):(console.warn(`No text content found in paragraph ${e}`),[])},{...l,id:t})}createPositionAwareInsertion(t,e,n,o,r={}){const i=this.generateId();return this.suggestionMeta.set(i,{id:i,authorId:r.authorId||"system",authorType:r.authorType||"ai",createdAt:Date.now(),status:"pending",insertionContext:{paragraphId:t,content:e,mustBeAfter:n,mustBeBefore:o},...r}),this.saveToLocalStorage(),this.notifyListeners(),n.length,o.length,i}materializeWithSuggestion(t){const e=this.proposals.get(t);if(!e)return null;const n=new I.Doc;return this.seedForkFromBase(n),I.applyUpdate(n,e),n}withMaterializedSuggestion(t,e){const n=this.materializeWithSuggestion(t);return n?e(n):null}expandPositionAwarePredecessors(t){const e=new Map;for(const r of this.suggestionMeta.values()){const i=r.insertionContext;i&&e.set(i.paragraphId,i)}const n=new Set,o=[...t.mustBeAfter];for(;o.length>0;){const r=o.pop();if(n.has(r))continue;n.add(r);const i=e.get(r);i&&o.push(...i.mustBeAfter)}return n}applyPositionAwareInsertionToDoc(t,e,n){const o=n.insertionContext;if(!o)return;const r=this.expandPositionAwarePredecessors(o),i=t.getXmlFragment("content");let a=0;for(let c=i.length-1;c>=0;c--){const d=i.get(c);if(!(d instanceof I.XmlElement))continue;const g=d.getAttribute("id");if(g&&r.has(g)){a=c+1;break}}const l=ka(o.content,o.paragraphId,e);i.insert(a,[l])}materializeWithSuggestions(t){const e=new I.Doc;this.seedForkFromBase(e);for(const n of t){const o=this.suggestionMeta.get(n);if(!(o&&o.status==="accepted"))if(o?.insertionContext)this.applyPositionAwareInsertionToDoc(e,n,o);else{const r=this.proposals.get(n);if(r){const i=I.encodeStateAsUpdate(e);mt(e),I.applyUpdate(e,r);const a=I.encodeStateAsUpdate(e);if(mt(e),!!Yg(i,a)&&o&&o.status==="pending")if(o.toolCallAction?.name==="remove_block"){const l=o.toolCallAction.arguments.id,c=ot(e,l);if(c){const{yParent:d,index:g}=c;d.delete(g,1)}}else o.anchors&&o.anchors.length>0?console.warn("[DetachedSuggestionStore] Anchor-based regeneration not yet implemented for:",n):console.warn("[DetachedSuggestionStore] Cannot regenerate proposal without sufficient metadata:",n)}}}return e}acceptProposal(t){const e=this.suggestionMeta.get(t);if(!e)return!1;if(e.insertionContext){const n=this.acceptPositionAwareInsertion(t,e);return n&&this.recordAction({type:"accept",suggestionId:t,timestamp:Date.now()}),this.notifyListeners(),n}else{const n=this.proposals.get(t);if(!n)return!1;const o=`proposal-${t}`;this.undoManager.trackedOrigins.add(o);const r=this.ydoc.getXmlFragment("content");this.ydoc.transact(()=>{I.applyUpdate(this.ydoc,n),this.ensureTrailingParagraphInTransaction(r)},o),this.undoManager.stopCapturing(),e.status="accepted",this.suggestionMeta.set(t,e),this.saveToLocalStorage();const i={type:"accept",suggestionId:t,timestamp:Date.now()};return i.suggestionId,this.undoStack.length,this.recordAction(i),this.notifyListeners(),!0}}acceptPositionAwareInsertion(t,e){const n=e.insertionContext,o=this.ydoc.getXmlFragment("content"),r=this.expandPositionAwarePredecessors(n);let i=0;const a=new Set;for(let c=0;c<o.length;c++){const d=o.get(c);if(d instanceof I.XmlElement){const g=d.getAttribute("id");g&&a.add(g)}}for(let c=o.length-1;c>=0;c--){const d=o.get(c);if(d instanceof I.XmlElement){const g=d.getAttribute("id");if(g&&r.has(g)){i=c+1;break}}}for(let c=0;c<o.length;c++){const d=o.get(c);if(d instanceof I.XmlElement){const g=d.getAttribute("id");if(g&&n.mustBeBefore.includes(g)){c<i&&(i=c);break}}}const l=`proposal-${t}`;return this.undoManager.trackedOrigins.add(l),this.ydoc.transact(()=>{const c=ka(n.content,n.paragraphId,t);o.insert(i,[c]),this.ensureTrailingParagraphInTransaction(o)},l),e.status="accepted",this.suggestionMeta.set(t,e),this.saveToLocalStorage(),this.notifyListeners(),!0}ensureTrailingParagraph(){const t=this.ydoc.getXmlFragment("content");this.ydoc.transact(()=>{this.ensureTrailingParagraphInTransaction(t)})}ensureTrailingParagraphInTransaction(t){if(t.length===0)return;const e=t.get(t.length-1);if(!(e instanceof I.XmlElement)||e.nodeName==="paragraph")return;const n=new I.XmlElement("paragraph");n.setAttribute("id",G());const o=new I.XmlText;n.insert(0,[o]),t.insert(t.length,[n])}acceptSuggestions(t){let e=!0;const n=[],o=()=>{if(n.length===0)return;const r=[...n];n.length=0;const i=this.ydoc.getXmlFragment("content");this.ydoc.transact(()=>{for(const a of r){const l=this.proposals.get(a);l?I.applyUpdate(this.ydoc,l):e=!1}this.ensureTrailingParagraphInTransaction(i)},"accept-proposals");for(const a of r){const l=this.suggestionMeta.get(a);l&&(l.status="accepted",this.suggestionMeta.set(a,l))}};for(const r of t)this.suggestionMeta.get(r)?.insertionContext?(o(),this.acceptProposal(r)||(e=!1)):n.push(r);return o(),this.saveToLocalStorage(),this.notifyListeners(),e}deleteSuggestion(t){this.proposals.delete(t),this.suggestionMeta.delete(t),this.removeProposalFromParagraphs(t),this.saveToLocalStorage()}rejectProposal(t){const e=this.suggestionMeta.get(t);return e?(e.status="rejected",this.suggestionMeta.set(t,e),this.saveToLocalStorage(),this.notifyListeners(),this.recordAction({type:"reject",suggestionId:t,timestamp:Date.now()}),!0):!1}unrejectProposal(t){const e=this.suggestionMeta.get(t);return!e||e.status!=="rejected"?!1:(e.status="pending",this.suggestionMeta.set(t,e),this.saveToLocalStorage(),this.recordAction({type:"unreject",suggestionId:t,timestamp:Date.now()}),this.notifyListeners(),!0)}rejectSuggestions(t){let e=!0;for(const n of t)this.suggestionMeta.has(n)?(this.proposals.delete(n),this.suggestionMeta.delete(n),this.removeProposalFromParagraphs(n)):e=!1;return this.saveToLocalStorage(),this.notifyListeners(),e}resolveAnchors(t){return this.resolveAnchorsAgainstDoc(t,this.ydoc)}resolveAnchorsAgainstDoc(t,e){const n=this.suggestionMeta.get(t);if(!n||!n.anchors)return[];const o=[];for(const r of n.anchors){const i=r.from?I.createAbsolutePositionFromRelativePosition(I.decodeRelativePosition(r.from),e):null,a=r.to?I.createAbsolutePositionFromRelativePosition(I.decodeRelativePosition(r.to),e):null;o.push({kind:r.kind,paragraphId:r.paragraphId,fromIndex:i?.index??null,toIndex:a?.index??null,text:r.text})}return o}checkConflicts(t){const e=this.suggestionMeta.get(t);if(!e)return"stale";if(e.anchors&&e.anchors.length>0){const n=this.resolveAnchors(t);for(let o=0;o<e.anchors.length;o++){const r=e.anchors[o],i=n[o];if(r.paragraphId&&i.fromIndex===null)return"conflicted"}}try{const n=this.materializeWithSuggestion(t);if(!n)return"stale";const o=wn(this.ydoc),r=wn(n),i=e.anchors?.filter(a=>a.kind==="insert"&&!a.paragraphId).length||0;return Math.abs(r-o)>i+1?"conflicted":"clean"}catch{return"conflicted"}}getAllSuggestions(){return new Map(this.suggestionMeta)}getSuggestion(t){return this.suggestionMeta.get(t)}getSuggestionCount(){return this.suggestionMeta.size}getPendingSuggestions(){const t=new Map;for(const[e,n]of this.suggestionMeta)n.status==="pending"&&t.set(e,n);return t}getParagraphIdsWithPendingProposals(){const t=new Set;for(const[n,o]of this.suggestionMeta)o.status==="pending"&&t.add(n);if(t.size===0)return[];const e=[];for(const[n,o]of this.paragraphSuggestions)!n||o.length===0||o.some(r=>t.has(r))&&e.push(n);return e}clearAllProposals(){this.proposals.clear(),this.suggestionMeta.clear(),this.paragraphSuggestions.clear(),this.disableLocalStorage||Ie("DetachedSuggestionStore")?.removeItem(this.storageKey),this.notifyListeners()}destroy(){this.destroyed||(this.destroyed=!0,this.ydoc.off("update",this.handleDocumentUpdate),this.undoManager.destroy(),this.listeners.clear(),this.onProposalsChanged=void 0,this.cachedBaseUpdate=null,this.cachedBaseUpdateV2=null,this.proposals.clear(),this.suggestionMeta.clear(),this.paragraphSuggestions.clear(),this.tableCellSuggestions.clear(),this.undoStack.length=0,this.redoStack.length=0,$r.get(this.documentId)===this&&$r.delete(this.documentId))}setSuggestionsForParagraph(t,e){this.paragraphSuggestions.set(t,e),this.saveToLocalStorage(),`${e.length}${t}`}getSuggestionsForParagraph(t){return this.paragraphSuggestions.get(t)||[]}setTableCellSuggestionMap(t,e){this.tableCellSuggestions.set(t,e),`${t}`,e.size}getProposalForTableCell(t,e){return this.tableCellSuggestions.get(t)?.get(e)}getTableCellSuggestionMap(t){return this.tableCellSuggestions.get(t)}async recomputeProposalsForParagraph(t){const e=this.getSuggestionsForParagraph(t).filter(d=>this.suggestionMeta.get(d)?.status==="pending");if(e.length===0)return;const{createGranularSuggestionsForParagraph:n}=await Promise.resolve().then(()=>fu),{findBlockById:o}=await import("./CanvasRenderer-C1Vegx9Y.js").then(d=>d.E),r=mt(this.ydoc),i=o(r,t);if(!i){console.warn(`[DetachedSuggestionStore] Paragraph ${t} not found in document`);return}if(i.type!=="paragraph")return;const a=new I.Doc;this.seedForkFromBase(a);for(const d of e){const g=this.proposals.get(d);g&&I.applyUpdate(a,g)}const l=mt(a),c=o(l,t);if(c&&c.type==="paragraph")for(const d of e)this.deleteSuggestion(d)}findParagraphForProposal(t){for(const[e,n]of this.paragraphSuggestions)if(n.includes(t))return e;return null}removeProposalFromParagraphs(t){for(const[e,n]of this.paragraphSuggestions){const o=n.filter(r=>r!==t);o.length!==n.length&&(o.length===0?this.paragraphSuggestions.delete(e):this.paragraphSuggestions.set(e,o))}}generateId(){return`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}async regenerateProposalFromDiff(t,e,n){const o=this.suggestionMeta.get(t);if(!o){console.warn("[DetachedSuggestionStore] Cannot regenerate - no metadata for proposal:",t);return}if(o.insertionContext)return;if(o.toolCallAction?.name==="remove_block"){const d=o.toolCallAction.arguments.id;Z(this.ydoc,d);const g=new I.Doc;this.seedForkFromBase(g);const u=I.encodeStateVector(g);wn(g),g.transact(()=>{if(Te(g)){const h=g.getArray("paragraphs");for(let p=0;p<h.length;p++)if(h.get(p).get("id")===d){h.delete(p,1);break}}else{const h=ot(g,d);if(h){const{yParent:p,index:m}=h;p.delete(m,1)}}}),wn(g);const f=I.encodeStateAsUpdate(g,u);this.proposals.set(t,f),f.length;return}const r=new I.Doc;I.applyUpdate(r,e);const i=new I.Doc;I.applyUpdate(i,n);const a=mt(r),l=mt(i);if(a.children.length===l.children.length)for(let d=0;d<a.children.length;d++){const g=a.children[d],u=l.children[d];if(g.type!=="paragraph"||u.type!=="paragraph")continue;const f=g,h=u,p=c(f),m=c(h);if(p!==m&&f.id===h.id){f.id;const y=new I.Doc;this.seedForkFromBase(y);const b=I.encodeStateVector(y),{analyzeParagraphDiff:k}=await import("./ParagraphDiffAnalysis-DrmStvmz.js").then(x=>x.P),S=k(p,m).diffs;y.transact(()=>{let x=null;if(Te(y)){const w=y.getArray("paragraphs");for(let A=0;A<w.length;A++){const P=w.get(A);if(P.get("id")===f.id){x=P.get("content");break}}}else{const w=Z(y,f.id);w&&(x=ct(w))}if(x){const w=[];for(const T of h.children)if(T.type==="text")for(let E=0;E<T.text.length;E++)w.push({node:T,indexInNode:E,marks:T.marks||{}});let A=0,P=0;for(const[T,E]of S)if(T===0)A+=E.length,P+=E.length;else if(T===-1)x.delete(A,E.length);else if(T===1){for(let B=0;B<E.length;B++){const N=w[P+B];if(N){const R={...N.marks,proposalId:t};lt(x,A+B,E[B],R)}}A+=E.length,P+=E.length}}});const v=I.encodeStateAsUpdate(y,b);this.proposals.set(t,v),this.saveToLocalStorage(),this.notifyListeners();return}}function c(d){return d.children.filter(g=>g.type==="text").map(g=>g.text).join("")}}recordAction(t){this.undoStack.push(t),t.type,t.suggestionId,this.undoStack.length,this.undoStack.map(e=>e.suggestionId),this.redoStack=[]}clearHistory(){this.undoStack=[],this.redoStack=[]}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}async undoLastAction(){if(this.undoStack.length===0)return!1;const t=this.undoStack.pop();switch(this.redoStack.push(t),t.type){case"accept":{if(this.undoManager.canUndo()){const e=this.getBaseUpdate();this.undoManager.undo();const n=this.getBaseUpdate();await this.regenerateProposalFromDiff(t.suggestionId,n,e);const o=this.suggestionMeta.get(t.suggestionId);return o&&(o.status="pending",this.suggestionMeta.set(t.suggestionId,o),this.saveToLocalStorage(),this.notifyListeners()),!0}return!1}case"reject":{const e=this.suggestionMeta.get(t.suggestionId);return e?(e.status="pending",this.suggestionMeta.set(t.suggestionId,e),this.saveToLocalStorage(),this.notifyListeners(),!0):!1}case"unreject":{const e=this.suggestionMeta.get(t.suggestionId);return e?(e.status="rejected",this.suggestionMeta.set(t.suggestionId,e),this.saveToLocalStorage(),this.notifyListeners(),!0):!1}}return!1}redoLastAction(){if(this.redoStack.length===0)return!1;const t=this.redoStack.pop();switch(this.undoStack.push(t),t.type){case"accept":{if(this.undoManager.canRedo()){this.undoManager.redo();const e=this.suggestionMeta.get(t.suggestionId);return e&&(e.status="accepted",this.suggestionMeta.set(t.suggestionId,e),this.saveToLocalStorage(),this.notifyListeners()),!0}return!1}case"reject":{const e=this.suggestionMeta.get(t.suggestionId);return e?(e.status="rejected",this.suggestionMeta.set(t.suggestionId,e),this.saveToLocalStorage(),this.notifyListeners(),!0):!1}case"unreject":{const e=this.suggestionMeta.get(t.suggestionId);return e?(e.status="pending",this.suggestionMeta.set(t.suggestionId,e),this.saveToLocalStorage(),this.notifyListeners(),!0):!1}}return!1}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}notifyListeners(){this.listeners.forEach(t=>t())}}function ka(s,t,e,n){if(s.type==="list"){const l=new I.XmlElement("list");return l.setAttribute("id",t),l.setAttribute("variant",s.variant??"unordered"),s.startNumber!==void 0&&l.setAttribute("startNumber",String(s.startNumber)),s.numberingChainId&&l.setAttribute("numberingChainId",s.numberingChainId),s.children.forEach(c=>{const d=new I.XmlElement("list-item");Ce(d,c),d.setAttribute("id",c.id||G()),c.checked!==void 0&&d.setAttribute("checked",String(c.checked)),typeof c.indentLevel=="number"&&c.indentLevel>0&&d.setAttribute("indentLevel",String(c.indentLevel)),c.direction!==void 0&&d.setAttribute("direction",c.direction);const g=new I.XmlText;let u=0;c.children.forEach(f=>{if(f.type==="text"){const h=f,p=Dr(h.marks,e);g.insert(u,h.text,p),u+=h.text.length}}),d.insert(0,[g]),l.push([d])}),l}if(s.type==="table"){const l=s,c=new I.XmlElement("table");c.setAttribute("id",t),l.columnWidths&&c.setAttribute("columnWidths",JSON.stringify(l.columnWidths)),l.hasHeader&&c.setAttribute("hasHeader","true"),l.tableWidth!==void 0&&c.setAttribute("tableWidth",String(l.tableWidth)),l.align&&c.setAttribute("align",l.align),l.borderColor&&c.setAttribute("borderColor",l.borderColor),l.borderWidth!==void 0&&c.setAttribute("borderWidth",String(l.borderWidth)),l.cellPadding!==void 0&&c.setAttribute("cellPadding",String(l.cellPadding));for(const d of l.children){const g=new I.XmlElement("table-row");g.setAttribute("id",d.id||G());for(const u of d.children){const f=new I.XmlElement("table-cell");f.setAttribute("id",u.id||G()),u.verticalAlign&&f.setAttribute("verticalAlign",u.verticalAlign),u.backgroundColor&&f.setAttribute("backgroundColor",u.backgroundColor);for(const h of u.children)if(h.type==="paragraph"){const p=h,m=new I.XmlElement("paragraph");m.setAttribute("id",p.id||G()),p.heading&&m.setAttribute("heading",String(p.heading)),p.align&&m.setAttribute("align",p.align);const y=new I.XmlText;let b=0;for(const k of p.children)if(k.type==="text"){const S=k,v=Dr(S.marks,e);lt(y,b,S.text,v),b+=S.text.length}m.insert(0,[y]),f.push([m])}g.push([f])}c.push([g])}return c}if(s.type==="code"){const l=s,c=new I.XmlElement("code");c.setAttribute("id",t),l.language&&c.setAttribute("language",l.language),l.renderDiagram!==void 0&&c.setAttribute("renderDiagram",String(l.renderDiagram)),l.showDiagramSource!==void 0&&c.setAttribute("showDiagramSource",String(l.showDiagramSource));const d=new I.XmlText;return c.insert(0,[d]),lt(d,0,l.content||""),c}if(s.type==="math"){const l=s,c=new I.XmlElement("math");c.setAttribute("id",t),l.displayMode&&c.setAttribute("displayMode",l.displayMode),l.align&&c.setAttribute("align",l.align);const d=new I.XmlText;return c.insert(0,[d]),lt(d,0,l.content||""),c}if(s.type==="image"){const l=s,c=new I.XmlElement("image");return c.setAttribute("id",t),c.setAttribute("src",l.src),l.sourceUrl&&c.setAttribute("sourceUrl",l.sourceUrl),c.setAttribute("width",String(l.width)),c.setAttribute("height",String(l.height)),l.alt&&c.setAttribute("alt",l.alt),l.align&&c.setAttribute("align",l.align),c}if(s.type==="page-break"){const l=new I.XmlElement("page-break");return l.setAttribute("id",t),l}if(s.type==="toc")return It({...s,id:t});if(s.type==="section-break"){const l=new I.XmlElement("section-break");return l.setAttribute("id",t),s.layout&&l.setAttribute("layout",JSON.stringify(s.layout)),s.breakType&&l.setAttribute("breakType",s.breakType),l}const o=new I.XmlElement("paragraph"),r=s;o.setAttribute("id",t),r.heading&&o.setAttribute("heading",String(r.heading)),r.align&&o.setAttribute("align",r.align);const i=new I.XmlText;let a=0;return r.children.forEach(l=>{if(l.type==="text"){const c=l,d=Dr(c.marks,e);lt(i,a,c.text,d),a+=c.text.length}}),o.insert(0,[i]),o}function Dr(s,t,e){return{...s||{},proposalId:t}}const $r=new Map;function Kg(s,t){$r.set(s,t)}const Vg=new Set(["Arial","Arial, sans-serif"]);function jr(s){if(typeof s!="string")return;const t=s.trim();if(!(!t||Vg.has(t)))return t}function fo(s){const t={};for(const e of xn)if(s[e]!==void 0)if(e==="fontFamily"){const n=jr(s[e]);n&&(t[e]=n)}else(e==="color"||e==="backgroundColor")&&typeof s[e]=="string"&&/^#[0-9a-fA-F]{6}$/.test(s[e])?t[e]=s[e].toLowerCase():t[e]=s[e];return t}const Sa=ps.filter(s=>!xn.includes(s));function je(s){const t=fo(s);for(const e of Sa)s[e]!==void 0&&(t[e]=s[e]);return t}function Gg(s){const t=Ia(s);for(const e of Sa)s[e]!==void 0&&(t[e]=s[e]);return t}function _r(s,t){return JSON.stringify(je(s||{}))===JSON.stringify(je(t||{}))}function Ia(s){const t=fo(s);t.docxRunPropertyResets=s.docxRunPropertyResets??null;for(const e of xn)e in t||(t[e]=null);return t}function Xr(s,t){const e=fo(s||{}),n=fo(t||{});return JSON.stringify(e)===JSON.stringify(n)}function va(s,t){for(const e of Tn){const n=s[e],o=t[e];if(e==="link"||e==="backgroundColor"||e==="color"){const r=l=>typeof l=="string"&&/^#[0-9a-fA-F]{6}$/.test(l),i=r(n)?n.toLowerCase():n,a=r(o)?o.toLowerCase():o;if(i!==a)return!1}else if(e==="fontFamily"){if(jr(n)!==jr(o))return!1}else if(e==="fontSize"){if((typeof n=="number"?n:void 0)!==(typeof o=="number"?o:void 0))return!1}else if(!!n!=!!o)return!1}return!0}class xa{constructor(){this.toolCalls=[]}addToolCalls(t,e){const n=Date.now();if(t.actions)for(const o of t.actions)this.toolCalls.push({toolCall:o,toolCallId:e,timestamp:n})}getAllToolCalls(){return this.toolCalls}clear(){this.toolCalls=[]}}function ae(s,t){return{...s,id:t}}function Qg(s,t,e){const n=new Set(s),o=r=>{if(r){if(r.block.type==="table"&&r.block.id){n.add(r.block.id);return}for(let i=r.containerPath.length-1;i>=0;i--){const a=r.containerPath[i];if((e.get(a)?.block??t.get(a)?.block)?.type==="table"){n.add(a);break}}}};for(const r of s)o(e.get(r)),o(t.get(r));return n}function wa(s){return JSON.stringify(s.children.map(t=>[t.id,t.children.map(e=>[e.id,e.rowSpan??1,e.colSpan??1])]))}function rn(s,t){return wa(s)!==wa(t)||He(s,t)}function Aa(s){return JSON.stringify({...s,children:s.children.map(t=>({...t,children:t.children.map(e=>({...e,children:[]}))}))})}function Zg(s,t){return{...t,children:t.children.map((e,n)=>({...e,children:e.children.map((o,r)=>({...o,children:s.children[n].children[r].children}))}))}}function Ur(s,t,e){const n=e?.affectedBlockIds?new Set(Array.from(e.affectedBlockIds).filter(M=>typeof M=="string"&&M.length>0)):null,o=t.getYDoc(),r=Array.from(t.getPendingSuggestions().keys()),i=r.length>0?t.materializeWithSuggestions(r):o,a=e?.precomputedLiveDocSchema??mt(o),l=e?.precomputedCurrentDocSchema??(i===o?a:mt(i)),c=e?.precomputedFinalDocSchema??mt(s),d=Ct(a),g=Ct(l),u=Ct(c),f=n?Qg(n,g,u):null,h=new Set;for(const M of new Set([...d.keys(),...u.keys()])){const O=d.get(M)?.block,$=u.get(M)?.block;O?.type!=="table"&&$?.type!=="table"||(O?.type!=="table"||$?.type!=="table"||rn(O,$))&&h.add(M)}if(f){const M=e?.precomputedVisibleBeforeDocSchema?Ct(e.precomputedVisibleBeforeDocSchema):null,O=D=>!Ut(M?.get(D)?.block??null,u.get(D)?.block??null),$=new Set,L=new Set;for(const D of f){const H=d.get(D)?.block,F=u.get(D)?.block;if(M&&H?.type==="table-cell"&&F?.type==="table-cell"){L.add(D);continue}H?.type!=="table"||F?.type!=="table"||h.has(D)||!M&&n?.has(D)?$.add(D):L.add(D)}for(const[D,H]of new Map([...d,...u]))(H.containerPath.some(F=>$.has(F))||M&&H.containerPath.some(F=>L.has(F))&&O(D))&&f.add(D)}const p=new Set(Array.from(e?.atomicReplaceBlockIds??[]).filter(M=>typeof M=="string"&&M.length>0)),m=new Map;for(const M of e?.replacementBlockMatches??[])typeof M?.currentBlockId!="string"||M.currentBlockId.length===0||typeof M?.finalBlockId!="string"||M.finalBlockId.length===0||m.set(M.finalBlockId,M.currentBlockId);const y=M=>{const O=m.get(M);return O&&d.has(O)?O:M},b=!!f&&f.size>0,k=t.getPendingSuggestions();if(b){const M=new Set;for(const O of f){const $=t.getSuggestionsForParagraph(O);for(const L of $)k.has(L)&&M.add(L)}for(const O of M)t.deleteSuggestion(O)}else for(const[M]of k)t.deleteSuggestion(M);const S=[],v=new Set,x=new Set,w=g;for(const[M,O]of d){const $=O.block;if($.type!=="list"||u.has(M)||$.children.length===0||b&&!f.has(M)||O.containerPath.some(U=>h.has(U)))continue;const L=w.get(M)?.block,D=(e?.listUnwrapMemberIds?.get(M)??(L?.type==="list"?L.children:$.children).map(U=>U.id)).map(U=>u.get(U)).filter(U=>!!U),H=D[0];if(!H||D.some((U,z)=>U.containerPath.join("/")!==O.containerPath.join("/")||z>0&&U.indexInParent<=D[z-1].indexInParent))continue;const F=H.containerPath.at(-1),X=F?u.get(F)?.block:null,C=(X&&"children"in X?X.children:c.children).slice(H.indexInParent,D.at(-1).indexInParent+1);if(C.some(U=>!U.id||d.has(U.id)))continue;const j=`prop_${G()}`;t.createSuggestion(j,U=>{const z=ot(U,M);return z?(z.yParent.delete(z.index,1),z.yParent.insert(z.index,C.map(tt=>It(tt))),[{kind:"replace",paragraphId:M,text:"Remove list markers"}]):[]},{authorType:"ai",blockSequencePreview:{blockId:M,blocks:C},description:"AI: remove list markers"}),S.push(j),v.add(M),t.setSuggestionsForParagraph(M,[j]);for(const U of C)x.add(U.id),t.setSuggestionsForParagraph(U.id,[j])}const A=[],P=b?Array.from(f).filter(M=>u.has(M)):Array.from(u.keys());for(const M of P){const O=u.get(M);if(!O||x.has(M)||O.containerPath.some(F=>x.has(F)))continue;const $=O.block,L=m.get(M);if($.type==="container"||$.type==="table-cell"||O.containerPath.some(F=>h.has(F)))continue;const D=L?d.get(L)??d.get(M):d.get(M),H=L&&D?.block.id===L&&L!==M?L:null;if(D?.block.id&&v.add(D.block.id),$.type==="paragraph"){const F=H!==null?ae($,H):$;if(!D)A.push({location:O});else if(D.block.type==="paragraph"){const X=D.block,C=Hr(X),j=Hr(F);if(C!==j||hu(X,F)){if(p.has(M)){const z=zr(t,F);z&&(S.push(z),F.id&&t.setSuggestionsForParagraph(F.id,[z]));continue}const U=Ta(t,X,F);S.push(...U)}}else{const X=zr(t,F);X&&(S.push(X),F.id&&t.setSuggestionsForParagraph(F.id,[X]))}}else if($.type==="list"){const F=H!==null?ae($,H):$;if(!D)A.push({location:O});else if(D.block.type==="list"){const X=D.block;if(Bo(X,F)){if(!au(X,F)){const C=tu(t,X,F);C.length>0&&X.id&&(S.push(...C),t.setSuggestionsForParagraph(X.id,C))}}else{const C=Jr(t,F);C&&X.id&&(S.push(C),t.setSuggestionsForParagraph(X.id,[C]))}}else{const X=Jr(t,F);X&&F.id&&(S.push(X),t.setSuggestionsForParagraph(F.id,[X]))}}else if($.type==="table"){const F=H!==null?ae($,H):$;if(!D)A.push({location:O});else if(D.block.type==="table"){const X=D.block,C=h.has(F.id);if(C||Aa(X)!==Aa(F)){const j=Ca(t,C?F:Zg(X,F));j&&(S.push(j),t.setSuggestionsForParagraph(F.id,[j]))}}else{const X=Ca(t,F);X&&F.id&&(S.push(X),t.setSuggestionsForParagraph(F.id,[X]))}}else if($.type==="code"){const F=H!==null?ae($,H):$;if(!D)A.push({location:O});else if(D.block.type==="code"){const X=D.block;if(X.content!==F.content||X.language!==F.language){const C=Pa(t,F);C&&F.id&&(S.push(C),t.setSuggestionsForParagraph(F.id,[C]))}}else{const X=Pa(t,F);X&&F.id&&(S.push(X),t.setSuggestionsForParagraph(F.id,[X]))}}else if($.type==="math"){const F=H!==null?ae($,H):$;if(!D)A.push({location:O});else if(D.block.type==="math"){const X=D.block;if(X.content!==F.content||X.displayMode!==F.displayMode||X.align!==F.align){const C=Ma(t,F);C&&F.id&&(S.push(C),t.setSuggestionsForParagraph(F.id,[C]))}}else{const X=Ma(t,F);X&&F.id&&(S.push(X),t.setSuggestionsForParagraph(F.id,[X]))}}else if($.type==="image"){const F=H!==null?ae($,H):$;if(!D)A.push({location:O});else if(D.block.type==="image"){const X=D.block;if(X.src!==F.src||X.width!==F.width||X.height!==F.height||X.alt!==F.alt||X.align!==F.align){const C=Ba(t,F);C&&F.id&&(S.push(C),t.setSuggestionsForParagraph(F.id,[C]))}}else{const X=Ba(t,F);X&&F.id&&(S.push(X),t.setSuggestionsForParagraph(F.id,[X]))}}else if($.type==="page-break"){const F=H!==null?ae($,H):$;if(!D)A.push({location:O});else if(D.block.type!=="page-break"){const X=su(t,F);X&&F.id&&(S.push(X),t.setSuggestionsForParagraph(F.id,[X]))}}else if($.type==="toc"){const F=H!==null?ae($,H):$;if(!D)A.push({location:O});else if(D.block.type!=="toc"||D.block.levels!==F.levels||D.block.instr!==F.instr||D.block.fontFamily!==F.fontFamily||D.block.fontSize!==F.fontSize||D.block.color!==F.color||D.block.direction!==F.direction||D.block.align!==F.align){const X=iu(t,F);X&&F.id&&(S.push(X),t.setSuggestionsForParagraph(F.id,[X]))}}}A.sort((M,O)=>{const $=M.location.containerPath,L=O.location.containerPath,D=Math.min($.length,L.length);for(let H=0;H<D;H++)if($[H]!==L[H])return $[H].localeCompare(L[H]);return $.length!==L.length?$.length-L.length:M.location.indexInParent-O.location.indexInParent});const T=M=>{const O=M.containerPath.at(-1),$=O?u.get(O)?.block:null;return $&&"children"in $?$.children:c.children},E=M=>{const O=T(M);for(let $=M.indexInParent-1;$>=0;$--){const L=O[$];if(L.id)return y(L.id)}return null},B=M=>{const O=T(M),$=(()=>{for(let D=M.indexInParent-1;D>=0;D--)if(O[D]?.id)return y(O[D].id);return null})(),L=(()=>{for(let D=M.indexInParent-1;D>=0;D--){const H=O[D]?.id;if(!H)continue;const F=y(H);if(d.has(F))return F}return null})();return Array.from(new Set([L,$].filter(D=>typeof D=="string"&&D.length>0)))},N=[];for(const M of A){const O=M.location,$=E(O),L=N[N.length-1];if(L&&L.afterId===$&&L.containerPath.join("/")===O.containerPath.join("/")&&L.blocks[L.blocks.length-1].location.indexInParent===O.indexInParent-1){L.blocks.push(M);continue}N.push({afterId:$,containerPath:O.containerPath,blocks:[M]})}for(const M of N){const O=M.afterId&&d.has(M.afterId);if(M.blocks.length===1&&O){const{location:$}=M.blocks[0],L=$.block,D=du(t,L,M.afterId,a);D&&(S.push(D),L.id&&t.setSuggestionsForParagraph(L.id,[D]))}else for(let $=0;$<M.blocks.length;$++){const{location:L}=M.blocks[$],D=L.block;if(D.type!=="paragraph"&&D.type!=="list"&&D.type!=="table"&&D.type!=="code"&&D.type!=="math"&&D.type!=="image"&&D.type!=="page-break"&&D.type!=="toc"){console.warn("[SuggestionPlanner] Skipping unsupported block type for position-aware insertion:",D.type);continue}const H=B(L),F=t.createPositionAwareInsertion(D.id,D,H,T(L).slice(L.indexInParent+1).map(X=>X.id).filter(X=>!!X&&d.has(X)).slice(0,1),{authorType:"ai",description:`AI: insert_${D.type} (position-aware)`});F&&(S.push(F),t.setSuggestionsForParagraph(D.id,[F]))}}const R=b?Array.from(f).filter(M=>d.has(M)):Array.from(d.keys());for(const M of R){const O=d.get(M);if(!O||v.has(M))continue;const $=O.block,L=$.type==="container"&&b&&!!f?.has(M);if(!($.type==="container"&&!L)&&$.type!=="table-cell"&&!O.containerPath.some(D=>h.has(D))&&($.type==="paragraph"||$.type==="list"||$.type==="table"||$.type==="code"||$.type==="math"||$.type==="image"||$.type==="docx-raw"||$.type==="page-break"||$.type==="section-break"||$.type==="toc"||L)){const D=cu(t,$);D&&(S.push(D),t.setSuggestionsForParagraph(M,[D]))}}return S}function Ta(s,t,e){const n=[];if(!Je(t,e)){const u=zr(s,e);if(u)return s.setSuggestionsForParagraph(e.id,[u]),[u]}const o=u=>{const f=[];return u.children.forEach((h,p)=>{if(h.type==="text"){const m=h;for(let y=0;y<m.text.length;y++)f.push({char:m.text[y],marks:m.marks||{},nodeIndex:p,charIndexInNode:y})}}),f},r=o(t),i=o(e),a=r.map(u=>u.char).join(""),l=i.map(u=>u.char).join(""),c=En(a,l).diffs;let d=0,g=0;for(let u=0;u<c.length;u++){const[f,h]=c[u];if(f===0){const p=h.length;for(let m=0;m<p;m++){const y=r[d+m],b=i[g+m],k=y?.marks||{},S=b?.marks||{};if(!va(k,S)){const v=m;let x=m+1;for(;x<p;){const E=r[d+x]?.marks||{},B=i[g+x]?.marks||{};if(va(E,B)||!_r(B,S))break;x++}const w=h.substring(v,x),A=`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,P=Gg(S),T=s.createTextReplacement(A,e.id,d+v,x-v,w,P,w,{authorType:"ai",description:"AI: apply formatting"});T&&n.push(T),m=x-1}}d+=h.length,g+=h.length}else if(f===-1){const p=h.length,m=u+1<c.length?c[u+1]:null;if(m&&m[0]===1){const y=m[1];let b=!0;if(y.length>1){const k=g<i.length?i[g].marks:{};for(let S=1;S<y.length;S++){const v=g+S<i.length?i[g+S].marks:{};if(!Xr(k,v)){b=!1;break}}}if(b){const k=g<i.length?i[g].marks:{},{...S}=k,v=`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,x=s.createTextReplacement(v,e.id,d,p,y,S,h,{authorType:"ai",description:"AI: replace text"});x&&n.push(x)}else{const k=`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,S=s.createSuggestion(k,v=>{const x=Z(v,e.id);let w=null;if(x)for(let T=0;T<x.length;T++){const E=x.get(T);if(E instanceof I.XmlText){w=E;break}}if(!w)return console.warn(`Paragraph ${e.id} not found for mixed formatting replacement`),[];w.delete(d,p);let A=d,P=0;for(;P<y.length;){const T=P,E=g+P,B=E<i.length?je(i[E].marks):{};let N=P+1;for(;N<y.length;){const M=g+N,O=M<i.length?je(i[M].marks):{};if(!_r(B,O))break;N++}const R=y.substring(T,N);lt(w,A,R,{...B,suggestionId:k}),A+=R.length,P=N}return[{kind:"replace",paragraphId:e.id,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(w,d,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(w,d+y.length,0)),text:y,oldText:h}]},{authorType:"ai",description:"AI: replace text"});S&&n.push(S)}u++,d+=p,g+=y.length}else{const y=`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,b=s.createTextDeletion(y,e.id,d,p,h,{authorType:"ai",description:"AI: delete text"});b&&n.push(b),d+=p}}else if(f===1){const p=h,m=u>0?c[u-1]:null;if(m&&m[0]===-1)continue;const y=[];let b=0;for(;b<p.length;){const k=b,S=g+b,v=S<i.length?i[S].marks:{},x=je(v);let w=b+1;for(;w<p.length;){const P=g+w,T=P<i.length?i[P].marks:{};if(!_r(x,T))break;w++}const A=p.substring(k,w);y.push({text:A,marks:x}),b=w}if(y.length===1&&Object.keys(y[0].marks).length===0){const k=`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,S=s.createTextInsertion(k,e.id,d,p,{},{authorType:"ai",description:"AI: insert text"});S&&n.push(S)}else{const k=`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,S=s.createSuggestion(k,v=>{const x=Z(v,e.id);let w=null;if(x)for(let P=0;P<x.length;P++){const T=x.get(P);if(T instanceof I.XmlText){w=T;break}}if(!w)return console.warn(`Paragraph ${e.id} not found for mixed formatting insertion`),[];let A=d;for(const P of y){const T={...P.marks,suggestionId:k};lt(w,A,P.text,T),A+=P.text.length}return[{kind:"insert",paragraphId:e.id,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(w,d,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(w,d+p.length,0)),text:p}]},{authorType:"ai",description:"AI: insert text"});S&&n.push(S)}g+=p.length}}return e.id&&n.length>0&&s.setSuggestionsForParagraph(e.id,n),n}function zr(s,t){const e={name:"replace_block",arguments:{id:t.id,content:it.toAgentHtml({type:"doc",children:[t]})}};if(s.createBlockReplacementSuggestion){const n=s.createBlockReplacementSuggestion(t,e);if(n)return n}return s.createSuggestionFromToolCall(e,(n,o)=>{const r=ot(n,t.id);if(!r||r.yBlock.nodeName!=="paragraph")return Wt(n,o);const i=ct(r.yBlock)?.toDelta().map(c=>typeof c.insert=="string"?c.insert:"").join("")??"";r.yParent.delete(r.index,1);const a=It(t);r.yParent.insert(r.index,[a]);const l=ct(a);return[{kind:"replace",paragraphId:t.id,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(l,0,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(l,l.length,0)),text:Hr(t),oldText:i}]})}function tu(s,t,e){const n=[],o=t.children.map(b=>({item:b,text:ve(b),signature:Wr(b)})),r=e.children.map(b=>({item:b,text:ve(b),signature:Wr(b)})),{beforeKeys:i,afterKeys:a}=ma(t.children,e.children,Wr),l=Fr(i,a),c=[],d=(b,k,S)=>{const v=Math.min(b.length,k.length);for(let x=0;x<v;x++)c.push({kind:"replace",index:S+x,currentItem:b[x],finalItem:k[x]});for(let x=v;x<b.length;x++)c.push({kind:"delete",index:S+x,currentItem:b[x]});for(let x=k.length-1;x>=v;x--)c.push({kind:"insert",index:S+v,finalItem:k[x]})};let g=0,u=0;for(const b of l){let k=g;for(;k<o.length&&i[k]!==b;)k+=1;let S=u;for(;S<r.length&&a[S]!==b;)S+=1;d(o.slice(g,k),r.slice(u,S),g),g=k+1,u=S+1;const v=o[k],x=r[S];v&&x&&(v.signature!==x.signature||!Ea(v.item,x.item))&&c.push({kind:"replace",index:k,currentItem:v,finalItem:x})}d(o.slice(g),r.slice(u),g);const f=c.some(b=>b.kind!=="replace"?!0:b.currentItem.signature!==b.finalItem.signature||b.currentItem.text!==b.finalItem.text);if(c.length>0&&!f){const b=eu(s,e);return b?[b]:[]}for(const b of c){if(b.kind==="insert"){const S=nu(s,t.id,b.finalItem.item,b.index,t.variant);S&&n.push(S);continue}if(b.kind==="delete"){const S=ou(s,t.id,b.index,b.currentItem.text);S&&n.push(S);continue}const k=ru(s,t.id,b.index,b.currentItem.item,b.finalItem.item,t.variant);k&&n.push(k)}const h=c.filter(b=>b.kind==="replace").length,p=c.some(b=>b.kind!=="replace"?b.kind==="insert"||b.kind==="delete":b.currentItem.signature!==b.finalItem.signature||b.currentItem.text!==b.finalItem.text),m=Math.max(o.length,r.length),y=m>0?n.length/m:0;if(h>0&&y>.7&&p){const b=Jr(s,e);return b?[b]:[]}return n}function eu(s,t){if(!t.id)return null;const e=`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return s.createSuggestion(e,n=>{const o=Z(n,t.id);if(!o||o.nodeName!=="list")return[];for(let r=0;r<t.children.length;r++){const i=o.get(r),a=t.children[r];if(!(i instanceof I.XmlElement)||!a)continue;const l=ct(i);if(!l)continue;let c=0;for(const d of a.children)d.type!=="text"||d.text.length===0||(at(l,c,d.text.length,Ia(d.marks||{})),c+=d.text.length)}return[{kind:"replace",paragraphId:t.id,text:t.children.map(ve).join(`
|
|
6
|
+
`),oldText:t.children.map(ve).join(`
|
|
7
|
+
`)}]},{authorType:"ai",description:"AI: apply list formatting"})}function nu(s,t,e,n,o){const r=`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return s.createSuggestion(r,i=>{const a=Z(i,t);if(!a||a.nodeName!=="list")return console.warn(`List ${t} not found for item insertion`),[];const l=new I.XmlElement("list-item");Ce(l,e),l.setAttribute("id",e.id||G()),e.checked!==void 0&&l.setAttribute("checked",String(e.checked)),e.indentLevel&&l.setAttribute("indentLevel",String(e.indentLevel)),e.direction!==void 0&&l.setAttribute("direction",e.direction);const c=new I.XmlText;let d=0;e.children.forEach(u=>{if(u.type==="text"){const f=u,h={...f.marks||{},suggestionId:r,toolType:"list_item_insert"};c.insert(d,f.text,h),d+=f.text.length}}),l.insert(0,[c]);const g=Math.min(n,a.length);return a.insert(g,[l]),[{kind:"insert",paragraphId:t,text:ve(e)}]},{authorType:"ai",description:"AI: insert list item"})}function ou(s,t,e,n){const o=`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return s.createSuggestion(o,r=>{const i=Z(r,t);return!i||i.nodeName!=="list"?(console.warn(`List ${t} not found for item deletion`),[]):e>=i.length?(console.warn(`Item index ${e} out of bounds for list ${t}`),[]):(i.delete(e,1),[{kind:"delete",paragraphId:t,text:n}])},{authorType:"ai",description:"AI: delete list item"})}function ru(s,t,e,n,o,r){const i=`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return s.createSuggestion(i,a=>{const l=Z(a,t);if(!l||l.nodeName!=="list")return console.warn(`List ${t} not found for item replacement`),[];if(e>=l.length)return console.warn(`Item index ${e} out of bounds for list ${t}`),[];const c=l.get(e);if(!(c instanceof I.XmlElement))return console.warn(`Item at index ${e} is not an XmlElement`),[];Ce(c,o),o.direction!==n.direction&&(o.direction!==void 0?c.setAttribute("direction",o.direction):c.removeAttribute("direction")),o.checked!==n.checked&&(o.checked!==void 0?c.setAttribute("checked",String(o.checked)):c.removeAttribute("checked")),o.indentLevel!==n.indentLevel&&(o.indentLevel?c.setAttribute("indentLevel",String(o.indentLevel)):c.removeAttribute("indentLevel"));let d=null;for(let f=0;f<c.length;f++){const h=c.get(f);if(h instanceof I.XmlText){d=h;break}}if(!d)return console.warn(`No content found in list item at index ${e}`),[];const g=d.length;g>0&&d.delete(0,g);let u=0;return o.children.forEach(f=>{if(f.type==="text"){const h=f,p={...je(h.marks||{}),suggestionId:i,toolType:"list_item_replace"};d.insert(u,h.text,p),u+=h.text.length}}),[{kind:"replace",paragraphId:t,text:ve(o),oldText:ve(n)}]},{authorType:"ai",description:"AI: replace list item"})}function ve(s){return s.children.filter(t=>t.type==="text").map(t=>t.text).join("")}function Wr(s){return JSON.stringify({...Object.fromEntries(An.map(t=>[t,s[t]])),direction:s.direction,checked:s.checked??!1,indentLevel:s.indentLevel??0,children:s.children.map(t=>t.type==="text"?{type:"text",text:t.text}:{type:t.type})})}function Jr(s,t){const e={name:"replace_block",arguments:{id:t.id,content:lu(t)}};return s.createSuggestionFromToolCall(e,n=>{const o=ot(n,t.id);return o?(o.yParent.delete(o.index,1),o.yParent.insert(o.index,[It(t)]),[{kind:"replace",paragraphId:t.id,text:"List replaced",oldText:o.yBlock.nodeName==="list"?"List":"Paragraph"}]):[]})}function Ca(s,t){const e={name:"replace_block",arguments:{id:t.id,content:it.toInternalHtml({type:"doc",children:[t]})}};return s.createSuggestionFromToolCall(e,(n,o)=>Wt(n,o))}function Pa(s,t){const e={name:"replace_block",arguments:{id:t.id,content:it.toAgentHtml({type:"doc",children:[t]})}};return s.createSuggestionFromToolCall(e,(n,o)=>Wt(n,o))}function Ma(s,t){const e={name:"replace_block",arguments:{id:t.id,content:it.toAgentHtml({type:"doc",children:[t]})}};return s.createSuggestionFromToolCall(e,(n,o)=>Wt(n,o))}function Ba(s,t){const e={name:"replace_block",arguments:{id:t.id,content:it.toInternalImageHtml(t)}};return s.createSuggestionFromToolCall(e,(n,o)=>Wt(n,o))}function su(s,t){const e={name:"replace_block",arguments:{id:t.id,content:it.toAgentHtml({type:"doc",children:[t]})}};return s.createSuggestionFromToolCall(e,(n,o)=>Wt(n,o))}function iu(s,t){const e={name:"replace_block",arguments:{id:t.id,content:it.toAgentHtml({type:"doc",children:[t]})}};return s.createSuggestionFromToolCall(e,(n,o)=>Wt(n,o))}function au(s,t){if(s.children.length!==t.children.length)return!1;for(let e=0;e<s.children.length;e++){const n=s.children[e],o=t.children[e];if(An.some(a=>n[a]!==o[a])||n.direction!==o.direction||n.checked!==o.checked||n.indentLevel!==o.indentLevel)return!1;const r=n.children.filter(a=>a.type==="text").map(a=>a.text).join(""),i=o.children.filter(a=>a.type==="text").map(a=>a.text).join("");if(r!==i||!Ea(n,o))return!1}return!0}function Ea(s,t){if(s.children.length!==t.children.length)return!1;for(let e=0;e<s.children.length;e++){const n=s.children[e],o=t.children[e];if(n.type!==o.type||n.type==="text"&&o.type==="text"&&(n.text!==o.text||!Xr(n.marks||{},o.marks||{})))return!1}return!0}function lu(s){return it.toInternalHtml({type:"doc",children:[s]})}function cu(s,t){if(!t.id)return console.warn("[SuggestionPlanner] Cannot create remove_block proposal for block without id:",t.type),null;const e=t.id,n={name:"remove_block",arguments:{id:e,count:1}},o=`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return s.createSuggestion(o,r=>{const i=ot(r,e);if(!i)return console.warn(`[SuggestionPlanner] Block ${e} not found for removal`),[];const{yBlock:a,yParent:l,index:c}=i,d=a.nodeName;let g;if(d==="list")g={kind:"delete",paragraphId:e,text:"List removed"};else{let u="";for(let f=0;f<a.length;f++){const h=a.get(f);if(h instanceof I.XmlText){const p=st(h);for(const m of p)m.insert&&typeof m.insert=="string"&&(u+=m.insert)}}g={kind:"delete",paragraphId:e,text:u||"Block removed"}}return l.delete(c,1),[g]},{authorType:"ai",toolCallAction:n,description:"AI: remove_block"})}function du(s,t,e,n){let o,r;e===null?n.children.length>0?(o=n.children[0].id,r="before"):(o=Ve,r="after"):(o=e,r="after");const i={name:"insert_block",arguments:{referenceId:o,position:r,content:[gu(t)]}};return wt(i,{stableId:t.id||G()}),s.createSuggestionFromToolCall(i,(a,l)=>Wt(a,l))}function gu(s){return s.type==="paragraph"?uu(s):s.type==="image"?it.toInternalImageHtml(s):s.type==="list"||s.type==="table"||s.type==="code"||s.type==="math"||s.type==="page-break"||s.type==="toc"?it.toInternalHtml({type:"doc",children:[s]}):""}function Dt(s){return s.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'")}function uu(s,t){const e=s.heading?`h${s.heading}`:"p",n=[];s.align&&n.push(`text-align: ${s.align}`);const o=n.length>0?` style="${n.join("; ")}"`:"";let r=`<${e}${o}>`;for(const i of s.children)if(i.type==="text"){let a=i.text.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'");if(i.marks?.bold&&(a=`<b>${a}</b>`),i.marks?.italic&&(a=`<i>${a}</i>`),i.marks?.underline&&(a=`<u>${a}</u>`),i.marks?.strikethrough&&(a=`<s>${a}</s>`),i.marks?.code&&(a=`<code>${a}</code>`),i.marks?.latex&&(a=`<latex-inline>${a}</latex-inline>`),i.marks?.superscript||i.marks?.footnoteRef){const g=i.marks?.footnotePendingBody!==void 0?` data-footnote="${Dt(i.marks.footnotePendingBody)}"${i.marks?.footnotePendingKind==="endnote"?' data-note-kind="endnote"':""}`:"";a=i.marks?.footnoteRef?`<sup data-footnote-ref="${Dt(i.marks.footnoteRef)}"${g}>${a}</sup>`:`<sup>${a}</sup>`}else i.marks?.subscript&&(a=`<sub>${a}</sub>`);const l=i.marks?.fontFamily,c=i.marks?.fontSize;if(l||c||i.marks?.color||i.marks?.doubleStrikethrough||i.marks?.smallCaps||i.marks?.allCaps||i.marks?.letterSpacing){const g=[];l&&g.push(`font-family: ${Dt(l)}`),c&&g.push(`font-size: ${c}px`),i.marks?.color&&g.push(`color: ${Dt(i.marks.color)}`),i.marks?.doubleStrikethrough&&g.push("text-decoration: line-through double"),i.marks?.smallCaps&&g.push("font-variant: small-caps"),i.marks?.allCaps&&g.push("text-transform: uppercase"),typeof i.marks?.letterSpacing=="number"&&Number.isFinite(i.marks.letterSpacing)&&i.marks.letterSpacing!==0&&g.push(`letter-spacing: ${i.marks.letterSpacing}px`),a=`<span style="${g.join("; ")}">${a}</span>`}i.marks?.hidden&&(a=`<span data-word-hidden="true">${a}</span>`),i.marks?.lang&&(a=`<span data-word-lang="${Dt(i.marks.lang)}">${a}</span>`),i.marks?.bookmark&&(a=`<span data-bookmark="${Dt(i.marks.bookmark)}">${a}</span>`),i.marks?.fieldInstr&&(a=`<span data-field-instr="${Dt(i.marks.fieldInstr)}">${a}</span>`),i.marks?.field&&(a=`<span data-dynamic-field="${Dt(i.marks.field)}">${a}</span>`),i.marks?.sdtInline&&(a=`<span data-sdt-inline="${Dt(i.marks.sdtInline)}">${a}</span>`),i.marks?.aiGenerated&&(a=`<span data-ai-generated="true">${a}</span>`),i.marks?.__htmlClassName&&(a=`<span data-html-class="${Dt(i.marks.__htmlClassName)}">${a}</span>`);const d=Ke(i.marks?.backgroundColor);if(d&&(a=`<mark color="${Dt(d)}">${a}</mark>`),i.marks?.link&&(a=`<a href="${Dt(i.marks.link)}">${a}</a>`),i.marks?.comment)for(const g of i.marks.comment.split(",").map(u=>u.trim()).filter(Boolean).reverse())a=`<comment-thread id="${Dt(g)}">${a}</comment-thread>`;r+=a}return r+=`</${e}>`,r}function Hr(s){return s.children.filter(t=>t.type==="text").map(t=>t.type==="text"?t.text:"").join("")}function hu(s,t){if(!Je(s,t)||s.children.length!==t.children.length)return!0;for(let e=0;e<s.children.length;e++){const n=s.children[e],o=t.children[e];if(n.type!==o.type||n.type==="text"&&o.type==="text"&&(n.text!==o.text||!Xr(n.marks||{},o.marks||{})))return!0}return!1}const fu=Object.freeze(Object.defineProperty({__proto__:null,ToolCallHistory:xa,createFlattenedSuggestions:Ur,createGranularSuggestionsForParagraph:Ta,isStructuralTableChange:rn},Symbol.toStringTag,{value:"Module"}));class qr{constructor(t,e=!1){this.allowDirectBlockReplacementPreviews=e,this.proposals=new Map,this.suggestionMeta=new Map,this.paragraphSuggestions=new Map,this.tableCellSuggestions=new Map,this.cachedBaseUpdate=null,this.invalidateBaseUpdate=()=>{this.cachedBaseUpdate=null,this.ydoc.off("update",this.invalidateBaseUpdate)},this.ydoc=t}getBaseUpdate(){return this.cachedBaseUpdate||(this.cachedBaseUpdate=I.encodeStateAsUpdateV2(this.ydoc),this.ydoc.on("update",this.invalidateBaseUpdate)),this.cachedBaseUpdate}seedFork(){const t=new I.Doc;return I.applyUpdateV2(t,this.getBaseUpdate()),t}createForklessTextSuggestion(t){const e=Z(this.ydoc,t.paragraphId),n=e?ct(e):null;if(!n||t.startOffset+t.deleteLength>n.length)return null;const o=t.kind==="delete"?t.startOffset+t.deleteLength:t.startOffset,r=I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(n,o,0)),i=I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(n,t.kind==="delete"?o:t.startOffset+t.deleteLength,0));return this.proposals.set(t.id,new Uint8Array(0)),this.suggestionMeta.set(t.id,{id:t.id,authorId:t.metadata.authorId||"system",authorType:t.metadata.authorType||"ai",createdAt:Date.now(),status:"pending",anchors:[{kind:t.kind,paragraphId:t.paragraphId,from:r,to:i,text:t.anchorText,...t.oldText!==void 0?{oldText:t.oldText}:{}}],...t.metadata,inlinePreview:{startOffset:t.startOffset,newText:t.newText,marks:t.marks}}),t.id}getYDoc(){return this.ydoc}createSuggestion(t,e,n={}){const o=this.seedFork(),r=I.encodeStateVector(o);let i=[];o.transact(()=>{i=e(o)},"proposal-edit");const a=I.encodeStateAsUpdate(o,r);return this.proposals.set(t,a),this.suggestionMeta.set(t,{id:t,authorId:n.authorId||"system",authorType:n.authorType||"ai",createdAt:Date.now(),status:"pending",anchors:i,...n}),t}createSuggestionFromToolCall(t,e){return this.createSuggestion(this.generateId(),n=>e(n,t),{authorType:"ai",toolCallAction:t,description:`AI: ${t.name}`})}createBlockReplacementSuggestion(t,e){if(!this.allowDirectBlockReplacementPreviews)return null;const n=t.id?Z(this.ydoc,t.id):null;if(!n||n.nodeName!=="paragraph")return null;const o=this.generateId();return this.suggestionMeta.set(o,{id:o,authorId:"system",authorType:"ai",createdAt:Date.now(),status:"pending",anchors:[{kind:"replace",paragraphId:t.id}],toolCallAction:e,description:`AI: ${e.name}`,blockPreview:t}),o}createTextDeletion(t,e,n,o,r,i={}){return this.createForklessTextSuggestion({id:t,kind:"delete",paragraphId:e,startOffset:n,deleteLength:o,newText:"",marks:{},anchorText:r,metadata:{...i,id:t}})||this.createSuggestion(t,l=>{const c=Z(l,e);if(!c)return[];const d=ct(c);return d?(d.delete(n,o),[{kind:"delete",paragraphId:e,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(d,n,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(d,n+o,0)),text:r}]):[]},{...i,id:t,inlinePreview:{startOffset:n,newText:"",marks:{}}})}createTextInsertion(t,e,n,o,r={},i={}){const a={...r,suggestionId:t};return this.createSuggestion(t,l=>{const c=Z(l,e);if(!c)return[];const d=ct(c);return d?(lt(d,n,o,a),[{kind:"insert",paragraphId:e,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(d,n,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(d,n+o.length,0)),text:o}]):[]},{...i,id:t})}createTextReplacement(t,e,n,o,r,i={},a,l={}){const c={...i,suggestionId:t};return this.createForklessTextSuggestion({id:t,kind:"replace",paragraphId:e,startOffset:n,deleteLength:o,newText:r,marks:c,anchorText:r,oldText:a,metadata:{...l,id:t}})||this.createSuggestion(t,g=>{const u=Z(g,e);if(!u)return[];const f=ct(u);return f?(f.delete(n,o),lt(f,n,r,c),[{kind:"replace",paragraphId:e,from:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(f,n,0)),to:I.encodeRelativePosition(I.createRelativePositionFromTypeIndex(f,n+r.length,0)),text:r,oldText:a}]):[]},{...l,id:t,inlinePreview:{startOffset:n,newText:r,marks:c}})}createPositionAwareInsertion(t,e,n,o,r={}){const i=this.generateId();return this.suggestionMeta.set(i,{id:i,authorId:r.authorId||"system",authorType:r.authorType||"ai",createdAt:Date.now(),status:"pending",insertionContext:{paragraphId:t,content:e,mustBeAfter:n,mustBeBefore:o},...r}),i}materializeWithSuggestion(t){const e=this.suggestionMeta.get(t);if(!e||e.status==="accepted")return null;const n=this.seedFork();if(e.blockPreview?.id){const r=ot(n,e.blockPreview.id);return r?(r.yParent.delete(r.index,1),r.yParent.insert(r.index,[It(e.blockPreview)]),n):null}if(e.insertionContext)return this.applyPositionAwareInsertion(n,t,e),n;const o=this.proposals.get(t);return o?(I.applyUpdate(n,o),n):null}withMaterializedSuggestion(t,e){const n=this.materializeWithSuggestion(t);return n?e(n):null}materializeWithSuggestions(t){const e=this.seedFork();for(const n of t){const o=this.suggestionMeta.get(n);if(!o||o.status==="accepted")continue;if(o.insertionContext){this.applyPositionAwareInsertion(e,n,o);continue}if(o.blockPreview?.id){const i=ot(e,o.blockPreview.id);i&&(i.yParent.delete(i.index,1),i.yParent.insert(i.index,[It(o.blockPreview)]));continue}const r=this.proposals.get(n);r&&I.applyUpdate(e,r)}return e}getSuggestion(t){return this.suggestionMeta.get(t)}getPendingSuggestions(){const t=new Map;for(const[e,n]of this.suggestionMeta)n.status==="pending"&&t.set(e,n);return t}deleteSuggestion(t){this.proposals.delete(t),this.suggestionMeta.delete(t),this.removeProposalFromParagraphs(t),this.removeProposalFromTableCellMaps(t)}resolveAnchorsAgainstDoc(t,e){const n=this.suggestionMeta.get(t);return n?.anchors?n.anchors.map(o=>{const r=o.from?I.createAbsolutePositionFromRelativePosition(I.decodeRelativePosition(o.from),e):null,i=o.to?I.createAbsolutePositionFromRelativePosition(I.decodeRelativePosition(o.to),e):null;return{kind:o.kind,paragraphId:o.paragraphId,fromIndex:r?.index??null,toIndex:i?.index??null,text:o.text}}):[]}setSuggestionsForParagraph(t,e){this.paragraphSuggestions.set(t,e)}getSuggestionsForParagraph(t){return this.paragraphSuggestions.get(t)||[]}setTableCellSuggestionMap(t,e){this.tableCellSuggestions.set(t,e)}applyPositionAwareInsertion(t,e,n){const o=n.insertionContext;if(!o)return;const r=t.getXmlFragment("content");let i=0;for(let l=r.length-1;l>=0;l--){const c=r.get(l);if(!(c instanceof I.XmlElement))continue;const d=c.getAttribute("id");if(d&&o.mustBeAfter.includes(d)){i=l+1;break}}const a=pu(o.content,o.paragraphId,e);r.insert(i,[a])}removeProposalFromParagraphs(t){for(const[e,n]of this.paragraphSuggestions){const o=n.filter(r=>r!==t);o.length!==n.length&&(o.length===0?this.paragraphSuggestions.delete(e):this.paragraphSuggestions.set(e,o))}}removeProposalFromTableCellMaps(t){for(const[e,n]of this.tableCellSuggestions){let o=!1;for(const[r,i]of n)i===t&&(n.delete(r),o=!0);o&&n.size===0&&this.tableCellSuggestions.delete(e)}}generateId(){return`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}}function pu(s,t,e,n){if(s.type==="list"){const a=new I.XmlElement("list");return a.setAttribute("id",t),a.setAttribute("variant",s.variant??"unordered"),s.startNumber!==void 0&&a.setAttribute("startNumber",String(s.startNumber)),s.numberingChainId&&a.setAttribute("numberingChainId",s.numberingChainId),s.children.forEach(l=>{const c=new I.XmlElement("list-item");Ce(c,l),c.setAttribute("id",l.id||G()),l.checked!==void 0&&c.setAttribute("checked",String(l.checked)),typeof l.indentLevel=="number"&&l.indentLevel>0&&c.setAttribute("indentLevel",String(l.indentLevel)),l.direction!==void 0&&c.setAttribute("direction",l.direction);const d=new I.XmlText;let g=0;l.children.forEach(u=>{if(u.type!=="text")return;const f=Yr(u.marks,e);d.insert(g,u.text,f),g+=u.text.length}),c.insert(0,[d]),a.push([c])}),a}if(s.type==="table")return It(ys({...s,id:t},a=>({...a,marks:Yr(a.marks,e)})));if(s.type==="code"){const a=new I.XmlElement("code");a.setAttribute("id",t),s.language&&a.setAttribute("language",s.language),s.renderDiagram!==void 0&&a.setAttribute("renderDiagram",String(s.renderDiagram)),s.showDiagramSource!==void 0&&a.setAttribute("showDiagramSource",String(s.showDiagramSource));const l=new I.XmlText;return a.insert(0,[l]),lt(l,0,s.content||""),a}if(s.type==="math"){const a=new I.XmlElement("math");a.setAttribute("id",t),s.displayMode&&a.setAttribute("displayMode",s.displayMode),s.align&&a.setAttribute("align",s.align);const l=new I.XmlText;return a.insert(0,[l]),lt(l,0,s.content||""),a}if(s.type==="image"){const a=new I.XmlElement("image");return a.setAttribute("id",t),a.setAttribute("src",s.src),s.sourceUrl&&a.setAttribute("sourceUrl",s.sourceUrl),a.setAttribute("width",String(s.width)),a.setAttribute("height",String(s.height)),s.alt&&a.setAttribute("alt",s.alt),s.align&&a.setAttribute("align",s.align),a}if(s.type==="page-break"){const a=new I.XmlElement("page-break");return a.setAttribute("id",t),a}if(s.type==="toc")return It({...s,id:t});if(s.type==="section-break"){const a=new I.XmlElement("section-break");return a.setAttribute("id",t),s.layout&&a.setAttribute("layout",JSON.stringify(s.layout)),s.breakType&&a.setAttribute("breakType",s.breakType),a}const o=new I.XmlElement("paragraph");o.setAttribute("id",t),s.heading&&o.setAttribute("heading",String(s.heading)),s.align&&o.setAttribute("align",s.align);const r=new I.XmlText;let i=0;return s.children.forEach(a=>{if(a.type!=="text")return;const l=Yr(a.marks,e);lt(r,i,a.text,l),i+=a.text.length}),o.insert(0,[r]),o}function Yr(s,t,e){return{...s||{},suggestionId:t}}const mu={pending_table_changes:{code:"pending_table_changes",summary:"A table edit that would rebuild a table whose cells hold pending changes the call must keep.",message:({subject:s,reason:t})=>`Table '${s}' has ${t??"a pending row or column change"} and pending edits in its cells, so this change would have to rebuild the whole table and would lose or re-author those pending edits. Nothing was changed. Resolve (accept or reject) the table's pending changes first, or edit its cell text with replace/edit_table_cells.`,why:"A table that already has a pending row/column revision, a horizontally merged cell, or blocks moved between cells is replanned as one whole-table proposal from its rejected and accepted views. That would re-create (tracked) or accept (direct) every pending change in its cells. Row/column revisions record grid widths and indexes as snapshots that only resolve in creation order, so a new one cannot be layered over a pending one.",realFix:"Stacked table revision markers: row/column insert/delete markers that compose with pending ones (grid widths derived from the live grid at decision time instead of snapshots), merged-cell (gridSpan) aware column operations, and cell-content moves expressed as text revisions, so the live table can be edited in place like the other structure edits (graftTableStructureChange).",tests:[{file:"src/editor/__tests__/SuggestionPlanner.test.ts",name:"a table edit that would rebuild a table holding pending cell changes"}]},pending_list_changes:{code:"pending_list_changes",summary:"A list-level change, reorder, conversion, or edit over an item's own pending revision, in a list whose items hold pending changes the call must keep.",message:({subject:s})=>`List '${s}' holds pending edits in its items, and this change (a list type or list-level change, reordering, or converting the list) would have to rebuild the whole list, losing or re-authoring those pending edits. Nothing was changed. Resolve (accept or reject) the list's pending changes first, or edit item text and item formatting directly.`,why:"Item text, item formatting, item fields, and item insertions/removals are applied in place on the live list (planPendingListEdit). Anything else replans the list as one whole-list proposal from its rejected and accepted views, which re-creates (tracked) or accepts (direct) the items' pending changes.",realFix:"List-level property revisions (Word w:pPrChange with prior w:numPr on every item, plus numbering-definition revisions), item moves (Word move revisions: w:moveFrom/w:moveTo), and item-level revisions that stack on an item's own pending revision.",tests:[{file:"src/editor/__tests__/SuggestionPlanner.test.ts",name:"a list edit that cannot keep the items' pending changes is refused"}]},list_reorder_unsupported:{code:"list_reorder_unsupported",summary:"A tracked reorder of a clean list's items.",message:({subject:s})=>`This change reorders the items of list '${s}'. Moving list items is not a tracked change Revise can suggest, so nothing was changed. Apply it as a direct edit, or remove the items and insert them again where they belong (each is then reviewable).`,why:"The list suggestion bridge has no item-move operation: a reorder reported success, accepting kept the old order, and rejecting after a .docx reopen duplicated an item. Direct mode rewrites a clean list in its new order.",realFix:"Item move suggestions: a move record (source and destination positions) that renders as a move, resolves either way, and exports as Word move revisions (w:moveFrom/w:moveTo with w:moveFromRangeStart/w:moveToRangeStart) on the list paragraphs.",tests:[{file:"src/editor/__tests__/SuggestionPlanner.test.ts",name:"reordering the items of a clean list"}]},list_numbering_tracked_unsupported:{code:"list_numbering_tracked_unsupported",summary:"A tracked numbering restart, list-type change, or numbering-format change, where a .docx is the source of truth (the revise library and CLI).",message:({subject:s})=>`This change restarts the numbering of list '${s}' or changes its list type. Revise cannot track that as a suggestion (Word stores it as a new numbering definition), so nothing was changed. Apply it as a direct edit.`,why:"In Word a restart or type change is a new numbering definition (a new w:numId, with w:lvlOverride/w:startOverride for a restart); a whole-list suggestion has no such representation, so it exported with no revision and could not be rejected after a reopen. Only sessions that require a .docx round trip (docxRoundTripRequired, set by the revise library) refuse it; the web editor keeps it as an in-app suggestion, and its .docx export writes the list as it now reads and reports a warning with this code.",realFix:"Numbering-definition revisions: export a new w:num (abstract numbering plus start override) for the changed list and a w:pPrChange holding each item's prior w:numPr (old w:numId and w:ilvl), and import that pair back as a list-level suggestion that restores the old numbering on reject.",tests:[{file:"src/editor/__tests__/SuggestionPlanner.test.ts",name:"tracked list numbering changes refuse only when a .docx round trip is required"},{file:"src/editor/converters/DocxConverter.redlines.roundtrip.test.ts",name:"warns when it exports a pending list numbering change Word cannot track"}]},footnote_in_note_unsupported:{code:"footnote_in_note_unsupported",summary:"A footnote or endnote inserted inside a footnote or endnote.",message:({subject:s})=>`Block '${s}' is inside a footnote or endnote, and a note cannot hold another note. Nothing was changed. Put the reference in the body text the note annotates, or write the extra remark into the note's own text.`,why:'Word has no note inside a note: a w:footnoteReference is only valid in the main story. The insertion reported success, but after a .docx round trip the nested reference read back as a superscript "0" and its body was gone.',realFix:"None in .docx. A note-in-note could only exist as a Revise-only structure, which a .docx export would have to flatten (for example into the note's text); until then the tool refuses it in every session.",tests:[{file:"src/embed-sdk/__tests__/serverDocumentSession.node.test.ts",name:"refuses a footnote inside a footnote and changes nothing"}]}};function sn(s,t,e){return{success:!1,error:mu[s].message(t),failure:{code:s,phase:"validation",retryable:!1,mutationOutcome:"unchanged",details:e}}}const bu=new Set(["footnoteRef","footnotePendingBody","footnotePendingKind","comment","bookmark","field","fieldInstr","oxmlRange","sdtInline","latex"]);class ft{constructor(t){this.host=t,this.batchYBlockLocationsById=null,this.stampedIdRecorder=null}recordStampedSuggestionIds(t){const e=this.stampedIdRecorder,n={deletionIds:new Set,insertionIds:new Set,structuralInsertIds:new Set,structuralDeleteIds:new Set};this.stampedIdRecorder=n;try{return{result:t(),stamped:n}}finally{this.stampedIdRecorder=e}}recordStampedId(t,e){this.stampedIdRecorder&&e&&this.stampedIdRecorder[t].add(e)}buildInlinePreviewTextNodes(t){return t.newText?[{type:"text",text:t.newText,marks:{...t.marks}}]:[]}setSuggestingMode(t){this.host.suggestingMode=t}isSuggestingMode(){return this.host.suggestingMode}cloneSuggestionSnapshot(t){return JSON.parse(JSON.stringify(t))}getLiveSuggestionStore(){return this.host.ydoc.getMap("liveSuggestions")}setDefaultSuggestionAuthorName(t){const e=t?.trim();this.host.defaultHumanAuthorName=e||null}resolveSuggestionAuthorName(t,e){return e?.trim()||(t==="ai"?Nt:this.host.defaultHumanAuthorName??Ws)}isOwnPendingSuggestionSpan(t){const e=typeof t.suggestionAuthorName=="string"?t.suggestionAuthorName.trim():"";if(!e)return!0;const n=this.host.liveSuggestionMetadataContext,o=this.resolveSuggestionAuthorName(n?.authorType??"human",n?.agentName);return e===o}withSuggestionMetadata(t,e){const n=this.host.liveSuggestionMetadataContext,o=new Set(this.getLiveSuggestionIds()),r={source:t.source,authorType:t.authorType,createdAt:t.createdAt??Date.now(),label:t.label,commentThreadId:t.commentThreadId,agentName:t.agentName,agentModel:t.agentModel,agentConversationId:t.agentConversationId,agentRequestId:t.agentRequestId,agentTurn:t.agentTurn},i=()=>{this.host.liveSuggestionMetadataContext=r;try{return e()}finally{this.host.liveSuggestionMetadataContext=n}},a=t.batchHistory===!1?i():this.host.runWithUndoGroup(t.historyOrigin??`live-suggestions:${r.createdAt}`,i),l=this.getLiveSuggestionIds().filter(c=>!o.has(c));return{result:a,suggestionIds:l}}normalizeLiveSuggestionRecord(t){const e=this.host.liveSuggestionMetadataContext,n=t.source??e?.source??"manual",o=t.authorType??e?.authorType??(n==="agent"?"ai":"human"),r=t.createdAt??e?.createdAt??Date.now(),i=t.label??e?.label,a=this.resolveSuggestionAuthorName(o,t.agentName??e?.agentName),l=t.agentModel??e?.agentModel,c=t.commentThreadId??e?.commentThreadId,d=t.agentConversationId??e?.agentConversationId,g=t.agentRequestId??e?.agentRequestId,u=t.agentTurn??e?.agentTurn;return{...t,source:n,authorType:o,createdAt:r,label:i,...c?{commentThreadId:c}:{},agentName:a,...l?{agentModel:l}:{},...d?{agentConversationId:d}:{},...g!==void 0?{agentRequestId:g}:{},...u!==void 0?{agentTurn:u}:{}}}saveLiveSuggestion(t,e){const n=this.normalizeLiveSuggestionRecord(t);this.getLiveSuggestionStore().set(n.id,this.cloneSuggestionSnapshot(n)),this.embedLiveSuggestionRecordInTree(n,e)}liveSuggestionRecordAnchorBlockId(t){switch(t.type){case"block-change":return t.sequenceBlockIds?this.getSequenceReplacementMembers(t)[0]?.yBlock.getAttribute("id")??null:t.blockId;case"block-insert":case"block-delete":case"paragraph-split":return t.blockId;case"table-change":return t.tableId;case"paragraph-merge":return t.firstBlockId;case"inline-text":return t.anchorBlockId??null;default:return null}}embedLiveSuggestionRecordInTree(t,e){const n=this.liveSuggestionRecordAnchorBlockId(t);if(!n||!this.host.ydoc)return;const o=e??Z(this.host.ydoc,n);if(o instanceof I.XmlElement)try{if(t.type==="table-change"){let r=[];const i=o.getAttribute("structuralSuggestionRecords");if(typeof i=="string")try{const a=JSON.parse(i);Array.isArray(a)&&(r=a)}catch{}r=r.filter(a=>a?.id!==t.id),r.push(t),o.setAttribute("structuralSuggestionRecords",JSON.stringify(r))}else o.setAttribute("structuralSuggestionRecord",JSON.stringify(t));this.host.liveSuggestionTreeRecordCache.delete(t.id)}catch{}}backfillLiveSuggestionTreeRecords(){if(!this.host.ydoc)return;const t=[];try{for(const[,e]of this.getLiveSuggestionStore()){const n=this.liveSuggestionRecordAnchorBlockId(e);if(!n)continue;const o=Z(this.host.ydoc,n);o instanceof I.XmlElement&&!o.getAttribute("structuralSuggestionRecord")&&t.push(e)}}catch{return}t.length!==0&&this.host.transact(()=>{for(const e of t)this.embedLiveSuggestionRecordInTree(this.normalizeLiveSuggestionRecord(e))})}findLiveSuggestionRecordInTree(t){if(this.host.liveSuggestionTreeRecordCacheReady)return this.host.liveSuggestionTreeRecordCache.get(t)??null;const e=this.host.liveSuggestionTreeRecordCache,n=r=>{r&&r.id&&r.type&&!e.has(r.id)&&e.set(r.id,r)},o=r=>{for(const i of r.toArray()){if(!(i instanceof I.XmlElement))continue;const a=i.getAttribute("structuralSuggestionRecord");if(typeof a=="string"&&a.length>0)try{n(JSON.parse(a))}catch{}const l=i.getAttribute("structuralSuggestionRecords");if(typeof l=="string"&&l.length>0)try{const c=JSON.parse(l);Array.isArray(c)&&c.forEach(n)}catch{}o(i)}};try{o(this.host.getYContentFragment()),o(this.host.getYNotesFragment())}catch{}return this.host.liveSuggestionTreeRecordCacheReady=!0,e.get(t)??null}getLiveSuggestion(t){const e=this.getLiveSuggestionStore().get(t);return e?this.cloneSuggestionSnapshot(e):this.findLiveSuggestionRecordInTree(t)??void 0}findInlineSuggestionMetadataInValue(t,e){if(!t||typeof t!="object")return null;if(Array.isArray(t)){for(const r of t){const i=this.findInlineSuggestionMetadataInValue(r,e);if(i)return i}return null}const n=t;if(n.marks?.suggestionId===e)return{id:e,source:n.marks.suggestionSource,authorType:n.marks.suggestionAuthorType,createdAt:n.marks.suggestionCreatedAt,label:n.marks.suggestionLabel,commentThreadId:n.marks.suggestionCommentThreadId,agentName:n.marks.suggestionAuthorName,agentModel:n.marks.suggestionAgentModel,agentConversationId:n.marks.suggestionAgentConversationId,agentRequestId:n.marks.suggestionAgentRequestId,agentTurn:n.marks.suggestionAgentTurn};const o=mn(n.marks?.layeredInsertion);return o&&o.id===e?{id:e,source:o.source,authorType:o.authorType,createdAt:o.createdAt,label:o.label,commentThreadId:o.commentThreadId,agentName:o.authorName,agentModel:o.agentModel,agentConversationId:o.agentConversationId,agentRequestId:o.agentRequestId,agentTurn:o.agentTurn}:n.children?this.findInlineSuggestionMetadataInValue(n.children,e):null}getInlineSuggestionMetadataFromDocument(t){return this.host.inlineSuggestionMetadataCache.has(t)?this.host.inlineSuggestionMetadataCache.get(t)??null:(this.getDocumentSuggestionIdsCache(),this.host.inlineSuggestionMetadataCache.has(t)?this.host.inlineSuggestionMetadataCache.get(t)??null:(this.host.inlineSuggestionMetadataCache.set(t,null),null))}getLiveSuggestionTooltipDescription(t){const e=this.getLiveSuggestion(t);if(!e)return null;switch(e.type){case"inline-text":return null;case"inline-format":return this.host.getInlineFormatDescription(e);case"paragraph-split":return"Split Paragraph";case"paragraph-merge":return"Join Paragraphs";case"block-insert":{const n=W(this.host.getDocument(),e.blockId)??void 0,o=this.host.getBlockDescription(n);return o?`Insert ${o}`:n?.type==="paragraph"?"Insert Paragraph":n?.type==="list"?"Insert List":null}case"block-delete":{const n=this.host.getBlockDescription(e.beforeBlock);return n?`Delete ${n}`:e.beforeBlock.type==="paragraph"?"Delete Paragraph":e.beforeBlock.type==="list"?"Delete List":e.label??null}case"table-change":return e.label??"Table change";case"block-change":{const n=e.acceptedBlock??W(this.host.getDocument(),e.blockId)??void 0,o=this.host.getTableDimensionDescription(e.label,e.beforeBlock,n);if(o)return o;if(e.label==="Format")return this.host.getBlockFormatDescription(e.beforeBlock,n);if(e.label==="Paragraph")return"Convert to Paragraph";if(e.beforeBlock.type==="list"&&n?.type==="list"&&(e.label==="Insert"||e.label==="Delete"||e.label==="Change"))return e.label==="Insert"?"Insert List Item":e.label==="Delete"?"Delete List Item":"Change List Item";if(e.label==="List")return e.beforeBlock.type==="paragraph"?"Convert to List":"List Change";if(e.label==="Indent"||e.label==="Outdent")return e.label;if(e.label==="Join")return"Join List Items";const r=this.host.getBlockDescription(n)??this.host.getBlockDescription(e.beforeBlock);if(r&&e.label)return`${e.label} ${r}`;if(e.label){if(e.beforeBlock.type==="paragraph")return`${e.label} Paragraph`;if(e.beforeBlock.type==="list")return`${e.label} List`}return e.label??null}default:return null}}deleteLiveSuggestion(t){this.getLiveSuggestionStore().delete(t),this.host.liveSuggestionTreeRecordCache.delete(t)}getLiveSuggestionIds(){if(this.host.liveSuggestionIdsCache)return this.host.liveSuggestionIdsCache.slice();const t=Array.from(new Set([...Array.from(this.getLiveSuggestionStore().keys()),...this.getResolvableSuggestionIdsFromDocument()]));return this.host.liveSuggestionIdsCache=t,t.slice()}getLiveSuggestionIdsBySource(t){const e=this.host.liveSuggestionIdsBySourceCache.get(t);if(e)return e.slice();const n=this.getLiveSuggestionIds().filter(o=>{const r=this.getInlineSuggestionMetadataFromDocument(o);if(r?.source)return r.source===t;if(t==="agent"&&r?.authorType==="ai")return!0;const i=this.getLiveSuggestion(o);return i?.source?i.source===t:t==="agent"&&i?.authorType==="ai"});return this.host.liveSuggestionIdsBySourceCache.set(t,n),n.slice()}getLiveSuggestionIdsByCommentThread(t){return t?this.getLiveSuggestionIds().filter(e=>{const n=this.getInlineSuggestionMetadataFromDocument(e);return n?.commentThreadId?n.commentThreadId===t:this.getLiveSuggestion(e)?.commentThreadId===t}):[]}getResolvableLiveSuggestionIdsBySource(t){return this.getLiveSuggestionIdsBySource(t).filter(e=>this.canResolveLiveSuggestion(e))}normalizeLiveSuggestionIds(t){return Array.from(new Set(t)).filter(e=>typeof e=="string"&&e.length>0)}getLiveSuggestionAuthorName(t){const e=this.getInlineSuggestionMetadataFromDocument(t),n=e?void 0:this.getLiveSuggestion(t),o=e?.agentName??n?.agentName;return o?.trim()?o.trim():(e?.authorType??n?.authorType)==="ai"?Nt:Ws}getLiveSuggestionKind(t){const e=this.getLiveSuggestion(t);if(e)switch(e.type){case"inline-format":return"format";case"block-change":return"format";case"table-change":return e.tableRevision.suggestionKind;case"block-insert":case"paragraph-split":return"insert";case"block-delete":case"paragraph-merge":return"delete"}return this.getInlineSuggestionKindFromDocument(t)}getInlineSuggestionKindFromDocument(t){return this.host.inlineSuggestionKindCache.has(t)?this.host.inlineSuggestionKindCache.get(t)??null:(this.getDocumentSuggestionIdsCache(),this.host.inlineSuggestionKindCache.has(t)?this.host.inlineSuggestionKindCache.get(t)??null:(this.host.inlineSuggestionKindCache.set(t,null),null))}getResolvableSuggestionIdsForScope(t){switch(t.kind){case"source":return this.getResolvableLiveSuggestionIdsBySource(t.source);case"author":{const e=t.authorName.trim();return this.getLiveSuggestionIds().filter(n=>this.getLiveSuggestionAuthorName(n)===e).filter(n=>this.canResolveLiveSuggestion(n))}case"suggestion-kind":return this.getLiveSuggestionIds().filter(e=>this.getLiveSuggestionKind(e)===t.suggestionKind).filter(e=>this.canResolveLiveSuggestion(e))}}getInitialSuggestionIdsForDecisionScope(t){return t.kind==="ids"?this.normalizeLiveSuggestionIds(t.suggestionIds):this.getResolvableSuggestionIdsForScope(t)}getNextSuggestionIdsForDecisionScope(t,e){return t.kind==="ids"?e===0?this.normalizeLiveSuggestionIds(t.suggestionIds):[]:this.getResolvableSuggestionIdsForScope(t)}getResolvableSuggestionIdsFromDocument(){return this.getSuggestionIdsFromDocument()}getSuggestionIdsFromDocument(){return this.getDocumentSuggestionIdsCache().ids.slice()}documentContainsSuggestionId(t){return this.getDocumentSuggestionIdsCache().idSet.has(t)}getDocumentSuggestionIdsCache(){return this.host.documentSuggestionIdsCache&&this.host.documentSuggestionIdsCache.revision===this.host.derivedDocumentRevision?this.host.documentSuggestionIdsCache:(this.host.documentSuggestionIdsCache=this.createDocumentSuggestionIdsCache(this.host.getDocument()),this.host.documentSuggestionIdsCache)}createDocumentSuggestionIdsCache(t){const e=new Set;for(const o of this.blocksWithNotesAndChrome(t)){for(const r of this.getSuggestionIdsForBlock(o))e.add(r);this.indexInlineSuggestionFacts(o)}const n=Array.from(e);return{revision:this.host.derivedDocumentRevision,ids:n,idSet:new Set(n)}}indexInlineSuggestionFacts(t){if(!t||typeof t!="object")return;if(Array.isArray(t)){for(const r of t)this.indexInlineSuggestionFacts(r);return}const e=t,n=e.marks?.suggestionId;if(typeof n=="string"&&n.length>0){this.host.inlineSuggestionMetadataCache.has(n)||this.host.inlineSuggestionMetadataCache.set(n,{id:n,source:e.marks?.suggestionSource,authorType:e.marks?.suggestionAuthorType,createdAt:e.marks?.suggestionCreatedAt,label:e.marks?.suggestionLabel,commentThreadId:e.marks?.suggestionCommentThreadId,agentName:e.marks?.suggestionAuthorName,agentModel:e.marks?.suggestionAgentModel,agentConversationId:e.marks?.suggestionAgentConversationId,agentRequestId:e.marks?.suggestionAgentRequestId,agentTurn:e.marks?.suggestionAgentTurn});const r=e.marks?.deletion?"delete":e.marks?.insertion?"insert":e.marks?.formatChange?"format":null;r&&!this.host.inlineSuggestionKindCache.has(n)&&this.host.inlineSuggestionKindCache.set(n,r)}const o=mn(e.marks?.layeredInsertion);if(o&&(this.host.inlineSuggestionMetadataCache.has(o.id)||this.host.inlineSuggestionMetadataCache.set(o.id,{id:o.id,source:o.source,authorType:o.authorType,createdAt:o.createdAt,label:o.label,commentThreadId:o.commentThreadId,agentName:o.authorName,agentModel:o.agentModel,agentConversationId:o.agentConversationId,agentRequestId:o.agentRequestId,agentTurn:o.agentTurn}),this.host.inlineSuggestionKindCache.set(o.id,"insert")),typeof e.structuralSuggestionId=="string"&&e.structuralSuggestionId.length>0){const r=e.structuralSuggestionKind==="insert"||e.structuralSuggestionKind==="split"?"insert":e.structuralSuggestionKind==="delete"||e.structuralSuggestionKind==="merge"?"delete":e.structuralSuggestionKind==="change"?"format":null;r&&this.host.inlineSuggestionKindCache.set(e.structuralSuggestionId,r)}if(typeof e.suggestionId=="string"&&e.suggestionId.length>0&&!this.host.inlineSuggestionKindCache.has(e.suggestionId)){const r=e.diffState==="insert"?"insert":e.diffState==="delete"?"delete":null;r&&this.host.inlineSuggestionKindCache.set(e.suggestionId,r)}e.children&&this.indexInlineSuggestionFacts(e.children)}getLiveSuggestionIdsForBlock(t){return this.getSuggestionIdsForBlock(t)}getSuggestionIdsForBlock(t){const e=this.host.suggestionIdsByBlockCache.get(t);if(e)return e;const n=new Set;this.collectSuggestionIdsFromBlockValue(t,n);const o=Array.from(n);return this.host.suggestionIdsByBlockCache.set(t,o),o}canResolveLiveSuggestion(t){if(this.host.canResolveLiveSuggestionCache.has(t))return this.host.canResolveLiveSuggestionCache.get(t)??!1;const e=this.computeCanResolveLiveSuggestion(t);return this.host.canResolveLiveSuggestionCache.set(t,e),e}computeCanResolveLiveSuggestion(t){const e=this.getLiveSuggestion(t);if(!e)return this.documentContainsSuggestionId(t);const n=this.host.getDocument();switch(e.type){case"inline-text":return this.documentContainsSuggestionId(e.id);case"inline-format":return this.host.inlineFormatRecordHasLiveMarker(e);case"block-change":{if(e.sequenceBlockIds)return this.getSequenceReplacementMembers(e).length>0;const o=W(n,e.blockId);return o?this.host.isListItemBlockChangeRecord(e)?o.type==="list"&&o.children.some(r=>r.structuralSuggestionId===e.id):e.acceptedBlock?this.blockChangeTargetIsOwned(e):this.blockContainsSuggestionMarker(o,e.id):!1}case"table-change":{const o=W(n,e.tableId);return o?.type!=="table"||!this.blockContainsSuggestionMarker(o,e.id)?!1:e.tableRevision.operations.some(r=>r.kind==="row"?o.children.some(i=>i.id===r.rowId):r.kind==="cell"?o.children.some(i=>i.id===r.rowId&&i.children.some(a=>a.id===r.cellId)):r.kind==="geometry"?r.pendingRows.some(i=>o.children.some(a=>a.id===i.id)):r.kind==="grid"||r.target==="table"?!0:r.target==="row"||r.target==="row-exception"?o.children.some(i=>i.id===r.rowId):o.children.some(i=>i.children.some(a=>a.id===r.cellId)))}case"block-insert":{const o=W(n,e.blockId);return o&&this.blockContainsSuggestionMarker(o,e.id)?!0:this.host.collectStructuralInsertBlockIds(n,e.id).length>0}case"block-delete":{const o=W(n,e.blockId);return!!(o&&this.blockContainsSuggestionMarker(o,e.id))}case"paragraph-split":{const o=W(n,e.blockId),r=W(n,e.insertedBlockId);return!!(o&&r&&(this.blockContainsSuggestionMarker(o,e.id)||this.blockContainsSuggestionMarker(r,e.id)))}case"paragraph-merge":{const o=W(n,e.firstBlockId),r=W(n,e.secondBlockId);return!r||r.type!=="paragraph"?!1:o&&o.type==="paragraph"?this.blockContainsSuggestionMarker(o,e.id)||this.blockContainsSuggestionMarker(r,e.id):this.blockContainsSuggestionMarker(r,e.id)}}}getUnresolvableLiveSuggestionRecords(){const t=[];for(const e of this.getLiveSuggestionIds()){if(this.canResolveLiveSuggestion(e))continue;const n=this.getLiveSuggestion(e);t.push({id:e,type:n?.type??"unknown",source:n?.source??"unknown",label:n?.label})}return t}pruneUnresolvableLiveSuggestionsInternal(){const t=this.getUnresolvableLiveSuggestionRecords();return t.length===0?[]:(this.host.transact(()=>{for(const e of t)this.deleteLiveSuggestion(e.id)}),t)}pruneUnresolvableLiveSuggestions(){const t=this.pruneUnresolvableLiveSuggestionsInternal();return this.host.lastPrunedUnresolvableLiveSuggestions=t,t}takeLastPrunedUnresolvableLiveSuggestions(){const t=this.host.lastPrunedUnresolvableLiveSuggestions;return this.host.lastPrunedUnresolvableLiveSuggestions=[],t}getDocumentWithAcceptedSuggestions(){return this.createLiveSuggestionProjection("accept").doc}getDocumentWithRejectedSuggestions(){return this.createLiveSuggestionProjection("reject").doc}getSelectionInRejectedSuggestionProjection(t){if(!t.anchor||!t.focus||this.getLiveSuggestionIds().length===0)return null;const e=this.host.getDocument(),n=Y(t,this.host.ydoc,e),o=this.createLiveSuggestionProjection("reject"),r=Or(n,o.ydoc);if(!r.anchor||!r.focus)return null;const i=xt(o.doc,r.anchor,r.focus)<=0;return{doc:o.doc,start:i?r.anchor:r.focus,end:i?r.focus:r.anchor}}createLiveSuggestionProjection(t){const e=this.getLiveSuggestionIds(),n=this.host.liveSuggestionProjectionCache.get(t);if(n&&n.revision===this.host.derivedDocumentRevision)return n.projection;const o=Co.createSuggestionProjectionFromYDoc(this.host.ydoc,t,e);return this.host.liveSuggestionProjectionCache.set(t,{revision:this.host.derivedDocumentRevision,projection:o}),o}mapAcceptedSuggestionRangeToLiveRange(t,e,n){if(e<0||n<=e)return null;if(this.getLiveSuggestionIds().length===0)return{start:e,end:n};const o=this.createLiveSuggestionProjection("accept"),r=Z(o.ydoc,t),i=r?ct(r):null,a=Z(this.host.ydoc,t),l=a?ct(a):null;if(!i||!l||n>i.length)return null;const c=I.createRelativePositionFromTypeIndex(i,e,0),d=I.createRelativePositionFromTypeIndex(i,n,-1),g=I.createAbsolutePositionFromRelativePosition(c,this.host.ydoc),u=I.createAbsolutePositionFromRelativePosition(d,this.host.ydoc);return!g||!u||g.type!==l||u.type!==l||u.index<=g.index?null:{start:g.index,end:u.index}}blocksWithNotesAndChrome(t){return[...t.children,...t.notes??[],...t.chrome??[]]}collectSuggestionIdsFromBlockValue(t,e){ft.collectSuggestionIdsFromBlockValue(t,e)}static collectSuggestionIdsFromBlockValue(t,e){if(!t||typeof t!="object")return;if(Array.isArray(t)){for(const r of t)ft.collectSuggestionIdsFromBlockValue(r,e);return}const n=t;typeof n.suggestionId=="string"&&n.suggestionId.length&&e.add(n.suggestionId);const o=mn(n.marks?.layeredInsertion);if(o&&e.add(o.id),typeof n.structuralSuggestionId=="string"&&n.structuralSuggestionId.length&&e.add(n.structuralSuggestionId),typeof n.structuralSuggestionRecords=="string"&&n.structuralSuggestionRecords.length)try{const r=JSON.parse(n.structuralSuggestionRecords);if(Array.isArray(r))for(const i of r)i&&typeof i.id=="string"&&i.id&&e.add(i.id)}catch{}n.marks&&typeof n.marks.suggestionId=="string"&&n.marks.suggestionId.length&&e.add(n.marks.suggestionId);for(const r of Object.values(n))r&&typeof r=="object"&&ft.collectSuggestionIdsFromBlockValue(r,e)}getSequenceReplacementMembers(t){const e=[],n=o=>{o.toArray().forEach((r,i)=>{r instanceof I.XmlElement&&(r.getAttribute("structuralSuggestionId")===t.id?e.push({yBlock:r,yParent:o,index:i}):n(r))})};for(const o of["content","notes"])this.host.ydoc.share.has(o)&&n(this.host.ydoc.getXmlFragment(o));return e}preserveSequenceAfterParagraphSplit(t,e){for(const r of e)this.setParagraphStructuralSuggestion(r,"change",void 0,t.id,"Paragraph");const n=this.getSequenceReplacementMembers(t),o={...t,blockId:n[0].yBlock.getAttribute("id"),sequenceBlockIds:n.map(({yBlock:r})=>r.getAttribute("id"))};this.saveLiveSuggestion(o,n[0].yBlock);for(const r of n.slice(1))this.embedLiveSuggestionRecordInTree(o,r.yBlock)}expandPendingSequenceBlockIds(t){for(const e of this.getLiveSuggestionIds()){const n=this.getLiveSuggestion(e);if(!(n?.type!=="block-change"||!n.sequenceBlockIds||!this.liveSuggestionRecordTouchesAnyBlock(n,t))){n.beforeBlock.id&&t.add(n.beforeBlock.id);for(const{yBlock:o}of this.getSequenceReplacementMembers(n)){const r=o.getAttribute("id");r&&t.add(r)}}}}resetTablePropertyRevisions(t,e,n,o){let r=null,i=null,a=null;for(const l of[...t]){if(r??(r=Ct(e)),i??(i=Ct(n)),!a){a=new Set;for(const{block:g}of r.values())if(g.type==="table")for(const u of g.children)a.add(u.id)}const c=r.get(l)?.block,d=i.get(l)?.block;if(c?.type==="table"&&d?.type==="table"){if(rn(c,d)){const g=o?W(o,l):null;if(g?.type==="table"&&!this.tableHasPendingStructure(l)&&this.buildTableStructureChange(g,d,"probe")){t.delete(l);for(const{block:u}of Ct({children:[g]}).values())t.delete(u.id)}continue}t.delete(l);for(const g of[...this.getLiveSuggestionStore().values()])if(!(g.type!=="table-change"||g.tableId!==l)){if(!this.applySuggestionRecordRejection(g))throw new Error("Could not restore the pending table formatting for replanning.");this.deleteLiveSuggestion(g.id)}}else(c?.type==="table-cell"||a.has(l))&&t.delete(l)}}resetLiveSuggestionsForBlocks(t,e){const n=new Set(t);this.expandPendingSequenceBlockIds(n);for(const g of this.getLiveSuggestionStore().values())if(g.type==="block-change"&&g.sequenceBlockIds&&this.liveSuggestionRecordTouchesAnyBlock(g,n)&&!this.applySuggestionRecordRejection(g))throw new Error("Could not restore the pending list conversion for replanning.");const o=this.host.collapseAffectedBlockIds(n,e);if(o.length===0)return;const r=new Set,i=this.host.getDocument(),a=Ct(i),l=Ct(e),c=new Set(o);for(const[g,u]of this.getLiveSuggestionStore())this.liveSuggestionRecordTouchesAnyBlock(u,c)&&r.add(g);for(const g of o){const u=a.get(g)?.block??W(i,g);u&&this.collectSuggestionIdsFromBlockValue(u,r)}const d=this.getSuggestionMutationSelection();for(const g of o){const u=a.get(g)?.block??W(i,g),f=l.get(g)?.block??W(e,g);if(f){if(!u||u.type==="paragraph"&&f.type==="paragraph"&&Ut(u,f))continue;this.runWithoutSuggesting(()=>this.host.replaceAnyBlockById(g,this.cloneSuggestionSnapshot(f),d,d));continue}u&&this.runWithoutSuggesting(()=>this.host.deleteBlockById(g,d,d))}this.host.transact(()=>{for(const g of r)this.deleteLiveSuggestion(g)})}liveSuggestionRecordTouchesAnyBlock(t,e){const n=o=>e.has(o.getAttribute("id")??"")||o.toArray().some(r=>r instanceof I.XmlElement&&n(r));switch(t.type){case"block-change":return e.has(t.blockId)||!!t.sequenceBlockIds&&(!!t.beforeBlock.id&&e.has(t.beforeBlock.id)||this.getSequenceReplacementMembers(t).some(({yBlock:o})=>n(o)));case"block-insert":case"block-delete":case"paragraph-split":return e.has(t.blockId);case"table-change":return e.has(t.tableId);case"paragraph-merge":return e.has(t.firstBlockId)||e.has(t.secondBlockId);case"inline-format":return t.spans.some(o=>e.has(o.blockId));case"inline-text":return!1}}applyLiveSuggestionDecisionInternal(t,e){const n=this.normalizeLiveSuggestionIds(t);if(n.length===0)return 0;const o=n.filter(l=>{const c=this.getLiveSuggestion(l);return!c||c.type==="inline-text"||c.type==="inline-format"});if(o.length===n.length)return this.applyInlineSuggestionDecisions(new Set(o),e).size;let r=this.applyInlineSuggestionDecisions(new Set(o),e).size;const i=this.host.documentId==="live-suggestion-projection"?this.applySimpleProjectionBlockDecisions(n,e):new Set;r+=i.size;const a=new Set;for(const l of n){if(i.has(l))continue;const c=this.getLiveSuggestion(l);if(!c||c.type==="inline-text"||c.type==="inline-format")continue;const d=c?.type==="block-change"&&!this.host.isListItemBlockChangeRecord(c);if(d&&a.has(c.blockId)){this.deleteLiveSuggestion(l),r+=1;continue}(e==="accept"?this.acceptLiveSuggestionWithoutPruning(l):this.rejectLiveSuggestionWithoutPruning(l))&&(d&&a.add(c.blockId),r+=1)}return r}applySimpleProjectionBlockDecisions(t,e){const n=new Set,o=new Set,r=new Set,i=new Set;for(const l of t){const c=this.getLiveSuggestion(l);if(c){if(e==="accept"&&c.type==="block-delete"||e==="reject"&&c.type==="block-insert"){n.add(l),o.add(c.blockId),c.cleanupTrailingParagraphId&&o.add(c.cleanupTrailingParagraphId),i.add(l);continue}(e==="accept"&&(c.type==="block-insert"||c.type==="paragraph-split")||e==="reject"&&(c.type==="block-delete"||c.type==="paragraph-merge"))&&(r.add(l),i.add(l))}}if(i.size===0)return i;const a=l=>{const c=l.toArray();for(let d=c.length-1;d>=0;d-=1){const g=c[d];if(!(g instanceof I.XmlElement))continue;const u=g.getAttribute("id"),f=g.getAttribute("structuralSuggestionId"),h=g.getAttribute("suggestionId");if(typeof u=="string"&&o.has(u)||typeof f=="string"&&n.has(f)||typeof h=="string"&&n.has(h)){l.delete(d,1);continue}typeof f=="string"&&r.has(f)&&this.clearElementStructuralSuggestion(g),typeof h=="string"&&r.has(h)&&this.setDiffSuggestionAttributes(g,void 0,void 0),a(g)}};return this.host.transact(()=>{a(this.host.getYContentFragment()),a(this.host.getYNotesFragment());for(const l of i)this.deleteLiveSuggestion(l)}),i}applyLiveSuggestionDecisionScopeInternal(t){let e=0,n=[];const o=new Set,r=new Set,i=[];for(let a=0;a<tl;a+=1){const l=this.getNextSuggestionIdsForDecisionScope(t.scope,a);if(a===0&&(n=l),l.length===0)break;const c=l.join("\0");if(r.has(c))break;r.add(c);for(const g of l)o.add(g);const d=this.applyLiveSuggestionDecisionInternal(l,t.decision);if(i.push(...this.pruneUnresolvableLiveSuggestionsInternal()),d<=0)break;e+=d}return{decision:t.decision,scope:t.scope,resolvedCount:e,initialSuggestionIds:n,attemptedSuggestionIds:Array.from(o),attemptedSuggestionIdCount:o.size,prunedSuggestions:i}}decideLiveSuggestions(t){this.host.lastPrunedUnresolvableLiveSuggestions=[];const e=this.getInitialSuggestionIdsForDecisionScope(t.scope),n={decision:t.decision,scope:t.scope,resolvedCount:0,initialSuggestionIds:e,attemptedSuggestionIds:[],attemptedSuggestionIdCount:0,prunedSuggestions:[]};if(e.length===0)return n;let o=n;const r=t.historyOrigin??this.getLiveSuggestionDecisionHistoryOrigin(t);return this.host.runWithUndoGroup(r,()=>{let i=this.applyLiveSuggestionDecisionScopeInternal(t);for(let l=0;l<e.length&&i.resolvedCount>0;l++){const c=new Set(this.getInitialSuggestionIdsForDecisionScope(t.scope)),d=e.filter(f=>c.has(f));if(d.length===0)break;const g=this.applyLiveSuggestionDecisionScopeInternal({...t,scope:{kind:"ids",suggestionIds:d}});if(g.resolvedCount===0)break;const u=[...new Set([...i.attemptedSuggestionIds,...g.attemptedSuggestionIds])];i={...i,resolvedCount:i.resolvedCount+g.resolvedCount,attemptedSuggestionIds:u,attemptedSuggestionIdCount:u.length,prunedSuggestions:i.prunedSuggestions.concat(g.prunedSuggestions)}}const a=i.prunedSuggestions.concat(this.pruneUnresolvableLiveSuggestionsInternal());o={...i,prunedSuggestions:a},this.host.lastPrunedUnresolvableLiveSuggestions=a,this.host.reconcileFootnotes(),this.host.resolveCommentsForSettledSuggestions(o.attemptedSuggestionIds)}),o}getLiveSuggestionDecisionHistoryOrigin(t){if(t.scope.kind==="source")return`live-suggestion-${t.decision}-source:${t.scope.source}`;if(t.scope.kind==="author")return`live-suggestion-${t.decision}-author:${t.scope.authorName}`;if(t.scope.kind==="suggestion-kind")return`live-suggestion-${t.decision}-kind:${t.scope.suggestionKind}`;const e=this.normalizeLiveSuggestionIds(t.scope.suggestionIds);return`live-suggestion-${t.decision}-individual:${e.join(",")}`}acceptLiveSuggestions(t){return this.decideLiveSuggestions({decision:"accept",scope:{kind:"ids",suggestionIds:t}}).resolvedCount}acceptLiveSuggestionsBySource(t){return this.decideLiveSuggestions({decision:"accept",scope:{kind:"source",source:t}})}acceptLiveSuggestionsByAuthor(t){return this.decideLiveSuggestions({decision:"accept",scope:{kind:"author",authorName:t}})}rejectLiveSuggestionsByAuthor(t){return this.decideLiveSuggestions({decision:"reject",scope:{kind:"author",authorName:t}})}acceptLiveSuggestionsByKind(t){return this.decideLiveSuggestions({decision:"accept",scope:{kind:"suggestion-kind",suggestionKind:t}})}rejectLiveSuggestionsByKind(t){return this.decideLiveSuggestions({decision:"reject",scope:{kind:"suggestion-kind",suggestionKind:t}})}rejectLiveSuggestions(t){return this.decideLiveSuggestions({decision:"reject",scope:{kind:"ids",suggestionIds:t}}).resolvedCount}rejectLiveSuggestionsBySource(t){return this.decideLiveSuggestions({decision:"reject",scope:{kind:"source",source:t}})}runWithoutSuggesting(t){const e=this.host.suggestingMode;this.host.suggestingMode=!1;try{return t()}finally{this.host.suggestingMode=e}}getSuggestionIdFromInheritedMarks(t){return t?.insertion&&t.suggestionId&&this.isOwnPendingSuggestionSpan(t)?t.suggestionId:gt()}getSuggestionIdForSuggestedSelectionOverwrite(t,e,n){if(!this.host.suggestingMode||!n?.anchor||!n.focus||xt(t,n.anchor,n.focus)===0)return null;const[o,r]=xt(t,n.anchor,n.focus)<=0?[n.anchor,n.focus]:[n.focus,n.anchor];if(o.block!==e.block||r.block!==e.block)return null;const i=W(t,e.block);if(!i)return null;if(i.type==="paragraph")return r.offset>o.offset?gt():null;if(i.type!=="list")return null;const a=this.host.getListCursorInfo(i,o),l=this.host.getListCursorInfo(i,r);return!a||!l||a.itemIndex!==l.itemIndex?null:(i.children[a.itemIndex],l.offsetInItem>a.offsetInItem?gt():null)}getInlineInsertionSuggestionNodeInTextChildren(t,e){let n=0,o=null;for(const r of t){if(r.type!=="text")continue;const i=r.text.length,a=n+i,l=!!(r.marks?.insertion&&r.marks.suggestionId&&this.isOwnPendingSuggestionSpan(r.marks));if(e>=n&&e<=a&&l)return r;e===a&&l&&(o=r),n=a}return o}getInlineInsertionSuggestionIdInTextChildren(t,e){return this.getInlineInsertionSuggestionNodeInTextChildren(t,e)?.marks?.suggestionId??null}getInlineInsertionSuggestionNodeAtPosition(t,e){const n=W(t,e.block);if(!n)return null;if(n.type==="paragraph")return this.getInlineInsertionSuggestionNodeInTextChildren(n.children,e.offset);if(n.type!=="list")return null;const o=this.host.getListCursorInfo(n,e);if(!o)return null;const r=n.children[o.itemIndex];return r?this.getInlineInsertionSuggestionNodeInTextChildren(r.children,o.offsetInItem):null}getInlineInsertionSuggestionIdAtPosition(t,e){return this.getInlineInsertionSuggestionNodeAtPosition(t,e)?.marks?.suggestionId??null}getStructuralInsertSuggestionIdAtPosition(t,e){const n=W(t,e.block);if(!n)return null;if("structuralSuggestionKind"in n&&n.structuralSuggestionKind==="insert"&&"structuralSuggestionId"in n&&typeof n.structuralSuggestionId=="string")return n.structuralSuggestionId;if(n.type!=="list")return null;const o=this.host.getListCursorInfo(n,e);if(!o)return null;const r=n.children[o.itemIndex];return r?.structuralSuggestionKind==="insert"&&r.structuralSuggestionId?r.structuralSuggestionId:null}getBlockInsertSuggestionIdForBlock(t){return t?(t.type==="paragraph"||t.type==="list")&&t.structuralSuggestionKind==="insert"&&typeof t.structuralSuggestionId=="string"&&t.structuralSuggestionId.length>0?t.structuralSuggestionId:"diffState"in t&&t.diffState==="insert"&&"suggestionId"in t&&typeof t.suggestionId=="string"&&t.suggestionId.length>0?t.suggestionId:null:null}getEnclosingBlockInsertSuggestionIdForBlockId(t,e){let n=W(t,e);for(;n;){const o=this.getBlockInsertSuggestionIdForBlock(n);if(o)return o;if(typeof n.id!="string")break;const r=Xt(t,n.id);if(!r||!("id"in r)||typeof r.id!="string")break;n=r}return null}stripSuggestionMarksFromTextMark(t){if(!t)return;const e={...t};return delete e.insertion,delete e.deletion,delete e.suggestionId,delete e.formatChange,delete e.suggestionSource,delete e.suggestionAuthorType,delete e.suggestionCreatedAt,delete e.suggestionLabel,delete e.suggestionCommentThreadId,delete e.suggestionAuthorName,delete e.suggestionAgentModel,delete e.suggestionAgentConversationId,delete e.suggestionAgentRequestId,delete e.suggestionAgentTurn,delete e.suggestionPriorAttributes,delete e.layeredInsertion,delete e.docxMove,Object.keys(e).length>0?e:void 0}buildInlineSuggestionMetadataMarks(t,e,n){const o=this.host.liveSuggestionMetadataContext,r=o?.source??"manual",i=o?.authorType??(r==="agent"?"ai":"human");return{suggestionId:t,suggestionSource:r,suggestionAuthorType:i,suggestionCreatedAt:n??o?.createdAt??Date.now(),suggestionLabel:e??o?.label,...o?.commentThreadId?{suggestionCommentThreadId:o.commentThreadId}:{},suggestionAuthorName:this.resolveSuggestionAuthorName(i,o?.agentName),...o?.agentModel?{suggestionAgentModel:o.agentModel}:{},...o?.agentConversationId?{suggestionAgentConversationId:o.agentConversationId}:{},...o?.agentRequestId!==void 0?{suggestionAgentRequestId:o.agentRequestId}:{},...o?.agentTurn!==void 0?{suggestionAgentTurn:o.agentTurn}:{}}}buildSuggestionInsertionMarks(t,e,n="Insert",o,r){const i=t?.suggestionId===e?t:r?.suggestionId===e?r:null;return this.recordStampedId("insertionIds",e),{...t||{},insertion:!0,...this.buildInlineSuggestionMetadataMarks(e,n,o),...this.pickInlineSuggestionMetadataMarks(i)}}pickInlineSuggestionMetadataMarks(t){return t?Object.fromEntries(Object.entries({suggestionSource:t.suggestionSource,suggestionAuthorType:t.suggestionAuthorType,suggestionCreatedAt:t.suggestionCreatedAt,suggestionLabel:t.suggestionLabel,suggestionCommentThreadId:t.suggestionCommentThreadId,suggestionAuthorName:t.suggestionAuthorName,suggestionAgentModel:t.suggestionAgentModel,suggestionAgentConversationId:t.suggestionAgentConversationId,suggestionAgentRequestId:t.suggestionAgentRequestId,suggestionAgentTurn:t.suggestionAgentTurn}).filter(([,e])=>e!==void 0)):{}}clearInheritedDeletionFromInsertedSuggestion(t,e,n){n<=0||at(t,e,n,{deletion:null})}findAdjacentDeletionSuggestionAttrs(t,e,n){if(n<=0)return null;const o=e+n,r=st(t);let i=0,a=null,l=null;for(const c of r){if(typeof c.insert!="string")continue;const d=i,g=i+c.insert.length,u=c.attributes||{},f=u.deletion&&typeof u.suggestionId=="string"&&this.isOwnPendingSuggestionSpan(u);if(f&&g===e&&(a=u),f&&d===o){l=u;break}if(i=g,i>o)break}return a??l}findAdjacentDeletionSuggestionId(t,e,n){return this.findAdjacentDeletionSuggestionAttrs(t,e,n)?.suggestionId??null}applySuggestedDeletionToTextRange(t,e,n,o){const r=this.host.collectOverlappingTextSpans(t,e,n);if(r.length===0)return{retainedLength:0,changed:!1};const i=o?null:this.findAdjacentDeletionSuggestionAttrs(t,e,n),a=o??i?.suggestionId??gt(),l={...this.buildInlineSuggestionMetadataMarks(a,"Delete"),...this.pickInlineSuggestionMetadataMarks(i?.suggestionId===a?i:null)};let c=0,d=!1;for(let g=r.length-1;g>=0;g--){const u=r[g],f=u.attributes||{};if(f.insertion){if(this.isOwnPendingSuggestionSpan(f)){t.delete(u.start,u.length),d=!0;continue}c+=u.length,this.recordStampedId("deletionIds",a),at(t,u.start,u.length,{deletion:!0,...l,layeredInsertion:JSON.stringify({id:f.suggestionId,source:f.suggestionSource,authorType:f.suggestionAuthorType,createdAt:f.suggestionCreatedAt,label:f.suggestionLabel,authorName:f.suggestionAuthorName,commentThreadId:f.suggestionCommentThreadId,agentModel:f.suggestionAgentModel,agentConversationId:f.suggestionAgentConversationId,agentRequestId:f.suggestionAgentRequestId,agentTurn:f.suggestionAgentTurn}),formatChange:null,suggestionPriorAttributes:null}),d=!0;continue}if(c+=u.length,f.deletion){o&&f.suggestionId!==o&&(this.recordStampedId("deletionIds",a),at(t,u.start,u.length,{...l,formatChange:null,suggestionPriorAttributes:null}),d=!0);continue}this.recordStampedId("deletionIds",a),at(t,u.start,u.length,{deletion:!0,...l,formatChange:null,suggestionPriorAttributes:null}),d=!0}return{retainedLength:c,changed:d}}clearElementStructuralSuggestion(t){t.removeAttribute("structuralSuggestionId"),t.removeAttribute("structuralSuggestionKind"),t.removeAttribute("structuralSuggestionRole"),t.removeAttribute("structuralSuggestionLabel"),t.removeAttribute("structuralSuggestionRecord")}clearParagraphStructuralSuggestion(t){this.clearElementStructuralSuggestion(t)}setElementStructuralSuggestion(t,e,n,o,r){this.recordStampedId(e==="insert"||e==="split"?"structuralInsertIds":"structuralDeleteIds",o),t.setAttribute("structuralSuggestionId",o),t.setAttribute("structuralSuggestionKind",e),n?t.setAttribute("structuralSuggestionRole",n):t.removeAttribute("structuralSuggestionRole"),r?t.setAttribute("structuralSuggestionLabel",r):t.removeAttribute("structuralSuggestionLabel")}setParagraphStructuralSuggestion(t,e,n,o,r){this.setElementStructuralSuggestion(t,e,n,o,r)}setDiffSuggestionAttributes(t,e,n){e?t.setAttribute("diffState",e):t.removeAttribute("diffState"),n?t.setAttribute("suggestionId",n):t.removeAttribute("suggestionId")}markInsertedBlockElement(t,e,n="Insert"){if(t.nodeName==="paragraph"||t.nodeName==="list"||t.nodeName==="list-item"){this.clearElementStructuralSuggestion(t),this.setElementStructuralSuggestion(t,"insert",void 0,e,n);return}this.setDiffSuggestionAttributes(t,"insert",e)}markDeletedBlockElement(t,e,n="Delete"){if(t.nodeName==="paragraph"||t.nodeName==="list"||t.nodeName==="list-item"){this.clearElementStructuralSuggestion(t),this.setElementStructuralSuggestion(t,"delete",void 0,e,n);return}this.setDiffSuggestionAttributes(t,"delete",e)}markTableSuggestionRows(t,e,n,o){const r=this.cloneSuggestionSnapshot(t);return r.children=r.children.map(i=>e.has(i.id)?{...i,diffState:n,suggestionId:o,children:i.children.map(a=>({...a,diffState:n,suggestionId:o}))}:i),r}markTableSuggestionColumn(t,e,n,o){const r=this.cloneSuggestionSnapshot(t);return r.children=r.children.map(i=>({...i,children:i.children.map((a,l)=>l===e?{...a,diffState:n,suggestionId:o}:a)})),r}buildMinimalParagraphEdit(t,e,n){if(t.children.some(f=>f.type!=="text")||e.children.some(f=>f.type!=="text"))return null;const o=t.children.map(f=>f.text).join(""),r=e.children.map(f=>f.text).join("");let i=0;for(;i<o.length&&i<r.length&&o[i]===r[i];)i++;let a=0;for(;a<o.length-i&&a<r.length-i&&o[o.length-1-a]===r[r.length-1-a];)a++;const l=/[\p{L}\p{N}_]/u;for(;i>0&&l.test(o[i-1]);)i--;for(;a>0&&l.test(o[o.length-a]);)a--;const c=gt(),d=this.buildInlineSuggestionMetadataMarks(c,n),g=(f,h)=>f.map(p=>{const m=this.sanitizePreviewMarks(p.marks)??{};return delete m.insertion,delete m.deletion,{...p,marks:{...m,...d,[h]:!0}}}),u=(f,h,p)=>h<p?this.host.extractTextNodesForRange(f,h,p):[];return{...e,children:[...u(e,0,i),...g(u(t,i,o.length-a),"deletion"),...g(u(e,i,r.length-a),"insertion"),...u(e,r.length-a,r.length)]}}blockChangeTarget(t,e){const n=i=>i&&"children"in i?Pt(Bn(JSON.parse(JSON.stringify(i.children),(a,l)=>a==="id"?void 0:l))):void 0,o=n(t.beforeBlock);if(!t.acceptedBlock||o===void 0||o!==n(t.acceptedBlock))return e;const r=W(this.host.getDocument(),t.blockId);return!r||r.type!==e.type||!("children"in r)?e:{...e,children:r.children}}buildTablePropertyOnlyChange(t,e,n,o,r){if(rn(n,o)||!this.hasSameTableGeometry(n,o)||!this.hasSameTableGeometry(e,o)||!n.children.every((d,g)=>d.children.every((u,f)=>Ut(u.children,o.children[g].children[f].children))))return null;const i=(d,g,u)=>{const f=d,h=g,p=u;for(const m of new Set([...Object.keys(h),...Object.keys(p)]))m==="children"||m==="id"||Ut(h[m],p[m])||(p[m]===void 0?delete f[m]:f[m]=structuredClone(p[m]))},a=d=>{const g=this.cloneSuggestionSnapshot(d);return i(g,n,o),g.children.forEach((u,f)=>{i(u,n.children[f],o.children[f]),u.children.forEach((h,p)=>i(h,n.children[f].children[p],o.children[f].children[p]))}),g},l=W(this.createLiveSuggestionProjection("accept").doc,t);if(l?.type!=="table"||!this.hasSameTableGeometry(l,o))return null;const c=this.buildSuggestedTableChange(l,a(l),r);return c?{liveBlock:a(e),record:c.record,label:c.label}:null}decomposeTableRowAndCellChanges(t,e,n,o){const r=new Map(t.children.map(f=>[f.id,f])),i=new Set(e.children.map(f=>f.id));if(t.children.some(f=>!i.has(f.id)))return null;const a=f=>Pt(Bn(JSON.parse(JSON.stringify(f),(h,p)=>h==="id"?void 0:p))),l=new Map;for(const f of e.children){const h=r.get(f.id);if(h){if(a({...h,children:[]})!==a({...f,children:[]})||h.children.length!==f.children.length)return null;for(let p=0;p<f.children.length;p++){const m=h.children[p],y=f.children[p];if(m.id!==y.id||a({...m,children:[]})!==a({...y,children:[]})||m.children.length!==y.children.length)return null;for(let b=0;b<y.children.length;b++){const k=m.children[b],S=y.children[b];if(k.id!==S.id)return null;if(a(k)===a(S))continue;if(k.type!=="paragraph"||S.type!=="paragraph")return null;const v=this.buildMinimalParagraphEdit(k,S,o);if(!v)return null;l.set(S.id,v)}}}}const c={...e,children:e.children.map(f=>r.get(f.id)??f)},d=e.children.length>t.children.length,g=d?this.buildSuggestedTableChange(t,c,n):null;if(d&&!g||!d&&l.size===0)return null;const u=g?.liveBlock??c;return{liveBlock:{...u,children:u.children.map(f=>r.has(f.id)?{...f,children:f.children.map((h,p)=>({...h,children:e.children.find(m=>m.id===f.id).children[p].children.map(m=>l.get(m.id)??m)}))}:f)},record:g?.record}}buildSuggestedTableChange(t,e,n){const o=(m,y,b)=>({id:n,type:"table-change",tableId:t.id,label:m,tableRevision:{version:1,suggestionKind:y,...b}}),r=t.children.map(m=>m.id),i=e.children.map(m=>m.id),a=(m,y)=>{const b=y==="accepted"?"deletion":"insertion";if(Array.isArray(m))return m.filter(S=>!(S&&typeof S=="object"&&S.type==="text"&&S.marks?.[b])).map(S=>a(S,y));if(!m||typeof m!="object")return m;const k={};for(const[S,v]of Object.entries(m))if(S!=="id"){if(S==="marks"&&v&&typeof v=="object"){const x={};for(const[w,A]of Object.entries(v))w==="insertion"||w==="deletion"||w.startsWith("suggestion")||w==="fontFamily"&&A===jt||(x[w]=A);Object.keys(x).length&&(k.marks=x);continue}k[S]=a(v,y)}return k},l=(m,y="accepted")=>Pt(Bn(a(JSON.parse(JSON.stringify(m??null)),y))),c=(m,y)=>l(m)===l(y)||l(m,"rejected")===l(y,"rejected"),d=c({...t,children:[]},{...e,children:[]}),g=(m,y)=>{let b=0;for(const k of y)k===m[b]&&b++;return b===m.length};if(e.children.length>t.children.length&&g(r,i)&&d&&t.children.every(m=>c(m,e.children.find(y=>y.id===m.id)))){const m=new Set(r),y=e.children.map((S,v)=>({row:S,rowIndex:v})).filter(({row:S})=>!m.has(S.id)),b=new Set(y.map(({row:S})=>S.id)),k=y.length===1?"Insert table row":"Insert table rows";return{liveBlock:this.markTableSuggestionRows(e,b,"insert",n),label:k,record:o(k,"insert",{markers:y.map(({row:S,rowIndex:v})=>({kind:"row-insert",rowId:S.id,rowIndex:v})),operations:y.map(({row:S,rowIndex:v})=>({kind:"row",action:"insert",rowId:S.id,rowIndex:v,row:this.cloneSuggestionSnapshot(S)}))})}}if(e.children.length<t.children.length&&g(i,r)&&d&&e.children.every(m=>c(m,t.children.find(y=>y.id===m.id)))){const m=new Set(i),y=t.children.map((x,w)=>({row:x,rowIndex:w})).filter(({row:x})=>!m.has(x.id)),b=new Set(y.map(({row:x})=>x.id)),k=new Map(e.children.map(x=>[x.id,x])),S=this.cloneSuggestionSnapshot(e);S.children=t.children.map(x=>k.get(x.id)??x);const v=y.length===1?"Delete table row":"Delete table rows";return{liveBlock:this.markTableSuggestionRows(S,b,"delete",n),label:v,record:o(v,"delete",{markers:y.map(({row:x,rowIndex:w})=>({kind:"row-delete",rowId:x.id,rowIndex:w})),operations:y.map(({row:x,rowIndex:w})=>({kind:"row",action:"delete",rowId:x.id,rowIndex:w,row:this.cloneSuggestionSnapshot(x)}))})}}const u=this.host.findSingleTableColumnDelta(t,e);if(u&&(!c({...t,children:[],columnWidths:[]},{...e,children:[],columnWidths:[]})||t.children.some((m,y)=>{const b=e.children[y];return c({...m,children:[]},{...b,children:[]})?m.children.some(k=>{const S=b.children.find(v=>v.id===k.id);return S&&!c(k,S)}):!0})))return null;if(u?.kind==="insert"){const m=[],y=[];for(let b=0;b<e.children.length;b++){const k=e.children[b],S=k.children[u.index];S&&(m.push({kind:"cell",action:"insert",rowId:k.id,cellId:S.id,cellIndex:u.index,cell:this.cloneSuggestionSnapshot(S)}),y.push({kind:"cell-insert",rowId:k.id,cellId:S.id,rowIndex:b,cellIndex:u.index,gridColumn:u.index}))}return m.push({kind:"grid",currentColumnWidths:[...e.columnWidths],priorColumnWidths:[...t.columnWidths],currentGridXml:"",priorGridXml:""}),{liveBlock:this.markTableSuggestionColumn(e,u.index,"insert",n),label:"Insert table column",record:o("Insert table column","insert",{markers:y,operations:m})}}if(u?.kind==="delete"){const m=[],y=[];for(let b=0;b<t.children.length;b++){const k=t.children[b],S=k.children[u.index];S&&(m.push({kind:"cell",action:"delete",rowId:k.id,cellId:S.id,cellIndex:u.index,cell:this.cloneSuggestionSnapshot(S)}),y.push({kind:"cell-delete",rowId:k.id,cellId:S.id,rowIndex:b,cellIndex:u.index,gridColumn:u.index}))}return m.push({kind:"grid",currentColumnWidths:[...e.columnWidths],priorColumnWidths:[...t.columnWidths],currentGridXml:"",priorGridXml:""}),{liveBlock:this.markTableSuggestionColumn(t,u.index,"delete",n),label:"Delete table column",record:o("Delete table column","delete",{markers:y,operations:m})}}const f=Mn(t),h=Mn(e);if(t.children.length===e.children.length&&f.rows===h.rows&&f.cols===h.cols&&t.children.every((m,y)=>m.id===e.children[y]?.id)){const m=f.cells.map(y=>{const b=h.byId.get(y.cell.id);return b?{before:y,after:b}:null}).filter(y=>!!y&&(y.before.rowSpan!==y.after.rowSpan||y.before.colSpan!==y.after.colSpan));if(m.length===1&&m[0].before.col===m[0].after.col&&m[0].before.row===m[0].after.row&&m[0].before.colSpan===m[0].after.colSpan&&m[0].before.rowSpan!==m[0].after.rowSpan){const y=m[0].before,b=m[0].after,k=b.rowSpan>y.rowSpan,S=k?y.row+y.rowSpan:b.row+b.rowSpan,v=k?b.row+b.rowSpan:y.row+y.rowSpan,x=[],w=new Set([t.children[y.row].id]);for(let E=S;E<v;E++){const B=e.children[E];B&&(w.add(B.id),x.push({kind:"cell-merge",rowId:B.id,rowIndex:E,gridColumn:b.col,...k?{vMerge:"cont"}:{vMergeOrig:"cont"}}))}const A=e.children.filter(E=>w.has(E.id)).map(E=>this.cloneSuggestionSnapshot(E)),P=t.children.filter(E=>w.has(E.id)).map(E=>this.cloneSuggestionSnapshot(E));if(!d||t.children.some(E=>!w.has(E.id)&&!c(E,e.children.find(B=>B.id===E.id))))return null;const T=k?"Merge table cells":"Split table cells";return{liveBlock:this.cloneSuggestionSnapshot(e),label:T,record:o(T,"format",{markers:x,operations:[{kind:"geometry",pendingRows:A,acceptedRows:this.cloneSuggestionSnapshot(A),rejectedRows:P}]})}}}const p=m=>Pt(JSON.parse(JSON.stringify(m.children,(y,b)=>{if(y!=="marks"||!b||typeof b!="object")return b;const k={...b};return k.fontFamily===jt&&delete k.fontFamily,Object.keys(k).length>0?k:void 0})));if(t.children.length===e.children.length&&t.children.every((m,y)=>{const b=e.children[y];return b?.id===m.id&&m.children.length===b.children.length&&m.children.every((k,S)=>{const v=b.children[S];return v?.id===k.id&&k.colSpan===v.colSpan&&k.rowSpan===v.rowSpan&&p(k)===p(v)})})){const m=[],y=[],b=(S,v,x)=>{const w={},A={};for(const P of x){const T=S[P],E=v[P];JSON.stringify(T)!==JSON.stringify(E)&&(E!==void 0&&(w[P]=E),T!==void 0&&(A[P]=T))}return{current:w,prior:A}};JSON.stringify(t.columnWidths)!==JSON.stringify(e.columnWidths)&&m.push({kind:"grid",currentColumnWidths:[...e.columnWidths],priorColumnWidths:[...t.columnWidths],currentGridXml:"",priorGridXml:""});const k=b(t,e,["tableWidth","align","borderColor","borderWidth","borders","cellPadding"]);(Object.keys(k.current).length>0||Object.keys(k.prior).length>0)&&(y.push({kind:"table-properties"}),m.push({kind:"properties",target:"table",currentPropertiesXml:"",priorPropertiesXml:"",currentAttributes:k.current,priorAttributes:k.prior})),t.hasHeader!==e.hasHeader&&e.children[0]&&(y.push({kind:"row-properties",rowId:e.children[0].id,rowIndex:0}),m.push({kind:"properties",target:"row",rowId:e.children[0].id,currentPropertiesXml:"",priorPropertiesXml:"",currentTableAttributes:e.hasHeader===void 0?{}:{hasHeader:e.hasHeader},priorTableAttributes:t.hasHeader===void 0?{}:{hasHeader:t.hasHeader}}));for(let S=0;S<e.children.length;S++){const v=t.children[S],x=e.children[S];for(let w=0;w<x.children.length;w++){const A=v.children[w],P=x.children[w],T=b(A,P,["verticalAlign","backgroundColor","borders","padding"]);if(Object.keys(T.current).length===0&&Object.keys(T.prior).length===0)continue;const E=h.byId.get(P.id);y.push({kind:"cell-properties",rowId:x.id,cellId:P.id,rowIndex:S,cellIndex:w,gridColumn:E?.col}),m.push({kind:"properties",target:"cell",rowId:x.id,cellId:P.id,currentPropertiesXml:"",priorPropertiesXml:"",currentAttributes:T.current,priorAttributes:T.prior})}}if(m.length>0)return{liveBlock:this.cloneSuggestionSnapshot(e),label:"Change table formatting",record:o("Change table formatting","format",{markers:y,operations:m})}}return null}buildTableStructureChange(t,e,n){const o=this.reconcileTableDescendantIds(t,e);if(He(t,o))return null;const r=this.buildSuggestedTableChange(t,o,n),i=r?.record.tableRevision.operations??[];return!r||!i.some(a=>a.kind==="row"||a.kind==="cell")||!i.every(a=>a.kind==="row"||a.kind==="cell"||a.kind==="grid")?null:{after:o,change:r}}graftTableStructureChange(t,e,n){const o=this.cloneSuggestionSnapshot(t),r=e.id,i=(l,c)=>{l.diffState=c,l.suggestionId=r},a=(l,c,d)=>{const g=c.findIndex(u=>u.id===d.id);for(let u=g-1;u>=0;u--){const f=l.findIndex(h=>h.id===c[u].id);if(f>=0){l.splice(f+1,0,d);return}}for(let u=g+1;u<c.length;u++){const f=l.findIndex(h=>h.id===c[u].id);if(f>=0){l.splice(f,0,d);return}}l.push(d)};for(const l of e.tableRevision.operations){if(l.kind==="grid"){e.tableRevision.suggestionKind==="insert"&&(o.columnWidths=[...l.currentColumnWidths]);continue}if(l.kind==="row"){const g=o.children.find(u=>u.id===l.rowId);if(l.action==="delete"){if(!g||g.diffState)return null;i(g,"delete"),g.children.forEach(u=>i(u,"delete"))}else{if(g)return null;const u=this.cloneSuggestionSnapshot(l.row);i(u,"insert"),u.children.forEach(f=>i(f,"insert")),a(o.children,n.children,u)}continue}if(l.kind!=="cell")return null;const c=o.children.find(g=>g.id===l.rowId);if(!c)return null;const d=c.children.find(g=>g.id===l.cellId);if(l.action==="delete"){if(!d||d.diffState)return null;i(d,"delete")}else{const g=n.children.find(f=>f.id===c.id);if(d||!g)return null;const u=this.cloneSuggestionSnapshot(l.cell);i(u,"insert"),a(c.children,g.children,u)}}return o}tableHasPendingStructure(t){for(const n of this.getLiveSuggestionStore().values())if(n.type==="table-change"&&n.tableId===t)return!0;const e=W(this.host.getDocument(),t);return e?.type==="table"&&e.children.some(n=>!!n.diffState||n.children.some(o=>!!o.diffState))}hasSameTableGeometry(t,e){return t.children.length===e.children.length&&t.children.every((n,o)=>{const r=e.children[o];return r?.id===n.id&&n.children.length===r.children.length&&n.children.every((i,a)=>{const l=r.children[a];return l?.id===i.id&&l.colSpan===i.colSpan&&l.rowSpan===i.rowSpan})})}reconcileTableDescendantIds(t,e){const n=this.cloneSuggestionSnapshot(e),o=new Set(["id","diffState","suggestionId","structuralSuggestionId","structuralSuggestionKind","structuralSuggestionRole","structuralSuggestionLabel","structuralSuggestionRecord","structuralSuggestionRecords"]),r=b=>Pt(JSON.parse(JSON.stringify(b,(k,S)=>o.has(k)?void 0:S))),i=t.children,a=n.children,l=new Set(i.map(b=>b.id)),c=new Set(a.map(b=>b.id)),d=new Set(i.flatMap(b=>b.children.map(k=>k.id))),g=new Set(a.flatMap(b=>b.children.map(k=>k.id))),u=new Map([...i,...a].map(b=>[b,r(b)])),f=(b,k)=>b.id===k.id?0:l.has(k.id)||c.has(b.id)?2.25:u.get(b)===u.get(k)?0:b.children.length===k.children.length&&b.children.every((S,v)=>{const x=k.children[v];return x?.colSpan===S.colSpan&&x?.rowSpan===S.rowSpan})?.75:2.25,h=Array.from({length:i.length+1},()=>Array(a.length+1).fill(0));for(let b=0;b<=i.length;b++)h[b][0]=b;for(let b=0;b<=a.length;b++)h[0][b]=b;for(let b=1;b<=i.length;b++)for(let k=1;k<=a.length;k++)h[b][k]=Math.min(h[b-1][k]+1,h[b][k-1]+1,h[b-1][k-1]+f(i[b-1],a[k-1]));const p=[];let m=i.length,y=a.length;for(;m>0&&y>0;){const b=f(i[m-1],a[y-1]);b<2&&Math.abs(h[m][y]-(h[m-1][y-1]+b))<1e-4?(p.push([i[m-1],a[y-1]]),m--,y--):h[m][y]===h[m-1][y]+1?m--:y--}for(const[b,k]of p)if(k.id=b.id,b.children.length===k.children.length)for(let S=0;S<b.children.length;S++){const v=b.children[S],x=k.children[S];v.colSpan!==x.colSpan||v.rowSpan!==x.rowSpan||v.id!==x.id&&(d.has(x.id)||g.has(v.id))||(x.id=v.id)}return n}mergePendingTableRevisionState(t,e){const n=this.cloneSuggestionSnapshot(e);t.structuralSuggestionRecords&&(n.structuralSuggestionRecords=t.structuralSuggestionRecords),t.docxTablePropertyOverrides&&(n.docxTablePropertyOverrides=t.docxTablePropertyOverrides);const o=(r,i)=>{!i.diffState&&r.diffState&&(i.diffState=r.diffState),!i.suggestionId&&r.suggestionId&&(i.suggestionId=r.suggestionId)};for(let r=0;r<t.children.length;r++){const i=t.children[r];let a=n.children.find(l=>l.id===i.id);if(!a&&i.diffState==="delete"){const l=t.children.slice(r+1).map(d=>d.id).find(d=>n.children.some(g=>g.id===d)),c=l?n.children.findIndex(d=>d.id===l):n.children.length;a=this.cloneSuggestionSnapshot(i),n.children.splice(c,0,a)}if(a){o(i,a);for(let l=0;l<i.children.length;l++){const c=i.children[l];let d=a.children.find(g=>g.id===c.id);if(!d&&c.diffState==="delete"){const g=i.children.slice(l+1).map(f=>f.id).find(f=>a.children.some(h=>h.id===f)),u=g?a.children.findIndex(f=>f.id===g):a.children.length;d=this.cloneSuggestionSnapshot(c),a.children.splice(u,0,d)}d&&o(c,d)}}}return n}getYTextForSuggestionSpan(t){const e=Z(this.host.ydoc,t.blockId);if(!(e instanceof I.XmlElement))return null;if(t.itemIndex===void 0)return ct(e);const n=[];for(let r=0;r<e.length;r++){const i=e.get(r);i instanceof I.XmlElement&&i.nodeName==="list-item"&&n.push(i)}const o=n[t.itemIndex];return o?ct(o):null}stripInlineSuggestionMarks(t,e,n){at(t,e,n,{insertion:null,deletion:null,suggestionId:null,formatChange:null,suggestionSource:null,suggestionAuthorType:null,suggestionCreatedAt:null,suggestionLabel:null,suggestionCommentThreadId:null,suggestionAuthorName:null,suggestionAgentModel:null,suggestionAgentConversationId:null,suggestionAgentRequestId:null,suggestionAgentTurn:null,suggestionPriorAttributes:null,layeredInsertion:null,docxMove:null})}restoreInlineSuggestionFormatting(t,e,n,o){const r=this.host.collectOverlappingTextSpans(t,e,n),i=r.length>0?r:[{start:e,length:n,attributes:{}}];for(const a of i){const l={insertion:null,deletion:null,suggestionId:null,formatChange:null,suggestionSource:null,suggestionAuthorType:null,suggestionCreatedAt:null,suggestionLabel:null,suggestionCommentThreadId:null,suggestionAuthorName:null,suggestionAgentModel:null,suggestionAgentConversationId:null,suggestionAgentRequestId:null,suggestionAgentTurn:null,suggestionPriorAttributes:null,layeredInsertion:null,docxMove:null},c=xo(a.attributes?.suggestionPriorAttributes)??o,d=new Set([...Object.keys(a.attributes||{}),...Object.keys(c||{})]);d.delete("insertion"),d.delete("deletion"),d.delete("suggestionId"),d.delete("formatChange"),d.delete("suggestionSource"),d.delete("suggestionAuthorType"),d.delete("suggestionCreatedAt"),d.delete("suggestionLabel"),d.delete("suggestionCommentThreadId"),d.delete("suggestionAuthorName"),d.delete("suggestionAgentModel"),d.delete("suggestionAgentConversationId"),d.delete("suggestionAgentRequestId"),d.delete("suggestionAgentTurn"),d.delete("suggestionPriorAttributes"),d.delete("layeredInsertion"),d.delete("docxMove");for(const g of d)Object.prototype.hasOwnProperty.call(c,g)?l[g]=c[g]:bu.has(g)||(l[g]=null);at(t,a.start,a.length,l)}}clearStructuralSuggestionById(t,e){for(const n of t.toArray()){if(!(n instanceof I.XmlElement))continue;n.getAttribute("structuralSuggestionId")===e&&this.clearElementStructuralSuggestion(n);const o=n.getAttribute("structuralSuggestionRecords");if(typeof o=="string"&&o.length>0)try{const r=JSON.parse(o);if(Array.isArray(r)){const i=r.filter(a=>a?.id!==e);i.length!==r.length&&(i.length>0?n.setAttribute("structuralSuggestionRecords",JSON.stringify(i)):n.removeAttribute("structuralSuggestionRecords"))}}catch{}n.getAttribute("suggestionId")===e&&this.setDiffSuggestionAttributes(n,void 0,void 0),this.clearStructuralSuggestionById(n,e)}}blockChangeTargetIsOwned(t){if(t.sequenceBlockIds)return this.getSequenceReplacementMembers(t).length>0;const e=W(this.host.getDocument(),t.blockId);return e?this.blockContainsSuggestionMarker(e,t.id)?!0:e.structuralSuggestionId?!1:Ml(this.host.ydoc,t.blockId)===1:!1}blockContainsSuggestionMarker(t,e){if(!t||typeof t!="object")return!1;if(t.suggestionId===e||t.structuralSuggestionId===e)return!0;const n=t.structuralSuggestionRecords;if(typeof n=="string"&&n.length>0)try{const o=JSON.parse(n);if(Array.isArray(o)&&o.some(r=>r?.id===e))return!0}catch{}return Array.isArray(t.children)?t.children.some(o=>this.blockContainsSuggestionMarker(o,e)):!1}getSuggestionMutationSelection(){return this.host.afterOperationSelection??this.host.beforeOperationSelection??{anchor:null,focus:null}}collectNestedSuggestionIdsForBlock(t,e){const n=W(this.host.getDocument(),t);if(!n)return[];const o=new Set;return this.collectSuggestionIdsFromBlockValue(n,o),e&&o.delete(e),Array.from(o)}clearSuggestionMarkerFromValue(t,e){if(!t||typeof t!="object")return;if(Array.isArray(t)){for(const o of t)this.clearSuggestionMarkerFromValue(o,e);return}const n=t;if(n.suggestionId===e&&(delete n.suggestionId,delete n.diffState),n.structuralSuggestionId===e&&(delete n.structuralSuggestionId,delete n.structuralSuggestionKind,delete n.structuralSuggestionRole,delete n.structuralSuggestionLabel,delete n.structuralSuggestionRecord),typeof n.structuralSuggestionRecords=="string")try{const o=JSON.parse(n.structuralSuggestionRecords);if(Array.isArray(o)){const r=o.filter(i=>i?.id!==e);r.length>0?n.structuralSuggestionRecords=JSON.stringify(r):delete n.structuralSuggestionRecords}}catch{}for(const o of Object.values(n))o&&typeof o=="object"&&this.clearSuggestionMarkerFromValue(o,e)}applyTableGeometryRows(t,e,n){const o=new Map(e.map(a=>[a.id,a])),r=new Map(n.map(a=>[a.id,a])),i=new Set([...o.keys(),...r.keys()]);for(const a of i){const l=t.children.find(f=>f.id===a),c=o.get(a),d=r.get(a);if(!l||!c||!d)continue;const g=new Set(c.children.map(f=>f.id)),u=new Set(d.children.map(f=>f.id));l.children=l.children.filter(f=>!g.has(f.id)||u.has(f.id));for(let f=0;f<d.children.length;f++){const h=d.children[f],p=c.children.find(y=>y.id===h.id);let m=l.children.find(y=>y.id===h.id);if(!m&&!p&&(m=this.cloneSuggestionSnapshot(h),l.children.splice(Math.min(f,l.children.length),0,m)),!(!m||!p)){JSON.stringify(p.children)!==JSON.stringify(h.children)&&JSON.stringify(m.children)===JSON.stringify(p.children)&&(m.children=this.cloneSuggestionSnapshot(h.children));for(const y of["rowSpan","colSpan"])p[y]!==h[y]&&(h[y]===void 0?delete m[y]:m[y]=h[y])}}}}applyTableRevisionDecision(t,e){const n=W(this.host.getDocument(),t.tableId);if(!n||n.type!=="table")return!1;const o=this.cloneSuggestionSnapshot(n);let r={version:1};if(o.docxTablePropertyOverrides)try{const l=JSON.parse(o.docxTablePropertyOverrides);l?.version===1&&(r=l)}catch{}for(const l of t.tableRevision.operations){if(l.kind==="row"){const p=l.action==="insert"?e==="accept":e==="reject",m=o.children.findIndex(y=>y.id===l.rowId);p&&m<0?o.children.splice(Math.min(l.rowIndex,o.children.length),0,this.cloneSuggestionSnapshot(l.row)):!p&&m>=0&&o.children.splice(m,1);continue}if(l.kind==="cell"){const p=o.children.find(b=>b.id===l.rowId);if(!p)continue;const m=l.action==="insert"?e==="accept":e==="reject",y=p.children.findIndex(b=>b.id===l.cellId);m&&y<0?p.children.splice(Math.min(l.cellIndex,p.children.length),0,this.cloneSuggestionSnapshot(l.cell)):!m&&y>=0&&p.children.splice(y,1);continue}if(l.kind==="geometry"){this.applyTableGeometryRows(o,l.pendingRows,e==="accept"?l.acceptedRows:l.rejectedRows);continue}if(l.kind==="grid"){const p=e==="accept"?l.currentColumnWidths:l.priorColumnWidths,m=e==="accept"?l.currentGridXml:l.priorGridXml;o.columnWidths=[...p],m&&(r.grid={xml:m,columnWidths:[...p]});continue}const c=e==="accept"?l.currentAttributes:l.priorAttributes,d=e==="accept"?l.priorAttributes:l.currentAttributes;let g;if(l.target==="table"?g=o:l.target==="row"||l.target==="row-exception"?g=o.children.find(p=>p.id===l.rowId):g=o.children.flatMap(p=>p.children).find(p=>p.id===l.cellId),g)for(const p of new Set([...Object.keys(d??{}),...Object.keys(c??{})]))c&&Object.prototype.hasOwnProperty.call(c,p)&&c[p]!==void 0?g[p]=this.cloneSuggestionSnapshot(c[p]):delete g[p];const u=e==="accept"?l.currentTableAttributes:l.priorTableAttributes,f=e==="accept"?l.priorTableAttributes:l.currentTableAttributes;for(const p of new Set([...Object.keys(f??{}),...Object.keys(u??{})]))u&&Object.prototype.hasOwnProperty.call(u,p)&&u[p]!==void 0?o[p]=this.cloneSuggestionSnapshot(u[p]):delete o[p];const h=e==="accept"?l.currentPropertiesXml:l.priorPropertiesXml;l.target==="table"?r.table=h:l.target==="row-exception"&&l.rowId?(r.rowExceptions=r.rowExceptions??{},r.rowExceptions[l.rowId]=h):l.target==="row"&&l.rowId?(r.rows=r.rows??{},r.rows[l.rowId]=h):l.target==="cell"&&l.cellId&&(r.cells=r.cells??{},r.cells[l.cellId]=h)}(r.table||r.grid||Object.keys(r.rows??{}).length>0||Object.keys(r.rowExceptions??{}).length>0||Object.keys(r.cells??{}).length>0)&&(o.docxTablePropertyOverrides=JSON.stringify(r)),this.clearSuggestionMarkerFromValue(o,t.id);const i=this.getSuggestionMutationSelection();if(n.children.length>0&&o.children.length===0){const l=this.runWithoutSuggesting(()=>this.host.deleteBlockById(t.tableId,i,i));return l&&this.deleteLiveSuggestion(t.id),l}const a=this.runWithoutSuggesting(()=>this.host.replaceAnyBlockById(t.tableId,o,i,i));return a&&this.deleteLiveSuggestion(t.id),a}applySuggestionRecordAcceptance(t){const e=this.getSuggestionMutationSelection();switch(t.type){case"inline-text":return this.applyInlineSuggestionDecision(t.id,"accept");case"table-change":return this.applyTableRevisionDecision(t,"accept");case"block-change":{if(this.host.isListItemBlockChangeRecord(t)&&this.host.applyListItemBlockChangeDecision(t,"accept",e))return!0;if(t.acceptedBlock){if(!this.blockChangeTargetIsOwned(t))return!1;const o=this.runWithoutSuggesting(()=>this.host.replaceAnyBlockById(t.blockId,this.blockChangeTarget(t,t.acceptedBlock),e,e));return o&&(this.host.transact(()=>this.clearStructuralSuggestionById(this.host.getYNotesFragment(),t.id)),this.deleteLiveSuggestion(t.id)),o}const n=W(this.host.getDocument(),this.liveSuggestionRecordAnchorBlockId(t)??t.blockId);return n&&this.blockContainsSuggestionMarker(n,t.id)?(this.host.transact(()=>{this.clearStructuralSuggestionById(this.host.getYContentFragment(),t.id),this.clearStructuralSuggestionById(this.host.getYNotesFragment(),t.id)}),this.host.setSelectionAfterOperation(e),this.host.afterOperationRelativeSelection=Y(e,this.host.ydoc,this.host.getDocument()),this.deleteLiveSuggestion(t.id),!0):!1}case"block-insert":{const n=this.collectNestedSuggestionIdsForBlock(t.blockId,t.id);for(const o of n)this.acceptLiveSuggestionWithoutPruning(o);return this.host.transact(()=>{this.clearStructuralSuggestionById(this.host.getYContentFragment(),t.id),this.clearStructuralSuggestionById(this.host.getYNotesFragment(),t.id)}),this.host.setSelectionAfterOperation(e),this.host.afterOperationRelativeSelection=Y(e,this.host.ydoc,this.host.getDocument()),this.deleteLiveSuggestion(t.id),!0}case"block-delete":{const n=this.host.getDocument(),o=Xt(n,t.blockId),r=W(n,t.blockId);if(o?.type==="table-cell"&&o.children?.length===1&&r?.type==="paragraph"){const a=this.runWithoutSuggesting(()=>this.host.replaceAnyBlockById(t.blockId,{type:"paragraph",id:t.blockId,children:[]},e,e));return a&&this.deleteLiveSuggestion(t.id),a}const i=this.runWithoutSuggesting(()=>this.host.deleteBlockById(t.blockId,e,e));return i&&(t.cleanupTrailingParagraphId&&this.runWithoutSuggesting(()=>this.host.deleteBlockById(t.cleanupTrailingParagraphId,e,e)),this.deleteLiveSuggestion(t.id)),i}case"paragraph-split":return this.host.transact(()=>{this.clearStructuralSuggestionById(this.host.getYContentFragment(),t.id),this.clearStructuralSuggestionById(this.host.getYNotesFragment(),t.id)}),this.host.setSelectionAfterOperation(e),this.host.afterOperationRelativeSelection=Y(e,this.host.ydoc,this.host.getDocument()),this.deleteLiveSuggestion(t.id),!0;case"paragraph-merge":{const n=this.host.getDocument(),o=W(n,t.secondBlockId);let r=W(n,t.firstBlockId),i=Xt(n,t.firstBlockId);if(!r||r.type!=="paragraph"){const d=Xt(n,t.secondBlockId),g=d?"children"in d?d.children:[]:n.children,u=g.findIndex(h=>h.id===t.secondBlockId),f=u>0?g[u-1]:null;f?.type==="paragraph"&&(r=f,i=d??n)}if(!r||!o||!i||r.type!=="paragraph"||o.type!=="paragraph")return!1;const a={block:r.id,offset:r.children.reduce((d,g)=>d+(g.type==="text"?g.text.length:0),0)},l={block:o.id,offset:0},c=this.runWithoutSuggesting(()=>this.host.mergeAdjacentParagraphs(r,o,a,l,i,e,e));return c&&this.deleteLiveSuggestion(t.id),c}case"inline-format":return this.host.transact(()=>{for(const n of t.spans){const o=this.getYTextForSuggestionSpan(n);o&&this.stripInlineSuggestionMarks(o,n.start,n.end-n.start)}}),this.host.setSelectionAfterOperation(e),this.host.afterOperationRelativeSelection=Y(e,this.host.ydoc,this.host.getDocument()),this.deleteLiveSuggestion(t.id),!0}}applySuggestionRecordRejection(t){const e=this.getSuggestionMutationSelection();switch(t.type){case"inline-text":return this.applyInlineSuggestionDecision(t.id,"reject");case"table-change":return this.applyTableRevisionDecision(t,"reject");case"block-change":{if(this.host.isListItemBlockChangeRecord(t)&&this.host.applyListItemBlockChangeDecision(t,"reject",e))return!0;if(!this.blockChangeTargetIsOwned(t))return!1;if(t.sequenceBlockIds){const o=this.getSequenceReplacementMembers(t),r=o[0];return!r||o.some(i=>i.yParent!==r.yParent)?!1:(this.host.transact(()=>{for(const i of[...o].sort((a,l)=>l.index-a.index))i.yParent.delete(i.index,1);r.yParent.insert(r.index,[this.host.blockToYjsElement(this.cloneSuggestionSnapshot(t.beforeBlock))]),this.deleteLiveSuggestion(t.id)}),this.host.setSelectionAfterOperation(e),this.host.afterOperationRelativeSelection=Y(e,this.host.ydoc,this.host.getDocument()),!0)}const n=this.runWithoutSuggesting(()=>this.host.replaceAnyBlockById(t.blockId,this.blockChangeTarget(t,t.beforeBlock),e,e));return n&&(this.host.transact(()=>this.clearStructuralSuggestionById(this.host.getYNotesFragment(),t.id)),this.deleteLiveSuggestion(t.id)),n}case"block-insert":{const n=this.collectNestedSuggestionIdsForBlock(t.blockId,t.id),o=this.host.collectStructuralInsertBlockIds(this.host.getDocument(),t.id),r=o.length>0?Array.from(new Set(o)):[t.blockId];let i=!1;for(const a of[...r].reverse())i=this.runWithoutSuggesting(()=>this.host.deleteBlockById(a,e,e))||i;if(i){t.cleanupTrailingParagraphId&&this.runWithoutSuggesting(()=>this.host.deleteBlockById(t.cleanupTrailingParagraphId,e,e)),this.host.transact(()=>this.clearStructuralSuggestionById(this.host.getYContentFragment(),t.id));for(const a of n)this.deleteLiveSuggestion(a);this.deleteLiveSuggestion(t.id)}return i}case"block-delete":return this.host.transact(()=>{this.clearStructuralSuggestionById(this.host.getYContentFragment(),t.id),this.clearStructuralSuggestionById(this.host.getYNotesFragment(),t.id)}),this.host.setSelectionAfterOperation(e),this.host.afterOperationRelativeSelection=Y(e,this.host.ydoc,this.host.getDocument()),this.deleteLiveSuggestion(t.id),!0;case"paragraph-split":{const n=this.host.getDocument(),o=W(n,t.insertedBlockId);if(!o)return!1;const r=W(n,t.blockId);let i=t.beforeBlock,a;if(r&&r.type==="paragraph"&&o.type==="paragraph"){const{id:c,children:d,structuralSuggestionId:g,structuralSuggestionKind:u,structuralSuggestionRole:f,structuralSuggestionLabel:h,structuralSuggestionRecord:p,...m}=o;let y={};if(g&&g!==t.id){a=g;let b=p;if(p)try{const k=JSON.parse(p);k.blockId===t.insertedBlockId&&(k.blockId=t.blockId),b=JSON.stringify(k)}catch{}y={structuralSuggestionId:g,...u?{structuralSuggestionKind:u}:{},...f?{structuralSuggestionRole:f}:{},...h?{structuralSuggestionLabel:h}:{},...b?{structuralSuggestionRecord:b}:{}}}i={...m,...y,type:"paragraph",id:t.blockId,children:[...r.children,...d]}}if(!this.runWithoutSuggesting(()=>this.host.replaceAnyBlockById(t.blockId,i,e,e)))return!1;this.runWithoutSuggesting(()=>this.host.deleteBlockById(t.insertedBlockId,e,e)),this.deleteLiveSuggestion(t.id);const l=new Set(a?[a]:[]);for(const[c,d]of this.getLiveSuggestionStore())c!==t.id&&d.blockId===t.insertedBlockId&&l.add(c);for(const c of l){const d=this.getLiveSuggestion(c);if(d&&d.blockId===t.insertedBlockId){const g=f=>{if(!f||typeof f!="object")return f;const h={...f};return h.structuralSuggestionId===t.id&&(delete h.structuralSuggestionId,delete h.structuralSuggestionKind,delete h.structuralSuggestionRole,delete h.structuralSuggestionLabel,delete h.structuralSuggestionRecord),"children"in h&&i.type==="paragraph"&&(h.children=i.children,h.id=t.blockId),h},u=d;this.saveLiveSuggestion({...u,blockId:t.blockId,...u.beforeBlock?{beforeBlock:g(u.beforeBlock)}:{},...u.acceptedBlock?{acceptedBlock:g(u.acceptedBlock)}:{}})}this.host.liveSuggestionTreeRecordCache.delete(c)}return!0}case"paragraph-merge":return this.host.transact(()=>{this.clearStructuralSuggestionById(this.host.getYContentFragment(),t.id),this.clearStructuralSuggestionById(this.host.getYNotesFragment(),t.id)}),this.host.setSelectionAfterOperation(e),this.host.afterOperationRelativeSelection=Y(e,this.host.ydoc,this.host.getDocument()),this.deleteLiveSuggestion(t.id),!0;case"inline-format":return this.host.transact(()=>{for(const n of t.spans){const o=this.getYTextForSuggestionSpan(n);o&&this.restoreInlineSuggestionFormatting(o,n.start,n.end-n.start,n.attributes)}}),this.host.setSelectionAfterOperation(e),this.host.afterOperationRelativeSelection=Y(e,this.host.ydoc,this.host.getDocument()),this.deleteLiveSuggestion(t.id),!0}}applyInlineSuggestionDecision(t,e){return this.applyInlineSuggestionDecisions(new Set([t]),e).has(t)}applyInlineSuggestionDecisions(t,e){const n=new Set;if(t.size===0)return n;const o=new Set,r=(l,c)=>l instanceof I.XmlText?st(l).some(d=>{if(d.attributes?.suggestionId!==c||!d.attributes.docxMove)return!1;try{return JSON.parse(d.attributes.docxMove).wholeBlocks===!0}catch{return!1}}):l.toArray().some(d=>(d instanceof I.XmlElement||d instanceof I.XmlText)&&r(d,c)),i=new Map;for(const l of this.host.getYContentFragment().toArray()){if(!(l instanceof I.XmlElement))continue;const c=l.getAttribute("structuralSuggestionId")??l.getAttribute("suggestionId");if(!c||!t.has(c)||o.has(c))continue;if(r(l,c)){o.add(c);continue}const d=l.getAttribute("structuralSuggestionKind")??l.getAttribute("diffState");if(d!=="insert"&&d!=="delete")continue;const g=i.get(c)??new Set;g.add(d),i.set(c,g)}for(const[l,c]of i){if(c.size!==2)continue;const d=this.getLiveSuggestion(l);(!d||d.type==="inline-text")&&o.add(l)}const a=(l,c,d)=>{if(l instanceof I.XmlText)return st(l).every(u=>u.insert===""||u.attributes?.suggestionId===c&&(d==="delete"?u.attributes?.deletion:u.attributes?.insertion));const g=l.getAttribute("structuralSuggestionId")??l.getAttribute("suggestionId");return g&&g!==c?!1:Ts(l.nodeName)?!0:l.toArray().every(u=>(u instanceof I.XmlElement||u instanceof I.XmlText)&&a(u,c,d))};if(this.host.transact(()=>{const l=c=>{for(const d of c.toArray()){if(d instanceof I.XmlElement){const h=d.getAttribute("structuralSuggestionId")??d.getAttribute("suggestionId"),p=d.getAttribute("structuralSuggestionKind")??d.getAttribute("diffState");if(c===this.host.getYContentFragment()&&typeof h=="string"&&typeof p=="string"&&o.has(h)&&a(d,h,p)&&(e==="accept"&&p==="delete"||e==="reject"&&p==="insert")){const b=c.toArray().indexOf(d);b>=0&&c.delete(b,1),n.add(h);continue}const m=d.getAttribute("structuralSuggestionId");typeof m=="string"&&t.has(m)&&(this.clearElementStructuralSuggestion(d),n.add(m));const y=d.getAttribute("suggestionId");if(typeof y=="string"&&t.has(y)){this.setDiffSuggestionAttributes(d,void 0,void 0);const b=d.getAttribute("structuralSuggestionRecord");let k;try{k=typeof b=="string"?JSON.parse(b)?.id:void 0}catch{k=void 0}k===y&&d.removeAttribute("structuralSuggestionRecord"),n.add(y)}l(d);continue}if(!(d instanceof I.XmlText))continue;const g=st(d),u=[];let f=0;for(const h of g)typeof h.insert=="string"&&(u.push({start:f,length:h.insert.length,attributes:h.attributes||{}}),f+=h.insert.length);for(let h=u.length-1;h>=0;h--){const p=u[h],m=typeof p.attributes.suggestionId=="string"?p.attributes.suggestionId:null,y=mn(p.attributes.layeredInsertion);if(m&&t.has(m)){e==="accept"?p.attributes.deletion?d.delete(p.start,p.length):this.stripInlineSuggestionMarks(d,p.start,p.length):p.attributes.deletion&&y?at(d,p.start,p.length,{deletion:null,layeredInsertion:null,insertion:!0,suggestionId:y.id,suggestionSource:y.source??null,suggestionAuthorType:y.authorType??null,suggestionCreatedAt:y.createdAt??null,suggestionLabel:y.label??"Insert",suggestionCommentThreadId:y.commentThreadId??null,suggestionAuthorName:y.authorName??null,suggestionAgentModel:y.agentModel??null,suggestionAgentConversationId:y.agentConversationId??null,suggestionAgentRequestId:y.agentRequestId??null,suggestionAgentTurn:y.agentTurn??null}):p.attributes.insertion?d.delete(p.start,p.length):p.attributes.formatChange&&xo(p.attributes.suggestionPriorAttributes)?this.restoreInlineSuggestionFormatting(d,p.start,p.length,xo(p.attributes.suggestionPriorAttributes)):this.stripInlineSuggestionMarks(d,p.start,p.length),n.add(m);continue}y&&t.has(y.id)&&(e==="accept"?at(d,p.start,p.length,{insertion:null,layeredInsertion:null}):d.delete(p.start,p.length),n.add(y.id))}}};l(this.host.getYContentFragment()),o.size>0&&this.host.ensureTrailingParagraph(),l(this.host.getYNotesFragment()),l(this.host.ydoc.getXmlFragment("chrome"))}),n.size>0){const l=this.getSuggestionMutationSelection();this.host.setSelectionAfterOperation(l),this.host.afterOperationRelativeSelection=Y(l,this.host.ydoc,this.host.getDocument());for(const c of n)this.deleteLiveSuggestion(c)}return n}acceptLiveSuggestionWithoutPruning(t){const e=this.getLiveSuggestion(t);return e?this.applySuggestionRecordAcceptance(e):this.applyInlineSuggestionDecision(t,"accept")}rejectLiveSuggestionWithoutPruning(t){const e=this.getLiveSuggestion(t);return e?this.applySuggestionRecordRejection(e):this.applyInlineSuggestionDecision(t,"reject")}acceptLiveSuggestion(t){this.host.lastPrunedUnresolvableLiveSuggestions=[];const e=this.acceptLiveSuggestionWithoutPruning(t);return this.host.lastPrunedUnresolvableLiveSuggestions=this.pruneUnresolvableLiveSuggestionsInternal(),e&&this.host.resolveCommentsForSettledSuggestions([t]),e}rejectLiveSuggestion(t){this.host.lastPrunedUnresolvableLiveSuggestions=[];const e=this.rejectLiveSuggestionWithoutPruning(t);return this.host.lastPrunedUnresolvableLiveSuggestions=this.pruneUnresolvableLiveSuggestionsInternal(),e&&this.host.resolveCommentsForSettledSuggestions([t]),e}deleteMultiParagraphSelectionAsSuggestion(t,e,n,o,r){const i=this.host.getDocument().children.slice(n,o+1);if(i.length<2||i.some(c=>c.type!=="paragraph"))return!1;const a=i.map((c,d)=>{const g=c,u=this.host.getParagraphTextLength(g),f=d===0?Math.min(t.offset,u):0,h=d===i.length-1?Math.min(e.offset,u):u;return{blockId:g.id,from:f,to:h}});if(!a.some(c=>c.to>c.from))return!1;const l=gt();return this.host.transact(()=>{for(const c of a){if(c.to<=c.from)continue;const d=Z(this.host.ydoc,c.blockId);if(!(d instanceof I.XmlElement))continue;const g=ct(d);g&&(this.getEnclosingBlockInsertSuggestionIdForBlockId(this.host.getDocument(),c.blockId)?g.delete(c.from,c.to-c.from):this.applySuggestedDeletionToTextRange(g,c.from,c.to-c.from,l).retainedLength>0&&this.host.normalizeAdjacentManualReplacementOrder(g,c.from))}for(let c=0;c+1<i.length;c++){const d=i[c],g=i[c+1],u=Z(this.host.ydoc,d.id),f=Z(this.host.ydoc,g.id);if(!(u instanceof I.XmlElement)||!(f instanceof I.XmlElement)||this.getEnclosingBlockInsertSuggestionIdForBlockId(this.host.getDocument(),d.id)||this.getEnclosingBlockInsertSuggestionIdForBlockId(this.host.getDocument(),g.id))continue;const h=gt();this.setParagraphStructuralSuggestion(u,"merge","before",h),this.setParagraphStructuralSuggestion(f,"merge","after",h),this.saveLiveSuggestion({id:h,type:"paragraph-merge",firstBlockId:d.id,secondBlockId:g.id})}}),this.host.setSelectionAfterOperation(r),this.host.afterOperationRelativeSelection=Y(r,this.host.ydoc,this.host.getDocument()),!0}sanitizePreviewMarks(t){let e=el(t);for(const n of fs)t?.[n]===!1&&(e??(e={}),e[n]=!1);return t?.footnoteRef?{...e,footnoteRef:t.footnoteRef,...t.superscript?{superscript:!0}:{}}:e}sanitizePreviewBlock(t){const e=o=>({...o,marks:this.sanitizePreviewMarks(o.marks)}),n=o=>{const r={...o};return delete r.diffState,delete r.suggestionId,delete r.proposalId,delete r.toolCallId,delete r.toolType,delete r.diffSegmentIndex,delete r.structuralSuggestionId,delete r.structuralSuggestionKind,delete r.structuralSuggestionRole,delete r.structuralSuggestionLabel,r};switch(t.type){case"paragraph":return n({...t,children:t.children.map(o=>e(o))});case"list":return n({...t,children:t.children.map(o=>n({...o,children:o.children.map(r=>e(r))}))});case"table":return n({...t,children:t.children.map(o=>n({...o,children:o.children.map(r=>n({...r,children:r.children.map(i=>this.sanitizePreviewBlock(i))}))}))});case"table-cell":return n({...t,children:t.children.map(o=>this.sanitizePreviewBlock(o))});case"container":case"footnote":return n({...t,children:t.children.map(o=>this.sanitizePreviewBlock(o))});default:return n({...t})}}markBlockForGenericSuggestionChange(t,e,n){const o=this.sanitizePreviewBlock(t);return o.type==="paragraph"||o.type==="list"?{...o,structuralSuggestionId:e,structuralSuggestionKind:"change",structuralSuggestionLabel:n}:{...o,diffState:"insert",suggestionId:e}}getListItemSignatureForSuggestionBridge(t){const e=n=>{const o=this.sanitizePreviewMarks(n);if(!o)return{};if(o.fontFamily===jt||o.fontFamily==="Arial"){const r={...o};return delete r.fontFamily,r}return o};return JSON.stringify({...Object.fromEntries(An.map(n=>[n,t[n]])),direction:t.direction,checked:t.checked??!1,indentLevel:t.indentLevel??0,children:t.children.map(n=>({text:n.text,marks:e(n.marks)}))})}computeListItemLcsForSuggestionBridge(t,e){const{beforeKeys:n,afterKeys:o}=this.getListItemAlignmentKeysForSuggestionBridge(t,e);return Fr(n,o)}getListItemAlignmentKeysForSuggestionBridge(t,e){return ma(t,e,n=>this.getListItemSignatureForSuggestionBridge(n))}computeListSuggestionBridgeOperations(t,e){const n=[],o=this.computeListItemLcsForSuggestionBridge(t.children,e.children),{beforeKeys:r,afterKeys:i}=this.getListItemAlignmentKeysForSuggestionBridge(t.children,e.children),a=t.children.map(u=>this.getListItemSignatureForSuggestionBridge(u)),l=e.children.map(u=>this.getListItemSignatureForSuggestionBridge(u)),c=(u,f,h,p)=>{const m=Math.min(u.length,f.length);for(let y=0;y<m;y++)n.push({kind:"change",index:h+y,beforeItem:u[y],afterItem:f[y]});for(let y=m;y<u.length;y++)n.push({kind:"delete",index:h+y,beforeItem:u[y]});for(let y=m;y<f.length;y++)n.push({kind:"insert",index:h+y,afterIndex:p+y,afterItem:f[y]})};let d=0,g=0;for(const u of o){let f=d;for(;f<r.length&&r[f]!==u;)f+=1;let h=g;for(;h<i.length&&i[h]!==u;)h+=1;c(t.children.slice(d,f),e.children.slice(g,h),d,g),a[f]!==l[h]&&n.push({kind:"change",index:f,beforeItem:t.children[f],afterItem:e.children[h]}),d=f+1,g=h+1}return c(t.children.slice(d),e.children.slice(g),d,g),n}findListItemIndexForSuggestionBridge(t,e){if(!e)return-1;if(e.id){const o=t.findIndex(r=>r.id===e.id);if(o!==-1)return o}const n=this.getListItemSignatureForSuggestionBridge(e);return t.findIndex(o=>this.getListItemSignatureForSuggestionBridge(o)===n)}buildListSuggestionChange(t,e,n,o,r){const i=this.sanitizePreviewBlock(t),a=this.sanitizePreviewBlock(e),l=r?this.cloneSuggestionSnapshot(r):null;if(o.kind==="insert"){const g=this.cloneSuggestionSnapshot(l??i),u=this.cloneSuggestionSnapshot(o.afterItem),f=this.findListItemIndexForSuggestionBridge(g.children,a.children[o.afterIndex-1]),h=this.findListItemIndexForSuggestionBridge(g.children,a.children[o.afterIndex+1]);let p=Math.min(o.afterIndex,g.children.length);return o.afterIndex===0?p=0:f!==-1?p=f+1:h!==-1&&(p=h),g.children.splice(p,0,{...u,structuralSuggestionId:n,structuralSuggestionKind:"insert",structuralSuggestionLabel:"Insert"}),{liveBlock:g,label:"Insert",listItemSuggestion:{kind:"insert",afterItem:this.cloneSuggestionSnapshot(u)}}}if(o.kind==="delete"){const g=this.cloneSuggestionSnapshot(l??i),u=this.findListItemIndexForSuggestionBridge(g.children,o.beforeItem);if(u!==-1){const f=g.children[u];return g.children[u]={...f,structuralSuggestionId:n,structuralSuggestionKind:"delete",structuralSuggestionLabel:"Delete"},{liveBlock:g,acceptedBlock:this.cloneSuggestionSnapshot(a),label:"Delete",listItemSuggestion:{kind:"delete",beforeItem:this.cloneSuggestionSnapshot(o.beforeItem)}}}}if(o.kind!=="change")return null;const c=this.cloneSuggestionSnapshot(l??i),d=this.findListItemIndexForSuggestionBridge(c.children,o.beforeItem);return d!==-1?(c.children[d]={...this.cloneSuggestionSnapshot(o.afterItem),structuralSuggestionId:n,structuralSuggestionKind:"change",structuralSuggestionLabel:"Change"},{liveBlock:c,label:"Change",listItemSuggestion:{kind:"change",beforeItem:this.cloneSuggestionSnapshot(o.beforeItem),afterItem:this.cloneSuggestionSnapshot(o.afterItem)}}):null}applyGranularListSuggestionChanges(t){const e=this.sanitizePreviewBlock(t.before),n=this.sanitizePreviewBlock(t.after);if(!Bo(e,n))return!1;const o=this.computeListSuggestionBridgeOperations(e,n);if(o.length===0)return!1;let r=this.cloneSuggestionSnapshot(t.currentLiveBlock??e),i=!1;const a=[],l=[];for(let c=0;c<o.length;c++){const d=c===0?t.suggestionId:gt(),g=o[c];if(g.kind==="change"&&this.host.canBridgeListItemChangeAsInline(g.beforeItem,g.afterItem)){const f=this.findListItemIndexForSuggestionBridge(r.children,g.beforeItem);if(f===-1)return!1;l.push({suggestionId:d,itemIndex:f,beforeItem:this.cloneSuggestionSnapshot(g.beforeItem),afterItem:this.cloneSuggestionSnapshot(g.afterItem),formatOnly:this.host.getListItemPlainText(g.beforeItem)===this.host.getListItemPlainText(g.afterItem)});continue}const u=this.buildListSuggestionChange(e,n,d,g,r);if(!u?.listItemSuggestion)return!1;r=u.liveBlock,i=!0,a.push({id:d,type:"block-change",blockId:t.blockId,beforeBlock:this.cloneSuggestionSnapshot(e),acceptedBlock:u.acceptedBlock?this.cloneSuggestionSnapshot(u.acceptedBlock):void 0,listItemSuggestion:{kind:u.listItemSuggestion.kind,beforeItem:u.listItemSuggestion.beforeItem?this.cloneSuggestionSnapshot(u.listItemSuggestion.beforeItem):void 0,afterItem:u.listItemSuggestion.afterItem?this.cloneSuggestionSnapshot(u.listItemSuggestion.afterItem):void 0},label:u.label,createdAt:t.createdAt})}if(i){for(const c of a){const d=r.children.find(g=>g.structuralSuggestionId===c.id);d&&(d.structuralSuggestionRecord=JSON.stringify(this.normalizeLiveSuggestionRecord(c)))}if(!this.host.replaceBlockByIdWithoutSelection(t.blockId,r))return!1}this.host.transact(()=>{for(const c of a)this.saveLiveSuggestion(c)});for(const c of l){const d=this.host.getListItemPlainText(c.afterItem);let g;if(c.formatOnly){const u=this.host.extractTextNodesForRange(c.afterItem,0,d.length);g=this.applyBridgeInlineFormatSuggestion({suggestionId:c.suggestionId,blockId:t.blockId,itemIndex:c.itemIndex,start:0,end:d.length,targetAttributes:{},targetTextNodes:u,createdAt:t.createdAt})}else{const u=this.host.getListItemPlainText(c.beforeItem),f=En(u,d).diffs;let h=0,p=0;g=!0;for(let m=0;m<f.length&&g;m++){const[y,b]=f[m];if(y===0){g=this.applyBridgeInlineFormatSuggestion({suggestionId:gt(),blockId:t.blockId,itemIndex:c.itemIndex,start:p,end:p+b.length,targetAttributes:{},targetTextNodes:this.host.extractTextNodesForRange(c.afterItem,h,h+b.length),createdAt:t.createdAt}),h+=b.length,p+=b.length;continue}if(y===-1){const k=f[m+1];if(k&&k[0]===1){const S=this.host.extractTextNodesForRange(c.afterItem,h,h+k[1].length);g=this.applyBridgeInlineTextSuggestion({suggestionId:c.suggestionId,blockId:t.blockId,itemIndex:c.itemIndex,start:p,deleteLength:b.length,insertNodes:S,label:"Replace",createdAt:t.createdAt}),p+=b.length+k[1].length,h+=k[1].length,m++}else g=this.applyBridgeInlineTextSuggestion({suggestionId:c.suggestionId,blockId:t.blockId,itemIndex:c.itemIndex,start:p,deleteLength:b.length,insertNodes:[],label:"Replace",createdAt:t.createdAt}),p+=b.length}else{const k=this.host.extractTextNodesForRange(c.afterItem,h,h+b.length);g=this.applyBridgeInlineTextSuggestion({suggestionId:c.suggestionId,blockId:t.blockId,itemIndex:c.itemIndex,start:p,deleteLength:0,insertNodes:k,label:"Replace",createdAt:t.createdAt}),p+=b.length,h+=b.length}}}if(!g)return!1}return a.length>0||l.length>0}applyBridgeInlineTextSuggestion(t){const e=this.getYTextForSuggestionSpan({blockId:t.blockId,itemIndex:t.itemIndex});if(!e)return!1;let n=!1;return this.host.transact(()=>{let o=t.start;if(t.deleteLength>0){const i=this.applySuggestedDeletionToTextRange(e,t.start,t.deleteLength,t.suggestionId);o=t.start+i.retainedLength,n=n||i.changed}let r=o;for(const i of t.insertNodes){if(!i.text)continue;const a=this.buildSuggestionInsertionMarks(this.sanitizePreviewMarks(i.marks),t.suggestionId,t.label,t.createdAt);lt(e,r,i.text,a),r+=i.text.length,n=!0}}),n}applyBridgeInlineFormatSuggestion(t){const e=this.getYTextForSuggestionSpan({blockId:t.blockId,itemIndex:t.itemIndex});if(!e||t.end<=t.start)return!1;const n=t.end-t.start,o=this.host.collectOverlappingTextSpans(e,t.start,n);if(o.length===0||t.targetTextNodes&&t.targetTextNodes.reduce((d,g)=>d+g.text.length,0)!==n)return!1;const r=[];let i=t.start;const a=t.targetTextNodes?t.targetTextNodes.map(d=>({length:d.text.length,marks:d.marks})):[{length:n,marks:t.targetAttributes}];let l=0;for(const d of a){const g=i+d.length;for(;l<o.length&&o[l].start+o[l].length<=i;)l++;for(let u=l;u<o.length&&o[u].start<g;u++){const f=o[u],h=Math.max(f.start,i),p=Math.min(f.start+f.length,g);if(p<=h)continue;const m=t.targetTextNodes?mi(f.attributes,d.marks):{...d.marks??{}};r.push({...f,start:h,length:p-h,targetAttributes:m})}i=g}const c=[];return this.host.transact(()=>{for(const d of r){const g={formatChange:!0,...this.buildInlineSuggestionMetadataMarks(t.suggestionId,"Format",t.createdAt)},u=new Set([...Object.keys(d.attributes||{}),...Object.keys(d.targetAttributes)]);if(u.delete("insertion"),u.delete("deletion"),u.delete("suggestionId"),u.delete("formatChange"),u.delete("suggestionSource"),u.delete("suggestionAuthorType"),u.delete("suggestionCreatedAt"),u.delete("suggestionLabel"),u.delete("suggestionCommentThreadId"),u.delete("suggestionAuthorName"),u.delete("suggestionAgentModel"),u.delete("suggestionAgentConversationId"),u.delete("suggestionAgentRequestId"),u.delete("suggestionAgentTurn"),u.delete("suggestionPriorAttributes"),u.delete("layeredInsertion"),u.delete("proposalId"),u.delete("toolCallId"),u.delete("toolType"),![...u].every(f=>(d.attributes?.[f]??null)===(d.targetAttributes[f]??null))){c.push(d);for(const f of u)Object.prototype.hasOwnProperty.call(d.targetAttributes,f)?g[f]=d.targetAttributes[f]:g[f]=null;at(e,d.start,d.length,{...g,suggestionPriorAttributes:Ue(d.attributes)})}}c.length!==0&&this.saveLiveSuggestion({id:t.suggestionId,type:"inline-format",spans:c.map(d=>({blockId:t.blockId,itemIndex:t.itemIndex,start:d.start,end:d.start+d.length,attributes:d.attributes})),label:"Format",createdAt:t.createdAt})}),!0}insertBlockRelativeWithSuggestion(t){const e=t.batchInsertedBlocks?.get(t.referenceId),n=e||ot(this.host.ydoc,t.referenceId),o=t.referenceId===Ve;if(!n&&!o)return!1;const r=n?.yParent??this.host.getYContentFragment(),i=n?.index??0,a=this.sanitizePreviewBlock(t.block),l=a.id||G();let c=null;this.host.transact(()=>{const g=this.host.blockToYjsElement({...a,id:l});c=g,g.setAttribute("id",l),this.markInsertedBlockElement(g,t.suggestionId,t.label);const u=o?r.length:t.position==="before"?i:i+1;r.insert(u,[g]),t.batchInsertedBlocks?.set(l,{yBlock:g,yParent:r,index:u})});const d=this.host.ensureTrailingParagraph();return this.host.transact(()=>{this.saveLiveSuggestion({id:t.suggestionId,type:"block-insert",blockId:l,label:t.label,createdAt:t.createdAt,cleanupTrailingParagraphId:d??void 0},c??void 0)}),!0}applyBridgeBlockDeleteSuggestion(t){const e=Z(this.host.ydoc,t.blockId);if(!(e instanceof I.XmlElement))return!1;const n=this.host.getTrailingCleanupParagraphIdForTopLevelBlock(this.host.getDocument(),t.blockId);return this.host.transact(()=>{this.markDeletedBlockElement(e,t.suggestionId,t.label),this.saveLiveSuggestion({id:t.suggestionId,type:"block-delete",blockId:t.blockId,beforeBlock:this.cloneSuggestionSnapshot(t.beforeBlock),label:t.label,createdAt:t.createdAt,cleanupTrailingParagraphId:n??void 0})}),!0}applyBridgeBlockChangeSuggestion(t){const e=this.sanitizePreviewBlock(t.beforeBlock),n=this.sanitizePreviewBlock(t.afterBlock),o=e.type==="list"||e.type==="table"?W(this.host.getDocument(),t.blockId):null;let r=this.markBlockForGenericSuggestionChange(n,t.suggestionId,t.label),i,a,l=null,c=t.label;if(e.type==="paragraph"&&n.type==="paragraph"&&Ot(e)!==Ot(n))r=this.host.buildParagraphReplacementLiveBlock(e,n,t.suggestionId,t.label),i=n;else if(e.type==="paragraph"&&n.type==="paragraph")i=n;else if(e.type==="list"&&n.type==="list"){if(!t.optimizeFormatting&&this.applyGranularListSuggestionChanges({blockId:t.blockId,before:e,after:n,suggestionId:t.suggestionId,currentLiveBlock:o?.type==="list"?o:void 0,createdAt:t.createdAt}))return!0;r={...n,structuralSuggestionId:t.suggestionId,structuralSuggestionKind:"change",structuralSuggestionLabel:"List"},i=n,c="List"}else if(e.type==="table"&&n.type==="table"&&o?.type==="table"&&(l=this.buildTablePropertyOnlyChange(t.blockId,o,e,n,t.suggestionId)))r=l.liveBlock,a=l.record,c=l.label;else if(e.type==="table"&&n.type==="table"){const d=W(this.createLiveSuggestionProjection("accept").doc,t.blockId),g=d?.type==="table"?d:e,u=this.reconcileTableDescendantIds(g,n),f=He(e,u),h=f?null:this.buildSuggestedTableChange(g,u,t.suggestionId),p=h||f?null:this.decomposeTableRowAndCellChanges(g,u,t.suggestionId,t.label);if(p)r=p.liveBlock,a=p.record,c=p.record?.label??t.label;else if(h)r=(o?.type==="table"&&!this.tableHasPendingStructure(t.blockId)&&this.buildTableStructureChange(g,u,t.suggestionId)?this.graftTableStructureChange(o,h.record,u):null)??(o?.type==="table"?this.mergePendingTableRevisionState(o,h.liveBlock):h.liveBlock),a=h.record,c=h.label;else if(!this.hasSameTableGeometry(g,u)||f||He(g,u))r=this.markBlockForGenericSuggestionChange(u,t.suggestionId,"Table"),i=u,c="Change";else{if(o?.type==="table"&&this.collectNestedSuggestionIdsForBlock(t.blockId,t.suggestionId).length>0)return!0;r={...this.cloneSuggestionSnapshot(u),diffState:"insert",suggestionId:t.suggestionId}}}if(t.optimizeFormatting&&e.type==="paragraph"&&n.type==="paragraph"&&Ot(e)===Ot(n)){const d=this.batchYBlockLocationsById?.get(t.blockId)?.yBlock??Z(this.host.ydoc,t.blockId),g=d?d._item:null,u=d?ct(d):null;if(d&&u&&!g?.deleted){const f=new Set(["insertion","deletion","suggestionId","formatChange","suggestionSource","suggestionAuthorType","suggestionCreatedAt","suggestionLabel","suggestionCommentThreadId","suggestionAuthorName","suggestionAgentModel","suggestionAgentConversationId","suggestionAgentRequestId","suggestionAgentTurn","suggestionPriorAttributes","layeredInsertion","proposalId","toolCallId","toolType"]),h=[];let p=0,m=!1;for(const y of n.children){if(y.type!=="text"||y.text.length===0)continue;const b=this.sanitizePreviewMarks(y.marks)??{},k=this.host.collectOverlappingTextSpans(u,p,y.text.length);m||(m=k.some(S=>["insertion","deletion","suggestionId","formatChange"].some(v=>Object.prototype.hasOwnProperty.call(S.attributes,v)))),h.push({targetAttributes:b,spans:k}),p+=y.text.length}if(!m)return this.host.transact(()=>{Zt(d,r);for(const{targetAttributes:y,spans:b}of h)for(const k of b){const S=new Set([...Object.keys(k.attributes??{}),...Object.keys(y)]),v={formatChange:!0,...this.buildInlineSuggestionMetadataMarks(t.suggestionId,"Format",t.createdAt)};for(const x of S)f.has(x)||(v[x]=Object.prototype.hasOwnProperty.call(y,x)?y[x]:null);v.suggestionPriorAttributes=Ue(k.attributes),at(u,k.start,k.length,v)}this.saveLiveSuggestion({id:t.suggestionId,type:"block-change",blockId:t.blockId,beforeBlock:this.cloneSuggestionSnapshot(e),acceptedBlock:this.cloneSuggestionSnapshot(n),label:c,createdAt:t.createdAt},d)}),!0}}if(e.type==="paragraph"&&n.type==="paragraph"&&JSON.stringify(e.children)===JSON.stringify(n.children)){const d=this.batchYBlockLocationsById?.get(t.blockId),g=d?d.yBlock._item:null;if(d&&!g?.deleted)return Zt(d.yBlock,r),this.saveLiveSuggestion({id:t.suggestionId,type:"block-change",blockId:t.blockId,beforeBlock:this.cloneSuggestionSnapshot(e),acceptedBlock:this.cloneSuggestionSnapshot(n),label:c,createdAt:t.createdAt},d.yBlock),!0}return this.host.replaceBlockByIdWithoutSelection(t.blockId,r,e.type==="paragraph"?this.batchYBlockLocationsById?.get(t.blockId):void 0)?(this.host.transact(()=>{a?this.saveLiveSuggestion({...a,label:c,createdAt:t.createdAt}):this.saveLiveSuggestion({id:t.suggestionId,type:"block-change",blockId:t.blockId,beforeBlock:this.cloneSuggestionSnapshot(e),acceptedBlock:i?this.cloneSuggestionSnapshot(i):void 0,label:c,createdAt:t.createdAt})}),!0):!1}sortBlockSuggestionPlansByDependency(t){if(t.length<=1)return t;const e=[],n=new Set,o=[...t],r=new Set(o.flatMap(i=>[i.blockId,...i.producedBlockIds??[]]).filter(i=>!!i));for(;o.length>0;){let i=!1;for(let a=0;a<o.length;a++){const l=o[a],c=l.insertReferenceId;if(!(c&&r.has(c)&&!n.has(c))){e.push(l),l.blockId&&n.add(l.blockId),l.producedBlockIds?.forEach(d=>n.add(d)),o.splice(a,1),i=!0;break}}if(!i){e.push(...o);break}}return e}buildAgentSuggestionPlanFromProposal(t,e,n,o,r,i,a,l=!1,c=!1){const d=e.getSuggestion(t);if(!d)return null;const g=r??d.createdAt;if(d.blockSequencePreview){const{blockId:v,blocks:x}=d.blockSequencePreview,w=W(n,v);return!w||x.length===0?null:{proposalId:t,category:"block",blockId:v,producedBlockIds:x.map(A=>A.id),apply:()=>{const A=ot(this.host.ydoc,v);if(!A)return!1;const P=x.map(T=>this.sanitizePreviewBlock(T));return this.host.transact(()=>{A.yParent.delete(A.index,1);const T=P.map(B=>this.host.blockToYjsElement(B));A.yParent.insert(A.index,T);for(const B of T)this.setElementStructuralSuggestion(B,"change",void 0,t,"Paragraph");const E=this.normalizeLiveSuggestionRecord({id:t,type:"block-change",blockId:P[0].id,beforeBlock:this.cloneSuggestionSnapshot(w),sequenceBlockIds:P.map(B=>B.id),label:"Paragraph",createdAt:g});this.saveLiveSuggestion(E,T[0]);for(const B of T.slice(1))this.embedLiveSuggestionRecordInTree(E,B)}),!0}}}if(d.blockPreview?.id){const v=W(n,d.blockPreview.id);if(!v)return null;const x=d.blockPreview;return{proposalId:t,category:"block",blockId:v.id,apply:()=>this.applyBridgeBlockChangeSuggestion({suggestionId:t,blockId:v.id,beforeBlock:v,afterBlock:x,optimizeFormatting:l,label:v.type==="paragraph"&&x.type==="paragraph"?Ot(v)===Ot(x)?"Format":"Replace":v.type==="table"?"Table":v.type==="list"?"List":"Change",createdAt:g})}}if(d.toolCallAction?.name==="insert_block"){const v=d.toolCallAction.arguments&&typeof d.toolCallAction.arguments=="object"?d.toolCallAction.arguments:null,x=typeof v?.referenceId=="string"?v.referenceId:null,w=v?.position==="before"||v?.position==="after"?v.position:null,A=typeof v?.content=="string"?v.content:Array.isArray(v?.content)&&typeof v?.content[0]=="string"?v?.content[0]:null;if(!x||!w||!A)return null;const P=Wn(d.toolCallAction),T=(P&&i?W(i,P):null)??it.fromAgentHtml(A,{existingDocument:n}).children[0];if(!T)return null;const E={...T,id:P||T.id||G()};return{proposalId:t,category:"block",blockId:E.id,insertReferenceId:x,apply:()=>this.insertBlockRelativeWithSuggestion({block:E,referenceId:x,position:w,suggestionId:t,label:"Insert",createdAt:g,batchInsertedBlocks:a})}}if(d.insertionContext){const v=this.host.resolvePositionAwareInsertionReference({baseDoc:n,mustBeAfter:d.insertionContext.mustBeAfter,mustBeBefore:d.insertionContext.mustBeBefore});return v?{proposalId:t,category:"block",blockId:d.insertionContext.paragraphId,insertReferenceId:v.referenceId,apply:()=>this.insertBlockRelativeWithSuggestion({block:{...this.cloneSuggestionSnapshot(d.insertionContext.content),id:d.insertionContext.content.id||d.insertionContext.paragraphId||G()},referenceId:v.referenceId,position:v.position,suggestionId:t,label:"Insert",createdAt:g,batchInsertedBlocks:a})}:null}const u=e.resolveAnchorsAgainstDoc(t,o),f=d.anchors?.[0]?.paragraphId??null,h=d.inlinePreview&&!d.toolCallAction?d.inlinePreview:null,p=h?{resolvedPreview:(d.anchors??[]).map(v=>({kind:v.kind,paragraphId:v.paragraphId,fromIndex:h.startOffset,toIndex:h.startOffset+h.newText.length,text:v.text})),previewAnchorBlock:null}:e.withMaterializedSuggestion(t,v=>({resolvedPreview:e.resolveAnchorsAgainstDoc(t,v),previewAnchorBlock:f?Bl(v,f):null}));if(!p)return null;const{resolvedPreview:m,previewAnchorBlock:y}=p;if(d.toolCallAction?.name==="remove_block"){const v=d.toolCallAction.arguments&&typeof d.toolCallAction.arguments=="object"?d.toolCallAction.arguments:null,x=typeof v?.id=="string"?v.id:null,w=x?W(n,x):null;return!x||!w?null:{proposalId:t,category:"block",blockId:x,apply:()=>this.applyBridgeBlockDeleteSuggestion({suggestionId:t,blockId:x,beforeBlock:w,label:"Delete",createdAt:g})}}const b=d.anchors?.[0],k=u[0],S=m[0];if(b?.paragraphId){const v=W(n,b.paragraphId);let x=v?.type==="table"&&i?W(i,v.id):null;v?.type==="table"&&x?.type==="table"&&this.hasSameTableGeometry(v,x)&&!He(v,x)&&(x={...x,children:x.children.map((T,E)=>({...T,children:T.children.map((B,N)=>({...B,children:v.children[E].children[N].children}))}))});const w=x??y;if(d.toolCallAction?.name==="replace_block"&&v&&w&&(v.type!=="paragraph"||w.type!=="paragraph"||this.host.paragraphReplaceShouldStayAtomic(v,w)))return{proposalId:t,category:"block",blockId:v.id,apply:()=>this.applyBridgeBlockChangeSuggestion({suggestionId:t,blockId:v.id,beforeBlock:v,afterBlock:w,optimizeFormatting:l,label:v.type==="paragraph"&&w.type==="paragraph"?Ot(v)===Ot(w)?"Format":"Replace":v.type==="table"?"Table":v.type==="list"?"List":"Change",createdAt:g})};if(v?.type==="paragraph"){const T=k?.fromIndex??k?.toIndex,E=b.previewStartOffset??S?.fromIndex??S?.toIndex;if(b.kind==="delete"){const B=T??E??0,N=b.text?.length??Math.max(0,(k?.toIndex??B)-B),R=Math.max(0,B-N);return{proposalId:t,category:"inline",blockId:v.id,start:R,inlinePriority:2,apply:()=>this.applyBridgeInlineTextSuggestion({suggestionId:t,blockId:v.id,start:R,deleteLength:N,insertNodes:[],label:"Delete",createdAt:g})}}if(b.kind==="insert"&&(h||w?.type==="paragraph")){const B=E??T??0,N=E??B,R=b.previewStartOffset!==void 0?N+(b.text?.length??0):S?.toIndex??N+(b.text?.length??0),M=b.previewTextNodes?b.previewTextNodes.map(O=>({...O,marks:O.marks?{...O.marks}:void 0})):h?this.buildInlinePreviewTextNodes(h):this.host.extractTextNodesForRange(w,N,R);return{proposalId:t,category:"inline",blockId:v.id,start:B,inlinePriority:0,apply:()=>this.applyBridgeInlineTextSuggestion({suggestionId:t,blockId:v.id,start:B,deleteLength:0,insertNodes:M,label:"Insert",createdAt:g})}}if(b.kind==="replace"&&(h||w?.type==="paragraph")){const B=E??T??0,N=E??B,R=b.previewStartOffset!==void 0?N+(b.text?.length??0):S?.toIndex??N+(b.text?.length??0),M=b.previewTextNodes?b.previewTextNodes.map(O=>({...O,marks:O.marks?{...O.marks}:void 0})):h?this.buildInlinePreviewTextNodes(h):this.host.extractTextNodesForRange(w,N,R);return b.oldText===b.text?{proposalId:t,category:"inline",blockId:v.id,start:B,inlinePriority:1,apply:()=>this.applyBridgeInlineFormatSuggestion({suggestionId:t,blockId:v.id,start:B,end:B+(b.text?.length??0),targetAttributes:{},targetTextNodes:M,createdAt:g})}:{proposalId:t,category:"inline",blockId:v.id,start:B,inlinePriority:2,apply:()=>this.applyBridgeInlineTextSuggestion({suggestionId:t,blockId:v.id,start:B,deleteLength:b.oldText?.length??0,insertNodes:M,label:"Replace",createdAt:g})}}}if(v?.type==="list"&&w?.type==="list")return{proposalId:t,category:"block",blockId:v.id,apply:()=>this.applyBridgeBlockChangeSuggestion({suggestionId:t,blockId:v.id,beforeBlock:v,afterBlock:w,optimizeFormatting:!c&&(l||b.oldText===b.text),label:"List",createdAt:g})};const A=v?.type,P=w?.type;if(A==="list-item"&&P==="list-item"){const T=v,E=w,B=Xt(n,T.id)?.children.find(N=>N?.type!=="list"?!1:N.children.some(R=>R.id===T.id));if(B?.id){const N=B.children.findIndex(R=>R.id===T.id);if(N!==-1){const R=this.cloneSuggestionSnapshot(B),M=this.cloneSuggestionSnapshot(B);return M.children[N]=this.cloneSuggestionSnapshot(E),{proposalId:t,category:"block",blockId:B.id,apply:()=>{const O=W(this.host.getDocument(),B.id);return this.applyGranularListSuggestionChanges({blockId:B.id,before:R,after:M,suggestionId:t,currentLiveBlock:O?.type==="list"?O:void 0,createdAt:g})}}}}}if(v&&w)return{proposalId:t,category:"block",blockId:v.id,apply:()=>this.applyBridgeBlockChangeSuggestion({suggestionId:t,blockId:v.id,beforeBlock:v,afterBlock:w,optimizeFormatting:l,label:v.type==="table"?"Table":v.type==="paragraph"?"Format":"Change",createdAt:g})}}return null}describeAgentSuggestionApplyFailure(t,e,n,o){const r=e.getSuggestion(t.proposalId),i=(S,v)=>{const x=W(S,v);if(!x||x.id===v)return x;if(x.type==="list"){const w=x.children.find(A=>A.id===v);if(w)return w}return x},a=r?.toolCallAction,l=a?.arguments&&typeof a.arguments=="object"?a.arguments:null,c=typeof l?.id=="string"&&l.id.length>0?l.id:t.blockId,d=o?.find(S=>{const v=S.arguments&&typeof S.arguments=="object"?S.arguments:null,x=typeof v?.id=="string"&&v.id.length>0?v.id:null,w=x?i(n,x):null;if(!w)return!1;if(x===c)return!0;const A=typeof v?.find=="string"?v.find:"";return A.length>0&&Ot(w).includes(A)})??a,g=d?.name??"agent change",u=d?.arguments&&typeof d.arguments=="object"?d.arguments:null,f=typeof u?.id=="string"&&u.id.length>0?u.id:t.blockId,h=this.host.getDocument(),p=f?i(h,f):null,m=f?i(n,f):null,y=p??m,b=y?y.type:null,k=f?`'${f}'${typeof b=="string"?` (${b})`:""}`:"the requested target";return!p&&m?`Could not apply ${t.category} suggestion for ${g} to block ${k}: the target was present when the action was planned but is no longer available at replay time. The attempted change was rolled back; re-read that block and retry.`:y?`Could not apply ${t.category} suggestion for ${g} to block ${k}: the requested edit is not compatible with the target's current structure. The attempted change was rolled back; re-read the target and retry with a narrower edit or the containing block.`:`Could not apply ${t.category} suggestion for ${g}: the target block is unavailable at replay time. The attempted change was rolled back; re-read the document and retry.`}liveTextRuns(t){const e=[];let n=0;for(const o of st(t)){if(typeof o.insert!="string")return null;const r=o.attributes??{};e.push({start:n,text:o.insert,attrs:r,hidden:!!r.deletion}),n+=o.insert.length}return e}visibleLiveChars(t){const e=this.liveTextRuns(t);if(!e)return null;const n=[],o=[];let r="";for(const i of e)if(!i.hidden){for(let a=0;a<i.text.length;a++)n.push(i.start+a),o.push(i.attrs);r+=i.text}return{offsets:n,attrs:o,text:r}}static formattingMarks(t){const e={};for(const[n,o]of Object.entries(t??{}))ho.has(n)||o==null||(e[n]=o);return e}static sliceTextNodes(t,e,n){const o=[];let r=0;for(const i of t){const a=Math.max(e,r),l=Math.min(n,r+i.text.length);l>a&&o.push({...i,text:i.text.slice(a-r,l-r)}),r+=i.text.length}return o}static textOf(t){return t.map(e=>e.text).join("")}static onlyTextNodes(t){return t?.type!=="paragraph"?null:t.children.every(e=>e.type==="text")?t.children:null}planLayeredParagraphText(t,e,n){const o=this.visibleLiveChars(t),r=ft.textOf(e),i=ft.textOf(n);if(!o||o.text!==r)return null;const a=y=>y.flatMap(b=>{const k=Pt(ft.formattingMarks(b.marks));return Array.from({length:b.text.length},()=>k)}),l=a(e),c=a(n),d=[],g=[],u=r===i?[[0,r]]:En(r,i).diffs;let f=0,h=0,p=null;const m=()=>{p&&(d.push({from:p.from,to:p.to,nodes:ft.sliceTextNodes(n,p.afterFrom,h)}),p=null)};for(const[y,b]of u){if(y===0){m();let k=-1;for(let S=0;S<=b.length;S++){const v=S<b.length&&l[f+S]!==c[h+S];v&&k<0&&(k=S),!v&&k>=0&&(g.push({from:f+k,to:f+S,nodes:ft.sliceTextNodes(n,h+k,h+S)}),k=-1)}f+=b.length,h+=b.length;continue}p??(p={from:f,to:f,afterFrom:h}),y<0?(f+=b.length,p.to=f):h+=b.length}return m(),{expected:r,text:d,format:g}}applyLayeredParagraphText(t,e,n){const o=Z(this.host.ydoc,t),r=o?ct(o):null;if(!r||this.visibleLiveChars(r)?.text!==e.expected)throw new Error("A paragraph with pending suggestions changed while this edit was applied.");let i=!1;const a=gt();for(const c of[...e.format].sort((d,g)=>g.from-d.from)){const d=this.visibleLiveChars(r);let g=c.from;for(const u of c.nodes){const f=ft.formattingMarks(this.sanitizePreviewMarks(u.marks)),h=g+u.text.length;for(;g<h;){const p=d.attrs[g];let m=g+1;for(;m<h&&d.attrs[m]===p&&d.offsets[m]===d.offsets[m-1]+1;)m++;const y=ft.formattingMarks(p),b={};for(const k of new Set([...Object.keys(y),...Object.keys(f)]))Pt(y[k]??null)!==Pt(f[k]??null)&&(b[k]=f[k]??null);if(Object.keys(b).length>0){const k=d.offsets[g],S=m-g;if(n||p.insertion||p.formatChange){let v={};if(n&&p.formatChange)try{const x=JSON.parse(p.suggestionPriorAttributes??"{}");for(const[w,A]of Object.entries(b))A===null?delete x[w]:x[w]=A;v={suggestionPriorAttributes:JSON.stringify(x)}}catch{v={}}at(r,k,S,{...b,...v})}else at(r,k,S,{...b,formatChange:!0,...this.buildInlineSuggestionMetadataMarks(a,"Format"),suggestionPriorAttributes:Ue(p)});i=!0}g=m}}if(n&&c.nodes.length>0){const u=this.visibleLiveChars(r),f=c.from>0?u.offsets[c.from-1]+1:0,h=c.to<u.offsets.length?u.offsets[c.to]:r.length,p=c.nodes.flatMap(m=>Array.from({length:m.text.length},()=>ft.formattingMarks(this.sanitizePreviewMarks(m.marks))));for(const m of this.liveTextRuns(r)??[]){if(!m.hidden||m.start<f||m.start+m.text.length>h)continue;let y=u.offsets.findIndex(v=>v>m.start);y<0&&(y=c.to-1);const b=p[Math.min(Math.max(y,c.from),c.to-1)-c.from],k=ft.formattingMarks(m.attrs),S={};for(const v of new Set([...Object.keys(k),...Object.keys(b)]))Pt(k[v]??null)!==Pt(b[v]??null)&&(S[v]=b[v]??null);Object.keys(S).length!==0&&(at(r,m.start,m.text.length,S),i=!0)}}}for(const c of[...e.text].sort((d,g)=>g.from-d.from)){const d=this.visibleLiveChars(r),g=gt(),u=c.to>0?d.offsets[c.to-1]+1:0;let f={};if(n){const m=c.from<c.to?d.attrs.slice(c.from,c.to):c.from>0&&c.from<d.attrs.length?[d.attrs[c.from-1],d.attrs[c.from]]:[],y=m[0];if(y?.insertion&&y.suggestionId&&m.every(b=>b.insertion&&!b.deletion&&b.suggestionId===y.suggestionId)){for(const[b,k]of Object.entries(y))(b==="insertion"||b==="layeredInsertion"||b.startsWith("suggestion"))&&(f[b]=k);delete f.suggestionPriorAttributes}}let h=u;for(const m of c.nodes){if(!m.text)continue;const y=this.sanitizePreviewMarks(m.marks)??{},b=n?{...y,...f}:this.buildSuggestionInsertionMarks(y,g,"Insert");lt(r,h,m.text,b),h+=m.text.length,i=!0}const p=[];for(let m=c.from;m<c.to;m++){const y=p[p.length-1];y&&y[0]+y[1]===d.offsets[m]?y[1]++:p.push([d.offsets[m],1])}for(const[m,y]of p.reverse())n?r.delete(m,y):this.applySuggestedDeletionToTextRange(r,m,y,g),i=!0}const l=[];for(const c of this.liveTextRuns(r)??[]){if(c.attrs.suggestionId!==a||!c.attrs.formatChange)continue;let d={};try{d=JSON.parse(c.attrs.suggestionPriorAttributes??"{}")}catch{d={}}l.push({blockId:t,start:c.start,end:c.start+c.text.length,attributes:d})}return l.length>0&&this.saveLiveSuggestion({id:a,type:"inline-format",label:"Format",spans:l}),i}static changedParagraphFields(t,e){const n=new Set(["children","id","type","diffState","suggestionId","structuralSuggestionId","structuralSuggestionKind","structuralSuggestionRole","structuralSuggestionLabel","structuralSuggestionRecord","structuralSuggestionRecords"]),o=t,r=e;return[...new Set([...Object.keys(o),...Object.keys(r)])].filter(i=>!n.has(i)&&Pt(o[i]??null)!==Pt(r[i]??null))}applyLayeredParagraphFields(t,e,n,o){const r=ft.changedParagraphFields(e,n);if(r.length===0)return!1;const i=Z(this.host.ydoc,t),a=W(this.host.getDocument(),t);if(!i||a?.type!=="paragraph")return!1;const l={...a,children:[]},c={...l};for(const u of r){const f=n[u],h=e[u];f===void 0?delete l[u]:l[u]=this.cloneSuggestionSnapshot(f),h===void 0?delete c[u]:c[u]=this.cloneSuggestionSnapshot(h)}if(o)return Zt(i,l),!0;const d=gt(),g=this.cloneSuggestionSnapshot(e.children);return Zt(i,this.markBlockForGenericSuggestionChange(l,d,"Format")),this.saveLiveSuggestion({id:d,type:"block-change",blockId:t,beforeBlock:{...c,children:g},acceptedBlock:{...l,children:g},label:"Format"},i),!0}static hasPendingInlineMarks(t){return t?.type==="paragraph"&&t.children.some(e=>{const n=e.marks;return!!n?.suggestionId&&!!(n.insertion||n.deletion||n.formatChange)})}static hasForeignPendingInlineMarks(t,e){return t.type==="paragraph"&&t.children.some(n=>{const o=n.marks,r=typeof o?.suggestionAuthorName=="string"?o.suggestionAuthorName.trim():"";return!!o?.suggestionId&&!!(o.insertion||o.deletion||o.formatChange)&&!!r&&r!==e})}planPendingListEdit(t,e,n,o,r,i,a,l){if(n?.type!=="list")return!1;if(!r&&this.host.docxRoundTripRequired&&o?.type==="list"&&(n.variant!==o.variant||(n.startNumber??1)!==(o.startNumber??1)||(n.numberingFormat??null)!==(o.numberingFormat??null)))return"numbering";const c=b=>({type:"paragraph",id:b.id,children:b.children}),d=e.children.filter(b=>ft.hasPendingInlineMarks(c(b)));if(o?.type==="list"){const b=new Set(o.children.map(x=>x.id)),k=new Set(n.children.map(x=>x.id)),S=n.children.filter(x=>b.has(x.id)),v=o.children.filter(x=>k.has(x.id));if(S.some((x,w)=>x.id!==v[w]?.id)){if(!(d.length===0&&!e.structuralSuggestionId&&e.children.every(w=>!w.structuralSuggestionId)))return"refuse";if(!r)return"reorder";a.add(t);for(const w of[...n.children,...o.children])a.add(w.id);const x=this.cloneSuggestionSnapshot(o);return l.push(()=>{if(!this.runWithoutSuggesting(()=>this.host.replaceBlockByIdWithoutSelection(t,x)))throw new Error("Could not reorder the list.");return!0}),!0}}if(d.length===0||!r&&!d.some(b=>ft.hasForeignPendingInlineMarks(c(b),i))||!o)return!1;if(o.type!=="list"||e.structuralSuggestionId||!Bo(n,o))return"refuse";const g=new Map(n.children.map(b=>[b.id,b])),u=new Map(o.children.map(b=>[b.id,b])),f=n.children.filter(b=>u.has(b.id)),h=o.children.filter(b=>g.has(b.id));if(f.some((b,k)=>b.id!==h[k]?.id))return"refuse";const p=[],m=[];for(const b of h){const k=g.get(b.id);if(Ut(k,b))continue;const S=e.children.find(A=>A.id===b.id);if(!S||S.structuralSuggestionId)return"refuse";if(ft.changedParagraphFields(k,b).length>0&&m.push({prior:k,item:b}),Ut(k.children,b.children))continue;const v=Z(this.host.ydoc,b.id),x=v?ct(v):null,w=x?this.planLayeredParagraphText(x,k.children,b.children):null;if(!w)return"refuse";p.push({itemId:b.id,plan:w})}const y=f.length!==n.children.length||h.length!==o.children.length;if(!y&&p.length===0&&m.length===0)return!1;a.add(t);for(const b of[...n.children,...o.children])a.add(b.id);return l.push(()=>{let b=!1;if(y){const k=W(this.host.getDocument(),t);if(k?.type!=="list")throw new Error("Could not apply the list edit.");const S={...n,children:n.children.map(x=>u.get(x.id)??x)},v=new Set(this.getLiveSuggestionIds());if(!this.applyGranularListSuggestionChanges({blockId:t,before:S,after:o,suggestionId:gt(),currentLiveBlock:k}))throw new Error("Could not apply the list edit.");for(const x of this.getLiveSuggestionIds()){if(v.has(x))continue;const w=this.getLiveSuggestion(x);if(w?.type!=="block-change"||w.listItemSuggestion?.kind!=="delete"||!w.listItemSuggestion.beforeItem)continue;const A=k.children.find(T=>T.id===w.listItemSuggestion.beforeItem.id);if(!A)continue;const P=this.cloneSuggestionSnapshot(A);delete P.structuralSuggestionId,delete P.structuralSuggestionKind,delete P.structuralSuggestionLabel,this.saveLiveSuggestion({...w,listItemSuggestion:{...w.listItemSuggestion,beforeItem:P}})}b=!0}for(const k of p)this.applyLayeredParagraphText(k.itemId,k.plan,r)&&(b=!0);for(const k of m)this.applyListItemFields(t,k.prior,k.item,r)&&(b=!0);return b}),!0}applyListItemFields(t,e,n,o){const r=ft.changedParagraphFields(e,n),i=Z(this.host.ydoc,n.id),a=W(this.host.getDocument(),t),l=a?.type==="list"?a.children.find(f=>f.id===n.id):void 0;if(!r.length||!i||!l)return!1;const c={...l,children:[]},d={...l,children:[]};for(const f of["structuralSuggestionId","structuralSuggestionKind","structuralSuggestionLabel","structuralSuggestionRecord"])delete c[f],delete d[f];for(const f of r){const h=n[f],p=e[f];h===void 0?delete c[f]:c[f]=this.cloneSuggestionSnapshot(h),p===void 0?delete d[f]:d[f]=this.cloneSuggestionSnapshot(p)}if(o)return Zt(i,c),!0;const g=gt(),u=this.normalizeLiveSuggestionRecord({id:g,type:"block-change",blockId:t,beforeBlock:{...a,children:[]},listItemSuggestion:{kind:"change",beforeItem:d,afterItem:c},label:"Format"});return Zt(i,{...c,structuralSuggestionId:g,structuralSuggestionKind:"change",structuralSuggestionLabel:"Format",structuralSuggestionRecord:JSON.stringify(u)}),this.saveLiveSuggestion(u),!0}planPendingParagraphEdits(t,e,n,o,r,i){const a=new Set,l=[],c=[],d=[],g=[],u=Ct(this.host.getDocument()),f=Ct(n),h=Ct(o),p=(k,S,v)=>{const x=k.get(v);if(!x)return null;const w=x.parentContainer,A=w?w.children:S.children;return A?{list:A,index:x.indexInParent}:null},m=k=>{const S=u.get(k)?.block;return S?.type==="paragraph"&&!S.structuralSuggestionId&&ft.hasPendingInlineMarks(S)&&(r||ft.hasForeignPendingInlineMarks(S,i))},y=k=>{const S=Z(this.host.ydoc,k);return S?ct(S):null},b=(k,S)=>{const v=S.get(k)?.block,x=u.get(k)?.block;return ft.onlyTextNodes(v)&&x?.type==="paragraph"&&!x.structuralSuggestionId?v:null};for(const k of new Set(t)){if(!a.has(k)&&u.get(k)?.block.type==="list"){const $=u.get(k).containerPath.some(L=>e.has(L))?!1:this.planPendingListEdit(k,u.get(k).block,f.get(k)?.block,h.get(k)?.block,r,i,a,l);if($==="refuse"&&c.push(k),$==="reorder"&&d.push(k),$==="numbering"&&g.push(k),$)continue}if(a.has(k)||!m(k)||u.get(k).containerPath.some($=>e.has($)))continue;const S=b(k,f);if(!S)continue;const v=h.get(k)?.block,x=y(k);if(!x)continue;if(v&&Ut(S,v)){a.add(k);continue}const w=p(f,n,k),A=v?p(h,o,k):null,P=($,L)=>{const D=b($,f),H=b(L,f),F=ft.onlyTextNodes(h.get($)?.block),X=y($),C=y(L);if(!D||!H||!F||h.has(L)||!X||!C||Z(this.host.ydoc,$)?.parent!==Z(this.host.ydoc,L)?.parent)return!1;const j=ft.textOf(F),U=ft.textOf(H.children);let z=0;for(;z<U.length&&z<j.length&&U[U.length-1-z]===j[j.length-1-z];)z++;if(z<U.trimStart().length)return!1;const tt=j.length-z,_=this.planLayeredParagraphText(X,D.children,ft.sliceTextNodes(F,0,tt)),V=this.planLayeredParagraphText(C,H.children,ft.sliceTextNodes(F,tt,j.length));if(!_||!V)return!1;const nt=h.get($).block;return a.add($),a.add(L),l.push(()=>{this.applyLayeredParagraphText($,_,r),this.applyLayeredParagraphText(L,V,r);const J=this.host.getDocument(),K=W(J,$),q=W(J,L),Q=Xt(J,$)??J;if(K?.type!=="paragraph"||q?.type!=="paragraph")throw new Error("Could not join the paragraphs.");const ut=this.getSuggestionMutationSelection(),yt=()=>this.host.mergeAdjacentParagraphs(K,q,{block:$,offset:ct(Z(this.host.ydoc,$)).length},{block:L,offset:0},Q,ut,ut),Lt=this.host.suggestingMode;this.host.suggestingMode=!r;try{if(!yt())throw new Error("Could not join the paragraphs.")}finally{this.host.suggestingMode=Lt}return this.applyLayeredParagraphFields($,D,nt,r),!0}),!0};if(!v){const $=w&&w.index>0?w.list[w.index-1]:null;if($&&!a.has($.id)&&P($.id,k))continue;!r&&!h.has(k)&&(a.add(k),l.push(()=>{const L=this.getSuggestionMutationSelection(),D=this.host.suggestingMode;this.host.suggestingMode=!0;try{if(!this.host.deleteBlockById(k,L,L))throw new Error("Could not remove the paragraph.")}finally{this.host.suggestingMode=D}return!0}));continue}if(v.type!=="paragraph")continue;const T=w&&w.index+1<w.list.length?w.list[w.index+1]:null;if(T&&!h.has(T.id)){a.has(T.id)||P(k,T.id);continue}const E=ft.onlyTextNodes(v);if(!E)continue;const B=A&&A.index+1<A.list.length?A.list[A.index+1]:null,N=B?ft.onlyTextNodes(B):null,R=ft.textOf(E),M=ft.textOf(S.children);if(B&&N&&!f.has(B.id)&&!u.has(B.id)&&R.length>0&&R.length<M.length&&R+ft.textOf(N)===M){const $=B.id,L=R.length;a.add(k),a.add($),l.push(()=>{const D=Z(this.host.ydoc,k),H=D?ct(D):null,F=H?this.visibleLiveChars(H):null;if(!F||F.text!==M)throw new Error("Could not split the paragraph.");const X=this.getSuggestionMutationSelection(),C=new Set(this.getLiveSuggestionIds()),j=this.host.suggestingMode;this.host.suggestingMode=!r;let U;try{U=this.host.splitParagraph({block:k,offset:F.offsets[L]},X)}finally{this.host.suggestingMode=j}const z=U&&U.block!==k?U.block:null,tt=z?Z(this.host.ydoc,z):null;if(!z||!tt)throw new Error("Could not split the paragraph.");tt.setAttribute("id",$);for(const _ of this.getLiveSuggestionIds()){if(C.has(_))continue;const V=this.getLiveSuggestion(_);V?.type==="paragraph-split"?this.saveLiveSuggestion({...V,insertedBlockId:$}):V?.type==="block-insert"&&this.saveLiveSuggestion({...V,blockId:$})}return!0});continue}const O=this.planLayeredParagraphText(x,S.children,E);O&&(a.add(k),l.push(()=>{const $=this.applyLayeredParagraphText(k,O,r);return this.applyLayeredParagraphFields(k,S,v,r)||$}))}return{owned:a,apply:l,refused:c,reordered:d,numbering:g}}tableKeepsLiveCells(t,e,n){const o=W(e,t),r=W(n,t);return o?.type==="table"&&r?.type==="table"&&!this.tableHasPendingStructure(t)&&(!rn(o,r)||!!this.buildTableStructureChange(o,r,"probe"))}applyValidatedAgentActionsAsSuggestions(t){const e=this.host.tryCancelInsertedBlockForRemoveAction(t.processedActions,t.docBeforeToolCall);if(e)return e;const n=!!t.processedActions?.length&&t.processedActions.every(C=>C.name==="style_blocks"),o=new qr(t.baseFork,n),r=new Map;for(const{block:C}of Ct(t.docBeforeToolCall).values())C.type==="list"&&C.id&&r.set(C.id,C.children.map(j=>j.id));for(const C of this.getLiveSuggestionIds()){const j=this.getLiveSuggestion(C);j?.type==="block-change"&&j.sequenceBlockIds&&j.beforeBlock.id&&r.set(j.beforeBlock.id,this.getSequenceReplacementMembers(j).map(({yBlock:U})=>U.getAttribute("id")))}const i=Ur(t.validationFork,o,{...t.flattenOptions,precomputedLiveDocSchema:t.baseDocForSuggestions,precomputedCurrentDocSchema:t.baseDocForSuggestions,listUnwrapMemberIds:r,precomputedFinalDocSchema:t.docAfterToolCall,precomputedVisibleBeforeDocSchema:t.docBeforeToolCall}),a=t.validationAnchorsByAction.flat().filter(C=>C.kind==="replace"&&C.previewStartOffset!==void 0&&!!C.paragraphId);for(const C of a){const j=i.filter(U=>(o.getSuggestion(U)?.anchors??[]).some(z=>z.kind==="replace"&&z.paragraphId===C.paragraphId&&(z.oldText??"").includes(C.oldText??"")&&(z.text??"").includes(C.text??"")));if(j.length===1){const U=o.getSuggestion(j[0]),z=C.sourceFrom?I.createAbsolutePositionFromRelativePosition(I.decodeRelativePosition(C.sourceFrom),t.baseFork):null,tt=C.paragraphId?Z(t.baseFork,C.paragraphId):null,_=tt?ct(tt):null,V=_?st(_).map(nt=>typeof nt.insert=="string"?nt.insert:"").join(""):"";U&&z&&z.type===_&&V.slice(z.index,z.index+(C.oldText?.length??0))===(C.oldText??"")&&(U.anchors=[{...C,previewStartOffset:z.index}])}}const l=i.length>=100,c=Date.now(),d=C=>{l&&(`${i.length}${C}`,Date.now()-c)};if(d("flattened"),i.length===0)return this.tryRejectRevertedPendingSuggestions({actions:t.processedActions,validationAnchorsByAction:t.validationAnchorsByAction,baseDoc:t.baseDocForSuggestions,docAfterToolCall:t.docAfterToolCall})||{success:!1,error:"No changes detected - the document already has the content you specified. Make sure you are modifying the correct block and providing different content."};const g=t.baseDocForSuggestions,u=(t.processedActions??[]).map((C,j)=>{const U=C.arguments&&typeof C.arguments=="object"?C.arguments:null,z=typeof U?.comment=="string"?U.comment.trim():"";return{action:C,comment:z,anchors:t.validationAnchorsByAction[j]??[]}}).filter(({action:C,comment:j})=>(C.name==="replace"||C.name==="replace_all")&&j.length>0),f=new Map;for(const C of u){const j=C.anchors.flatMap(U=>{if(!U.from||!U.to||!U.paragraphId)return[];const z=I.createAbsolutePositionFromRelativePosition(I.decodeRelativePosition(U.from),t.validationFork),tt=I.createAbsolutePositionFromRelativePosition(I.decodeRelativePosition(U.to),t.validationFork);if(!z||!tt||z.type!==tt.type)return[];const _=U.oldText??"",V=U.text??"";let nt=0;for(;nt<_.length&&nt<V.length&&_[nt]===V[nt];)nt++;let J=0;for(;J<_.length-nt&&J<V.length-nt&&_[_.length-1-J]===V[V.length-1-J];)J++;const K=_.length>V.length&&nt+J===V.length?z.index+nt:null;return[{paragraphId:U.paragraphId,start:z.index,end:tt.index,deletionPoint:K}]});f.set(C,j)}const h=new Map,p=i.map(C=>this.buildAgentSuggestionPlanFromProposal(C,o,g,t.baseFork,void 0,t.docAfterToolCall,h,t.optimizeStyleFormatting===!0,u.length>0)).filter(C=>!!C);if(d("built plans"),p.length!==i.length)return{success:!1,error:"Could not translate one or more agent changes into live suggestions."};const m=new Set;for(const C of p){if(C.category!=="block"||!C.blockId)continue;const j=W(this.host.getDocument(),C.blockId);j&&j.type!=="paragraph"&&!(j.type==="table"&&this.tableKeepsLiveCells(C.blockId,t.docBeforeToolCall,t.docAfterToolCall))&&m.add(C.blockId)}const y=t.directMode===!0&&u.length===0,b=t.agentName??Nt;for(const C of m){const j=W(this.host.getDocument(),C);if(!(j?.type!=="table"||!j.children.some(U=>U.children.some(z=>z.children.some(tt=>tt.type==="paragraph"&&ft.hasPendingInlineMarks(tt)&&(y||ft.hasForeignPendingInlineMarks(tt,b)))))))return sn("pending_table_changes",{subject:C,reason:this.tableHasPendingStructure(C)?"a pending row or column change":"merged cells or moved content"},{tableId:C})}const k=C=>[C.blockId,...C.producedBlockIds??[]].filter(j=>!!j),S=new Set(t.flattenOptions?.affectedBlockIds??[]);for(const C of p)for(const j of k(C))S.add(j);let v=this.planPendingParagraphEdits(S,m,t.docBeforeToolCall,t.docAfterToolCall,t.directMode===!0&&u.length===0,t.agentName??Nt);if(v.numbering.length>0)return sn("list_numbering_tracked_unsupported",{subject:v.numbering[0]},{listIds:v.numbering});if(v.reordered.length>0)return sn("list_reorder_unsupported",{subject:v.reordered[0]},{listIds:v.reordered});if(v.refused.length>0)return sn("pending_list_changes",{subject:v.refused[0]},{listIds:v.refused});p.some(C=>{const j=k(C);return j.some(U=>v.owned.has(U))&&!j.every(U=>v.owned.has(U))})&&(v={owned:new Set,apply:[],refused:[],reordered:[],numbering:[]});const x=C=>k(C).some(j=>v.owned.has(j));let w=!1;const A=this.sortBlockSuggestionPlansByDependency(p.filter(C=>C.category==="block"&&!x(C))),P=new Map(i.map((C,j)=>[C,j])),T=p.filter(C=>C.category==="inline"&&!x(C)).sort((C,j)=>{if(C.blockId&&j.blockId&&C.blockId===j.blockId){const U=(j.start??0)-(C.start??0);if(U!==0)return U;const z=(j.inlinePriority??0)-(C.inlinePriority??0);if(z!==0)return z}return(P.get(C.proposalId)??0)-(P.get(j.proposalId)??0)});let E=[];const B=this.host.beginRollbackScope();let N=null;try{d("applying plans"),E=this.withSuggestionMetadata({source:"agent",authorType:"ai",label:`${t.agentName??Nt} revision`,agentName:t.agentName??Nt,agentModel:t.agentModel,commentThreadId:t.commentThreadId,agentConversationId:t.agentConversationId,agentRequestId:t.agentRequestId,agentTurn:t.agentTurn,historyOrigin:`live-suggestions:${t.toolCallId}`},()=>this.host.transact(()=>{const C=new Set(Array.from(t.flattenOptions?.affectedBlockIds??[]));for(const z of p)z.blockId&&C.add(z.blockId);for(const z of v.owned)C.delete(z);N=A[0]??T[0]??null,this.resetTablePropertyRevisions(C,g,t.docAfterToolCall,t.docBeforeToolCall),this.resetLiveSuggestionsForBlocks(C,g),this.batchYBlockLocationsById=new Map;const j=new Map;for(const z of A){if(!z.blockId)continue;const tt=Z(this.host.ydoc,z.blockId);tt&&j.set(tt,z.blockId)}const U=new Map;for(const[z,tt]of j){const _=z.parent;if(!(_ instanceof I.XmlElement||_ instanceof I.XmlFragment))continue;const V=U.get(_)??new Map;V.set(z,tt),U.set(_,V)}for(const[z,tt]of U)z.toArray().forEach((_,V)=>{if(!(_ instanceof I.XmlElement))return;const nt=tt.get(_);nt&&this.batchYBlockLocationsById.set(nt,{yBlock:_,yParent:z,index:V})});try{for(const z of A)if(N=z,!z.apply())throw new Error("suggestion application returned false");for(const z of T)if(N=z,!z.apply())throw new Error("suggestion application returned false");N=null;for(const z of v.apply)z()&&(w=!0)}finally{this.batchYBlockLocationsById=null}d("finished plan loop"),N=null})).suggestionIds,d("applied plans"),B.dispose()}catch(C){B.revert();const j=C instanceof Error?C.message:"suggestion application failed",U=j==="suggestion application returned false"?null:j,z=N?this.describeAgentSuggestionApplyFailure(N,o,g,t.originalActions):null;return{success:!1,error:z?`${z}${U?` Detail: ${U}`:""}`:U??"Could not apply the requested edit."}}this.host.relinkCommentSuggestionIds();const R=u.length?this.host.getSuggestionCommentRanges(E):[],M=[],O=[];let $=0,L=0;const D=(C,j)=>C.flatMap(U=>j.flatMap(z=>{if(U.structural){if(z.paragraphId!==U.blockId)return[];const tt=Math.max(U.projectedStart,z.start),_=Math.min(U.projectedEnd,z.end);return _<tt||_===tt&&z.start!==z.end?[]:[{...U,start:U.start+tt-U.projectedStart,end:U.start+_-U.projectedStart}]}return(()=>{if(z.paragraphId!==U.blockId)return!1;const tt=U.projectedStart,_=U.projectedEnd;return tt===_&&z.start===z.end?tt===z.start:tt===_?z.deletionPoint===tt||z.start<tt&&tt<z.end:z.start===z.end?tt<z.start&&z.start<_:tt<z.end&&z.start<_})()?[U]:[]}));let H=null;for(const[C,j]of f){const U=D(R,j),z=Array.from(new Set(U.map(V=>V.suggestionId)));if(z.length===0&&j.length>0&&(H??(H=this.host.getSuggestionCommentRanges(this.getLiveSuggestionIds())),D(H,j).length===0)){L++;continue}if(z.length===0){$++;for(const V of E)M.includes(V)||M.push(V);continue}for(const V of z)M.includes(V)||M.push(V);const tt={author:t.agentName??Nt,authorType:"ai",agentName:t.agentName??Nt,agentModel:t.agentModel,suggestionId:z[0],...z.length>1?{relatedSuggestionIds:z}:{}},_=U.every(V=>V.structural&&V.start===V.end)?this.host.addBlockComment(U[0].blockId,C.comment,tt):this.host.addCommentToRanges(U.map(({blockId:V,start:nt,end:J})=>({blockId:V,start:nt,end:J})),C.comment,tt);_?O.push(_):$++}const F=cl(t.agentFeedback,t.originalActions,i,t.docBeforeToolCall,t.docAfterToolCall),X=E.length>0||w;return{success:X,planningSuggestionIds:i,suggestionIds:E,commentedSuggestionIds:M,attachedCommentIds:O,commentAttachmentFailureCount:$,commentOnRestoredTextCount:L,agentFeedback:X?F:void 0,error:X?void 0:"No changes detected - the document already has the content you specified. Make sure you are modifying the correct block and providing different content."}}captureLiveSuggestionApplicationSnapshot(){return{doc:this.cloneSuggestionSnapshot(this.host.getDocument()),liveSuggestions:Array.from(this.getLiveSuggestionStore().entries()).map(([t,e])=>[t,this.cloneSuggestionSnapshot(e)])}}restoreLiveSuggestionApplicationSnapshot(t){const e=this.host.getYContentFragment(),n=this.host.getYNotesFragment();this.host.transact(()=>{e.length>0&&e.delete(0,e.length),n.length>0&&n.delete(0,n.length)}),El(this.host.ydoc,t.doc),this.host.transact(()=>{const o=this.getLiveSuggestionStore();for(const r of Array.from(o.keys()))o.delete(r);for(const[r,i]of t.liveSuggestions)o.set(r,this.cloneSuggestionSnapshot(i))}),this.host.cachedDoc=this.cloneSuggestionSnapshot(t.doc),Rn(this.host.ydoc,this.host.cachedDoc),this.host.invalidateDerivedDocumentState()}tryRejectRevertedPendingSuggestions(t){const e=Array.from(new Set([...this.host.getActionTargetBlockIds(t.actions,t.baseDoc),...(t.validationAnchorsByAction??[]).flatMap(a=>a.map(l=>l?.paragraphId).filter(l=>typeof l=="string"&&l.length>0))]));if(e.length===0)return null;const n=this.host.getDocument(),o=new Set,r=[];for(const a of e){const l=W(n,a);l&&this.collectSuggestionIdsFromBlockValue(l,o);const c=W(t.baseDoc,a),d=W(t.docAfterToolCall,a);c&&d&&Ut(c,d)&&r.push(a)}if(o.size===0||r.length===0||this.rejectLiveSuggestions(Array.from(o))===0)return null;const i=r.length===1?`block ${r[0]}`:`${r.length} blocks`;return{success:!0,planningSuggestionIds:[],suggestionIds:[],agentFeedback:`Rejected pending suggestion changes for ${i}.`}}resetToolCallHistory(){this.host.toolCallHistory.clear()}getToolCallHistory(){return this.host.toolCallHistory.getAllToolCalls()}setToolCallHistory(t){this.host.toolCallHistory.clear();for(const e of t)this.host.toolCallHistory.getAllToolCalls().push(e)}getDetachedSuggestionStore(){return this.host.detachedSuggestionStore}hasSerializedDetachedSuggestions(t){return t?Object.keys(t.proposals||{}).length>0||Object.keys(t.metadata||{}).length>0:!1}rebuildDetachedSuggestionsFromSnapshot(t){const e=new qr(this.host.cloneYDoc(this.host.ydoc));return this.rebuildDetachedSuggestionsFromSnapshotWithStore(t,e)}rebuildDetachedSuggestionsFromSnapshotWithStore(t,e){const n=Eo(t);return Ur(n,e)}setDetachedSuggestionConversation(t,e){this.host.detachedSuggestionStore.setConversation(t,e)}clearLegacyDetachedSuggestionState(){const t=Array.from(this.host.detachedSuggestionStore.getAllSuggestions().keys());t.length>0&&this.host.detachedSuggestionStore.rejectSuggestions(t),Rr.clearAllStoredSuggestions(this.host.documentId)}migrateLegacyDetachedSuggestionsToLiveSuggestions(t){const e=this.host.cloneYDoc(this.host.ydoc),n=new qr(e);if(this.hasSerializedDetachedSuggestions(t.serverDetachedSuggestions)){const d=this.host.cloneYDoc(this.host.ydoc),g=new Rr(d,`${this.host.documentId}-legacy-proposal-materialization`,!0,t.conversationId);g.loadFromServerData(t.serverDetachedSuggestions);const u=Array.from(g.getPendingSuggestions().keys());if(u.length>0){const f=mt(g.materializeWithSuggestions(u));this.rebuildDetachedSuggestionsFromSnapshotWithStore(f,n)}}else t.legacyDetachedSuggestionSnapshot?.proposedDocument&&this.rebuildDetachedSuggestionsFromSnapshotWithStore(t.legacyDetachedSuggestionSnapshot.proposedDocument,n);const o=Array.from(n.getPendingSuggestions().keys());if(o.length===0)return{success:!1,migratedSuggestionCount:0,error:"No legacy proposals to migrate."};const r=mt(e),i=o.map(d=>this.buildAgentSuggestionPlanFromProposal(d,n,r,e,t.legacyCreatedAt)).filter(d=>!!d);if(i.length!==o.length)return{success:!1,migratedSuggestionCount:0,error:"Could not translate one or more legacy proposals into live suggestions."};const a=this.sortBlockSuggestionPlansByDependency(i.filter(d=>d.category==="block")),l=i.filter(d=>d.category==="inline").sort((d,g)=>d.blockId&&g.blockId&&d.blockId===g.blockId?(g.start??0)-(d.start??0):o.indexOf(d.proposalId)-o.indexOf(g.proposalId));let c=[];try{c=this.withSuggestionMetadata({source:"agent",authorType:"ai",createdAt:t.legacyCreatedAt,label:"Agent revision",agentName:Nt,historyOrigin:`migrated-legacy-proposals:${t.conversationId}`},()=>{for(const d of a)if(!d.apply())throw new Error(`Failed migrating block proposal ${d.proposalId}`);for(const d of l)if(!d.apply())throw new Error(`Failed migrating inline proposal ${d.proposalId}`)}).suggestionIds}catch(d){return{success:!1,migratedSuggestionCount:0,error:d instanceof Error?d.message:"Failed applying migrated live suggestions."}}return{success:c.length>0,suggestionIds:c,migratedSuggestionCount:o.length,error:c.length===0?"No legacy proposals were migrated.":void 0}}hydrateLegacyDetachedSuggestionSnapshotForConversation(t,e,n){if(!t||!e?.proposedDocument||this.host.detachedSuggestionStore.getConversationId()!==t||this.host.rebuiltMigrationSnapshotConversations.has(t))return 0;if(this.hasSerializedDetachedSuggestions(n))return this.host.rebuiltMigrationSnapshotConversations.add(t),0;const o=typeof e.pendingSuggestionCount=="number"?e.pendingSuggestionCount:0;try{const r=this.rebuildDetachedSuggestionsFromSnapshot(e.proposedDocument);return(r.length>0||o<=0)&&this.host.rebuiltMigrationSnapshotConversations.add(t),r.length}catch(r){return console.error("[DocumentMutator] Failed rebuilding detached changes from migration snapshot:",r),o<=0&&this.host.rebuiltMigrationSnapshotConversations.add(t),0}}setOnDetachedSuggestionsChanged(t){this.host.detachedSuggestionStore.setOnSuggestionsChanged(t)}}class yu{constructor(t){this.host=t}resolveListContext(t,e){const n=this.host.resolveEditableContext(t,e);if(!n||n.editable.block.type!=="list"||!n.yContext)return null;const o=[];for(let r=0;r<n.yContext.yBlock.length;r++){const i=n.yContext.yBlock.get(r);i instanceof I.XmlElement&&i.nodeName==="list-item"&&o.push(i)}return{doc:n.doc,list:n.editable.block,blockPath:n.editable.blockPath,yContext:n.yContext,yListItems:o}}convertParagraphToList(t,e,n){const o=this.host.getDocument().children[t];return o?.id?this.convertParagraphToListById(o.id,e,n):!1}convertParagraphToListById(t,e,n){const o=this.host.getDocument(),r=W(o,t);if(!r||r.type!=="paragraph")return!1;const i=this.host.suggestingMode?this.host.suggestionEngine.cloneSuggestionSnapshot(r):null,a=this.host.suggestingMode?gt():null,l=ot(this.host.ydoc,t);if(!l)return!1;const{yBlock:c,yParent:d,index:g}=l;this.host.transact(()=>{if(!(c instanceof I.XmlElement))return;const h=new I.XmlElement("list"),p=c.getAttribute("id")||G();h.setAttribute("id",p),h.setAttribute("variant",e),a&&this.host.suggestionEngine.setElementStructuralSuggestion(h,"change",void 0,a,"List"),n&&e==="ordered"?(h.setAttribute("startNumber",String(n)),this.host.listStartNumberCache.set(p,n)):e==="ordered"?(h.setAttribute("startNumber",String(1)),this.host.listStartNumberCache.set(p,1)):this.host.listStartNumberCache.delete(p);let m,y;for(let x=0;x<c.length;x++){const w=c.get(x);if(w instanceof I.XmlText){y=w;break}}if(y&&y.length>0){const x=st(y);for(const w of x)if(w.attributes?.fontFamily){m=w.attributes.fontFamily;break}}if(!m&&r.type==="paragraph"){for(const x of r.children)if(x.type==="text"&&x.marks?.fontFamily){m=x.marks.fontFamily;break}}const b=[],k=[],S=(x,w)=>{k.push({ops:x,plain:w})};if(y&&y.length>0){const x=st(y);let w=[],A="";const P=()=>{S(w,A),w=[],A=""};x.forEach(T=>{if(typeof T.insert=="string"){let E=T.insert;for(;E.length>0;){const B=E.indexOf(`
|
|
8
|
+
`);if(B===-1)E.length>0&&(w.push({insert:E,attributes:T.attributes&&Object.keys(T.attributes).length>0?{...T.attributes}:void 0}),A+=E),E="";else{const N=E.slice(0,B);N.length>0&&(w.push({insert:N,attributes:T.attributes&&Object.keys(T.attributes).length>0?{...T.attributes}:void 0}),A+=N),P(),E=E.slice(B+1)}}}else if(T.insert!==void 0&&T.insert!==null){let E=null;if(typeof T.insert=="string")E=T.insert;else try{E=JSON.stringify(T.insert)}catch{E=String(T.insert)}E&&E.length>0&&(w.push({insert:E,attributes:T.attributes&&Object.keys(T.attributes).length>0?{...T.attributes}:void 0}),A+=E)}}),P()}else k.push({ops:[],plain:""});k.length===0&&k.push({ops:[],plain:""});const v=rt(c,"direction");k.forEach(x=>{const w=new I.XmlElement("list-item");w.setAttribute("id",G()),e==="todo"&&w.setAttribute("checked","false"),(v==="rtl"||v==="ltr")&&w.setAttribute("direction",v);const A=new I.XmlText;if(k.length===1&&(e==="unordered"&&(x.plain==="-"||x.plain==="*")||e==="ordered"&&/^\d+\.$/.test(x.plain.trim())||e==="todo"&&(x.plain==="[]"||x.plain.trim()==="[]"))){const P=[...x.ops].reverse().find(E=>E.insert.length>0)?.attributes,T={...de(P)??{}};T.fontFamily||(T.fontFamily=m||jt),w.setAttribute("_emptyTextMarks",JSON.stringify(T))}else{let P=0;x.ops.forEach(({insert:T,attributes:E})=>{if(T.length===0)return;const B=E?{...E}:{};B.fontFamily||(m||console.warn("[DocumentMutator] convertParagraphToList: No font found, defaulting to Arial. This may indicate a bug."),B.fontFamily=m||jt),A.insert(P,T,B),P+=T.length})}w.insert(0,[A]),b.push(w)}),h.insert(0,b),d.delete(g,1),d.insert(g,[h]),this.host.suggestingMode&&a&&i&&this.host.suggestionEngine.saveLiveSuggestion({id:a,type:"block-change",blockId:t,beforeBlock:i,label:"List"})});const u={block:c.getAttribute("id")||t,offset:0};this.host.setSelectionAfterOperation({anchor:u,focus:u});const f=this.host.getDocument();return this.host.updateAfterOperationRelativeSelection(f),!0}setListDirectionById(t,e){const n=ot(this.host.ydoc,t);if(!n)return!1;const{yBlock:o}=n;return!(o instanceof I.XmlElement)||o.nodeName!=="list"?!1:(this.host.transact(()=>{for(let r=0;r<o.length;r++){const i=o.get(r);!(i instanceof I.XmlElement)||i.nodeName!=="list-item"||(e===null?et(i,"direction"):i.setAttribute("direction",e))}}),!0)}getListItemPlainText(t){return t.children.filter(e=>e.type==="text").map(e=>e.text).join("")}convertParagraphRangeToList(t,e,n){t>e&&([t,e]=[e,t]);const o=this.host.getDocument();if(t<0||e>=o.children.length||t>=o.children.length)return!1;const r=[];for(let i=t;i<=e;i++){const a=o.children[i];if(!a)return!1;if(a.type==="paragraph")r.push({type:"paragraph",node:a});else if(a.type==="list")r.push({type:"list",node:a});else return!1}return r.length===0?!1:(this.host.transact(()=>{const i=this.host.getYContentFragment(),a=i.get(t),l=a instanceof I.XmlElement?a.getAttribute("id"):void 0,c=new I.XmlElement("list"),d=l||G();c.setAttribute("id",d),c.setAttribute("variant",n),n==="ordered"?(c.setAttribute("startNumber",String(1)),this.host.listStartNumberCache.set(d,1)):this.host.listStartNumberCache.delete(d);const g=[];let u;for(const p of r){if(p.type==="paragraph"){for(const m of p.node.children)if(m.type==="text"&&m.marks?.fontFamily){u=m.marks.fontFamily;break}}else if(p.type==="list")for(const m of p.node.children){for(const y of m.children)if(y.type==="text"&&y.marks?.fontFamily){u=y.marks.fontFamily;break}if(u)break}if(u)break}let f=!1;const h=(p,m)=>{const y=new I.XmlElement("list-item");y.setAttribute("id",G()),n==="todo"&&y.setAttribute("checked",String(m?.checked??!1)),(m?.direction==="rtl"||m?.direction==="ltr")&&y.setAttribute("direction",m.direction);const b=new I.XmlText;let k=p;if((n==="unordered"&&(p==="-"||p==="*")||n==="ordered"&&/^\d+\.$/.test(p)||n==="todo"&&p==="[]")&&(k=""),k){const v=m?.fontFamily||u;v||console.warn("[DocumentMutator] convertParagraphRangeToList: No font found for list item, defaulting to Arial. This may indicate a bug."),b.insert(0,k,{fontFamily:v||jt})}const S=m?.indentLevel;typeof S=="number"&&S>0&&y.setAttribute("indentLevel",String(S)),y.insert(0,[b]),g.push(y),f=!0};r.forEach(p=>{if(p.type==="paragraph"){const m=p.node.children.filter(b=>b.type==="text").map(b=>b.text).join("");let y;for(const b of p.node.children)if(b.type==="text"&&b.marks?.fontFamily){y=b.marks.fontFamily;break}(m.length>0?m.split(`
|
|
9
|
+
`):[""]).forEach(b=>{h(b,{fontFamily:y,direction:p.node.direction})})}else{const m=p.node;m.children.forEach(y=>{const b=this.getListItemPlainText(y),k=m.variant==="todo"?y.checked??!1:void 0;let S;for(const v of y.children)if(v.type==="text"&&v.marks?.fontFamily){S=v.marks.fontFamily;break}h(b,{checked:k,indentLevel:y.indentLevel,fontFamily:S,direction:y.direction})})}}),f||h(""),c.insert(0,g),i.delete(t,e-t+1),i.insert(t,[c])}),!0)}convertListToParagraph(t){const e=this.host.getDocument().children[t];if(!e||e.type!=="list")return!1;const n=e;this.host.suggestingMode&&this.host.suggestionEngine.cloneSuggestionSnapshot(n);const o=this.host.suggestingMode?gt():null;n.id&&this.host.listStartNumberCache.delete(n.id),this.host.transact(()=>{const a=this.host.getYContentFragment(),l=a.get(t);if(!(l instanceof I.XmlElement))return;const c=[];for(let f=0;f<l.length;f++){const h=l.get(f);if(h instanceof I.XmlElement&&h.nodeName==="list-item"){let p=null;for(let m=0;m<h.length;m++){const y=h.get(m);if(y instanceof I.XmlText){p=y;break}}p?c.push({delta:st(p)}):c.push({delta:[]})}}const d=new I.XmlElement("paragraph");d.setAttribute("id",l.getAttribute("id")||G());{const f=n.children[0]?.direction;(f==="rtl"||f==="ltr")&&d.setAttribute("direction",f)}o&&this.host.suggestionEngine.setParagraphStructuralSuggestion(d,"change",void 0,o,"Paragraph");const g=new I.XmlText;let u=0;c.forEach((f,h)=>{f.delta.forEach(p=>{typeof p.insert=="string"&&(p.attributes&&Object.keys(p.attributes).length>0?g.insert(u,p.insert,p.attributes):g.insert(u,p.insert),u+=p.insert.length)}),h<c.length-1&&(g.insert(u,`
|
|
10
|
+
`),u+=1)}),d.insert(0,[g]),a.delete(t,1),a.insert(t,[d])});const r=this.host.getDocument(),i=r.children[t]?.id?this.host.cursorAtBlock(t,0,r):null;return i&&(this.host.setSelectionAfterOperation({anchor:i,focus:i}),this.host.updateAfterOperationRelativeSelection(r)),!0}updateListVariant(t,e,n){const o=this.host.getDocument().children[t];if(!o||o.type!=="list")return!1;const r=o,i=r.id||String(t),a=r.startNumber;return this.host.transact(()=>{const l=this.host.getYContentFragment().get(t);if(l instanceof I.XmlElement){if(l.setAttribute("variant",e),e==="ordered"){const c=l.getAttribute("startNumber"),d=c?parseInt(c,10):void 0,g=this.host.listStartNumberCache.get(i),u=n??a??d??g??1;l.setAttribute("startNumber",String(u)),this.host.listStartNumberCache.set(i,u)}else a!==void 0&&this.host.listStartNumberCache.set(i,a),l.removeAttribute("startNumber");for(let c=0;c<l.length;c++){const d=l.get(c);d instanceof I.XmlElement&&d.nodeName==="list-item"&&(e==="todo"?d.getAttribute("checked")===void 0&&d.setAttribute("checked","false"):d.removeAttribute("checked"))}}}),!0}convertListToParagraphById(t){const e=this.host.getDocument(),n=W(e,t);if(!n||n.type!=="list")return!1;const o=n,r=this.host.suggestingMode?this.host.suggestionEngine.cloneSuggestionSnapshot(o):null,i=this.host.suggestingMode?gt():null;o.id&&this.host.listStartNumberCache.delete(o.id);const a=ot(this.host.ydoc,t);if(!a)return!1;const{yBlock:l,yParent:c,index:d}=a;this.host.transact(()=>{if(!(l instanceof I.XmlElement))return;const f=[];for(let p=0;p<l.length;p++){const m=l.get(p);if(m instanceof I.XmlElement&&m.nodeName==="list-item"){let y=null;for(let k=0;k<m.length;k++){const S=m.get(k);if(S instanceof I.XmlText){y=S;break}}const b=m.getAttribute("direction");f.push({delta:y?st(y):[],...b==="rtl"||b==="ltr"?{direction:b}:{}})}}f.length===0&&f.push({delta:[]});const h=f.map((p,m)=>{const y=new I.XmlElement("paragraph");y.setAttribute("id",m===0?l.getAttribute("id")||G():G()),p.direction&&y.setAttribute("direction",p.direction),i&&this.host.suggestionEngine.setParagraphStructuralSuggestion(y,"change",void 0,i,"Paragraph");const b=new I.XmlText;let k=0;return p.delta.forEach(S=>{typeof S.insert=="string"&&(S.attributes&&Object.keys(S.attributes).length>0?b.insert(k,S.insert,S.attributes):b.insert(k,S.insert),k+=S.insert.length)}),y.insert(0,[b]),y});if(c.delete(d,1),c.insert(d,h),this.host.suggestingMode&&i&&r){const p=h.map(y=>y.getAttribute("id")),m={id:i,type:"block-change",blockId:p[0],beforeBlock:r,...p.length>1?{sequenceBlockIds:p}:{},label:"Paragraph"};this.host.suggestionEngine.saveLiveSuggestion(m,h[0]);for(const y of h.slice(1))this.host.suggestionEngine.embedLiveSuggestionRecordInTree(this.host.suggestionEngine.getLiveSuggestion(i)??m,y)}});const g={block:l.getAttribute("id")||t,offset:0};this.host.setSelectionAfterOperation({anchor:g,focus:g});const u=this.host.getDocument();return this.host.updateAfterOperationRelativeSelection(u),!0}updateListVariantById(t,e,n){const o=this.host.getDocument(),r=W(o,t);if(!r||r.type!=="list")return!1;const i=r,a=this.host.suggestingMode?this.host.suggestionEngine.cloneSuggestionSnapshot(i):null,l=i.id||t,c=i.startNumber,d=this.host.suggestingMode?gt():null,g=ot(this.host.ydoc,t);if(!g)return!1;const{yBlock:u}=g;return this.host.transact(()=>{if(u instanceof I.XmlElement){if(u.setAttribute("variant",e),d&&(this.host.suggestionEngine.clearElementStructuralSuggestion(u),this.host.suggestionEngine.setElementStructuralSuggestion(u,"change",void 0,d,"List")),e==="ordered"){const f=u.getAttribute("startNumber"),h=f?parseInt(f,10):void 0,p=this.host.listStartNumberCache.get(l),m=n??c??h??p??1;u.setAttribute("startNumber",String(m)),this.host.listStartNumberCache.set(l,m)}else c!==void 0&&this.host.listStartNumberCache.set(l,c),u.removeAttribute("startNumber");for(let f=0;f<u.length;f++){const h=u.get(f);h instanceof I.XmlElement&&h.nodeName==="list-item"&&(e==="todo"?h.getAttribute("checked")===void 0&&h.setAttribute("checked","false"):h.removeAttribute("checked"))}this.host.suggestingMode&&d&&a&&this.host.suggestionEngine.saveLiveSuggestion({id:d,type:"block-change",blockId:t,beforeBlock:a,label:"List"})}}),!0}continueListFromPrevious(t){const e=this.host.getDocument(),n=W(e,t);if(!n||n.type!=="list"||n.variant!=="ordered")return!1;const o=[],r=g=>{for(const u of g)if(u.type==="list")o.push(u);else if(u.type==="container"||u.type==="footnote")r(u.children);else if(u.type==="table")for(const f of u.children)for(const h of f.children)r(h.children)};r(e.children);const i=o.findIndex(g=>g.id===t);let a;for(let g=i-1;g>=0;g--)if(o[g].variant==="ordered"){a=o[g];break}if(i<0||!a)return!1;const l=ot(this.host.ydoc,t)?.yBlock,c=ot(this.host.ydoc,a.id)?.yBlock;if(!(l instanceof I.XmlElement)||!(c instanceof I.XmlElement))return!1;const d=a.numberingChainId??G();return this.host.transact(()=>{a.numberingChainId||c.setAttribute("numberingChainId",d),l.setAttribute("numberingChainId",d),l.removeAttribute("startNumber")}),!0}restartListNumberingAt(t,e,n=0){const o=this.host.getDocument(),r=W(o,t);if(!r||r.type!=="list"||r.variant!=="ordered"||!Number.isFinite(e)||e<1)return null;const i=r,a=Math.max(0,Math.min(Math.floor(n),i.children.length-1)),l=Math.floor(e),c=ot(this.host.ydoc,t);if(!c)return null;const{yBlock:d,yParent:g,index:u}=c;if(!(d instanceof I.XmlElement))return null;if(a===0)return this.host.transact(()=>{d.setAttribute("startNumber",String(l))}),this.host.listStartNumberCache.set(i.id,l),i.id;const f=G();return this.host.transact(()=>{const h=new I.XmlElement("list");h.setAttribute("id",f),h.setAttribute("variant",i.variant);const p=i.numberingChainId;p&&h.setAttribute("numberingChainId",p),i.numberingFormat&&h.setAttribute("numberingFormat",i.numberingFormat),h.setAttribute("startNumber",String(l)),i.lineSpacing!==void 0&&h.setAttribute("lineSpacing",String(i.lineSpacing)),h.insert(0,this.cloneYListItemRange(d,a)),d.delete(a,d.length-a),g.insert(u+1,[h])}),this.host.listStartNumberCache.set(f,l),f}cloneYListItemRange(t,e){const n=[];for(let o=e;o<t.length;o++){const r=t.get(o);if(!(r instanceof I.XmlElement)||r.nodeName!=="list-item")continue;const i=new I.XmlElement("list-item");i.setAttribute("id",r.getAttribute("id")||G());const a=r.getAttribute("checked");a!==void 0&&i.setAttribute("checked",a);const l=r.getAttribute("indentLevel");l!==void 0&&i.setAttribute("indentLevel",l);const c=rt(r,"direction");c!==void 0&&i.setAttribute("direction",c);let d=null;for(let u=0;u<r.length;u++){const f=r.get(u);if(f instanceof I.XmlText){d=f;break}}const g=new I.XmlText;if(d&&d.length>0){const u=st(d);let f=0;u.forEach(h=>{typeof h.insert=="string"&&(g.insert(f,h.insert,h.attributes||{}),f+=h.insert.length)})}i.insert(0,[g]),n.push(i)}return n}splitListItem(t,e){this.host.beforeOperationSelection=e;const n=this.host.getDocument(),o=W(n,t.block);if(!o||o.type!=="list")return null;const r=o,i=ie(t,this.host.ydoc,n);if(!i)return null;const a=I.createAbsolutePositionFromRelativePosition(i.textOffset,this.host.ydoc);if(!a||!(a.type instanceof I.XmlText))return null;const l=a.type,c=a.index,d=this.host.suggestingMode?this.host.suggestionEngine.cloneSuggestionSnapshot(r):null,g=this.host.suggestingMode?gt():null;let u=null,f=null,h=!0;if(this.host.transact(()=>{const p=ot(this.host.ydoc,r.id);if(!p)return;const{yBlock:m,yParent:y,index:b}=p;if(!(m instanceof I.XmlElement))return;const k=[];for(let L=0;L<m.length;L++){const D=m.get(L);D instanceof I.XmlElement&&D.nodeName==="list-item"&&k.push(D)}let S=-1;for(let L=0;L<k.length;L++){const D=k[L];for(let H=0;H<D.length;H++){const F=D.get(H);if(F instanceof I.XmlText&&F===l){S=L;break}}if(S!==-1)break}if(S===-1||S>=r.children.length)return;const v=k[S],x=r.children[S],w=x.children.map(L=>L.type==="text"?L.text:"").join(""),A=this.host.suggestingMode&&c<w.length&&(()=>{let L=0,D=!1;for(const H of x.children){if(H.type!=="text")continue;const F=L+H.text.length;if(F>c&&H.text.length>0&&(D=!0,!H.marks?.deletion))return!1;L=F}return D})();if(w.trim().length===0&&r.children.length===1){const L=new I.XmlElement("paragraph");u=G(),L.setAttribute("id",u),(x.direction==="rtl"||x.direction==="ltr")&&L.setAttribute("direction",x.direction),h=!1;let D;for(const F of x.children)if(F.type==="text"&&F.marks?.fontFamily){D=F.marks.fontFamily;break}D||(D=this.host.resolveFontFamilyForList(r)),D&&L.setAttribute("_emptyTextMarks",JSON.stringify({fontFamily:D}));const H=new I.XmlText;L.insert(0,[H]),y.delete(b,1),y.insert(b,[L]);return}if(w.trim().length===0&&r.children.length>1){const L=S===r.children.length-1,D=S===0;if(D||L){m.delete(S,1);const H=new I.XmlElement("paragraph");u=G(),H.setAttribute("id",u),(x.direction==="rtl"||x.direction==="ltr")&&H.setAttribute("direction",x.direction),h=!1;let F;for(const C of x.children)if(C.type==="text"&&C.marks?.fontFamily){F=C.marks.fontFamily;break}F||(F=this.host.resolveFontFamilyForList(r)),F&&H.setAttribute("_emptyTextMarks",JSON.stringify({fontFamily:F}));const X=new I.XmlText;H.insert(0,[X]),D?y.insert(b,[H]):y.insert(b+1,[H])}else{const H=r.children.length-S-1,F=new I.XmlElement("list");if(F.setAttribute("id",G()),F.setAttribute("variant",r.variant),r.variant==="ordered"){const z=r.numberingChainId??G();r.numberingChainId||m.setAttribute("numberingChainId",z),F.setAttribute("numberingChainId",z),r.numberingFormat&&F.setAttribute("numberingFormat",r.numberingFormat)}const X=new I.XmlElement("paragraph");u=G(),X.setAttribute("id",u),(x.direction==="rtl"||x.direction==="ltr")&&X.setAttribute("direction",x.direction),h=!1;let C;for(const z of x.children)if(z.type==="text"&&z.marks?.fontFamily){C=z.marks.fontFamily;break}C||(C=this.host.resolveFontFamilyForList(r)),C&&X.setAttribute("_emptyTextMarks",JSON.stringify({fontFamily:C}));const j=new I.XmlText;X.insert(0,[j]);const U=[];for(let z=S+1;z<k.length;z++){const tt=k[z],_=new I.XmlElement("list-item");_.setAttribute("id",tt.getAttribute("id")||G());const V=tt.getAttribute("checked");V!==void 0&&_.setAttribute("checked",V);const nt=tt.getAttribute("indentLevel");nt!==void 0&&_.setAttribute("indentLevel",nt);const J=rt(tt,"direction");J!==void 0&&_.setAttribute("direction",J);let K=null;for(let Q=0;Q<tt.length;Q++){const ut=tt.get(Q);if(ut instanceof I.XmlText){K=ut;break}}const q=new I.XmlText;if(K&&K.length>0){const Q=st(K);let ut=0;Q.forEach(yt=>{if(typeof yt.insert=="string"){const Lt=yt.attributes||{};q.insert(ut,yt.insert,Lt),ut+=yt.insert.length}})}_.insert(0,[q]),U.push(_)}F.insert(0,U),m.delete(S,H+1),y.insert(b+1,[X,F])}return}if(c===0){const L=new I.XmlElement("list-item"),D=G();L.setAttribute("id",D),u=D,r.variant==="todo"&&L.setAttribute("checked","false");const H=x.indentLevel??0;H>0&&L.setAttribute("indentLevel",String(H)),(x.direction==="rtl"||x.direction==="ltr")&&L.setAttribute("direction",x.direction);let F;for(const C of x.children)if(C.type==="text"&&C.marks?.fontFamily){F=C.marks.fontFamily;break}F||(F=this.host.resolveFontFamilyForList(r));const X=new I.XmlText;L.insert(0,[X]),F?L.setAttribute("_emptyTextMarks",JSON.stringify({fontFamily:F})):L.setAttribute("_emptyTextMarks",JSON.stringify({fontFamily:jt})),g&&(this.host.suggestionEngine.clearElementStructuralSuggestion(L),this.host.suggestionEngine.setElementStructuralSuggestion(L,"insert",void 0,g,"Insert")),m.insert(S,[L]),u=x.id??null,f=S+1;return}if(c>=w.length||A){const L=new I.XmlElement("list-item");u=G(),L.setAttribute("id",u),f=S+1,r.variant==="todo"&&L.setAttribute("checked","false");const D=x.indentLevel??0;D>0&&L.setAttribute("indentLevel",String(D)),(x.direction==="rtl"||x.direction==="ltr")&&L.setAttribute("direction",x.direction);let H=this.host.getFontAtOffsetInListItem(x,c);H||(H=this.host.resolveFontFamilyForList(r));const F=new I.XmlText;L.insert(0,[F]),H?L.setAttribute("_emptyTextMarks",JSON.stringify({fontFamily:H})):L.setAttribute("_emptyTextMarks",JSON.stringify({fontFamily:jt})),g&&(this.host.suggestionEngine.clearElementStructuralSuggestion(L),this.host.suggestionEngine.setElementStructuralSuggestion(L,"insert",void 0,g,"Insert")),m.insert(S+1,[L]);return}let P=null;for(let L=0;L<v.length;L++){const D=v.get(L);if(D instanceof I.XmlText){P=D;break}}if(!P)return;const T=st(P);let E=0;const B=[];for(const L of T)if(L.insert&&typeof L.insert=="string"){const D=L.insert.length;if(E+D<=c)E+=D;else if(E>=c)B.push(L);else{const H=c-E,F=L.insert.slice(H);F&&B.push({insert:F,...L.attributes&&{attributes:L.attributes}}),E=c}}c<P.length&&P.delete(c,P.length-c);const N=new I.XmlElement("list-item");u=G(),N.setAttribute("id",u),f=S+1,r.variant==="todo"&&N.setAttribute("checked","false");const R=x.indentLevel??0;R>0&&N.setAttribute("indentLevel",String(R)),(x.direction==="rtl"||x.direction==="ltr")&&N.setAttribute("direction",x.direction);const M=this.host.getFontAtOffsetInListItem(x,c),O=new I.XmlText;let $=0;if(B.length>0){for(const L of B)if(L.insert&&typeof L.insert=="string"){const D=L.attributes&&Object.keys(L.attributes).length>0?{...L.attributes}:{};D.fontFamily||(M||console.warn("[DocumentMutator] splitListItem: No font found for new list item, defaulting to Arial. This may indicate a bug."),D.fontFamily=M||jt),O.insert($,L.insert,D),$+=L.insert.length}}else{const L=M||this.host.resolveFontFamilyForList(r)||jt;N.setAttribute("_emptyTextMarks",JSON.stringify({fontFamily:L}))}g&&(this.host.suggestionEngine.clearElementStructuralSuggestion(v),this.host.suggestionEngine.clearElementStructuralSuggestion(N),this.host.suggestionEngine.setElementStructuralSuggestion(v,"split","before",g,"Split"),this.host.suggestionEngine.setElementStructuralSuggestion(N,"split","after",g,"Split")),N.insert(0,[O]),m.insert(S+1,[N])}),h){const p=this.host.getDocument(),m=W(p,r.id);if(!m||m.type!=="list"||f===null)return null;const y=m;let b=0;for(let v=0;v<f;v++){const x=y.children[v];for(const w of x.children)w.type==="text"&&(b+=w.text.length);v<f-1&&(b+=1)}f>0&&(b+=1);const k={block:y.id,offset:b},S={anchor:k,focus:k};return this.host.suggestingMode&&g&&d&&this.host.suggestionEngine.saveLiveSuggestion({id:g,type:"block-change",blockId:r.id,beforeBlock:d,label:"List"}),this.host.setSelectionAfterOperation(S),this.host.afterOperationRelativeSelection=Y(S,this.host.ydoc,p),k}else{if(!u)return null;const p={block:u,offset:0},m={anchor:p,focus:p};return this.host.setSelectionAfterOperation(m),this.host.afterOperationRelativeSelection=Y(m,this.host.ydoc,this.host.getDocument()),p}}insertTextInListItem(t,e,n,o){const r=this.resolveListContext(t);if(!r)return null;const{doc:i}=r,a=ie(t,this.host.ydoc,i);if(!a)return null;const l=I.createAbsolutePositionFromRelativePosition(a.textOffset,this.host.ydoc);if(!l||!(l.type instanceof I.XmlText))return null;const c=l.type,d=l.index;let g=null;if(o?.anchor&&o.focus&&xt(r.doc,o.anchor,o.focus)!==0){const w=ie(o.anchor,this.host.ydoc,r.doc),A=ie(o.focus,this.host.ydoc,r.doc),P=w?I.createAbsolutePositionFromRelativePosition(w.textOffset,this.host.ydoc):null,T=A?I.createAbsolutePositionFromRelativePosition(A.textOffset,this.host.ydoc):null;P?.type instanceof I.XmlText&&T?.type instanceof I.XmlText&&P.type===T.type&&P.type===c&&(g={yText:c,startOffset:Math.min(P.index,T.index),endOffset:Math.max(P.index,T.index)})}const u={},f=[],h=Ns(i,t),p=Fo(i,t),m=Oo(i,t),y=this.host.suggestionEngine.getEnclosingBlockInsertSuggestionIdForBlockId(i,t.block),b=y?null:this.host.suggestionEngine.getInlineInsertionSuggestionNodeAtPosition(i,t),k=b?.marks?.suggestionId??null,S=this.host.suggestionEngine.getSuggestionIdForSuggestedSelectionOverwrite(i,t,o);{const w=!y&&this.host.suggestingMode&&e.length>0,A=Tr({explicitMarks:n&&Object.keys(n).length>0?n:void 0,inheritedMarks:h?.marks,exitingLink:p,exitingComment:m,suggestionMarks:w?this.host.suggestionEngine.buildSuggestionInsertionMarks(void 0,S??k??this.host.suggestionEngine.getSuggestionIdFromInheritedMarks(h?.marks),void 0,void 0,b?.marks??h?.marks):void 0});Object.assign(u,A.marksToApply),f.push(...A.marksToRemove)}let v=g?.startOffset??d;this.host.transact(()=>{if(g&&g.endOffset>g.startOffset){const w=g.endOffset-g.startOffset;if(this.host.suggestingMode&&!y){const A=this.host.suggestionEngine.applySuggestedDeletionToTextRange(g.yText,g.startOffset,w,S??void 0);v=g.startOffset+A.retainedLength}else g.yText.delete(g.startOffset,w),v=g.startOffset}la(c,v,e,{marksToApply:u,marksToRemove:f}),!y&&this.host.suggestingMode&&e.length>0&&this.host.suggestionEngine.clearInheritedDeletionFromInsertedSuggestion(c,v,e.length)});const x=I.createRelativePositionFromTypeIndex(c,v+e.length);return on({blockId:a.blockId,textOffset:x},this.host.ydoc)}insertTextInList(t,e,n,o){this.host.beforeOperationSelection=n;const r=this.insertTextInListItem(t,e,null,n);if(r){const i={anchor:r,focus:r};return this.host.setSelectionAfterOperation(i),this.host.afterOperationRelativeSelection=Y(i,this.host.ydoc,this.host.getDocument()),!0}return this.host.setSelectionAfterOperation(o),this.host.afterOperationRelativeSelection=Y(o,this.host.ydoc,this.host.getDocument()),!0}insertFormattedTextInList(t,e,n,o,r){this.host.beforeOperationSelection=o;const i=this.insertTextInListItem(t,e,n,o);if(i){const a={anchor:i,focus:i};return this.host.setSelectionAfterOperation(a),this.host.afterOperationRelativeSelection=Y(a,this.host.ydoc,this.host.getDocument()),!0}return this.host.setSelectionAfterOperation(r),this.host.afterOperationRelativeSelection=Y(r,this.host.ydoc,this.host.getDocument()),!0}deleteTextInList(t,e,n,o){const r=this.resolveListContext(t);if(!r)return!1;const i=ie(t,this.host.ydoc,r.doc);if(!i)return!1;const a=I.createAbsolutePositionFromRelativePosition(i.textOffset,this.host.ydoc);if(!a||!(a.type instanceof I.XmlText))return!1;const l=a.type,c=a.index,d=this.host.suggestionEngine.getEnclosingBlockInsertSuggestionIdForBlockId(r.doc,t.block);return this.host.transact(()=>{const g=l.length,u=Math.min(e,g-c);if(u>0)if(this.host.suggestingMode&&!d){const f=this.host.suggestionEngine.applySuggestedDeletionToTextRange(l,c,u);u>1&&f.retainedLength>0&&this.host.normalizeAdjacentManualReplacementOrder(l,c)}else l.delete(c,u)}),this.host.setSelectionAfterOperation(o),this.host.afterOperationRelativeSelection=Y(o,this.host.ydoc,this.host.getDocument()),!0}tryApplyParagraphListTrigger(t,e,n){if(n!==" "||!t.id)return null;const o=this.host.getParagraphPlainText(t);return e.offset!==o.length?null:o==="-"||o==="*"?this.convertParagraphToListById(t.id,"unordered"):/^\d+\.$/.test(o)?this.convertParagraphToListById(t.id,"ordered",parseInt(o,10)):o==="[]"?this.convertParagraphToListById(t.id,"todo"):null}mergeAdjacentListsOnDelete(t,e,n,o,r,i,a){if(o!==n+1||!this.isCursorAtEndOfList(t,r)||!this.isCursorAtStartOfList(e,i))return!1;const l=this.host.getYContentFragment(),c=l.get(n),d=l.get(o);if(!(c instanceof I.XmlElement)||!(d instanceof I.XmlElement))return!1;let g=!1;return this.host.transact(()=>{const u=[];for(let h=0;h<d.length;h++){const p=d.get(h);if(p instanceof I.XmlElement&&p.nodeName==="list-item"){const m=new I.XmlElement("list-item");m.setAttribute("id",G());const y=p.getAttribute("checked");t.variant==="todo"&&m.setAttribute("checked",y??"false");const b=p.getAttribute("indentLevel");b!==void 0&&m.setAttribute("indentLevel",b);const k=rt(p,"direction");k!==void 0&&m.setAttribute("direction",k);const S=new I.XmlText;for(let v=0;v<p.length;v++){const x=p.get(v);if(x instanceof I.XmlText){const w=st(x);let A=0;w.forEach(P=>{typeof P.insert=="string"&&(S.insert(A,P.insert,P.attributes||{}),A+=P.insert.length)});break}}m.insert(0,[S]),u.push(m)}}u.length>0&&c.insert(c.length,u),l.delete(o,1);const f=d.getAttribute("id")||e.id;f&&this.host.listStartNumberCache.delete(f),g=!0}),g?(this.host.setSelectionAfterOperation(a),!0):!1}isCursorAtStartOfList(t,e){return e.offset===0}isCursorAtEndOfList(t,e){if(t.children.length===0)return!0;let n=0;for(let o=0;o<t.children.length;o++){const r=t.children[o];n+=r.children.filter(i=>i.type==="text").reduce((i,a)=>i+a.text.length,0),o<t.children.length-1&&(n+=1)}return e.offset>=n}getListCursorInfo(t,e){const n=t;if(n.type!=="list")return null;let o=e.offset,r=0;for(let c=0;c<n.children.length;c++){const d=n.children[c].children.filter(g=>g.type==="text").reduce((g,u)=>g+u.text.length,0);if(o<=d){r=c;break}if(o-=d,c<n.children.length-1){if(o===0){r=c+1;break}o-=1}}if(r<0||r>=t.children.length)return null;const i=t.children[r],a=this.getListItemTextLength(i),l=Math.max(0,Math.min(o,a));return{itemIndex:r,offsetInItem:l,itemLength:a}}getListItemTextLength(t){return t.children.reduce((e,n)=>n.type==="text"?e+n.text.length:e,0)}setListItemIndent(t,e,n,o,r){const i=this.host.getDocument();if(!t||t.type!=="list"||e<0||e>=t.children.length)return!1;const a=t,l=a.children[e].indentLevel??0,c=Math.max(0,Math.min(2,Math.floor(n)));if(c===l)return!1;const d=c-l;if(d>0&&(e===0||(a.children[e-1].indentLevel??0)<c-1))return!1;const g=[],u=this.host.suggestingMode?this.host.suggestionEngine.cloneSuggestionSnapshot(a):null,f=this.host.suggestingMode?gt():null;if(d!==0)for(let m=e+1;m<a.children.length;m++){const y=a.children[m].indentLevel??0;if(y<=l)break;if(d>0&&y+d>2)return!1;const b=Math.max(0,Math.min(2,y+d));g.push({index:m,newIndent:b})}this.host.beforeOperationSelection=o;const h=te().getHandlerForBlock(t);this.host.beforeOperationRelativeSelection=h?.allowsInternalCursor()?Y(o,this.host.ydoc,i):null;const p=Z(this.host.ydoc,t.id??"");return!p||!(p instanceof I.XmlElement)?!1:(this.host.transact(()=>{const m=[];for(let b=0;b<p.length;b++){const k=p.get(b);k instanceof I.XmlElement&&k.nodeName==="list-item"&&m.push(k)}const y=m[e];y&&(c>0?y.setAttribute("indentLevel",String(c)):y.removeAttribute("indentLevel"),f&&(this.host.suggestionEngine.clearElementStructuralSuggestion(y),this.host.suggestionEngine.setElementStructuralSuggestion(y,"change",void 0,f,d>0?"Indent":"Outdent")),g.forEach(({index:b,newIndent:k})=>{const S=m[b];S&&(k>0?S.setAttribute("indentLevel",String(k)):S.removeAttribute("indentLevel"),f&&(this.host.suggestionEngine.clearElementStructuralSuggestion(S),this.host.suggestionEngine.setElementStructuralSuggestion(S,"change",void 0,f,d>0?"Indent":"Outdent")))}),this.host.suggestingMode&&f&&u&&this.host.suggestionEngine.saveLiveSuggestion({id:f,type:"block-change",blockId:t.id,beforeBlock:u,label:d>0?"Indent":"Outdent"}))}),this.host.setSelectionAfterOperation(r),this.host.afterOperationRelativeSelection=h?.allowsInternalCursor()?Y(r,this.host.ydoc,this.host.getDocument()):null,!0)}}function ku(s,t){const e=st(s).map(l=>typeof l.insert=="string"?l.insert:"").join(""),n=t.map(l=>l.text).join("");let o=0;for(const[l,c]of e===n?[]:En(e,n).diffs)l===-1?s.delete(o,c.length):(l===1&<(s,o,c),o+=c.length);const r=st(s);let i=0,a=0;o=0;for(const l of r){if(typeof l.insert!="string")continue;let c=l.insert.length;for(;c>0;){for(;i<t.length&&a===t[i].text.length;)i++,a=0;const d=t[i],g=Math.min(c,d.text.length-a),u=d.marks??{},f=l.attributes??{},h={};for(const p of new Set([...Object.keys(u),...Object.keys(f)])){const m=u[p];JSON.stringify(m)!==JSON.stringify(f[p])&&(h[p]=m??null)}Object.keys(h).length&&at(s,o,g,h),o+=g,a+=g,c-=g}}}function Kr(s,t){const e=s.toArray().filter(c=>c instanceof I.XmlElement),n=e.map(c=>String(c.getAttribute("id"))),o=t.children.map(c=>c.id),r=new Map;let i=0,a=0;for(const c of Fr(n,o)){for(;n[i]!==c;)i++;for(;o[a]!==c;)a++;r.set(a++,e[i++])}const l=new Set(r.values());Zt(s,t);for(let c=s.length-1;c>=0;c--){const d=s.get(c);(!(d instanceof I.XmlElement)||!l.has(d))&&s.delete(c,1)}t.children.forEach((c,d)=>{const g=r.get(d);if(!g){s.insert(d,[It(c)]);return}Zt(g,c);const u=g.toArray().find(h=>h instanceof I.XmlText);u&&ku(u,c.children);const f=c.children.every(h=>h.text.length===0)?c.children.find(h=>h.marks&&Object.keys(h.marks).length)?.marks:void 0;if(f){const h=JSON.stringify(f);rt(g,"_emptyTextMarks")!==h&&g.setAttribute("_emptyTextMarks",h)}else et(g,"_emptyTextMarks")})}const Su=300;function Iu(s){return Array.from(s).slice(0,Su).join("")}function vu(s){return s.children.every(t=>t.type==="paragraph"&&t.children.every(e=>e.type==="text"&&e.text.trim().length===0))}class Vr extends Error{constructor(t,e,n){super(n instanceof Error?n.message:String(n)),this.actionIndex=t,this.action=e,this.originalError=n,this.name="PreprocessActionError"}}class an{constructor(){this.afterIdChain=new Map,this.currentTurnId=""}startNewTurn(){const t="turn_"+Date.now();this.afterIdChain.clear(),this.currentTurnId=t}getChainedAfterId(t){return t?this.afterIdChain.get(t)||t:null}updateChain(t,e){this.afterIdChain.set(t,e)}hasChain(t){return this.afterIdChain.has(t)}getCurrentTurnId(){return this.currentTurnId}reset(){this.afterIdChain.clear(),this.currentTurnId=""}}function Gr(s){return s.replace(/\s+id="[^"]*"/g,"")}function Na(s){const t=Gr(s),e=t.match(/^<p\b([^>]*)>([\s\S]*)<\/p>$/i);return e?e[1].trim().length>0?t:e[2]:t}function La(s){return it.toInternalHtml({type:"doc",children:[s]})}function xu(s,t,e,n){if(!s.actions)return s;const o=s.actions.map((c,d)=>{const g=y=>{throw new Vr(d,c,new Error(y))};if(c.name==="replace_block"&&(typeof c.arguments.id!="string"||!c.arguments.id.trim())&&g('replace_block id is required. Read the target block and use its current ID. To write into a blank document, use insert_block with referenceId="" and position="after".'),c.name!=="insert_block")return c;const{referenceId:u,position:f}=c.arguments;if(f!=="before"&&f!=="after"&&g("insert_block position must be before or after."),typeof u=="string"&&u.trim())return c;if(!n||!vu(n))return g("insert_block referenceId is required for a document with content. Read the target location and use a current block ID. Use an empty referenceId only for a blank document.");const h=f==="before"?n.children[0]:n.children.at(-1),p={...c,arguments:{...c.arguments,referenceId:h?.id??Ve}},m=Rt(c);return m&&wt(p,m),p}),r=e||new an;`${s.actions.length}${t}${r.getCurrentTurnId()}`;const i=[],a=n?it.createParsingContext(n):void 0,l=(c,d,g)=>{try{const u=d.name==="insert_block"?d.arguments.referenceId:d.name==="replace_block"?d.arguments.id:void 0,f=typeof u=="string"&&n?W(n,u):null,h=f?.type==="list"?f.children.find(p=>p.id===u):void 0;return it.fromAgentHtml(c,{existingDocument:n,parsingContext:a,preserveImageReferenceIds:!0,listItemBaseIndent:h?h.indentLevel??0:void 0})}catch(u){throw new Vr(g,d,u)}};for(const[c,d]of o.entries()){const g=Rt(d);if(d.name==="insert_block"){const{referenceId:u,position:f,content:h}=d.arguments;let p=u;const m=f;if(f==="after"&&r.hasChain(u)){const k=r.getChainedAfterId(u);k&&(p=k)}const y=it.coalesceAdjacentBareListFragments(Array.isArray(h)?h:[h]),b=[];for(const k of y){const S=l(k,d,c);if(S.children.length!==0)if(S.children.length===1){const v=G();wt(d,{stableId:v});const x=S.children[0];let w;x.type==="list"||x.type==="table"||x.type==="page-break"||x.type==="toc"?w=Gr(it.toInternalHtml(S)):w=Gr(it.toInternalHtml(S)),b.push({content:w,id:v})}else for(let v=0;v<S.children.length;v++){const x=S.children[v],w=La(x);let A;x.type==="list"||x.type==="table"||x.type==="page-break"||x.type==="toc"?A=w:A=Na(w);const P=G();b.push({content:A,id:P})}}for(let k=0;k<b.length;k++){const{content:S,id:v}=b[k],x={name:"insert_block",arguments:{}};k===0?(x.arguments.referenceId=p,x.arguments.position=m,wt(x,{stableId:b[k].id})):(x.arguments.referenceId=b[k-1].id,x.arguments.position="after"),x.arguments.content=[S],wt(x,{...g,stableId:v}),i.push(x)}if(f==="after"&&b.length>0){const k=b[b.length-1].id;r.updateChain(u,k)}}else if(d.name==="replace_block"){const{id:u,content:f,count:h}=d.arguments,p=it.coalesceAdjacentBareListFragments(Array.isArray(f)?f:[f]),m=[];for(const y of p){const b=l(y,d,c);if(b.children.length===0)m.push({content:y,id:u,type:"paragraph"});else for(const k of b.children){const S=La(k),v=m.length===0?u:G();m.push({content:S,id:v,type:k.type})}}if(m.length<=1){const y={...d,arguments:{...d.arguments,content:m.length>0?[m[0].content]:p}};g&&wt(y,g),i.push(y)}else{const y={name:"replace_block",arguments:{id:u,...typeof h=="number"?{count:h}:{},content:[m[0].content]}};wt(y,{...g,allowNoopContinuation:!0,splitReplacementGroup:m[0].id,multiBlockReplace:{replacementBlockIds:m.map(b=>b.id),replacedCount:typeof h=="number"?h:1}}),i.push(y);for(let b=1;b<m.length;b++){const{content:k,id:S,type:v}=m[b];let x;v==="list"||v==="table"||v==="code"||v==="page-break"||v==="toc"?x=k:x=Na(k);const w={name:"insert_block",arguments:{referenceId:b===1?u:m[b-1].id,position:"after",content:[x]}};wt(w,{...g,stableId:S,splitReplacementGroup:m[0].id}),i.push(w)}m.length>1&&r.updateChain(u,m[m.length-1].id)}}else i.push(d)}return{...s,actions:i}}const wu=Math.floor,Au=(s,t)=>s<t?s:t,Tu=(s,t)=>s>t?s:t,Fa=128,po=127,Cu=Number.MAX_SAFE_INTEGER,Pu=s=>{const t=unescape(encodeURIComponent(s)),e=t.length,n=new Uint8Array(e);for(let o=0;o<e;o++)n[o]=t.codePointAt(o);return n},ln=typeof TextEncoder<"u"?new TextEncoder:null,Mu=s=>ln.encode(s),Bu=ln?Mu:Pu;let cn=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});cn&&cn.decode(new Uint8Array).length===1&&(cn=null);const mo=(s,t)=>{const e=s.cbuf.length;s.cpos===e&&(s.bufs.push(s.cbuf),s.cbuf=new Uint8Array(e*2),s.cpos=0),s.cbuf[s.cpos++]=t},bo=(s,t)=>{for(;t>po;)mo(s,Fa|po&t),t=wu(t/128);mo(s,po&t)},Qr=new Uint8Array(3e4),Eu=Qr.length/3,Nu=(s,t)=>{if(t.length<Eu){const e=ln.encodeInto(t,Qr).written||0;bo(s,e);for(let n=0;n<e;n++)mo(s,Qr[n])}else Ru(s,Bu(t))},Lu=(s,t)=>{const e=unescape(encodeURIComponent(t)),n=e.length;bo(s,n);for(let o=0;o<n;o++)mo(s,e.codePointAt(o))},Fu=ln&&ln.encodeInto?Nu:Lu,Ou=(s,t)=>{const e=s.cbuf.length,n=s.cpos,o=Au(e-n,t.length),r=t.length-o;s.cbuf.set(t.subarray(0,o),n),s.cpos+=o,r>0&&(s.bufs.push(s.cbuf),s.cbuf=new Uint8Array(Tu(e*2,r)),s.cbuf.set(t.subarray(o)),s.cpos=r)},Ru=(s,t)=>{bo(s,t.byteLength),Ou(s,t)},Oa=s=>new Error(s),Du=Oa("Unexpected end of array"),$u=Oa("Integer out of Range"),ju=(s,t)=>{const e=new Uint8Array(s.arr.buffer,s.pos+s.arr.byteOffset,t);return s.pos+=t,e},_u=s=>ju(s,Zr(s)),Ra=s=>s.arr[s.pos++],Zr=s=>{let t=0,e=1;const n=s.arr.length;for(;s.pos<n;){const o=s.arr[s.pos++];if(t=t+(o&po)*e,e*=128,o<Fa)return t;if(t>Cu)throw $u}throw Du},Xu=s=>{let t=Zr(s);if(t===0)return"";{let e=String.fromCodePoint(Ra(s));if(--t<100)for(;t--;)e+=String.fromCodePoint(Ra(s));else for(;t>0;){const n=t<1e4?t:1e4,o=s.arr.subarray(s.pos,s.pos+n);s.pos+=n,e+=String.fromCodePoint.apply(null,o),t-=n}return decodeURIComponent(escape(e))}},Uu=s=>cn.decode(_u(s)),Da=cn?Uu:Xu;var dn;(function(s){s[s.Token=0]="Token",s[s.PermissionDenied=1]="PermissionDenied",s[s.Authenticated=2]="Authenticated"})(dn||(dn={}));const zu=(s,t)=>{bo(s,dn.Token),Fu(s,t)},Wu=(s,t,e)=>{switch(Zr(s)){case dn.PermissionDenied:{t(Da(s));break}case dn.Authenticated:{e(Da(s));break}}},$a=s=>Array.from(s.entries()).map(([t,e])=>({clientId:t,...e}));var ts;(function(s){s[s.Connecting=0]="Connecting",s[s.Open=1]="Open",s[s.Closing=2]="Closing",s[s.Closed=3]="Closed"})(ts||(ts={}));function Ju(s){return s||(s={}),{delay:s.delay===void 0?200:s.delay,initialDelay:s.initialDelay===void 0?0:s.initialDelay,minDelay:s.minDelay===void 0?0:s.minDelay,maxDelay:s.maxDelay===void 0?0:s.maxDelay,factor:s.factor===void 0?0:s.factor,maxAttempts:s.maxAttempts===void 0?3:s.maxAttempts,timeout:s.timeout===void 0?0:s.timeout,jitter:s.jitter===!0,initialJitter:s.initialJitter===!0,handleError:s.handleError===void 0?null:s.handleError,handleTimeout:s.handleTimeout===void 0?null:s.handleTimeout,beforeAttempt:s.beforeAttempt===void 0?null:s.beforeAttempt,calculateDelay:s.calculateDelay===void 0?null:s.calculateDelay}}async function es(s){return new Promise(t=>setTimeout(t,s))}function Hu(s,t){let e=t.delay;if(e===0)return 0;if(t.factor&&(e*=Math.pow(t.factor,s.attemptNum-1),t.maxDelay!==0&&(e=Math.min(e,t.maxDelay))),t.jitter){const n=Math.ceil(t.minDelay),o=Math.floor(e);e=Math.floor(Math.random()*(o-n+1))+n}return Math.round(e)}async function qu(s,t){const e=Ju(t);for(const a of["delay","initialDelay","minDelay","maxDelay","maxAttempts","timeout"]){const l=e[a];if(!Number.isInteger(l)||l<0)throw new Error(`Value for ${a} must be an integer greater than or equal to 0`)}if(e.factor.constructor!==Number||e.factor<0)throw new Error("Value for factor must be a number greater than or equal to 0");if(e.delay<e.minDelay)throw new Error(`delay cannot be less than minDelay (delay: ${e.delay}, minDelay: ${e.minDelay}`);const n={attemptNum:0,attemptsRemaining:e.maxAttempts?e.maxAttempts:-1,aborted:!1,abort(){n.aborted=!0}},o=e.calculateDelay||Hu;async function r(){if(e.beforeAttempt&&e.beforeAttempt(n,e),n.aborted){const l=new Error("Attempt aborted");throw l.code="ATTEMPT_ABORTED",l}const a=async l=>{if(e.handleError&&await e.handleError(l,n,e),n.aborted||n.attemptsRemaining===0)throw l;n.attemptNum++;const c=o(n,e);return c&&await es(c),r()};return n.attemptsRemaining>0&&n.attemptsRemaining--,e.timeout?new Promise((l,c)=>{const d=setTimeout(()=>{if(e.handleTimeout)try{l(e.handleTimeout(n,e))}catch(g){c(g)}else{const g=new Error(`Retry timeout (attemptNum: ${n.attemptNum}, timeout: ${e.timeout})`);g.code="ATTEMPT_TIMEOUT",c(g)}},e.timeout);s(n,e).then(g=>{clearTimeout(d),l(g)}).catch(g=>{clearTimeout(d),a(g).then(l).catch(c)})}):s(n,e).catch(a)}const i=e.calculateDelay?e.calculateDelay(n,e):e.initialDelay;if(i&&await es(i),n.attemptNum<1&&e.initialJitter){const a=o(n,e);a&&await es(a)}return r()}const ja=Math.floor,Yu=(s,t)=>s<t?s:t,Ku=(s,t)=>s>t?s:t,Vu=64,yo=128,Gu=63,gn=127,_a=Number.MAX_SAFE_INTEGER,Qu=()=>new Set,Zu=Array.from,th=s=>{const t=unescape(encodeURIComponent(s)),e=t.length,n=new Uint8Array(e);for(let o=0;o<e;o++)n[o]=t.codePointAt(o);return n},un=typeof TextEncoder<"u"?new TextEncoder:null,eh=s=>un.encode(s),nh=un?eh:th;let hn=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});hn&&hn.decode(new Uint8Array).length===1&&(hn=null);class oh{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const ns=()=>new oh,Xa=s=>{let t=s.cpos;for(let e=0;e<s.bufs.length;e++)t+=s.bufs[e].length;return t},os=s=>{const t=new Uint8Array(Xa(s));let e=0;for(let n=0;n<s.bufs.length;n++){const o=s.bufs[n];t.set(o,e),e+=o.length}return t.set(new Uint8Array(s.cbuf.buffer,0,s.cpos),e),t},ko=(s,t)=>{const e=s.cbuf.length;s.cpos===e&&(s.bufs.push(s.cbuf),s.cbuf=new Uint8Array(e*2),s.cpos=0),s.cbuf[s.cpos++]=t},Et=(s,t)=>{for(;t>gn;)ko(s,yo|gn&t),t=ja(t/128);ko(s,gn&t)},rs=new Uint8Array(3e4),rh=rs.length/3,sh=(s,t)=>{if(t.length<rh){const e=un.encodeInto(t,rs).written||0;Et(s,e);for(let n=0;n<e;n++)ko(s,rs[n])}else _e(s,nh(t))},ih=(s,t)=>{const e=unescape(encodeURIComponent(t)),n=e.length;Et(s,n);for(let o=0;o<n;o++)ko(s,e.codePointAt(o))},Vt=un&&un.encodeInto?sh:ih,ah=(s,t)=>{const e=s.cbuf.length,n=s.cpos,o=Yu(e-n,t.length),r=t.length-o;s.cbuf.set(t.subarray(0,o),n),s.cpos+=o,r>0&&(s.bufs.push(s.cbuf),s.cbuf=new Uint8Array(Ku(e*2,r)),s.cbuf.set(t.subarray(o)),s.cpos=r)},_e=(s,t)=>{Et(s,t.byteLength),ah(s,t)},Ua=s=>new Error(s),za=Ua("Unexpected end of array"),Wa=Ua("Integer out of Range");class lh{constructor(t){this.arr=t,this.pos=0}}const Ja=s=>new lh(s),ch=(s,t)=>{const e=new Uint8Array(s.arr.buffer,s.pos+s.arr.byteOffset,t);return s.pos+=t,e},So=s=>ch(s,xe(s)),Ha=s=>s.arr[s.pos++],xe=s=>{let t=0,e=1;const n=s.arr.length;for(;s.pos<n;){const o=s.arr[s.pos++];if(t=t+(o&gn)*e,e*=128,o<yo)return t;if(t>_a)throw Wa}throw za},dh=s=>{let t=s.arr[s.pos++],e=t&Gu,n=64;const o=(t&Vu)>0?-1:1;if((t&yo)===0)return o*e;const r=s.arr.length;for(;s.pos<r;){if(t=s.arr[s.pos++],e=e+(t&gn)*n,n*=128,t<yo)return o*e;if(e>_a)throw Wa}throw za},gh=s=>{let t=xe(s);if(t===0)return"";{let e=String.fromCodePoint(Ha(s));if(--t<100)for(;t--;)e+=String.fromCodePoint(Ha(s));else for(;t>0;){const n=t<1e4?t:1e4,o=s.arr.subarray(s.pos,s.pos+n);s.pos+=n,e+=String.fromCodePoint.apply(null,o),t-=n}return decodeURIComponent(escape(e))}},uh=s=>hn.decode(So(s)),fn=hn?uh:gh,hh=s=>{const t=s.pos,e=fn(s);return s.pos=t,e},Xe=Date.now,ss=()=>new Map,fh=(s,t,e)=>{let n=s.get(t);return n===void 0&&s.set(t,n=e()),n};class ph{constructor(){this._observers=ss()}on(t,e){fh(this._observers,t,Qu).add(e)}once(t,e){const n=(...o)=>{this.off(t,n),e(...o)};this.on(t,n)}off(t,e){const n=this._observers.get(t);n!==void 0&&(n.delete(e),n.size===0&&this._observers.delete(t))}emit(t,e){return Zu((this._observers.get(t)||ss()).values()).forEach(n=>n(...e))}destroy(){this._observers=ss()}}const mh=Object.keys,qa=s=>mh(s).length,bh=(s,t)=>Object.prototype.hasOwnProperty.call(s,t),yh=(s,t)=>s===t,pn=(s,t)=>{if(s==null||t==null)return yh(s,t);if(s.constructor!==t.constructor)return!1;if(s===t)return!0;switch(s.constructor){case ArrayBuffer:s=new Uint8Array(s),t=new Uint8Array(t);case Uint8Array:{if(s.byteLength!==t.byteLength)return!1;for(let e=0;e<s.length;e++)if(s[e]!==t[e])return!1;break}case Set:{if(s.size!==t.size)return!1;for(const e of s)if(!t.has(e))return!1;break}case Map:{if(s.size!==t.size)return!1;for(const e of s.keys())if(!t.has(e)||!pn(s.get(e),t.get(e)))return!1;break}case Object:if(qa(s)!==qa(t))return!1;for(const e in s)if(!bh(s,e)||!pn(s[e],t[e]))return!1;break;case Array:if(s.length!==t.length)return!1;for(let e=0;e<s.length;e++)if(!pn(s[e],t[e]))return!1;break;default:return!1}return!0},is=3e4;class kh extends ph{constructor(t){super(),this.doc=t,this.clientID=t.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{const e=Xe();this.getLocalState()!==null&&is/2<=e-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());const n=[];this.meta.forEach((o,r)=>{r!==this.clientID&&is<=e-o.lastUpdated&&this.states.has(r)&&n.push(r)}),n.length>0&&Io(this,n,"timeout")},ja(is/10)),t.on("destroy",()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit("destroy",[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(t){const e=this.clientID,n=this.meta.get(e),o=n===void 0?0:n.clock+1,r=this.states.get(e);t===null?this.states.delete(e):this.states.set(e,t),this.meta.set(e,{clock:o,lastUpdated:Xe()});const i=[],a=[],l=[],c=[];t===null?c.push(e):r==null?t!=null&&i.push(e):(a.push(e),pn(r,t)||l.push(e)),(i.length>0||l.length>0||c.length>0)&&this.emit("change",[{added:i,updated:l,removed:c},"local"]),this.emit("update",[{added:i,updated:a,removed:c},"local"])}setLocalStateField(t,e){const n=this.getLocalState();n!==null&&this.setLocalState({...n,[t]:e})}getStates(){return this.states}}const Io=(s,t,e)=>{const n=[];for(let o=0;o<t.length;o++){const r=t[o];if(s.states.has(r)){if(s.states.delete(r),r===s.clientID){const i=s.meta.get(r);s.meta.set(r,{clock:i.clock+1,lastUpdated:Xe()})}n.push(r)}}n.length>0&&(s.emit("change",[{added:[],updated:[],removed:n},e]),s.emit("update",[{added:[],updated:[],removed:n},e]))},as=(s,t,e=s.states)=>{const n=t.length,o=ns();Et(o,n);for(let r=0;r<n;r++){const i=t[r],a=e.get(i)||null,l=s.meta.get(i).clock;Et(o,i),Et(o,l),Vt(o,JSON.stringify(a))}return os(o)},Sh=(s,t,e)=>{const n=Ja(t),o=Xe(),r=[],i=[],a=[],l=[],c=xe(n);for(let d=0;d<c;d++){const g=xe(n);let u=xe(n);const f=JSON.parse(fn(n)),h=s.meta.get(g),p=s.states.get(g),m=h===void 0?0:h.clock;(m<u||m===u&&f===null&&s.states.has(g))&&(f===null?g===s.clientID&&s.getLocalState()!=null?u++:s.states.delete(g):s.states.set(g,f),s.meta.set(g,{clock:u,lastUpdated:o}),h===void 0&&f!==null?r.push(g):h!==void 0&&f===null?l.push(g):f!==null&&(pn(f,p)||a.push(g),i.push(g)))}(r.length>0||a.length>0||l.length>0)&&s.emit("change",[{added:r,updated:a,removed:l},e]),(r.length>0||i.length>0||l.length>0)&&s.emit("update",[{added:r,updated:i,removed:l},e])};class Ya{constructor(){this.callbacks={}}on(t,e){return this.callbacks[t]||(this.callbacks[t]=[]),this.callbacks[t].push(e),this}emit(t,...e){const n=this.callbacks[t];return n&&n.forEach(o=>o.apply(this,e)),this}off(t,e){const n=this.callbacks[t];return n&&(e?this.callbacks[t]=n.filter(o=>o!==e):delete this.callbacks[t]),this}removeAllListeners(){this.callbacks={}}}class ls{constructor(t){this.data=t,this.encoder=ns(),this.decoder=Ja(new Uint8Array(this.data))}peekVarString(){return hh(this.decoder)}readVarUint(){return xe(this.decoder)}readVarString(){return fn(this.decoder)}readVarUint8Array(){return So(this.decoder)}writeVarUint(t){return Et(this.encoder,t)}writeVarString(t){return Vt(this.encoder,t)}writeVarUint8Array(t){return _e(this.encoder,t)}length(){return Xa(this.encoder)}}var At;(function(s){s[s.Sync=0]="Sync",s[s.Awareness=1]="Awareness",s[s.Auth=2]="Auth",s[s.QueryAwareness=3]="QueryAwareness",s[s.Stateless=5]="Stateless",s[s.CLOSE=7]="CLOSE",s[s.SyncStatus=8]="SyncStatus"})(At||(At={}));var $t;(function(s){s.Connecting="connecting",s.Connected="connected",s.Disconnected="disconnected"})($t||($t={}));class we{constructor(){this.encoder=ns()}get(t){return t.encoder}toUint8Array(){return os(this.encoder)}}class Ih extends we{constructor(){super(...arguments),this.type=At.CLOSE,this.description="Ask the server to close the connection"}get(t){return Vt(this.encoder,t.documentName),Et(this.encoder,this.type),this.encoder}}class vh extends Ya{constructor(t){super(),this.messageQueue=[],this.configuration={url:"",document:void 0,WebSocketPolyfill:void 0,messageReconnectTimeout:3e4,delay:1e3,initialDelay:0,factor:2,maxAttempts:0,minDelay:1e3,maxDelay:3e4,jitter:!0,timeout:0,onOpen:()=>null,onConnect:()=>null,onMessage:()=>null,onOutgoingMessage:()=>null,onStatus:()=>null,onDisconnect:()=>null,onClose:()=>null,onDestroy:()=>null,onAwarenessUpdate:()=>null,onAwarenessChange:()=>null,providerMap:new Map},this.webSocket=null,this.webSocketHandlers={},this.shouldConnect=!0,this.status=$t.Disconnected,this.lastMessageReceived=0,this.identifier=0,this.intervals={connectionChecker:null},this.connectionAttempt=null,this.receivedOnOpenPayload=void 0,this.closeTries=0,this.setConfiguration(t),this.configuration.WebSocketPolyfill=t.WebSocketPolyfill?t.WebSocketPolyfill:WebSocket,this.on("open",this.configuration.onOpen),this.on("open",this.onOpen.bind(this)),this.on("connect",this.configuration.onConnect),this.on("message",this.configuration.onMessage),this.on("outgoingMessage",this.configuration.onOutgoingMessage),this.on("status",this.configuration.onStatus),this.on("disconnect",this.configuration.onDisconnect),this.on("close",this.configuration.onClose),this.on("destroy",this.configuration.onDestroy),this.on("awarenessUpdate",this.configuration.onAwarenessUpdate),this.on("awarenessChange",this.configuration.onAwarenessChange),this.on("close",this.onClose.bind(this)),this.on("message",this.onMessage.bind(this)),this.intervals.connectionChecker=setInterval(this.checkConnection.bind(this),this.configuration.messageReconnectTimeout/10),this.shouldConnect&&this.connect()}async onOpen(t){this.cancelWebsocketRetry=void 0,this.receivedOnOpenPayload=t}attach(t){this.configuration.providerMap.set(t.configuration.name,t),this.status===$t.Disconnected&&this.shouldConnect&&this.connect(),this.receivedOnOpenPayload&&this.status===$t.Connected&&t.onOpen(this.receivedOnOpenPayload)}detach(t){this.configuration.providerMap.has(t.configuration.name)&&(t.send(Ih,{documentName:t.configuration.name}),this.configuration.providerMap.delete(t.configuration.name))}setConfiguration(t={}){this.configuration={...this.configuration,...t}}async connect(){if(this.status===$t.Connected)return;this.cancelWebsocketRetry&&(this.cancelWebsocketRetry(),this.cancelWebsocketRetry=void 0),this.receivedOnOpenPayload=void 0,this.shouldConnect=!0;const t=()=>{let o=!1;return{retryPromise:qu(this.createWebSocketConnection.bind(this),{delay:this.configuration.delay,initialDelay:this.configuration.initialDelay,factor:this.configuration.factor,maxAttempts:this.configuration.maxAttempts,minDelay:this.configuration.minDelay,maxDelay:this.configuration.maxDelay,jitter:this.configuration.jitter,timeout:this.configuration.timeout,beforeAttempt:r=>{(!this.shouldConnect||o)&&r.abort()}}).catch(r=>{if(r&&r.code!=="ATTEMPT_ABORTED")throw r}),cancelFunc:()=>{o=!0}}},{retryPromise:e,cancelFunc:n}=t();return this.cancelWebsocketRetry=n,e}attachWebSocketListeners(t,e){const{identifier:n}=t,o=c=>this.emit("message",c),r=c=>this.emit("close",{event:c}),i=c=>this.emit("open",c),a=c=>{e(c)};this.webSocketHandlers[n]={message:o,close:r,open:i,error:a};const l=this.webSocketHandlers[t.identifier];Object.keys(l).forEach(c=>{t.addEventListener(c,l[c])})}cleanupWebSocket(){if(!this.webSocket)return;const{identifier:t}=this.webSocket,e=this.webSocketHandlers[t];Object.keys(e).forEach(n=>{var o;(o=this.webSocket)===null||o===void 0||o.removeEventListener(n,e[n]),delete this.webSocketHandlers[t]}),this.webSocket.close(),this.webSocket=null}createWebSocketConnection(){return new Promise((t,e)=>{this.webSocket&&(this.messageQueue=[],this.cleanupWebSocket()),this.lastMessageReceived=0,this.identifier+=1;const n=new this.configuration.WebSocketPolyfill(this.url);n.binaryType="arraybuffer",n.identifier=this.identifier,this.attachWebSocketListeners(n,e),this.webSocket=n,this.status=$t.Connecting,this.emit("status",{status:$t.Connecting}),this.connectionAttempt={resolve:t,reject:e}})}onMessage(t){var e;this.resolveConnectionAttempt(),this.lastMessageReceived=Xe();const n=new ls(t.data).peekVarString();(e=this.configuration.providerMap.get(n))===null||e===void 0||e.onMessage(t)}resolveConnectionAttempt(){this.connectionAttempt&&(this.connectionAttempt.resolve(),this.connectionAttempt=null,this.status=$t.Connected,this.emit("status",{status:$t.Connected}),this.emit("connect"),this.messageQueue.forEach(t=>this.send(t)),this.messageQueue=[])}stopConnectionAttempt(){this.connectionAttempt=null}rejectConnectionAttempt(){var t;(t=this.connectionAttempt)===null||t===void 0||t.reject(),this.connectionAttempt=null}checkConnection(){var t;this.status===$t.Connected&&this.lastMessageReceived&&(this.configuration.messageReconnectTimeout>=Xe()-this.lastMessageReceived||(this.closeTries+=1,this.closeTries>2?(this.onClose({event:{code:4408,reason:"forced"}}),this.closeTries=0):((t=this.webSocket)===null||t===void 0||t.close(),this.messageQueue=[])))}get serverUrl(){for(;this.configuration.url[this.configuration.url.length-1]==="/";)return this.configuration.url.slice(0,this.configuration.url.length-1);return this.configuration.url}get url(){return this.serverUrl}disconnect(){if(this.shouldConnect=!1,this.webSocket!==null)try{this.webSocket.close(),this.messageQueue=[]}catch(t){console.error(t)}}send(t){var e;((e=this.webSocket)===null||e===void 0?void 0:e.readyState)===ts.Open?this.webSocket.send(t):this.messageQueue.push(t)}onClose({event:t}){this.closeTries=0,this.cleanupWebSocket(),this.connectionAttempt&&this.rejectConnectionAttempt(),this.status=$t.Disconnected,this.emit("status",{status:$t.Disconnected}),this.emit("disconnect",{event:t}),!this.cancelWebsocketRetry&&this.shouldConnect&&setTimeout(()=>{this.connect()},this.configuration.delay)}destroy(){this.emit("destroy"),clearInterval(this.intervals.connectionChecker),this.stopConnectionAttempt(),this.disconnect(),this.removeAllListeners(),this.cleanupWebSocket()}}const Ka=0,cs=1,Va=2,xh=(s,t)=>{Et(s,Ka);const e=I.encodeStateVector(t);_e(s,e)},wh=(s,t,e)=>{Et(s,cs),_e(s,I.encodeStateAsUpdate(t,e))},Ah=(s,t,e)=>wh(t,e,So(s)),Ga=(s,t,e)=>{try{I.applyUpdate(t,So(s),e)}catch(n){console.error("Caught error while handling a Yjs update",n)}},Th=(s,t)=>{Et(s,Va),_e(s,t)},Ch=Ga,Ph=(s,t,e,n)=>{const o=xe(s);switch(o){case Ka:Ah(s,t,e);break;case cs:Ga(s,e,n);break;case Va:Ch(s,e,n);break;default:throw new Error("Unknown message type")}return o};class Mh{constructor(t){this.message=t}apply(t,e){const{message:n}=this,o=n.readVarUint(),r=n.length();switch(o){case At.Sync:this.applySyncMessage(t,e);break;case At.Awareness:this.applyAwarenessMessage(t);break;case At.Auth:this.applyAuthMessage(t);break;case At.QueryAwareness:this.applyQueryAwarenessMessage(t);break;case At.Stateless:t.receiveStateless(fn(n.decoder));break;case At.SyncStatus:this.applySyncStatusMessage(t,dh(n.decoder)===1);break;case At.CLOSE:const i={code:1e3,reason:fn(n.decoder),target:t.configuration.websocketProvider.webSocket,type:"close"};t.onClose(),t.configuration.onClose({event:i}),t.forwardClose(i);break;default:throw new Error(`Can’t apply message of unknown type: ${o}`)}n.length()>r+1&&t.send(we,{encoder:n.encoder})}applySyncMessage(t,e){const{message:n}=this;n.writeVarUint(At.Sync);const o=Ph(n.decoder,n.encoder,t.document,t);e&&o===cs&&(t.synced=!0)}applySyncStatusMessage(t,e){e&&t.decrementUnsyncedChanges()}applyAwarenessMessage(t){if(!t.awareness)return;const{message:e}=this;Sh(t.awareness,e.readVarUint8Array(),t)}applyAuthMessage(t){const{message:e}=this;Wu(e.decoder,t.permissionDeniedHandler.bind(t),t.authenticatedHandler.bind(t))}applyQueryAwarenessMessage(t){if(!t.awareness)return;const{message:e}=this;e.writeVarUint(At.Awareness),e.writeVarUint8Array(as(t.awareness,Array.from(t.awareness.getStates().keys())))}}class Bh{constructor(t,e={}){this.message=new t,this.encoder=this.message.get(e)}create(){return os(this.encoder)}send(t){t?.send(this.create())}}class Eh extends we{constructor(){super(...arguments),this.type=At.Auth,this.description="Authentication"}get(t){if(typeof t.token>"u")throw new Error("The authentication message requires `token` as an argument.");return Vt(this.encoder,t.documentName),Et(this.encoder,this.type),zu(this.encoder,t.token),this.encoder}}class Qa extends we{constructor(){super(...arguments),this.type=At.Awareness,this.description="Awareness states update"}get(t){if(typeof t.awareness>"u")throw new Error("The awareness message requires awareness as an argument");if(typeof t.clients>"u")throw new Error("The awareness message requires clients as an argument");Vt(this.encoder,t.documentName),Et(this.encoder,this.type);let e;return t.states===void 0?e=as(t.awareness,t.clients):e=as(t.awareness,t.clients,t.states),_e(this.encoder,e),this.encoder}}class Nh extends we{constructor(){super(...arguments),this.type=At.Stateless,this.description="A stateless message"}get(t){var e;return Vt(this.encoder,t.documentName),Et(this.encoder,this.type),Vt(this.encoder,(e=t.payload)!==null&&e!==void 0?e:""),this.encoder}}class Za extends we{constructor(){super(...arguments),this.type=At.Sync,this.description="First sync step"}get(t){if(typeof t.document>"u")throw new Error("The sync step one message requires document as an argument");return Vt(this.encoder,t.documentName),Et(this.encoder,this.type),xh(this.encoder,t.document),this.encoder}}class Lh extends we{constructor(){super(...arguments),this.type=At.Sync,this.description="A document update"}get(t){return Vt(this.encoder,t.documentName),Et(this.encoder,this.type),Th(this.encoder,t.update),this.encoder}}class Fh extends Error{constructor(){super(...arguments),this.code=1001}}class Oh extends Ya{constructor(t){var e,n,o;super(),this.configuration={name:"",document:void 0,awareness:void 0,token:null,forceSyncInterval:!1,onAuthenticated:()=>null,onAuthenticationFailed:()=>null,onOpen:()=>null,onConnect:()=>null,onMessage:()=>null,onOutgoingMessage:()=>null,onSynced:()=>null,onDisconnect:()=>null,onClose:()=>null,onDestroy:()=>null,onAwarenessUpdate:()=>null,onAwarenessChange:()=>null,onStateless:()=>null,onUnsyncedChanges:()=>null},this.isSynced=!1,this.unsyncedChanges=0,this.isAuthenticated=!1,this.authorizedScope=void 0,this.manageSocket=!1,this._isAttached=!1,this.intervals={forceSync:null},this.boundDocumentUpdateHandler=this.documentUpdateHandler.bind(this),this.boundAwarenessUpdateHandler=this.awarenessUpdateHandler.bind(this),this.boundPageHide=this.pageHide.bind(this),this.boundOnOpen=this.onOpen.bind(this),this.boundOnClose=this.onClose.bind(this),this.forwardConnect=r=>this.emit("connect",r),this.forwardClose=r=>this.emit("close",r),this.forwardDisconnect=r=>this.emit("disconnect",r),this.forwardDestroy=r=>this.emit("destroy",r),this.setConfiguration(t),this.configuration.document=t.document?t.document:new I.Doc,this.configuration.awareness=t.awareness!==void 0?t.awareness:new kh(this.document),this.on("open",this.configuration.onOpen),this.on("message",this.configuration.onMessage),this.on("outgoingMessage",this.configuration.onOutgoingMessage),this.on("synced",this.configuration.onSynced),this.on("destroy",this.configuration.onDestroy),this.on("awarenessUpdate",this.configuration.onAwarenessUpdate),this.on("awarenessChange",this.configuration.onAwarenessChange),this.on("stateless",this.configuration.onStateless),this.on("unsyncedChanges",this.configuration.onUnsyncedChanges),this.on("authenticated",this.configuration.onAuthenticated),this.on("authenticationFailed",this.configuration.onAuthenticationFailed),(e=this.awareness)===null||e===void 0||e.on("update",()=>{this.emit("awarenessUpdate",{states:$a(this.awareness.getStates())})}),(n=this.awareness)===null||n===void 0||n.on("change",()=>{this.emit("awarenessChange",{states:$a(this.awareness.getStates())})}),this.document.on("update",this.boundDocumentUpdateHandler),(o=this.awareness)===null||o===void 0||o.on("update",this.boundAwarenessUpdateHandler),this.registerEventListeners(),this.configuration.forceSyncInterval&&typeof this.configuration.forceSyncInterval=="number"&&(this.intervals.forceSync=setInterval(this.forceSync.bind(this),this.configuration.forceSyncInterval)),this.manageSocket&&this.attach()}setConfiguration(t={}){if(!t.websocketProvider){const e=t;this.manageSocket=!0,this.configuration.websocketProvider=new vh({url:e.url})}this.configuration={...this.configuration,...t}}get document(){return this.configuration.document}get isAttached(){return this._isAttached}get awareness(){return this.configuration.awareness}get hasUnsyncedChanges(){return this.unsyncedChanges>0}resetUnsyncedChanges(){this.unsyncedChanges=1,this.emit("unsyncedChanges",{number:this.unsyncedChanges})}incrementUnsyncedChanges(){this.unsyncedChanges+=1,this.emit("unsyncedChanges",{number:this.unsyncedChanges})}decrementUnsyncedChanges(){this.unsyncedChanges>0&&(this.unsyncedChanges-=1),this.unsyncedChanges===0&&(this.synced=!0),this.emit("unsyncedChanges",{number:this.unsyncedChanges})}forceSync(){this.resetUnsyncedChanges(),this.send(Za,{document:this.document,documentName:this.configuration.name})}pageHide(){this.awareness&&Io(this.awareness,[this.document.clientID],"page hide")}registerEventListeners(){typeof window>"u"||!("addEventListener"in window)||window.addEventListener("pagehide",this.boundPageHide)}sendStateless(t){this.send(Nh,{documentName:this.configuration.name,payload:t})}documentUpdateHandler(t,e){e!==this&&(this.incrementUnsyncedChanges(),this.send(Lh,{update:t,documentName:this.configuration.name}))}awarenessUpdateHandler({added:t,updated:e,removed:n},o){const r=t.concat(e).concat(n);this.send(Qa,{awareness:this.awareness,clients:r,documentName:this.configuration.name})}get synced(){return this.isSynced}set synced(t){this.isSynced!==t&&(this.isSynced=t,t&&this.emit("synced",{state:t}))}receiveStateless(t){this.emit("stateless",{payload:t})}async connect(){if(this.manageSocket)return this.configuration.websocketProvider.connect();console.warn("HocuspocusProvider::connect() is deprecated and does not do anything. Please connect/disconnect on the websocketProvider, or attach/deattach providers.")}disconnect(){if(this.manageSocket)return this.configuration.websocketProvider.disconnect();console.warn("HocuspocusProvider::disconnect() is deprecated and does not do anything. Please connect/disconnect on the websocketProvider, or attach/deattach providers.")}async onOpen(t){this.isAuthenticated=!1,this.emit("open",{event:t});let e;try{e=await this.getToken()}catch(n){this.permissionDeniedHandler(`Failed to get token: ${n}`);return}this.send(Eh,{token:e??"",documentName:this.configuration.name}),this.startSync()}async getToken(){return typeof this.configuration.token=="function"?await this.configuration.token():this.configuration.token}startSync(){this.resetUnsyncedChanges(),this.send(Za,{document:this.document,documentName:this.configuration.name}),this.awareness&&this.awareness.getLocalState()!==null&&this.send(Qa,{awareness:this.awareness,clients:[this.document.clientID],documentName:this.configuration.name})}send(t,e){if(!this._isAttached)return;const n=new Bh(t,e);this.emit("outgoingMessage",{message:n.message}),n.send(this.configuration.websocketProvider)}onMessage(t){const e=new ls(t.data),n=e.readVarString();e.writeVarString(n),this.emit("message",{event:t,message:new ls(t.data)}),new Mh(e).apply(this,!0)}onClose(){this.isAuthenticated=!1,this.synced=!1,this.awareness&&Io(this.awareness,Array.from(this.awareness.getStates().keys()).filter(t=>t!==this.document.clientID),this)}destroy(){this.emit("destroy"),this.intervals.forceSync&&clearInterval(this.intervals.forceSync),this.awareness&&(Io(this.awareness,[this.document.clientID],"provider destroy"),this.awareness.off("update",this.boundAwarenessUpdateHandler),this.awareness.destroy()),this.document.off("update",this.boundDocumentUpdateHandler),this.removeAllListeners(),this.detach(),this.manageSocket&&this.configuration.websocketProvider.destroy(),!(typeof window>"u"||!("removeEventListener"in window))&&window.removeEventListener("pagehide",this.boundPageHide)}detach(){this.configuration.websocketProvider.off("connect",this.configuration.onConnect),this.configuration.websocketProvider.off("connect",this.forwardConnect),this.configuration.websocketProvider.off("open",this.boundOnOpen),this.configuration.websocketProvider.off("close",this.boundOnClose),this.configuration.websocketProvider.off("close",this.configuration.onClose),this.configuration.websocketProvider.off("close",this.forwardClose),this.configuration.websocketProvider.off("disconnect",this.configuration.onDisconnect),this.configuration.websocketProvider.off("disconnect",this.forwardDisconnect),this.configuration.websocketProvider.off("destroy",this.configuration.onDestroy),this.configuration.websocketProvider.off("destroy",this.forwardDestroy),this.configuration.websocketProvider.detach(this),this._isAttached=!1}attach(){this._isAttached||(this.configuration.websocketProvider.on("connect",this.configuration.onConnect),this.configuration.websocketProvider.on("connect",this.forwardConnect),this.configuration.websocketProvider.on("open",this.boundOnOpen),this.configuration.websocketProvider.on("close",this.boundOnClose),this.configuration.websocketProvider.on("close",this.configuration.onClose),this.configuration.websocketProvider.on("close",this.forwardClose),this.configuration.websocketProvider.on("disconnect",this.configuration.onDisconnect),this.configuration.websocketProvider.on("disconnect",this.forwardDisconnect),this.configuration.websocketProvider.on("destroy",this.configuration.onDestroy),this.configuration.websocketProvider.on("destroy",this.forwardDestroy),this.configuration.websocketProvider.attach(this),this._isAttached=!0)}permissionDeniedHandler(t){this.emit("authenticationFailed",{reason:t}),this.isAuthenticated=!1}authenticatedHandler(t){this.isAuthenticated=!0,this.authorizedScope=t,this.emit("authenticated",{scope:t})}setAwarenessField(t,e){if(!this.awareness)throw new Fh(`Cannot set awareness field "${t}" to ${JSON.stringify(e)}. You have disabled Awareness for this provider by explicitly passing awareness: null in the provider configuration.`);this.awareness.setLocalStateField(t,e)}}const tl=10,vo=(s,t,e)=>Math.max(t,Math.min(e,s));function Ue(s){const t={};for(const[e,n]of Object.entries(s??{}))ho.has(e)&&e!=="aiGenerated"&&e!=="__htmlClassName"||n==null||(t[e]=n);return JSON.stringify(t)}function mn(s){if(typeof s!="string"||s.length===0)return null;try{const t=JSON.parse(s);return t&&typeof t=="object"&&typeof t.id=="string"?t:null}catch{return null}}function xo(s){if(typeof s!="string"||s.length===0)return null;try{const t=JSON.parse(s);return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function el(s,t){if(!s)return;const e={},n=!!s.footnoteRef;for(const[o,r]of Object.entries(s))r===void 0||r===!1||r===null||ho.has(o)||o==="link"&&t?.excludeLink||o!=="footnoteRef"&&(o==="superscript"&&n||(e[o]=r));return Object.keys(e).length>0?e:void 0}const nl=["spaceBefore","spaceAfter","contextualSpacing"];function bn(s,t){t.spaceBefore!==void 0&&s.setAttribute("spaceBefore",String(t.spaceBefore)),t.spaceAfter!==void 0&&s.setAttribute("spaceAfter",String(t.spaceAfter)),t.contextualSpacing!==void 0&&s.setAttribute("contextualSpacing",String(t.contextualSpacing))}function Rh(s,t,e=!1){for(const n of nl){const o=rt(s,n);o!=null?t.setAttribute(n,o):e&&et(t,n)}}function ol(s){if(!s)return{};if(typeof s=="string")try{return JSON.parse(s)}catch{return{}}return typeof s=="object"?{...s}:{}}function rl(s){const t=ol(s.getAttribute("_emptyTextMarks"));if(Object.keys(t).length===0)return!1;for(const e of _s)delete t[e];return Object.keys(t).length===0?s.removeAttribute("_emptyTextMarks"):s.setAttribute("_emptyTextMarks",JSON.stringify(t)),!0}function sl(s,t,e,n){const o=s.getAttribute("_emptyTextMarks"),r=o!=null,i=e==null||e===!1;if(!r&&!n&&!i)return!1;const a=ol(o),l=Object.prototype.hasOwnProperty.call(a,t);if(i){if(!l)return!1;delete a[t]}else{if(a[t]===e)return!1;a[t]=e}return Object.keys(a).length===0?s.removeAttribute("_emptyTextMarks"):s.setAttribute("_emptyTextMarks",JSON.stringify(a)),!0}function wo(s,t){t&&Object.keys(t).length>0?s.setAttribute("_emptyTextMarks",JSON.stringify(t)):s.removeAttribute("_emptyTextMarks")}function Ao(s){return s.children.some(t=>t.type==="text"&&t.text.length>0)}function yn(s,t,e,n){if(!Ao(t))return de(n);if(e.offset<=0){const r=t.children.find(i=>i.type==="text"&&i.text.length>0);return de(r?.marks)}const o=Ns(s,e);return de(o?.marks)}const kn=s=>s?.type==="code"||s?.type==="math",ze=s=>{if(!s||s.type!=="code")return!1;const t=s.language?.trim().toLowerCase();return t==="latex"||t==="latex-inline"},jt="Arial, sans-serif";function il(s){if(s==null)return;const t=Number.parseFloat(s);return Number.isFinite(t)?t:void 0}function al(s,t){for(const e of s.toArray())if(e instanceof I.XmlElement){if(e.nodeName==="paragraph"){t(e);continue}(e.nodeName==="container"||e.nodeName==="table"||e.nodeName==="table-row"||e.nodeName==="table-cell")&&al(e,t)}}const ll=s=>s.name==="set_title"||s.name==="set_notes"||s.name==="set_page_layout"||s.name==="set_header_footer",Dh=s=>`${s} ${s===1?"proposal":"proposals"}`;function Ot(s){if(!s||typeof s!="object")return"";if(s.type==="text"&&typeof s.text=="string")return s.text;if((s.type==="code"||s.type==="math")&&typeof s.content=="string")return s.content;if(Array.isArray(s.children)){const t=s.type==="paragraph"||s.type==="list-item"?"":" ";return s.children.map(e=>Ot(e)).filter(e=>e.length>0).join(t)}return""}function ds(s){const t=s.replace(/\s+/g," ").trim();return t.length===0?[]:t.split(" ")}function $h(s,t){if(s.length===0||t.length===0)return 0;const e=new Array(t.length+1).fill(0),n=new Array(t.length+1).fill(0);for(let o=1;o<=s.length;o++){for(let r=1;r<=t.length;r++)n[r]=s[o-1]===t[r-1]?e[r-1]+1:Math.max(e[r],n[r-1]);for(let r=0;r<=t.length;r++)e[r]=n[r],n[r]=0}return e[t.length]}function jh(s,t){const e=ds(s),n=ds(t),o=Math.max(e.length,n.length);if(o===0)return null;const r=$h(e,n),i=Math.max(0,o-r);return Math.round(i/o*100)}function _h(s,t,e){const n=W(s,e),o=W(t,e);if(!n||!o)return null;const r=Ot(n),i=Ot(o);return jh(r,i)}function cl(s,t,e,n,o){if(!s||!t||e.length===0)return s;const r=t.filter(u=>!ll(u));if(r.length!==1||r[0].name!=="replace_block")return s;const i=r[0].arguments&&typeof r[0].arguments=="object"?r[0].arguments:void 0,a=typeof i?.id=="string"&&i.id.trim().length>0?i.id.trim():null;if(!a||(typeof i?.count=="number"&&Number.isFinite(i.count)?Math.max(1,Math.floor(i.count)):1)!==1)return s;const l=[Dh(e.length)],c=_h(n,o,a);c!==null&&l.push(`~${c}% words changed`);const d=s.trim(),g=d.endsWith(".")?`${d.slice(0,-1)} (${l.join("; ")}).`:`${d} (${l.join("; ")}).`;return Uh(n,o,a)>=Xh?`${g} ${dl}`:g}const Xh=80,dl="Most of this block's content would be removed. This is only a pending suggestion: the original content stays in the document until the user accepts it. If that was not intended, undo it with rollback_agent_suggestions for this request instead of rewriting the content; the user can also reject it.";function To(s){return ds(Ot(s)).length}function Uh(s,t,e){const n=To(W(s,e));if(n<3)return 0;const o=W(t,e),r=o?n-To(o):To(s)-To(t);return Math.round(Math.max(0,r)/n*100)}function zh(s,t,e){if(e<=0)return[];const n=Ct(s).get(t);if(!n)return[];const o=n.parentContainer?n.parentContainer.children:s.children,r=[];for(let i=n.indexInParent;i<o.length&&r.length<e;i+=1){const a=o[i];if(!a?.id)break;r.push(a.id)}return r}function Wh(s,t){if(!t||t.length===0)return[];const e=[];for(const n of t){if(n.name!=="replace_block")continue;const o=Ac(n);if(!o||o.replacementBlockIds.length<=1||o.replacedCount<=1)continue;const r=n.arguments&&typeof n.arguments=="object"?n.arguments:void 0,i=typeof r?.id=="string"&&r.id.trim().length>0?r.id.trim():null;if(!i)continue;const a=zh(s,i,o.replacedCount),l=a.length===o.replacedCount&&o.replacementBlockIds.length===o.replacedCount?o.replacedCount:1;for(let c=0;c<l;c+=1){const d=a[c],g=o.replacementBlockIds[c];!d||!g||e.push({currentBlockId:d,finalBlockId:g})}}return e}const gl=(s,t,e)=>{if(!s||!t)return;const n=s.filter(a=>!ll(a));if(n.length!==1){if(n.length===0){const a=s.some(g=>g.name==="set_title"),l=s.some(g=>g.name==="set_notes"),c=s.some(g=>g.name==="set_page_layout");if(a&&l&&c)return"Updated title, notes, and page layout.";if(a&&l)return"Updated title and notes.";if(c&&a)return"Updated page layout and title.";if(c&&l)return"Updated page layout and notes.";if(a){const g=s.find(u=>u.name==="set_title")?.arguments?.title;return g?`Title set to "${g}".`:"Title set."}if(l)return"Notes updated.";if(c)return"Page layout updated.";const d=s.find(g=>g.name==="set_header_footer");if(d){const g=d.arguments?.side==="footer"?"Footer":"Header";return d.arguments?.clear?`${g} removed.`:`${g} updated.`}}return}const o=n[0],r=e?.[0]??[],i=a=>{if(typeof a=="string"&&a.trim().length>0)return a.trim();if(Array.isArray(a)){const l=Array.from(new Set(a.filter(c=>typeof c=="string").map(c=>c.trim()).filter(c=>c.length>0)));return l.length===0?"the target blocks":l.length===1?l[0]:`${l.length} blocks (${l.join(", ")})`}return"the target blocks"};if(o.name==="insert_block"){const a=t.filter(g=>g.name==="insert_block").map(g=>Wn(g)).filter(g=>typeof g=="string"&&g.length>0);if(a.length===0)return;const l=a.length,c=a[0],d=a[a.length-1];return l===1?`Inserted block ${c}.`:`Inserted ${l} blocks; first inserted block ID was ${c}; last inserted block ID was ${d}.`}if(o.name==="replace_block"){const a=t.find(u=>u.name==="replace_block"),l=a&&"id"in a.arguments?a.arguments.id:void 0;if(!l)return;const c=t.filter(u=>u.name==="insert_block").map(u=>Wn(u)).filter(u=>typeof u=="string"&&u.length>0),d=1+c.length,g=c.length>0?c[c.length-1]:l;return d===1?`Replaced block ${l}.`:`Inserted ${d} blocks; first inserted block ID was ${l}; last inserted block ID was ${g}.`}if(o.name==="remove_block"){const{id:a,count:l=1}=o.arguments,c=r.length>0?r.length:l;return`Removed ${c} ${c===1?"block":"blocks"} starting at block ID ${a}.`}if(o.name==="set_block_attribute"){const{id:a,attribute:l,operation:c="set"}=o.arguments,d=i(a);return c==="toggle"?`Toggled ${l} on ${d}.`:c==="remove"?`Removed ${l} from ${d}.`:`Updated ${l} on ${d}.`}if(o.name==="clear_formatting"){const{id:a}=o.arguments;return`Cleared removable formatting on ${i(a)}. Font family, font size, text color, and paragraph attributes were intentionally preserved.`}if(o.name==="replace"||o.name==="replace_all"){const{id:a}=o.arguments,l=r.length>0?r.length:1;return`Replaced ${l} ${l===1?"occurrence":"occurrences"} in block ${a}.`}if(o.name==="append_to_paragraph"){const{id:a}=o.arguments,l=r.map(c=>c.text?.length??0).reduce((c,d)=>c+d,0);return l>0?`Appended ${l} characters to block ${a}.`:`Appended content to block ${a}.`}if(o.name==="break_paragraph"){const{id:a}=o.arguments,l=r.find(c=>c.kind==="insert"&&c.paragraphId!==a);return l?.paragraphId?`Split block ${a}; new block ID ${l.paragraphId}.`:`Split block ${a}.`}if(o.name==="join_paragraphs"){const{firstId:a,secondId:l}=o.arguments;return`Joined adjacent blocks ${a} and ${l}; preserved block ${a}.`}if(o.name==="insert_table_row"){const{tableId:a,referenceIndex:l,referenceRowId:c,position:d}=o.arguments,g=r.find(u=>u.kind==="insert"&&u.paragraphId===a);return g?.text?`${g.text} in table ${a}.`:`Inserted 1 row ${d} row ${c??l} in table ${a}.`}if(o.name==="remove_table_row"){const{tableId:a}=o.arguments,l=r.filter(c=>c.kind==="delete"&&c.paragraphId===a).map(c=>(c.text??"").replace(/ removed$/,""));return l.length?`Removed ${l.length} row${l.length===1?"":"s"} from table ${a}: ${l.join(", ")}. Row indexes after them shifted up; keep targeting rows by rowIds.`:`Removed rows from table ${a}.`}if(o.name==="insert_table_column"){const{tableId:a,referenceIndex:l,position:c}=o.arguments;return`Inserted 1 column ${c} column ${l} in table ${a}.`}if(o.name==="remove_table_column"){const{tableId:a,columnIndex:l}=o.arguments;return`Removed column ${l} from table ${a}.`}},ul=class le{constructor(t,e=()=>{},n,o,r,i,a,l){this.cachedDoc=null,this.incrementalRefreshPending=!1,this.derivedDocumentRevision=0,this.liveSuggestionIdsCache=null,this.liveSuggestionIdsBySourceCache=new Map,this.inlineSuggestionMetadataCache=new Map,this.inlineSuggestionKindCache=new Map,this.canResolveLiveSuggestionCache=new Map,this.liveSuggestionProjectionCache=new Map,this.suggestionIdsByBlockCache=new WeakMap,this.documentSuggestionIdsCache=null,this.afterOperationSelection=null,this.beforeOperationSelection=null,this.beforeOperationRelativeSelection=null,this.afterOperationRelativeSelection=null,this.origin="local-user",this.trackedUndoOrigins=new Set([null,"local-user"]),this.remoteOrigins=new Set,this.isRedoing=!1,this.currentSelectionBeforeRedo=null,this.afterSelectionForRedo=null,this.rebuiltMigrationSnapshotConversations=new Set,this.listStartNumberCache=new Map,this.batchingUpdates=!1,this.pendingUpdate=null,this.disposed=!1,this.handleYDocUpdate=(p,m,y,b)=>{if(this.disposed)return;m!==Cs&&m!==sa&&this.canRepairIdentity()&&(this.classifyTransactionOrigin(m)==="local"?this.repairDocumentIdentity(b,m):this.scheduleDeferredIdentityRepair());const k=this.ydoc.share.get("agent-presence"),S=k&&b.changedParentTypes.size>0&&[...b.changedParentTypes.keys()].every(x=>x===k),v=this.classifyTransactionOrigin(m);S||(this.invalidateDerivedDocumentState(),this.cachedDoc=null,this.incrementalRefreshPending=!0),this.batchingUpdates?this.pendingUpdate=()=>this.onDocumentChange(this.getDocument(),{origin:v}):this.onDocumentChange(this.getDocument(),{origin:v})},this.suggestingMode=!1,this.docxRoundTripRequired=!1,this.liveSuggestionMetadataContext=null,this.defaultHumanAuthorName=null,this.liveSuggestionTreeRecordCache=new Map,this.liveSuggestionTreeRecordCacheReady=!1,this.lastPrunedUnresolvableLiveSuggestions=[],this.listOperations=new yu(this),this.suggestionEngine=new ft(this),this.cachedKernel=null,this.strandedObservers=!1,this.strandedCheck=null,this.identityRepairedOnConstruct=!1,this.deferredIdentityRepair=null,this.ydoc=o||Eo(t),ra(this.ydoc,Ar),this.canRepairIdentity=l?.canRepairIdentity??(()=>!0),!l?.deferIdentityRepair&&this.canRepairIdentity()&&this.repairDocumentIdentity()&&(this.identityRepairedOnConstruct=!0,t=mt(this.ydoc)),this.documentId=r||"default",this.onDocumentChange=e,this.onTitleChange=n,this.detachedSuggestionStore=new Rr(this.ydoc,this.documentId,i),this.toolCallHistory=new xa,this.preprocessorSession=a||new an,this.ensureParagraphIndentStorageUsesUnits(),this.cachedDoc=t,Rn(this.ydoc,t),this.documentSuggestionIdsCache=this.suggestionEngine.createDocumentSuggestionIdsCache(t);const c=this.ydoc.getXmlFragment("content"),d=this.ydoc.getXmlFragment("chrome"),g=this.ydoc.getXmlFragment("notes"),u=this.ydoc.getArray("annotations"),f=this.suggestionEngine.getLiveSuggestionStore(),h=this.ydoc.getMap("comments");this.undoManager=new I.UndoManager([c,d,g,u,f,h],{captureTimeout:1e3,trackedOrigins:this.trackedUndoOrigins}),this.ydoc.on("update",this.handleYDocUpdate),this.undoManager.on("stack-item-added",p=>{this.isRedoing?(this.currentSelectionBeforeRedo&&p.stackItem.meta.set("beforeSelection",this.currentSelectionBeforeRedo),this.afterSelectionForRedo&&p.stackItem.meta.set("afterSelection",this.afterSelectionForRedo),this.currentSelectionBeforeRedo=null,this.afterSelectionForRedo=null,this.isRedoing=!1):(this.beforeOperationRelativeSelection?p.stackItem.meta.set("beforeSelection",this.beforeOperationRelativeSelection):this.beforeOperationSelection&&p.stackItem.meta.set("beforeSelectionAbsolute",this.beforeOperationSelection),this.afterOperationRelativeSelection&&p.stackItem.meta.set("afterSelection",this.afterOperationRelativeSelection),this.beforeOperationSelection&&p.stackItem.meta.set("beforeSelectionAbsolute",this.beforeOperationSelection)),this.beforeOperationRelativeSelection=null,this.afterOperationRelativeSelection=null}),this.undoManager.on("stack-item-popped",p=>{if(p.type==="undo"){const m=this.undoManager.redoStack;if(m.length>0&&p.stackItem.meta.size>0){const y=m[m.length-1];p.stackItem.meta.forEach((b,k)=>{y.meta.set(k,b)})}}})}invalidateDerivedDocumentState(){this.derivedDocumentRevision+=1,this.liveSuggestionIdsCache=null,this.liveSuggestionIdsBySourceCache.clear(),this.inlineSuggestionMetadataCache.clear(),this.inlineSuggestionKindCache.clear(),this.canResolveLiveSuggestionCache.clear();for(const t of this.liveSuggestionProjectionCache.values())t.projection.ydoc.destroy();this.liveSuggestionProjectionCache.clear(),this.documentSuggestionIdsCache=null,this.liveSuggestionTreeRecordCache.clear(),this.liveSuggestionTreeRecordCacheReady=!1}getTopLevelIndexFromPath(t){return!t||t.length===0?null:t.length>0?t[0]:0}getTopLevelIndexFromPosition(t){if(!t)return null;const e=this.getBlockContextById(this.getDocument(),t.block);return e?e.topLevelIndex:null}getBlockContextById(t,e){const n=W(t,e);if(!n)return null;const o=ue(t,e);if(!o||o.length===0)return Ps(t,e)?{block:n,blockPath:[-1],topLevelIndex:-1}:null;const r=o[0];return{block:n,blockPath:o,topLevelIndex:r}}cursorAtBlock(t,e,n=this.getDocument()){const o=n.children[t];return o?.id?{block:o.id,offset:e}:null}resolveFontFamilyForList(t){for(const e of t.children)for(const n of e.children)if(n.type==="text"&&n.marks?.fontFamily)return n.marks.fontFamily}getFontAtOffsetInListItem(t,e){if(e<=0){for(const r of t.children)if(r.type==="text"&&r.marks?.fontFamily)return r.marks.fontFamily;return}let n=0,o;for(const r of t.children)if(r.type==="text"){const i=r.text.length;if(r.marks?.fontFamily&&(o=r.marks.fontFamily),n+i>=e)return r.marks?.fontFamily||o;n+=i}return o}registerTrackedUndoOrigin(t){t!==void 0&&this.trackedUndoOrigins.add(t)}registerRemoteOrigin(t){if(t==null)throw new Error("A collaboration provider must apply updates with a non-null transaction origin");this.remoteOrigins.add(t),this.trackedUndoOrigins.delete(t)}unregisterRemoteOrigin(t){this.remoteOrigins.delete(t)}classifyTransactionOrigin(t){return t===this.origin||this.trackedUndoOrigins.has(t)?"local":this.remoteOrigins.has(t)||t instanceof Oh?"remote":"unknown"}runWithUndoGroup(t,e){const n=this.origin;this.registerTrackedUndoOrigin(t),this.undoManager.stopCapturing(),this.beginGroup(t),this.origin=t;try{return e()}finally{this.origin=n,this.endGroup()}}getTextMarksAtBlockOffset(t,e,n){const o=W(this.getDocument(),t);if(!o)return;const r=o.type==="paragraph"?o.children:o.type==="list"&&e!==void 0?o.children[e]?.children:void 0;if(!r)return;let i=0;for(const a of r){if(a.type!=="text")continue;const l=i+a.text.length;if(n<l||a.text.length===0&&n===i)return a.marks;i=l}return[...r].reverse().find(a=>a.type==="text")?.marks}getFormattingDescriptionFromMarkKey(t){switch(t){case"bold":return"Bold";case"italic":return"Italic";case"underline":return"Underline";case"strikethrough":return"Strikethrough";case"doubleStrikethrough":return"Double Strikethrough";case"smallCaps":return"Small Caps";case"allCaps":return"All Caps";case"letterSpacing":return"Letter Spacing";case"code":return"Code";case"latex":return"LaTeX";case"superscript":return"Superscript";case"subscript":return"Subscript";case"backgroundColor":return"Highlight";case"fontSize":return"Font Size";case"color":return"Text Color";case"fontFamily":return"Font";case"link":return"Link";default:return"Format"}}getNaturalFormatCategoryFromMarkKey(t){switch(t){case"bold":return"bold";case"italic":return"italic";case"underline":return"underline";case"strikethrough":return"strikethrough";case"doubleStrikethrough":return"double strikethrough";case"smallCaps":return"small caps";case"allCaps":return"all caps";case"letterSpacing":return"letter spacing";case"superscript":return"superscript";case"subscript":return"subscript";case"fontSize":return"font size";case"color":return"text color";case"fontFamily":return"font";case"backgroundColor":return"highlight";case"link":return"link";case"code":return"code style";case"latex":return"LaTeX";default:return"formatting"}}getNaturalFormatCategoryFromDescription(t){return t.trim().toLowerCase()||"formatting"}buildNaturalFormatChangeDescription(t){const e=t.filter((o,r)=>t.indexOf(o)===r);if(e.length===0)return"Formatting";const n=e.join(", ");return n.charAt(0).toUpperCase()+n.slice(1)}getInlineFormatDescription(t){const e=new Set,n=new Set,o=["bold","italic","underline","strikethrough","doubleStrikethrough","smallCaps","allCaps","letterSpacing","code","latex","superscript","subscript","fontFamily","fontSize","color","backgroundColor","link"];for(const r of t.spans){const i=this.getTextMarksAtBlockOffset(r.blockId,r.itemIndex,r.start);for(const a of o){const l=r.attributes[a],c=i?.[a];a==="fontFamily"&&(l??void 0)===void 0&&c===jt||(l??void 0)!==(c??void 0)&&(e.add(a),(c??void 0)===void 0||c===!1?n.add(a):n.delete(a))}}if(e.size>0){const r=Array.from(e).map(i=>{const a=this.getNaturalFormatCategoryFromMarkKey(i);return n.has(i)?`remove ${a}`:a});return this.buildNaturalFormatChangeDescription(r)}return t.label&&t.label!=="Format"?this.buildNaturalFormatChangeDescription([this.getNaturalFormatCategoryFromDescription(t.label)]):null}getBlockDescription(t){if(!t)return null;switch(t.type){case"image":return"Image";case"table":return"Table";case"code":return t.language==="latex"?"LaTeX Block":t.renderDiagram?"Diagram":"Code Block";case"math":return"LaTeX Block";case"page-break":return"Page Break";case"section-break":return"Section Break";case"placeholder":return"Placeholder";case"toc":return"Table of Contents";case"container":return"Container";case"paragraph":case"list":return null;default:return null}}getTableDimensionDescription(t,e,n){if(!t||t!=="Row"&&t!=="Column"||e?.type!=="table"||n?.type!=="table")return null;const o=t==="Row"?e.children.length:e.columnWidths.length,r=t==="Row"?n.children.length:n.columnWidths.length;return r>o?`Insert Table ${t}`:r<o?`Delete Table ${t}`:`Change Table ${t}`}getTextFormattingChangeKeys(t,e){const n=new Set,o=t.map(a=>a.text).join(""),r=e.map(a=>a.text).join("");if(o!==r)return[];const i=Math.max(o.length,r.length);for(let a=0;a<i;a++){const l=this.getTextMarksAtOffset(t,a),c=this.getTextMarksAtOffset(e,a);for(const d of Tn)this.formattingMarkValuesEqual(l?.[d],c?.[d])||n.add(d)}if(i===0){const a=t[0]?.marks,l=e[0]?.marks;for(const c of Tn)this.formattingMarkValuesEqual(a?.[c],l?.[c])||n.add(c)}return Tn.filter(a=>n.has(a))}getTextMarksAtOffset(t,e){let n=0;for(const o of t){const r=n+o.text.length;if(e<r)return o.marks;n=r}return t[t.length-1]?.marks}formattingMarkValuesEqual(t,e){const n=t??void 0,o=e??void 0;return n===o?!0:typeof n=="string"&&typeof o=="string"&&/^#[0-9a-fA-F]{6}$/.test(n)&&/^#[0-9a-fA-F]{6}$/.test(o)?n.toLowerCase()===o.toLowerCase():!1}getBlockFormatDescription(t,e){const n=[],o=r=>{n.includes(r)||n.push(r)};if(t?.type==="paragraph"&&e?.type==="paragraph"&&(t.heading!==e.heading&&o("heading"),t.align!==e.align&&o("alignment"),t.lineSpacing!==e.lineSpacing&&o("line spacing"),(t.leftIndent!==e.leftIndent||t.firstLineIndent!==e.firstLineIndent)&&o("indent"),n.length===0))for(const r of this.getTextFormattingChangeKeys(t.children,e.children))o(this.getNaturalFormatCategoryFromMarkKey(r));if(t?.type==="list"&&e?.type==="list"){t.lineSpacing!==e.lineSpacing&&o("line spacing");const r=Math.max(t.children.length,e.children.length);if(n.length===0)for(let i=0;i<r;i++){const a=t.children[i],l=e.children[i];if(!(!a||!l))for(const c of this.getTextFormattingChangeKeys(a.children,l.children))o(this.getNaturalFormatCategoryFromMarkKey(c))}}return this.buildNaturalFormatChangeDescription(n)}inlineFormatRecordHasLiveMarker(t){return t.spans.some(e=>{const n=this.suggestionEngine.getYTextForSuggestionSpan(e);return n?this.collectOverlappingTextSpans(n,e.start,e.end-e.start).some(o=>o.attributes.suggestionId===t.id&&!!o.attributes.formatChange):!1})}cloneYDoc(t){const e=new I.Doc;return I.applyUpdate(e,I.encodeStateAsUpdate(t)),e}collapseAffectedBlockIds(t,e){const n=Array.from(new Set(Array.from(t).filter(d=>typeof d=="string"&&d.length>0))),o=new Set(n),r=this.getDocument(),i=Ct(r),a=Ct(e),l=new Map;for(const d of[i,a])for(const{block:g}of d.values())if(g.type==="list")for(const u of g.children)l.set(u.id,g.id);const c=(d,g)=>{let u=Xt(d,g);for(;u&&u.type!=="doc";){if(u.id)return u.id;u=Xt(d,u.id)}return null};return n.filter(d=>{const g=l.get(d);if(g&&o.has(g))return!1;const u=[i.get(d),a.get(d)];let f=!1;for(const p of u)if(p&&(f=!0,p.containerPath.some(m=>m!==d&&o.has(m))))return!1;if(f)return!0;let h=d;for(;h;){const p=c(r,h)??c(e,h);if(!p)break;if(o.has(p))return!1;h=p}return!0})}collectOverlappingTextSpans(t,e,n){if(n<=0)return[];const o=[],r=e+n,i=st(t);let a=0;for(const l of i){if(typeof l.insert!="string")continue;const c=a,d=a+l.insert.length,g=Math.max(e,c),u=Math.min(r,d);if(g<u&&o.push({start:g,length:u-g,attributes:{...l.attributes||{}}}),a=d,a>=r)break}return o}normalizeAdjacentManualReplacementOrder(t,e){const n=[];let o=0;for(const h of st(t)){if(typeof h.insert!="string"||h.insert.length===0){o+=typeof h.insert=="string"?h.insert.length:1;continue}const p=o,m=p+h.insert.length;n.push({start:p,end:m,text:h.insert,attributes:{...h.attributes||{}}}),o=m}const r=n.findIndex(h=>h.start===e&&h.attributes.deletion);if(r<=0)return null;let i=r-1;if(n[i].end!==e||!n[i].attributes.insertion)return null;for(;i>0&&n[i-1].end===n[i].start&&n[i-1].attributes.insertion;)i-=1;let a=r;for(;a+1<n.length&&n[a].end===n[a+1].start&&n[a+1].attributes.deletion;)a+=1;const l=n.slice(i,a+1);if(l.some(h=>!h.attributes.insertion&&!h.attributes.deletion||h.attributes.insertion&&h.attributes.deletion))return null;const c=l.filter(h=>h.attributes.insertion),d=l.filter(h=>h.attributes.deletion);if(c.length===0||d.length===0)return null;const g=l[0].start,u=l[l.length-1].end-g;t.delete(g,u);let f=g;for(const h of[...d,...c])lt(t,f,h.text,h.attributes),f+=h.text.length;return{regionStart:g,insertionLength:c.reduce((h,p)=>h+p.text.length,0),deletionLength:d.reduce((h,p)=>h+p.text.length,0)}}static remapOffsetAcrossReplacementNormalization(t,e){const{regionStart:n,insertionLength:o,deletionLength:r}=e,i=n+o+r;return t<=n||t>i?t:t<=n+o?t+r:t-o}findSingleTableColumnDelta(t,e){if(t.children.length===0||t.children.length!==e.children.length)return null;let n=null,o=null;for(let r=0;r<t.children.length;r++){const i=t.children[r].children,a=e.children[r].children,l=a.length-i.length;if(Math.abs(l)!==1)return null;const c=l>0?"insert":"delete",d=l>0?a:i,g=l>0?i:a;let u=0;for(;u<g.length&&d[u]?.id===g[u]?.id;)u++;for(let f=u;f<g.length;f++)if(d[f+1]?.id!==g[f]?.id)return null;if(n!==null&&n!==c||o!==null&&o!==u)return null;n=c,o=u}return n!==null&&o!==null?{kind:n,index:o}:null}getTrailingCleanupParagraphIdForTopLevelBlock(t,e){const n=t.children.findIndex(r=>r.id===e);if(n===-1||n!==t.children.length-2)return;const o=t.children[n+1];if(!(!o||o.type!=="paragraph"||o.children.some(r=>r.type!=="text"||r.text.length>0)))return o.id}collectStructuralInsertBlockIds(t,e,n=[]){if("id"in t&&typeof t.id=="string"&&"structuralSuggestionKind"in t&&t.structuralSuggestionKind==="insert"&&"structuralSuggestionId"in t&&t.structuralSuggestionId===e&&n.push(t.id),t.type==="doc"&&Array.isArray(t.notes))for(const o of t.notes)this.collectStructuralInsertBlockIds(o,e,n);if(!("children"in t)||!Array.isArray(t.children))return n;for(const o of t.children)o&&typeof o=="object"&&this.collectStructuralInsertBlockIds(o,e,n);return n}replaceAnyBlockById(t,e,n,o){this.beforeOperationSelection=n;const r=this.getDocument();if(!W(r,t))return!1;const i=ot(this.ydoc,t);return i?(this.beforeOperationRelativeSelection=Y(n,this.ydoc,r),this.transact(()=>{this.replaceBlockByIdWithoutSelection(t,e,i)}),this.setSelectionAfterOperation(o),this.afterOperationRelativeSelection=Y(o,this.ydoc,this.getDocument()),!0):!1}isListItemBlockChangeRecord(t){return!!(t.beforeBlock.type==="list"&&t.listItemSuggestion)}applyListItemBlockChangeDecision(t,e,n){const o=W(this.getDocument(),t.blockId);if(!o||o.type!=="list")return!1;const r=this.suggestionEngine.cloneSuggestionSnapshot(o),i=r.children.findIndex(u=>u.structuralSuggestionId===t.id);if(i===-1)return!1;const a=this.suggestionEngine.cloneSuggestionSnapshot(r);if(a.structuralSuggestionRecord)try{JSON.parse(a.structuralSuggestionRecord).id===t.id&&delete a.structuralSuggestionRecord}catch{}const{kind:l,beforeItem:c,afterItem:d}=t.listItemSuggestion;if(l==="insert")e==="accept"?a.children[i]=this.suggestionEngine.cloneSuggestionSnapshot(d??a.children[i]):a.children.splice(i,1);else if(l==="delete")e==="accept"?a.children.splice(i,1):a.children[i]=this.suggestionEngine.cloneSuggestionSnapshot(c??a.children[i]);else{const u=e==="accept"?d??a.children[i]:c;if(!u)return!1;let f=this.suggestionEngine.cloneSuggestionSnapshot(u);if(c?.children?.length===0&&d?.children?.length===0){const h={...a.children[i]};for(const y of["structuralSuggestionId","structuralSuggestionKind","structuralSuggestionLabel","structuralSuggestionRecord"])delete h[y];const p=u,m=new Set([...Object.keys(c),...Object.keys(d)].filter(y=>y!=="type"&&y!=="id"&&y!=="children"));for(const y of m)p[y]===void 0?delete h[y]:h[y]=this.suggestionEngine.cloneSuggestionSnapshot(p[y]);f=h}a.children[i]=f}const g=this.suggestionEngine.runWithoutSuggesting(()=>this.replaceAnyBlockById(t.blockId,a,n,n));return g&&this.suggestionEngine.deleteLiveSuggestion(t.id),g}arePathsEqual(t,e){return!t||!e||t.length!==e.length?!1:t.every((n,o)=>n===e[o])}getParagraphContextForPosition(t,e){const n=e??this.getDocument(),o=this.getBlockContextById(n,t.block);return!o||o.block.type!=="paragraph"?null:{paragraph:o.block,paragraphPath:o.blockPath,topLevelIndex:o.topLevelIndex}}getParagraphOffsetForPosition(t,e){const n=e??this.getDocument(),o=this.getParagraphContextForPosition(t,n);return o?{...o,offset:t.offset}:null}getParagraphTextLength(t){return t.children.reduce((e,n)=>e+(n.type==="text"?n.text.length:0),0)}getCancelableParagraphSplitRecord(t,e){const n=t.structuralSuggestionId;if(!n||n!==e.structuralSuggestionId||t.structuralSuggestionKind!=="split"||e.structuralSuggestionKind!=="split")return null;const o=this.suggestionEngine.getLiveSuggestion(n);if(!o||o.type!=="paragraph-split")return null;const r=new Set([o.blockId,o.insertedBlockId]);return!r.has(t.id)||!r.has(e.id)?null:o}getCancelableParagraphMergeRecord(t,e){const n=t.structuralSuggestionId;if(!n||t.structuralSuggestionKind!=="merge"||!t.structuralSuggestionRole)return null;const o=this.getParagraphTextLength(t);if(!(t.structuralSuggestionRole==="before"&&e===o||t.structuralSuggestionRole==="after"&&e===0))return null;const r=this.suggestionEngine.getLiveSuggestion(n);return!r||r.type!=="paragraph-merge"||r.firstBlockId!==t.id&&r.secondBlockId!==t.id?null:r}isPlainEmptyParagraph(t){return!t.structuralSuggestionId&&!t.structuralSuggestionKind&&this.getParagraphTextLength(t)===0}isInsertedParagraph(t){return t.structuralSuggestionKind==="insert"&&typeof t.structuralSuggestionId=="string"&&t.structuralSuggestionId.length>0}cursorFromParagraphOffset(t,e,n){let o=0;for(const i of e.children)i.type==="text"&&(o+=i.text.length);const r=Math.min(Math.max(0,n),o);return{block:e.id,offset:r}}arePositionsInSameEditableBlock(t,e,n){return e.block===n.block}getYContentFragment(){return We(this.ydoc)}getYChromeFragment(){if(!this.ydoc)throw new Error("No Y.Doc");return this.ydoc.getXmlFragment("chrome")}getYNotesFragment(){if(!this.ydoc)throw new Error("No Y.Doc");return this.ydoc.getXmlFragment("notes")}getYBlockContext(t,e){if(!t.length)return null;const n=this.getYContentFragment(),o=t[0];if(o<0||o>=n.length)return null;const r=n.get(o);return r instanceof I.XmlElement?{parent:n,index:o,yBlock:r}:null}getYParagraphContext(t,e){const n=this.getYBlockContext(t,e);if(!n)return null;for(let o=0;o<n.yBlock.length;o++){const r=n.yBlock.get(o);if(r instanceof I.XmlText)return{yBlock:n.yBlock,yText:r}}return null}getEmptyTextMarksForParagraph(t){const e=this.getYBlockContext(t);if(!e)return;const n=e.yBlock.getAttribute("_emptyTextMarks");if(n)try{return typeof n=="string"?JSON.parse(n):n}catch(o){console.warn("Failed to parse _emptyTextMarks",o);return}}getEmptyTextMarksForBlockId(t){const e=Z(this.ydoc,t);if(!e)return;const n=e.getAttribute("_emptyTextMarks");if(n)try{return typeof n=="string"?JSON.parse(n):n}catch(o){console.warn("Failed to parse _emptyTextMarks",o);return}}resolveEditableContext(t,e){const n=e??this.getDocument(),o=this.getBlockContextById(n,t.block);if(!o)return null;const r={block:o.block,blockPath:o.blockPath},i=ot(this.ydoc,o.block.id),a=i?{parent:i.yParent,index:i.index,yBlock:i.yBlock}:null;return{doc:n,editable:r,yContext:a}}dispose(){this.disposed||(this.disposed=!0,this.ydoc.off("update",this.handleYDocUpdate),this.strandedCheck&&clearTimeout(this.strandedCheck),this.strandedCheck=null,this.deferredIdentityRepair&&clearTimeout(this.deferredIdentityRepair),this.deferredIdentityRepair=null,this.detachedSuggestionStore.destroy(),this.undoManager.destroy(),this.pendingUpdate=null,this.onDocumentChange=()=>{},this.onTitleChange=void 0,this.remoteOrigins.clear(),this.trackedUndoOrigins.clear(),this.toolCallHistory.clear(),this.invalidateDerivedDocumentState())}setSelectionAfterOperation(t){this.afterOperationSelection=t,this.updateAfterOperationRelativeSelection(this.getDocument())}updateAfterOperationRelativeSelection(t){const e=this.afterOperationSelection;this.afterOperationRelativeSelection=e?Y(e,this.ydoc,t):null}getDocument(){return this.cachedDoc||(this.cachedDoc=this.incrementalRefreshPending?Kt(this.ydoc):mt(this.ydoc),this.incrementalRefreshPending=!1),this.cachedDoc}mergeAdjacentListItemsSnapshot(t,e,n){if(e<0||e>=t.children.length-1)return null;const o=this.suggestionEngine.cloneSuggestionSnapshot(t),r=o.children[e],i=o.children[e+1];if(!r||!i)return null;const a=this.suggestionEngine.cloneSuggestionSnapshot(r.children),l=this.suggestionEngine.cloneSuggestionSnapshot(i.children),c=a[a.length-1],d=l[0];return c?.type==="text"&&d?.type==="text"&&JSON.stringify(c.marks||{})===JSON.stringify(d.marks||{})&&(c.text+=d.text,l.shift()),r.children=[...a,...l],n&&(r.structuralSuggestionId=n,r.structuralSuggestionKind="change",r.structuralSuggestionLabel="Join",delete r.structuralSuggestionRole),o.children.splice(e+1,1),o}collectInlineFormattingRanges(t,e,n,o){const r=[],i=xt(o,t,e)<=0,a=i?t:e,l=i?e:t;if(a.block===l.block)return this.collectSingleBlockFormattingRange(a,l,o);{const u=Ps(o,a.block)?.block??(o.notes??[]).find(f=>f.children.some(h=>h.id===a.block));if(u){const f=u.children.map(m=>m.id),h=f.indexOf(a.block),p=f.indexOf(l.block);if(h!==-1&&p!==-1){const[m,y]=h<=p?[h,p]:[p,h],b=[];for(let k=m;k<=y;k++){const S=u.children[k];if(!S.id)continue;const v=k===h?a:{block:S.id,offset:0},x=k===p?l:{block:S.id,offset:Number.MAX_SAFE_INTEGER};b.push(...this.collectSingleBlockFormattingRange({block:S.id,offset:k===h?v.offset:0},{block:S.id,offset:k===p?x.offset:Number.MAX_SAFE_INTEGER},o))}return b}}}const c=ue(o,a.block),d=ue(o,l.block);if(!c||!d){if(a.block===l.block)return this.collectSingleBlockFormattingRange(a,l,o);const u=this.collectSingleBlockFormattingRange(a,a,o),f=this.collectSingleBlockFormattingRange(l,l,o);return[...u,...f]}let g=!0;for(const{block:u,path:f}of Ls(o)){const h=Pe(f,c),p=Pe(f,d);if(h<0)continue;if(p>0)break;const m=p===0,y=ot(this.ydoc,u.id);if(!y){g=!1;continue}const b=y.yBlock;if(u.type==="paragraph"){const k=ct(b);if(!k){g=!1;continue}let S=0,v=k.length;g&&a.block===u.id&&(S=a.offset),m&&l.block===u.id&&(v=l.offset),S=vo(S,0,k.length),v=vo(v,0,k.length);const x=Math.min(S,v),w=Math.max(S,v);w>x&&r.push({yText:k,start:x,end:w,blockId:u.id}),g=!1;continue}if(u.type==="list"){const k=u,S=[];for(let T=0;T<b.length;T++){const E=b.get(T);E instanceof I.XmlElement&&E.nodeName==="list-item"&&S.push(E)}const v=Math.min(k.children.length,S.length);if(v===0){g=!1;continue}let x=0,w=v-1,A=0,P=Number.MAX_SAFE_INTEGER;if(g&&a.block===u.id){const T=this.listOperations.getListCursorInfo(k,a);T&&(x=Math.min(T.itemIndex,v-1),A=T.offsetInItem)}if(m&&l.block===u.id){const T=this.listOperations.getListCursorInfo(k,l);T&&(w=Math.min(T.itemIndex,v-1),P=T.offsetInItem)}for(let T=x;T<=w;T++){const E=S[T];if(!E)continue;const B=ct(E);if(!B||B.length===0)continue;let N=0,R=B.length;T===x&&(N=Math.min(A,B.length)),T===w&&(R=Math.min(P,B.length)),R>N&&r.push({yText:B,start:N,end:R})}g=!1}}return r}collectSingleBlockFormattingRange(t,e,n){const o=[],r=W(n,t.block);if(!r)return o;const i=ot(this.ydoc,t.block);if(!i)return o;const a=i.yBlock;if(r.type==="paragraph"){const l=ct(a);if(!l)return o;let c=t.offset,d=e.offset;c=vo(c,0,l.length),d=vo(d,0,l.length);const g=Math.min(c,d),u=Math.max(c,d);u>g&&o.push({yText:l,start:g,end:u,blockId:r.id})}else if(r.type==="list"){const l=r,c=[];for(let y=0;y<a.length;y++){const b=a.get(y);b instanceof I.XmlElement&&b.nodeName==="list-item"&&c.push(b)}const d=Math.min(l.children.length,c.length);if(d===0)return o;const g=this.listOperations.getListCursorInfo(l,t),u=this.listOperations.getListCursorInfo(l,e);if(!g||!u)return o;let f=Math.min(g.itemIndex,d-1),h=Math.min(u.itemIndex,d-1),p=g.offsetInItem,m=u.offsetInItem;f>h&&([f,h]=[h,f],[p,m]=[m,p]);for(let y=f;y<=h;y++){const b=c[y];if(!b)continue;const k=ct(b);if(!k||k.length===0)continue;let S=0,v=k.length;y===f&&(S=Math.min(p,k.length)),y===h&&(v=Math.min(m,k.length)),v>S&&o.push({yText:k,start:S,end:v,blockId:r.id,itemIndex:y})}}return o}collectParagraphBlockIdsInRange(t,e,n){const o=[],r=new Set,i=u=>{const f=W(n,u);f?.type==="paragraph"&&f.id&&!r.has(f.id)&&(r.add(f.id),o.push(f.id))},a=xt(n,t,e)<=0,l=a?t:e,c=a?e:t,d=ue(n,l.block),g=ue(n,c.block);if(!d||!g)return i(l.block),i(c.block),o;for(const{block:u,path:f}of Ls(n)){const h=Pe(f,d),p=Pe(f,g);if(!(h<0)){if(p>0)break;u.type==="paragraph"&&u.id&&!r.has(u.id)&&(r.add(u.id),o.push(u.id))}}return o.length===0&&i(l.block),o}clearFormattingEmptyMarksAtPosition(t,e){const n=W(e,t.block);if(!n)return!1;if(n.type==="paragraph"){const c=ot(this.ydoc,n.id);return c?rl(c.yBlock):!1}if(n.type!=="list")return!1;const o=n;this.suggestingMode&&this.suggestionEngine.cloneSuggestionSnapshot(o),this.suggestingMode&>();const r=ot(this.ydoc,n.id);if(!r)return!1;const i=this.listOperations.getListCursorInfo(o,t);if(!i)return!1;const a=[];for(let c=0;c<r.yBlock.length;c++){const d=r.yBlock.get(c);d instanceof I.XmlElement&&d.nodeName==="list-item"&&a.push(d)}const l=a[i.itemIndex];return l?rl(l):!1}updateEmptyTextMarksAtPosition(t,e,n,o){const r=W(o,t.block);if(!r)return!1;if(r.type==="paragraph"){const g=ot(this.ydoc,r.id);if(!g)return!1;const u=r.children.some(f=>f.type==="text"&&f.text.length>0);return sl(g.yBlock,e,n,!u)}if(r.type!=="list")return!1;const i=r,a=ot(this.ydoc,r.id);if(!a)return!1;const l=this.listOperations.getListCursorInfo(i,t);if(!l)return!1;const c=[];for(let g=0;g<a.yBlock.length;g++){const u=a.yBlock.get(g);u instanceof I.XmlElement&&u.nodeName==="list-item"&&c.push(u)}const d=c[l.itemIndex];return d?sl(d,e,n,l.itemLength===0):!1}updateBackgroundColorEmptyMarksAtPosition(t,e,n){return this.updateEmptyTextMarksAtPosition(t,"backgroundColor",e,n)}insertTextInCodeBlock(t,e,n,o){this.beforeOperationSelection=n;const r=this.getDocument(),i=W(r,t.block);if(!kn(i))return!1;const a=Z(this.ydoc,t.block);if(!a)return!1;let l=null;for(let u=0;u<a.length;u++){const f=a.get(u);if(f instanceof I.XmlText){l=f;break}}if(!l)return!1;const c=Math.min(t.offset,l.length);this.transact(()=>{l.insert(c,e)});const d={block:t.block,offset:c+e.length},g={anchor:d,focus:d};return this.setSelectionAfterOperation(g),this.afterOperationRelativeSelection=Y(g,this.ydoc,this.getDocument()),!0}deleteTextInCodeBlock(t,e,n,o){this.beforeOperationSelection=n;const r=this.getDocument();this.beforeOperationRelativeSelection=Y(n,this.ydoc,r);const i=W(r,t.block);if(!kn(i))return!1;const a=Z(this.ydoc,t.block);if(!a)return!1;let l=null;for(let g=0;g<a.length;g++){const u=a.get(g);if(u instanceof I.XmlText){l=u;break}}if(!l)return!1;const c=l.length-t.offset,d=Math.min(e,c);return this.transact(()=>{l.delete(t.offset,d)}),this.setSelectionAfterOperation(o),this.afterOperationRelativeSelection=Y(o,this.ydoc,this.getDocument()),!0}getYDoc(){return this.ydoc}getAfterOperationSelection(){return this.afterOperationSelection}captureSelectionBeforeOperation(t){if(!t){this.beforeOperationSelection=null,this.beforeOperationRelativeSelection=null;return}const e=o=>o?{block:o.block,offset:o.offset}:null;this.beforeOperationSelection={anchor:e(t.anchor),focus:e(t.focus)};const n=this.getDocument();this.beforeOperationRelativeSelection=Y(t,this.ydoc,n)}setAfterOperationSelectionFromEditor(t){if(t){const n=o=>o?{block:o.block,offset:o.offset}:null;this.setSelectionAfterOperation({anchor:n(t.anchor),focus:n(t.focus)})}else this.setSelectionAfterOperation(null);if(!t){this.afterOperationRelativeSelection=null;return}const e=this.getDocument();this.afterOperationRelativeSelection=Y(t,this.ydoc,e)}ensureParagraphIndentStorageUsesUnits(){const t=this.ydoc.getMap("metadata");if(t.get(Gt.paragraphIndentStorageVersion)===Po)return;const e=this.ydoc.getXmlFragment("content");if(e.length===0&&Te(this.ydoc))return;const n=t.get(Gt.indentStepPx),o=Ae({indentStepPx:typeof n=="number"?n:void 0}).indentStepPx;this.ydoc.transact(()=>{e.length>0&&al(e,r=>{const i=Es(il(rt(r,"leftIndent")),{indentStepPx:o,storedAsUnits:!1}),a=Es(il(rt(r,"firstLineIndent")),{indentStepPx:o,storedAsUnits:!1,firstLine:!0});i===void 0?et(r,"leftIndent"):r.setAttribute("leftIndent",String(i)),a===void 0?et(r,"firstLineIndent"):r.setAttribute("firstLineIndent",String(a))}),t.set(Gt.paragraphIndentStorageVersion,Po)},"indent-storage-migration")}setTitle(t){const e=Iu(t);this.transact(()=>{this.ydoc.getMap("metadata").set("title",e)}),this.onTitleChange&&this.onTitleChange(e)}setNotes(t){const e=typeof t=="string"?t:String(t??"");this.transact(()=>{const n=this.ydoc.getMap("metadata");e.length===0?n.delete("notes"):n.set("notes",e)})}getDocumentNotes(){const t=this.ydoc.getMap("metadata").get("notes");return typeof t=="string"?t:""}updateSectionBreakLayout(t,e){const n=this.getYContentFragment();let o=null;for(const r of n.toArray())if(r instanceof I.XmlElement&&r.nodeName==="section-break"&&r.getAttribute("id")===t){o=r;break}return o?(this.transact(()=>{o.setAttribute("layout",JSON.stringify(e))}),!0):!1}pinInheritedPageNumbering(t){const e=Ae(this.getPageLayoutSettings()),n=this.getDocument().children.filter(i=>i.type==="section-break"),o=t.pageNumberFormat!==void 0&&t.pageNumberFormat!==e.pageNumberFormat,r=t.pageNumberStart!==void 0&&t.pageNumberStart!==e.pageNumberStart;n.forEach((i,a)=>{const l=i.layout,c={...o&&l?.pageNumberFormat===void 0?{pageNumberFormat:e.pageNumberFormat}:{},...r&&a===0&&l?.pageNumberStart===void 0?{pageNumberStart:e.pageNumberStart}:{}};Object.keys(c).length>0&&this.updateSectionBreakLayout(i.id,{...l??{},...c})})}applyLayoutToAllSectionBreaks(t){const e=this.getYContentFragment();this.transact(()=>{for(const n of e.toArray())if(n instanceof I.XmlElement&&n.nodeName==="section-break"){let o={};try{const i=n.getAttribute("layout");o=typeof i=="string"?JSON.parse(i):{}}catch{o={}}const r={...o.oxmlSectPr!==void 0?{oxmlSectPr:o.oxmlSectPr}:{},...o.pageBorders!==void 0?{pageBorders:o.pageBorders}:{},...o.pageNumberStart!==void 0?{pageNumberStart:o.pageNumberStart}:{},...o.pageNumberFormat!==void 0?{pageNumberFormat:o.pageNumberFormat}:{}};n.setAttribute("layout",JSON.stringify(Ms(r,t)??t))}})}applySetHeaderFooterAction(t){const e=t.side==="footer"?"footer":"header",n=e==="footer"?"Footer":"Header",o=Nl(t.slot);if(o===null)return{changed:!1,error:`set_header_footer: slot must be "default", "first", or "even" (or omitted), got ${JSON.stringify(t.slot)}. Nothing was changed.`};const r=this.getDocument().children.filter(P=>P.type==="section-break").length+1;let i;if(t.sectionIndex!=null){if(typeof t.sectionIndex!="number"||!Number.isInteger(t.sectionIndex)||t.sectionIndex<1||t.sectionIndex>r)return{changed:!1,error:`set_header_footer: sectionIndex must be an integer between 1 and ${r}, got ${JSON.stringify(t.sectionIndex)}.`};i=t.sectionIndex-1}const a={left:t.left??void 0,center:t.center??void 0,right:t.right??void 0},l=t.clear===!0,c=t.image??void 0;let d;if(c){if(l)return{changed:!1,error:"set_header_footer: pass either image or clear=true, not both. To replace the image, pass only image."};if(i!==void 0)return{changed:!1,error:"set_header_footer: header/footer images apply to every section; omit sectionIndex when passing image."};const P=this.resolveHeaderFooterImage(c,e,o??"default");if("error"in P)return{changed:!1,error:`set_header_footer: ${P.error}`};d={side:e,slot:o??"default",...P.image}}const g=a.left!==void 0||a.center!==void 0||a.right!==void 0,u=l||g?wg(this.kernel,{side:e,slot:o,sectionIndex:i,zones:a,clear:l}):{changed:!1,removedCount:0},f=l&&i===void 0?Ag(this.kernel,e,o):0,h=d?Tg(this.kernel,d):!1,p=this.getDocument(),m=p.chrome??[],y=[...Ll(m),...gc(p.chromeImages??[],P=>P.fit==="band"?this.chromeImageDrawnSize(P):void 0)],b=y.length>0?`Headers/footers now in the document:
|
|
11
|
+
${y.map(P=>`- ${P}`).join(`
|
|
12
|
+
`)}`:"The document has no headers or footers.";if(!u.changed&&f===0&&!h){const P=[e,o??(l?"(any slot)":"default"),i===void 0?l?"(any section)":"(all sections)":`(section ${i+1})`].join(" ");return{changed:!1,error:`No changes detected - ${l?`there is no ${P} to remove`:!g&&!d?"no zones (left/center/right), image, or clear were given":`the ${P} already has that content`}. ${b}`}}const k=u.removedCount+f,S=(o??"default")==="first"?"first-page":(o??"default")==="even"?"even-page":"default",v="createdEmpty"in u&&u.createdEmpty?`${n} ${S} slot created empty${i===void 0?"":` for section ${i+1}`}; those pages now show no ${e}.`:l?`${n} removed (${k} item${k===1?"":"s"}).`:`${n} updated.`,x=!l&&g&&i===void 0?m.filter(P=>P.type==="header-footer"&&P.side===e&&P.slot===(o??"default")&&P.sectionIndex!==void 0):[],w=x.length>0?` Note: section ${x.map(P=>P.type==="header-footer"?(P.sectionIndex??0)+1:0).join(", ")} keep their own ${e} (a per-section override); pass sectionIndex to edit it, or clear it to fall back to this one.`:"",A=d?` The image is set at ${Math.round(d.width)}x${Math.round(d.height)}px, fitted to the ${e} margin band (never into the body); check it with render_document_pages. For a larger logo, widen the ${e} margin with set_page_layout, then set the image again.`:"";return{changed:!0,feedback:`${v}${w}${A}
|
|
13
|
+
${b}`}}resolveHeaderFooterImage(t,e,n){const o=t.zone==="center"||t.zone==="right"?t.zone:"left";let r,i,a,l=typeof t.alt=="string"?t.alt:void 0;const c=typeof t.image_id=="string"?t.image_id.trim():"";if(c){const k=W(this.getDocument(),c),S=k?.type==="image"?k:null;if(!S)return{error:`image_id "${c}" is not an image block in this document. Use an existing image block's id, or pass url.`};r=S.src,i=S.width,a=S.height,l??(l=S.alt)}else if(typeof t.url=="string"&&t.url.trim())r=t.url.trim(),i=t.naturalWidth??void 0,a=t.naturalHeight??void 0;else return{error:"image needs image_id or url."};const d=k=>typeof k=="number"&&Number.isFinite(k)&&k>0?k:void 0,g=d(i),u=d(a);let f=d(t.width),h=d(t.height);if(f&&!h&&g&&u&&(h=f*u/g),h&&!f&&g&&u&&(f=h*g/u),f??(f=g),h??(h=u),!f||!h)return{error:"the image's size is unknown; pass width and height in px (it keeps that aspect ratio when scaled to fit the margin)."};const p={side:e,slot:n,src:r,width:f,height:h,fit:"band",...l?{alt:l}:{},...o!=="left"?{align:o}:{}};if(!this.chromeImageDrawnSize(p,{hasText:!1}))return{error:`the ${e} margin is too small to hold an image. Enlarge it with set_page_layout (${e==="header"?"marginTop":"marginBottom"}) first.`};const{side:m,slot:y,...b}=p;return{image:b}}chromeImageDrawnSize(t,e={}){const n=Ae(this.getPageLayoutSettings()),{pageWidth:o,pageHeight:r}=bs(n),i=Fl(this.getDocument().chrome??[],t.side,t.slot),[a]=uc({side:t.side,records:[t],pageWidth:o,pageHeight:r,marginTop:n.marginTopPx,marginRight:n.marginRightPx,marginBottom:n.marginBottomPx,marginLeft:n.marginLeftPx,hasText:e.hasText??!!(i&&As(i))});return a?{width:Math.max(1,Math.floor(a.width)),height:Math.max(1,Math.floor(a.height))}:null}applySetPageLayoutAction(t){const e=t.clearPageBorders===!0?null:Ol(t.pageBorders);if(t.pageBorders!==void 0&&e===void 0)throw new Error("Invalid pageBorders: use supported side styles, #RRGGBB colors, widthPt 0.25–12 and spacePt 0–31, or null to remove.");const n=this.getPageLayoutSettings(),o=this.getDocument().children.filter(B=>B.type==="section-break"),r=o.length+1,i=typeof t.sectionIndex=="number"&&Number.isInteger(t.sectionIndex)&&t.sectionIndex>=1&&t.sectionIndex<=r?t.sectionIndex:void 0;if(t.sectionIndex!=null&&i===void 0){const B=typeof t.sectionIndex=="number"&&Number.isInteger(t.sectionIndex)?`sectionIndex ${t.sectionIndex} is out of range: document has ${r} section${r===1?"":"s"}`:`sectionIndex must be an integer between 1 and ${r}, got ${JSON.stringify(t.sectionIndex)}`;return{settings:n,pageless:this.getPagelessMode(),error:B}}if(t.pageNumberFormat!=null&&!No(t.pageNumberFormat))return{settings:n,pageless:this.getPagelessMode(),error:`pageNumberFormat must be one of ${Rl.join(", ")}, got ${JSON.stringify(t.pageNumberFormat)}`};const a=i?o[i-1]:void 0,l=a?ms(n,a.layout):n,c=this.getPagelessMode(),d=Dl(t.preset)?$l(t.preset):void 0,g={...d?.pageLayout??{}},u={...l,...d?.pageLayout??{}};jl(t.pageSize)&&(u.pageSize=t.pageSize,g.pageSize=t.pageSize),(t.orientation==="portrait"||t.orientation==="landscape")&&(u.orientation=t.orientation,g.orientation=t.orientation);const f=Yt(t.margin);f!==void 0&&(u.marginTopPx=f,u.marginRightPx=f,u.marginBottomPx=f,u.marginLeftPx=f,g.marginTopPx=f,g.marginRightPx=f,g.marginBottomPx=f,g.marginLeftPx=f);const h=Yt(t.marginTop);h!==void 0&&(u.marginTopPx=h,g.marginTopPx=h);const p=Yt(t.marginRight);p!==void 0&&(u.marginRightPx=p,g.marginRightPx=p);const m=Yt(t.marginBottom);m!==void 0&&(u.marginBottomPx=m,g.marginBottomPx=m);const y=Yt(t.marginLeft);y!==void 0&&(u.marginLeftPx=y,g.marginLeftPx=y);const b=Yt(t.indentStep);b!==void 0&&(u.indentStepPx=b,g.indentStepPx=b);const k=Yt(t.blockSpacing);k!==void 0&&(u.blockSpacingPx=k,g.blockSpacingPx=k),_l(t.columnCount)&&(u.columnCount=t.columnCount,g.columnCount=t.columnCount);const S=Yt(t.columnGap);if(S!==void 0){const B=Math.max(0,Kl(S));u.columnGapTwips=B,g.columnGapTwips=B}if((t.noteMode==="footnotes"||t.noteMode==="endnotes")&&this.convertAllNoteKinds(t.noteMode==="endnotes"?"endnote":"footnote"),typeof t.showPageNumbers=="boolean"||Lo(t.pageNumberPosition)){const B=Lo(t.pageNumberPosition)?t.pageNumberPosition:this.ydoc.getMap("metadata").get(Gt.pageNumberPosition)??"bottom-right",N=typeof t.showPageNumbers=="boolean"?t.showPageNumbers:!0;this.setPageNumberSlot(N,B)}if(typeof t.showPageNumbers=="boolean"&&(u.showPageNumbers=!1),Lo(t.pageNumberPosition)&&(u.pageNumberPosition=t.pageNumberPosition),typeof t.pageNumberStart=="number"?(u.pageNumberStart=t.pageNumberStart,g.pageNumberStart=t.pageNumberStart):t.pageNumberRestart===!0&&(g.pageNumberStart=a?.layout?.pageNumberStart??1),No(t.pageNumberFormat)&&(u.pageNumberFormat=t.pageNumberFormat,g.pageNumberFormat=t.pageNumberFormat),!a){const B=i===r&&r>1;t.pageNumberRestart===!0||B&&typeof t.pageNumberStart=="number"&&t.pageNumberRestart!==!1?u.pageNumberRestart=!0:t.pageNumberRestart===!1&&delete u.pageNumberRestart}if((t.pageBorders!==void 0||t.clearPageBorders===!0)&&(u.pageBorders=e,g.pageBorders=e),t.lineNumbering!==void 0){const B=Xl(t.lineNumbering);B?u.lineNumbering=B:delete u.lineNumbering,g.lineNumbering=Ul(B)??"",B&&t.pleadingGrid===void 0&&(delete u.pleadingGrid,g.pleadingGrid="")}if(t.pleadingGrid!==void 0){const B=zl(t.pleadingGrid);B?u.pleadingGrid=Bs(B):delete u.pleadingGrid,g.pleadingGrid=Bs(B)??"",B&&(delete u.lineNumbering,g.lineNumbering="")}const v=Yt(t.pageWidth),x=Yt(t.pageHeight);if(v!==void 0&&x!==void 0){const B=Wl(v,x);B&&(u.pageSize=B.pageSize,u.orientation=B.orientation,g.pageSize=B.pageSize,g.orientation=B.orientation)}if(t.watermark!==void 0){const B=zs(t.watermark);this.transact(()=>{const N=this.ydoc.getMap("metadata");B?N.set("watermark",B):N.delete("watermark")})}const w=Ae(u),A=typeof t.pageless=="boolean"?t.pageless:d?.pageless??c,P=t.pageNumberRestart===!1&&typeof t.pageNumberStart!="number",T=B=>{const N=Ms(B,g)??{...g};if(!P)return N;const{pageNumberStart:R,...M}=N;return M},E=Object.keys(g).length>0||P;if(i&&a)E&&this.updateSectionBreakLayout(a.id,T(a.layout));else if(i===r){if(t.pageBorders!==void 0||t.clearPageBorders===!0)for(const B of o)B.layout?.pageBorders!==void 0||/<w:pgBorders\b/.test(B.layout?.oxmlSectPr??"")||this.updateSectionBreakLayout(B.id,{...B.layout,pageBorders:n.pageBorders??null});this.pinInheritedPageNumbering({...No(t.pageNumberFormat)?{pageNumberFormat:t.pageNumberFormat}:{},...typeof t.pageNumberStart=="number"?{pageNumberStart:t.pageNumberStart}:{}}),this.setPageLayoutSettings(w)}else{if(E)for(const B of o)this.updateSectionBreakLayout(B.id,T(B.layout));this.setPageLayoutSettings(w)}return this.setPagelessMode(A),{settings:w,pageless:A}}setPagelessMode(t){this.transact(()=>{this.ydoc.getMap("metadata").set("pageless",t)})}getPagelessMode(){return!!this.ydoc.getMap("metadata").get("pageless")}convertParagraphToList(t,e,n){return this.listOperations.convertParagraphToList(t,e,n)}convertParagraphToListById(t,e,n){return this.listOperations.convertParagraphToListById(t,e,n)}getListItemPlainText(t){return this.listOperations.getListItemPlainText(t)}convertParagraphRangeToList(t,e,n){return this.listOperations.convertParagraphRangeToList(t,e,n)}updateListVariant(t,e,n){return this.listOperations.updateListVariant(t,e,n)}convertListToParagraphById(t){return this.listOperations.convertListToParagraphById(t)}updateListVariantById(t,e,n){return this.listOperations.updateListVariantById(t,e,n)}continueListFromPrevious(t){return this.listOperations.continueListFromPrevious(t)}restartListNumberingAt(t,e,n){return this.listOperations.restartListNumberingAt(t,e,n)}splitListItem(t,e){return this.listOperations.splitListItem(t,e)}insertTextInListItem(t,e,n,o){return this.listOperations.insertTextInListItem(t,e,n,o)}insertTextInList(t,e,n,o){return this.listOperations.insertTextInList(t,e,n,o)}insertFormattedTextInList(t,e,n,o,r){return this.listOperations.insertFormattedTextInList(t,e,n,o,r)}getListCursorInfo(t,e){return this.listOperations.getListCursorInfo(t,e)}getListItemTextLength(t){return this.listOperations.getListItemTextLength(t)}setListItemIndent(t,e,n,o,r){return this.listOperations.setListItemIndent(t,e,n,o,r)}setSuggestingMode(t){this.suggestionEngine.setSuggestingMode(t)}isSuggestingMode(){return this.suggestionEngine.isSuggestingMode()}getLiveSuggestionStore(){return this.suggestionEngine.getLiveSuggestionStore()}setDefaultSuggestionAuthorName(t){this.suggestionEngine.setDefaultSuggestionAuthorName(t)}withSuggestionMetadata(t,e){return this.suggestionEngine.withSuggestionMetadata(t,e)}saveLiveSuggestion(t){this.suggestionEngine.saveLiveSuggestion(t)}backfillLiveSuggestionTreeRecords(){this.suggestionEngine.backfillLiveSuggestionTreeRecords()}getLiveSuggestion(t){return this.suggestionEngine.getLiveSuggestion(t)}getInlineSuggestionMetadataFromDocument(t){return this.suggestionEngine.getInlineSuggestionMetadataFromDocument(t)}getLiveSuggestionTooltipDescription(t){return this.suggestionEngine.getLiveSuggestionTooltipDescription(t)}deleteLiveSuggestion(t){this.suggestionEngine.deleteLiveSuggestion(t)}getLiveSuggestionIds(){return this.suggestionEngine.getLiveSuggestionIds()}completeInternalTextMove(t,e,n,o){const r=new Set(t),i=new Set(e),a=[],l=[],c=[],d=h=>{if(h instanceof I.XmlText){let p=0;for(const m of st(h)){const y=typeof m.insert=="string"?m.insert.length:1,b=m.attributes??{};b.deletion&&r.has(b.suggestionId)?a.push({text:h,start:p,length:y,attributes:b}):b.insertion&&i.has(b.suggestionId)&&l.push({text:h,start:p,length:y,attributes:b}),p+=y}}if(h instanceof I.XmlFragment||h instanceof I.XmlElement){h instanceof I.XmlElement&&(r.has(h.getAttribute("structuralSuggestionId"))||i.has(h.getAttribute("structuralSuggestionId")))&&c.push(h);for(let p=0;p<h.length;p++){const m=h.get(p);m instanceof I.AbstractType&&d(m)}}};if(d(this.getYContentFragment()),a.length===0||l.length===0)return!1;const g=1e7+Math.floor(Math.random()*9e7),u=`reviseMove-${n}`,f=(h,p,m)=>{const y=JSON.stringify({version:1,...o?.wholeBlocks?{wholeBlocks:!0}:{},name:u,role:p,rangeId:`${g}${m}`,wrapperId:`${g+1}${m}`,fallbackSuggestionId:h[0].attributes.suggestionId,...h[0].attributes.suggestionAuthorName?{rangeAuthor:h[0].attributes.suggestionAuthorName}:{},...typeof h[0].attributes.suggestionCreatedAt=="number"?{rangeCreatedAt:h[0].attributes.suggestionCreatedAt}:{}});for(const b of h)at(b.text,b.start,b.length,{suggestionId:n,suggestionLabel:"Move",docxMove:y})};return this.transact(()=>{f(a,"from","1"),f(l,"to","2");for(const h of c)h.setAttribute("structuralSuggestionId",n)}),!0}recordStampedSuggestionIds(t){return this.suggestionEngine.recordStampedSuggestionIds(t)}runTrackedMovePaste(t,e,n,o){return this.runWithUndoGroup("tracked-move-paste",()=>{const{result:r,stamped:i}=this.recordStampedSuggestionIds(n);return o(r)&&this.completeInternalTextMove(e,[...i.insertionIds,...i.structuralInsertIds,t],t),r})}getLiveSuggestionIdsBySource(t){return this.suggestionEngine.getLiveSuggestionIdsBySource(t)}getLiveSuggestionIdsByCommentThread(t){return this.suggestionEngine.getLiveSuggestionIdsByCommentThread(t)}getLiveSuggestionAuthorName(t){return this.suggestionEngine.getLiveSuggestionAuthorName(t)}getLiveSuggestionKind(t){return this.suggestionEngine.getLiveSuggestionKind(t)}getLiveSuggestionIdsForBlock(t){return this.suggestionEngine.getLiveSuggestionIdsForBlock(t)}canResolveLiveSuggestion(t){return this.suggestionEngine.canResolveLiveSuggestion(t)}getUnresolvableLiveSuggestionRecords(){return this.suggestionEngine.getUnresolvableLiveSuggestionRecords()}takeLastPrunedUnresolvableLiveSuggestions(){return this.suggestionEngine.takeLastPrunedUnresolvableLiveSuggestions()}getDocumentWithAcceptedSuggestions(){return this.suggestionEngine.getDocumentWithAcceptedSuggestions()}mapAcceptedSuggestionRangeToLiveRange(t,e,n){return this.suggestionEngine.mapAcceptedSuggestionRangeToLiveRange(t,e,n)}getDocumentWithRejectedSuggestions(){return this.suggestionEngine.getDocumentWithRejectedSuggestions()}sanitizeBlocksForClipboard(t){const e=n=>{if(Array.isArray(n))return n.map(e);if(!n||typeof n!="object")return n;const o={};for(const[r,i]of Object.entries(n))r==="structuralSuggestionRecord"||r==="structuralSuggestionRecords"||(o[r]=r==="children"?e(i):i);return o};return t.map(n=>e(this.suggestionEngine.sanitizePreviewBlock(n)))}getSelectionInRejectedSuggestionProjection(t){return this.suggestionEngine.getSelectionInRejectedSuggestionProjection(t)}static materializeAcceptedSuggestions(t){const e=o=>{if(!o||typeof o!="object")return!1;if(Array.isArray(o))return o.some(e);const r=o;return typeof r.suggestionId=="string"&&r.suggestionId||typeof r.structuralSuggestionId=="string"&&r.structuralSuggestionId||r.marks&&typeof r.marks.suggestionId=="string"&&r.marks.suggestionId?!0:e(r.children)};if(!t.children.some(e))return t;const n=Eo(t);try{const o=le.createSuggestionProjectionFromYDoc(n,"accept");try{return{...t,children:o.doc.children}}finally{o.ydoc.destroy()}}finally{n.destroy()}}static createSuggestionProjectionFromYDoc(t,e,n){const o=new I.Doc;I.applyUpdate(o,I.encodeStateAsUpdate(t));const r=new le(mt(o),()=>{},void 0,o,"live-suggestion-projection",!0,new an,{canRepairIdentity:()=>!1}),i=n?Array.from(new Set(n.filter(a=>typeof a=="string"&&a.length>0))):r.getLiveSuggestionIds();try{return e==="accept"?r.suggestionEngine.applyLiveSuggestionDecisionInternal(i,"accept"):r.suggestionEngine.applyLiveSuggestionDecisionInternal(i,"reject"),t.getXmlFragment("notes").length>0&&r.reconcileFootnotes(),{ydoc:o,doc:r.getDocument()}}finally{r.dispose()}}decideLiveSuggestions(t){return this.suggestionEngine.decideLiveSuggestions(t)}acceptLiveSuggestions(t){return this.suggestionEngine.acceptLiveSuggestions(t)}acceptLiveSuggestionsBySource(t){return this.suggestionEngine.acceptLiveSuggestionsBySource(t)}acceptLiveSuggestionsByAuthor(t){return this.suggestionEngine.acceptLiveSuggestionsByAuthor(t)}rejectLiveSuggestionsByAuthor(t){return this.suggestionEngine.rejectLiveSuggestionsByAuthor(t)}acceptLiveSuggestionsByKind(t){return this.suggestionEngine.acceptLiveSuggestionsByKind(t)}rejectLiveSuggestionsByKind(t){return this.suggestionEngine.rejectLiveSuggestionsByKind(t)}rejectLiveSuggestions(t){return this.suggestionEngine.rejectLiveSuggestions(t)}rejectLiveSuggestionsBySource(t){return this.suggestionEngine.rejectLiveSuggestionsBySource(t)}setElementStructuralSuggestion(t,e,n,o,r){this.suggestionEngine.setElementStructuralSuggestion(t,e,n,o,r)}setDiffSuggestionAttributes(t,e,n){this.suggestionEngine.setDiffSuggestionAttributes(t,e,n)}acceptLiveSuggestion(t){return this.suggestionEngine.acceptLiveSuggestion(t)}rejectLiveSuggestion(t){return this.suggestionEngine.rejectLiveSuggestion(t)}applyBridgeBlockChangeSuggestion(t){return this.suggestionEngine.applyBridgeBlockChangeSuggestion(t)}resetToolCallHistory(){return this.suggestionEngine.resetToolCallHistory()}setToolCallHistory(t){return this.suggestionEngine.setToolCallHistory(t)}getDetachedSuggestionStore(){return this.suggestionEngine.getDetachedSuggestionStore()}setDetachedSuggestionConversation(t,e){this.suggestionEngine.setDetachedSuggestionConversation(t,e)}clearLegacyDetachedSuggestionState(){this.suggestionEngine.clearLegacyDetachedSuggestionState()}migrateLegacyDetachedSuggestionsToLiveSuggestions(t){return this.suggestionEngine.migrateLegacyDetachedSuggestionsToLiveSuggestions(t)}get kernel(){return this.cachedKernel||(this.cachedKernel={ydoc:this.ydoc,transact:t=>this.transact(t),getYContentFragment:()=>this.getYContentFragment(),getYChromeFragment:()=>this.getYChromeFragment(),getYNotesFragment:()=>this.getYNotesFragment(),blockToYjsElement:t=>this.blockToYjsElement(t),getDocument:()=>this.getDocument(),insertTextNodes:(t,e,n)=>this.insertTextNodes(t,e,n),suggestions:{isSuggesting:()=>this.suggestingMode,buildInlineMetadataMarks:(t,e,n)=>this.suggestionEngine.buildInlineSuggestionMetadataMarks(t,e,n),setElementStructuralSuggestion:(t,e,n,o,r)=>this.suggestionEngine.setElementStructuralSuggestion(t,e,n,o,r)}}),this.cachedKernel}setHeadersAndFooters(t,e){Cr(this.kernel,t,e)}ensureHeaderFooterBlock(t,e){return Mr(this.kernel,t,e)}migrateLegacyHeaderFooterMetadata(){kg(this.kernel)}migrateNotesOutOfContent(){jg(this.kernel)}migrateChromeOutOfContent(){yg(this.kernel)}getHeadersAndFooters(){return ca(this.kernel)}setSectionHeadersAndFooters(t,e,n){mg(this.kernel,t,e,n)}getSectionHeadersAndFooters(t){return bg(this.kernel,t)}setPageNumberSlot(t,e="bottom-right"){Sg(this.kernel,t,e)}migrateLegacyPageNumbers(){Ig(this.kernel)}setPageLayoutSettings(t){this.ensureParagraphIndentStorageUsesUnits(),this.transact(()=>{Jl(this.ydoc.getMap("metadata"),t)})}setWatermark(t){const e=zs(t);this.transact(()=>{const n=this.ydoc.getMap("metadata");e?n.set("watermark",e):n.delete("watermark")})}getWatermarkRaw(){const t=this.ydoc.getMap("metadata").get("watermark");return typeof t=="string"&&t.trim()!==""?t:void 0}getPageLayoutSettings(){return us(this.ydoc.getMap("metadata"))??Ae(void 0)}getIndentStepPx(){return this.getPageLayoutSettings().indentStepPx??0}getTitle(){return this.ydoc.getMap("metadata").get("title")}transact(t){return this.assertObserversNotStranded(),this.incrementalRefreshPending=!1,this.cachedDoc=null,this.invalidateDerivedDocumentState(),this.ydoc.transact(t,this.origin)}assertObserversNotStranded(){if(this.strandedObservers)throw new Error("The editor lost sync with the document. Reload the page to continue editing.");this.hasQueuedCleanupsOutsideTransaction()&&!this.strandedCheck&&(this.strandedCheck=setTimeout(()=>{this.strandedCheck=null,!(this.disposed||!this.hasQueuedCleanupsOutsideTransaction())&&(this.strandedObservers=!0,Ar(new Error(`Refusing further writes: ${this.ydoc._transactionCleanups.length} stranded transaction cleanups`),"transact"))},0))}hasQueuedCleanupsOutsideTransaction(){const t=this.ydoc;return t._transaction===null&&t._transactionCleanups.length>0}scheduleDeferredIdentityRepair(){this.deferredIdentityRepair||(this.deferredIdentityRepair=setTimeout(()=>{this.deferredIdentityRepair=null,!(this.disposed||!this.canRepairIdentity())&&this.repairDocumentIdentity()&&this.onDocumentChange(this.getDocument(),{origin:"local"})},le.DEFERRED_IDENTITY_REPAIR_MS))}repairDocumentIdentity(t,e){const n=t!==void 0&&e===this.undoManager,o=this.ydoc.clientID,r=t?.beforeState.get(o)??0,i=n?c=>{const d=c._item?.id;return d!==void 0&&d.client===o&&d.clock>=r}:void 0,a=Hl(this.ydoc,{transaction:t,shouldDrop:i});if(n&&a.droppedIds.length>0){const c=new Set(a.droppedIds),d=this.suggestionEngine.getLiveSuggestionStore(),g=[];for(const[u,f]of d._map){if(f.deleted||f.id.client!==o||f.id.clock<r)continue;const h=d.get(u);h&&this.suggestionEngine.liveSuggestionRecordTouchesAnyBlock(h,c)&&g.push(u)}g.length>0&&this.ydoc.transact(()=>{for(const u of g)this.suggestionEngine.deleteLiveSuggestion(u)},Cs)}const l=cg(this.ydoc,t,n?"strip":"recover");return a.duplicatesFound===0&&l===0?!1:(this.cachedDoc=null,this.incrementalRefreshPending=!1,Rn(this.ydoc,mt(this.ydoc)),!0)}get localOrigin(){return this.origin}beginRollbackScope(){const t=new I.UndoManager([this.ydoc.getXmlFragment("content"),this.ydoc.getXmlFragment("chrome"),this.ydoc.getXmlFragment("notes"),this.ydoc.getArray("annotations"),this.suggestionEngine.getLiveSuggestionStore(),this.ydoc.getMap("comments")],{captureTimeout:0,trackedOrigins:this.trackedUndoOrigins}),e=this.undoManager.undoStack.length,n=this.undoManager.redoStack.length;let o=!1;const r=()=>{o||(o=!0,t.destroy())};return{revert:()=>{if(!o){for(;t.canUndo();)t.undo();this.undoManager.undoStack.length=Math.min(this.undoManager.undoStack.length,e),this.undoManager.redoStack.length=Math.min(this.undoManager.redoStack.length,n),this.cachedDoc=null,this.incrementalRefreshPending=!1,this.invalidateDerivedDocumentState(),r()}},dispose:r}}canUndo(){return this.undoManager.canUndo()}canRedo(){return this.undoManager.canRedo()}undo(){try{const t=this.undoManager.undoStack;if(t.length===0)return null;const e=t[t.length-1],n=e.meta.get("beforeSelection"),o=e.meta.get("beforeSelectionAbsolute");return this.undoManager.undo(),n?Or(n,this.ydoc):o||null}catch(t){return console.error("Error during undo:",t),t instanceof Error&&t.message.includes("forEach")&&(console.warn("Clearing undo history due to corrupted state"),this.undoManager.clear()),null}}redo(t){try{const e=this.undoManager.redoStack;if(e.length===0)return null;const n=e[e.length-1].meta.get("afterSelection"),o=this.getDocument();return this.currentSelectionBeforeRedo=t?Y(t,this.ydoc,o):null,this.afterSelectionForRedo=n||null,this.isRedoing=!0,this.undoManager.redo(),n?Or(n,this.ydoc):null}catch(e){return console.error("Error during redo:",e),this.isRedoing=!1,this.currentSelectionBeforeRedo=null,this.afterSelectionForRedo=null,e instanceof Error&&e.message.includes("forEach")&&(console.warn("Clearing undo history due to corrupted state"),this.undoManager.clear()),null}}getParagraphPlainText(t){return t.children.map(e=>e.text).join("")}insertText(t,e,n,o){this.beforeOperationSelection=n;const r=this.getDocument();try{this.beforeOperationRelativeSelection=Y(n,this.ydoc,r)}catch{this.beforeOperationRelativeSelection=null}const i=this.resolveEditableContext(t,r);if(!i)return!1;const{editable:a}=i,l=a.block;if(l.type==="list")return this.listOperations.insertTextInList(t,e,n,o);if(kn(l))return this.insertTextInCodeBlock(t,e,n,o);if(l.type!=="paragraph")return!1;const c=l,d=this.listOperations.tryApplyParagraphListTrigger(c,t,e);if(d!==null)return d;const g={type:"text",text:e},u={},f=Fo(r,t),h=Oo(r,t),p=Ro(r,t,n),m=this.suggestionEngine.getInlineInsertionSuggestionNodeAtPosition(r,t),y=m?.marks?.suggestionId??null,b=this.suggestionEngine.getEnclosingBlockInsertSuggestionIdForBlockId(r,t.block),k=this.suggestionEngine.getSuggestionIdForSuggestedSelectionOverwrite(r,t,n),S=!b&&this.suggestingMode&&e.length>0,v=Tr({inheritedMarks:p?.marks,emptyParagraphMarks:Ao(c)?void 0:this.getEmptyTextMarksForBlockId(t.block),exitingLink:f,exitingComment:h,suggestionMarks:S?this.suggestionEngine.buildSuggestionInsertionMarks(void 0,k??y??this.suggestionEngine.getSuggestionIdFromInheritedMarks(p?.marks),void 0,void 0,m?.marks??p?.marks):void 0});Object.assign(u,v.marksToApply),Object.keys(u).length>0&&(g.marks=u);const x=this.insertTextNodes(t,[g],n,k??void 0);if(x){const w={anchor:x,focus:x};this.setSelectionAfterOperation(w),this.afterOperationRelativeSelection=Y(w,this.ydoc,this.getDocument())}return x!==null}insertFormattedText(t,e,n,o,r,i){this.beforeOperationSelection=o;const a=this.getDocument();this.beforeOperationRelativeSelection=Y(o,this.ydoc,a);const l=W(a,t.block);if(!l)return!1;if(l.type==="list")return this.listOperations.insertFormattedTextInList(t,e,n,o,r);if(kn(l))return this.insertTextInCodeBlock(t,e,o,r);if(l.type!=="paragraph")return!1;const c=l,d=this.listOperations.tryApplyParagraphListTrigger(c,t,e);if(d!==null)return d;const g=ie(t,this.ydoc,a);if(!g)return!1;const u=I.createAbsolutePositionFromRelativePosition(g.textOffset,this.ydoc);if(!u||!(u.type instanceof I.XmlText))return!1;const f=u.type,h=u.index,p=Ro(a,t,o),m=this.suggestionEngine.getInlineInsertionSuggestionNodeAtPosition(a,t),y=m?.marks?.suggestionId??null,b=this.suggestionEngine.getEnclosingBlockInsertSuggestionIdForBlockId(a,t.block),k=this.suggestionEngine.getSuggestionIdForSuggestedSelectionOverwrite(a,t,o),S=Fo(a,t),v=Oo(a,t),x=!b&&this.suggestingMode&&e.length>0,{marksToApply:w,marksToRemove:A}=Tr({explicitMarks:n&&Object.keys(n).length>0?n:void 0,inheritedMarks:p?.marks,emptyParagraphMarks:Ao(c)?void 0:this.getEmptyTextMarksForBlockId(t.block),exitingLink:S,exitingComment:v,noteBodyFontSize:this.isBlockInsideFootnote(a,t.block)?ge:void 0,suggestionMarks:x?this.suggestionEngine.buildSuggestionInsertionMarks(void 0,i??k??y??this.suggestionEngine.getSuggestionIdFromInheritedMarks(p?.marks),void 0,void 0,m?.marks??p?.marks):void 0});let P=h;this.transact(()=>{if(o&&o.anchor&&o.focus&&xt(a,o.anchor,o.focus)!==0){const[B,N]=xt(a,o.anchor,o.focus)===-1?[o.anchor,o.focus]:[o.focus,o.anchor];if(B.block===t.block&&N.block===t.block)if(this.suggestingMode&&!b){const{retainedLength:R}=this.suggestionEngine.applySuggestedDeletionToTextRange(f,B.offset,N.offset-B.offset,k??void 0);P=B.offset+R}else f.delete(B.offset,N.offset-B.offset),P=B.offset}la(f,P,e,{marksToApply:w,marksToRemove:A}),!b&&this.suggestingMode&&e.length>0&&this.suggestionEngine.clearInheritedDeletionFromInsertedSuggestion(f,P,e.length)});const T=I.createRelativePositionFromTypeIndex(f,P+e.length),E=on({blockId:g.blockId,textOffset:T},this.ydoc);if(E){const B={anchor:E,focus:E};return this.setSelectionAfterOperation(B),this.afterOperationRelativeSelection=Y(B,this.ydoc,this.getDocument()),!0}return this.setSelectionAfterOperation(r),this.afterOperationRelativeSelection=Y(r,this.ydoc,this.getDocument()),!0}insertTextNodes(t,e,n,o){if(e.length===0)return null;const r=this.getDocument(),i=Z(this.ydoc,t.block);if(!i)return null;const a=ct(i);if(!a)return null;const l=this.suggestionEngine.getEnclosingBlockInsertSuggestionIdForBlockId(r,t.block),c=l?e.map(h=>({...h,marks:this.suggestionEngine.stripSuggestionMarksFromTextMark(h.marks)})):e;let d=t.offset,g=0;const u=[];this.transact(()=>{if(n&&n.anchor&&n.focus&&xt(r,n.anchor,n.focus)!==0){const[p,m]=xt(r,n.anchor,n.focus)===-1?[n.anchor,n.focus]:[n.focus,n.anchor];if(p.block===t.block&&m.block===t.block)if(this.suggestingMode&&!l){const{retainedLength:y}=this.suggestionEngine.applySuggestedDeletionToTextRange(a,p.offset,m.offset-p.offset,o);d=p.offset+y}else a.delete(p.offset,m.offset-p.offset),d=p.offset}let h=d;for(const p of c)if(p.text.length>0){const m={...p.marks||{}};lt(a,h,p.text,m),m.insertion&&u.push({start:h,length:p.text.length}),h+=p.text.length,g+=p.text.length}for(const p of u)this.suggestionEngine.clearInheritedDeletionFromInsertedSuggestion(a,p.start,p.length);i.getAttribute("_emptyTextMarks")&&i.removeAttribute("_emptyTextMarks")});const f=d+g;return{block:t.block,offset:f}}insertParagraphInternal(t,e,n=this.getYContentFragment()){if(t<0||t>n.length)return!1;const o=new I.XmlElement("paragraph");o.setAttribute("id",e.id||G()),e.heading&&o.setAttribute("heading",String(e.heading)),e.align&&o.setAttribute("align",e.align),e.lineSpacing!==void 0&&o.setAttribute("lineSpacing",String(e.lineSpacing)),bn(o,e);const r=qt(e);r!==void 0&&o.setAttribute("pagination",r),e.styleId!==void 0&&o.setAttribute("styleId",e.styleId),e.direction!==void 0&&o.setAttribute("direction",e.direction),e.tabStops!==void 0&&o.setAttribute("tabStops",e.tabStops),e.borders!==void 0&&o.setAttribute("borders",e.borders),e.shading!==void 0&&o.setAttribute("shading",e.shading),e.oxmlAttrs!==void 0&&o.setAttribute("oxmlAttrs",e.oxmlAttrs),e.oxmlPPr!==void 0&&o.setAttribute("oxmlPPr",e.oxmlPPr);const i=Ht(e.leftIndent);i!==void 0&&o.setAttribute("leftIndent",String(i));const a=Jt(e.firstLineIndent);a!==void 0&&o.setAttribute("firstLineIndent",String(a));const l=new I.XmlText;n.insert(t,[o]),o.insert(0,[l]);let c=0;return e.children.forEach(d=>{if(d.type==="text"&&d.text.length>0){const g={...d.marks||{}};lt(l,c,d.text,g),c+=d.text.length}}),!0}insertParagraph(t,e){const n=this.getYContentFragment();return t<0||t>n.length?!1:(this.transact(()=>{this.insertParagraphInternal(t,e)}),!0)}deleteText(t,e,n,o){this.beforeOperationSelection=n;const r=this.getDocument();this.beforeOperationRelativeSelection=Y(n,this.ydoc,r);const i=W(r,t.block);if(!i)return!1;if(i.type==="list")return this.listOperations.deleteTextInList(t,e,n,o);if(kn(i))return this.deleteTextInCodeBlock(t,e,n,o);if(i.type!=="paragraph")return!1;const a=i,l=this.getEmptyTextMarksForBlockId(t.block),c=yn(r,a,t,l);let d=0;for(const k of a.children)k.type==="text"&&(d+=k.text.length);let g=t.offset,u=t.offset+e,f=!1;{let k=0;for(const S of a.children){if(S.type!=="text")continue;const v=k+S.text.length;S.marks?.footnoteRef&&k<u&&v>g&&(f=!0,g=Math.min(g,k),u=Math.max(u,v)),k=v}}f&&(t={...t,offset:g},e=u-g);const h=d-t.offset,p=Math.min(e,h),m=this.suggestionEngine.getEnclosingBlockInsertSuggestionIdForBlockId(r,t.block);let y=null;this.transact(()=>{const k=Z(this.ydoc,t.block);if(!k)return;const S=ct(k);if(S){if(this.suggestingMode&&!m){const v=this.suggestionEngine.applySuggestedDeletionToTextRange(S,t.offset,p);p>1&&v.retainedLength>0&&(y=this.normalizeAdjacentManualReplacementOrder(S,t.offset))}else S.delete(t.offset,p);S.length===0&&wo(k,c)}});const b=y?gs(o,t.block,y):o;return this.setSelectionAfterOperation(b),this.afterOperationRelativeSelection=Y(b,this.ydoc,this.getDocument()),f&&!this.suggestingMode&&this.reconcileFootnotes(),!0}deleteSelection(t,e,n,o){this.beforeOperationSelection||(this.beforeOperationSelection=n);const r=this.getDocument();this.beforeOperationRelativeSelection||(this.beforeOperationRelativeSelection=Y(n,this.ydoc,r));let i=Cn(r,t.block),a=Cn(r,e.block);if(i===-1||a===-1){const f=h=>{const p=(r.chrome??[]).findIndex(y=>y.id===h||y.children.some(b=>b.id===h));if(p!==-1)return r.children.length+p;const m=(r.notes??[]).findIndex(y=>y.id===h||y.children.some(b=>b.id===h));return m!==-1?r.children.length+(r.chrome?.length??0)+m:-1};if(i=f(t.block),a=f(e.block),i===-1||a===-1||t.block!==e.block&&(r.chrome??[]).some(h=>h.children.some(p=>p.id===t.block)))return!1}const l=t.block===e.block;if(l){const f=W(r,t.block);if(!f)return!1;if(this.suggestingMode&&f.type==="paragraph")return this.deleteSingleParagraphSelection(t,e,n,o);if(this.suggestingMode&&f.type==="list"){const p=f,m=this.listOperations.getListCursorInfo(p,t),y=this.listOperations.getListCursorInfo(p,e);if(m&&y&&m.itemIndex+1===y.itemIndex&&m.offsetInItem===this.listOperations.getListItemPlainText(p.children[m.itemIndex]).length&&y.offsetInItem===0){const b=gt(),k=this.mergeAdjacentListItemsSnapshot(p,m.itemIndex,b);if(k){const S=this.suggestionEngine.runWithoutSuggesting(()=>this.updateBlockById(p.id,k,n,o));return S&&this.suggestionEngine.saveLiveSuggestion({id:b,type:"block-change",blockId:p.id,beforeBlock:this.suggestionEngine.cloneSuggestionSnapshot(p),label:"Join"}),S}}}const h=te().getHandlerForBlock(f);if(h&&h.handleDeleteSelection){const p=Z(this.ydoc,f.id);if(!p)return!1;let m=!1;if(this.transact(()=>{m=!h.handleDeleteSelection(f,p,t,e),f.type==="paragraph"&&t.offset===0&&e.offset>=f.children.reduce((y,b)=>y+(b.type==="text"?b.text.length:0),0)&&Ao(f)&&wo(p,yn(r,f,t))}),m){const y=Vl(r,t.block),b=Gl(r,t.block);let k;if(y&&y.id){const v=fc(r,y.id);v?k=v:k={block:y.id,offset:0}}else if(b&&b.id)k={block:b.id,offset:0};else return!1;const S={anchor:k,focus:k};return this.deleteBlockById(t.block,n,S)}return this.setSelectionAfterOperation(o),this.afterOperationRelativeSelection=Y(o,this.ydoc,this.getDocument()),!0}return f.type==="paragraph"?this.deleteSingleParagraphSelection(t,e,n,o):this.deleteBlockById(t.block,n,o)}if(this.suggestingMode&&!l&&this.suggestionEngine.deleteMultiParagraphSelectionAsSuggestion(t,e,i,a,o))return!0;const c=Xt(r,t.block),d=Xt(r,e.block),g=W(r,t.block),u=W(r,e.block);return c&&d&&c===d&&g?.type==="paragraph"&&u?.type==="paragraph"?this.mergeAdjacentParagraphs(g,u,t,e,c,n,o):this.deleteMultiBlockSelection(t,e,r,n,o)}mergeAdjacentParagraphs(t,e,n,o,r,i,a){const l=Z(this.ydoc,t.id),c=Z(this.ydoc,e.id);if(!l||!c)return console.error("[mergeAdjacentParagraphs] Could not find Y.js blocks"),!1;let d=null,g=null;for(let y=0;y<l.length;y++){const b=l.get(y);if(b instanceof I.XmlText){d=b;break}}for(let y=0;y<c.length;y++){const b=c.get(y);if(b instanceof I.XmlText){g=b;break}}if(!d||!g)return console.error("[mergeAdjacentParagraphs] Could not find Y.XmlText"),!1;const u=n.offset===d.length&&o.offset===0;if(u){const y=this.isPlainEmptyParagraph(t),b=this.isPlainEmptyParagraph(e),k=this.isInsertedParagraph(t),S=this.isInsertedParagraph(e);if(y&&S||k&&b){const v=y?t:e,x=y?e:t,w=y?0:this.getParagraphTextLength(x),A={block:x.id,offset:w},P={anchor:A,focus:A};return this.deleteBlockById(v.id,i,P)}}if(this.suggestingMode&&u){const y=this.getCancelableParagraphSplitRecord(t,e);if(y){const k=this.suggestionEngine.rejectLiveSuggestion(y.id);if(k){const S={block:y.blockId,offset:this.getParagraphTextLength(t)},v={anchor:S,focus:S};this.setSelectionAfterOperation(v),this.afterOperationRelativeSelection=Y(v,this.ydoc,this.getDocument())}return k}const b=gt();return this.transact(()=>{this.suggestionEngine.clearParagraphStructuralSuggestion(l),this.suggestionEngine.clearParagraphStructuralSuggestion(c),this.suggestionEngine.setParagraphStructuralSuggestion(l,"merge","before",b),this.suggestionEngine.setParagraphStructuralSuggestion(c,"merge","after",b),this.suggestionEngine.saveLiveSuggestion({id:b,type:"paragraph-merge",firstBlockId:t.id,secondBlockId:e.id})}),this.setSelectionAfterOperation(a),this.afterOperationRelativeSelection=Y(a,this.ydoc,this.getDocument()),!0}const f=ot(this.ydoc,t.id),h=ot(this.ydoc,e.id);if(!f||!h)return console.error("[mergeAdjacentParagraphs] Could not find Y.js parent"),!1;if(f.yParent!==h.yParent)return console.error("[mergeAdjacentParagraphs] Paragraphs have different Y.js parents"),!1;const p=f.index,m=h.index;return this.transact(()=>{this.suggestionEngine.clearParagraphStructuralSuggestion(l);const y=d.length;n.offset<y&&d.delete(n.offset,y-n.offset);const b=st(g).slice(0);let k=[],S=0;for(const w of b)if(typeof w.insert=="string"){const A=w.insert;if(S+A.length<=o.offset)S+=A.length;else if(S>=o.offset)k.push(w);else{const P=o.offset-S,T=A.slice(P);T.length>0&&k.push({...w,insert:T}),S+=A.length}}for(const w of k)typeof w.insert=="string"&&d.insert(d.length,w.insert,w.attributes||{});const{yParent:v}=f,x=m-p;x>0&&v.delete(p+1,x)}),this.setSelectionAfterOperation(a),this.afterOperationRelativeSelection=Y(a,this.ydoc,this.getDocument()),!0}deleteMultiBlockSelection(t,e,n,o,r){const i=ue(n,t.block),a=ue(n,e.block);if(!i||!a)return!1;const l=W(n,t.block),c=W(n,e.block);if(!l||!c)return!1;const d=[];for(const{block:w,path:A}of Ql(n)){const P=Pe(A,i),T=Pe(A,a);if(!(P<0)){if(T>0)break;d.push({block:w,path:A,isFirst:P===0,isLast:T===0})}}if(d.length===0)return!1;const g=i[0],u=a[0],f=n.children[g],h=n.children[u];if(g!==u&&f?.type==="list"&&h?.type==="list"&&this.listOperations.mergeAdjacentListsOnDelete(f,h,g,u,t,e,r))return!0;const p=d[0],m=d[d.length-1],y=p.block.type==="paragraph",b=m.block.type==="paragraph",k=ot(this.ydoc,p.block.id),S=ot(this.ydoc,m.block.id);if(!k||!S)return!1;const v=k.yBlock,x=S.yBlock;return this.transact(()=>{let w=null,A=null;y&&(w=ct(v)),b&&(A=ct(x));const P=y?t.offset:0,T=b?e.offset:0,E=d.length===2&&y&&b&&w!==null&&P===w.length&&T===0;let B="";const N={};if(b&&A){const R=st(A);let M=0;for(const O of R)if(O.insert&&typeof O.insert=="string"){const $=O.insert.length;M>=T?(B+=O.insert,O.attributes&&Object.assign(N,O.attributes)):M+$>T&&(B+=O.insert.slice(T-M),O.attributes&&Object.assign(N,O.attributes)),M+=$}}if(y&&w&&P<w.length&&w.delete(P,w.length-P),E&&v instanceof I.XmlElement&&x instanceof I.XmlElement){const R=x.getAttribute("heading");R?v.setAttribute("heading",R):v.removeAttribute("heading");const M=rt(x,"align");M&&v.setAttribute("align",M);const O=rt(x,"lineSpacing");O?v.setAttribute("lineSpacing",O):et(v,"lineSpacing"),Rh(x,v,!0);const $=rt(x,"pagination");$?v.setAttribute("pagination",$):et(v,"pagination");const L=rt(x,"tabStops");L?v.setAttribute("tabStops",L):et(v,"tabStops");for(const F of["oxmlAttrs","oxmlPPr"]){const X=rt(x,F);X?v.setAttribute(F,X):et(v,F)}const D=rt(x,"leftIndent");D?v.setAttribute("leftIndent",D):et(v,"leftIndent");const H=rt(x,"firstLineIndent");H?v.setAttribute("firstLineIndent",H):et(v,"firstLineIndent")}y&&w&&B?lt(w,w.length,B,N):!y&&b&&A&&T>0&&A.delete(0,Math.min(T,A.length));for(let R=d.length-1;R>=0;R--){const M=d[R],O=M.isFirst&&y,$=!y&&M.isLast&&b;if(O||$)continue;const L=ot(this.ydoc,M.block.id);if(L){const{yBlock:D,yParent:H,index:F}=L;if(H.length===1){if(M.block.type==="paragraph"){const X=Xt(n,M.block.id);if(X?.type==="container"&&X.id){const j=ot(this.ydoc,X.id);if(j&&j.yParent.length>1){j.yParent.delete(j.index,1);continue}}const C=ct(D);C&&C.length>0&&C.delete(0,C.length)}else{H.delete(F,1);const X=new I.XmlElement("paragraph");X.setAttribute("id",G());const C=new I.XmlText;X.insert(0,[C]),H.insert(0,[X])}continue}H.delete(F,1)}}}),this.setSelectionAfterOperation(r),this.afterOperationRelativeSelection=Y(r,this.ydoc,this.getDocument()),!0}deleteSingleParagraphSelection(t,e,n,o){const r=this.getDocument(),i=this.suggestionEngine.getEnclosingBlockInsertSuggestionIdForBlockId(r,t.block),a=this.getParagraphOffsetForPosition(t,r),l=this.getParagraphOffsetForPosition(e,r);if(!a||!l||!this.arePathsEqual(a.paragraphPath,l.paragraphPath))return!1;const c=this.getEmptyTextMarksForBlockId(t.block),d=yn(r,a.paragraph,t,c);let g=null;this.transact(()=>{const f=Z(this.ydoc,t.block);if(!(f instanceof I.XmlElement))return;let h=null;for(let p=0;p<f.length;p++){const m=f.get(p);if(m instanceof I.XmlText){h=m;break}}!h||a.paragraph.type!=="paragraph"||(this.suggestingMode&&!i?this.suggestionEngine.applySuggestedDeletionToTextRange(h,a.offset,l.offset-a.offset).retainedLength>0&&(g=this.normalizeAdjacentManualReplacementOrder(h,a.offset)):h.delete(a.offset,l.offset-a.offset),h.length===0&&wo(f,d))});const u=g?gs(o,t.block,g):o;return this.setSelectionAfterOperation(u),this.afterOperationRelativeSelection=Y(u,this.ydoc,this.getDocument()),!0}deleteBlock(t,e,n){this.beforeOperationSelection=e;const o=this.getDocument();return o.children.length<=1?!1:(this.beforeOperationRelativeSelection=Y(e,this.ydoc,o),this.transact(()=>{const r=this.getYContentFragment();t<r.length&&r.delete(t,1)}),this.afterOperationRelativeSelection=Y(n,this.ydoc,this.getDocument()),!0)}deleteBlockById(t,e,n){this.beforeOperationSelection=e;const o=this.getDocument(),r=W(o,t);if(!r)return!1;const i=ot(this.ydoc,t);if(!i)return!1;const{yBlock:a,yParent:l,index:c}=i;if(this.suggestingMode&&a instanceof I.XmlElement){const d=(r.type==="paragraph"||r.type==="list"?r.structuralSuggestionKind==="insert"?r.structuralSuggestionId:void 0:"diffState"in r&&r.diffState==="insert"&&"suggestionId"in r?r.suggestionId:void 0)??void 0;if(d&&this.suggestionEngine.getLiveSuggestion(d)?.type==="block-insert")return this.suggestionEngine.rejectLiveSuggestion(d);if(r.type==="paragraph"){const g=ct(a),u=g?.length??0;if(g&&u>0)return this.beforeOperationRelativeSelection=Y(e,this.ydoc,o),this.transact(()=>{this.suggestionEngine.applySuggestedDeletionToTextRange(g,0,u)}),this.afterOperationRelativeSelection=Y(n,this.ydoc,this.getDocument()),!0}else{const g=gt(),u=this.getTrailingCleanupParagraphIdForTopLevelBlock(o,t);return this.beforeOperationRelativeSelection=Y(e,this.ydoc,o),this.transact(()=>{this.suggestionEngine.markDeletedBlockElement(a,g),this.suggestionEngine.saveLiveSuggestion({id:g,type:"block-delete",blockId:t,beforeBlock:this.suggestionEngine.cloneSuggestionSnapshot(r),label:"Delete",cleanupTrailingParagraphId:u})}),this.afterOperationRelativeSelection=Y(n,this.ydoc,this.getDocument()),!0}}if(l.length===1){if(r.type==="paragraph"){const u=ct(a);return u&&u.length>0?(this.beforeOperationRelativeSelection=Y(e,this.ydoc,o),this.transact(()=>{u.delete(0,u.length)}),this.afterOperationRelativeSelection=Y(n,this.ydoc,this.getDocument()),!0):!1}this.beforeOperationRelativeSelection=Y(e,this.ydoc,o);const d=G();this.transact(()=>{l.delete(c,1);const u=new I.XmlElement("paragraph");u.setAttribute("id",d);const f=new I.XmlText;u.insert(0,[f]),l.insert(0,[u])});const g={anchor:{block:d,offset:0},focus:{block:d,offset:0}};return this.afterOperationRelativeSelection=Y(g,this.ydoc,this.getDocument()),this.setSelectionAfterOperation(g),!0}return this.beforeOperationRelativeSelection=Y(e,this.ydoc,o),this.transact(()=>{l.delete(c,1)}),this.afterOperationRelativeSelection=Y(n,this.ydoc,this.getDocument()),this.ensureTrailingParagraph(),!0}static splitBordersAttr(t){try{const e=JSON.parse(t),n=o=>{const r={};for(const i of o)e[i]!==void 0&&(r[i]=e[i]);return Object.keys(r).length>0?JSON.stringify(r):null};return{upper:n(["top","left","right"]),lower:n(["bottom","left","right"])}}catch{return{upper:t,lower:t}}}static isTailFullyDeletionMarked(t,e){if(!("children"in t)||!Array.isArray(t.children))return!1;let n=0,o=!1;for(const r of t.children){if(r.type!=="text")continue;const i=n+r.text.length;if(i>e&&r.text.length>0&&(o=!0,!r.marks?.deletion))return!1;n=i}return o}splitParagraph(t,e){this.beforeOperationSelection=e;const n=this.getDocument();this.beforeOperationRelativeSelection=Y(e,this.ydoc,n);const o=W(n,t.block);if(!o)return null;let r=null;if(o.type==="list")return this.listOperations.splitListItem(t,e);if(o.type!=="paragraph")return null;if(this.suggestingMode){const T=this.getCancelableParagraphMergeRecord(o,t.offset);if(T&&this.suggestionEngine.rejectLiveSuggestion(T.id)){const E={anchor:t,focus:t};return this.setSelectionAfterOperation(E),this.afterOperationRelativeSelection=Y(E,this.ydoc,this.getDocument()),t}}const i=ot(this.ydoc,t.block);if(!i)return null;const{yBlock:a,yParent:l,index:c}=i,d=o.structuralSuggestionId?this.suggestionEngine.getLiveSuggestion(o.structuralSuggestionId):void 0,g=d?.type==="block-change"&&d.sequenceBlockIds?d:null,u=this.getEmptyTextMarksForBlockId(t.block),f=t.offset,h=this.suggestionEngine.getStructuralInsertSuggestionIdAtPosition(n,t),p=o.children.reduce((T,E)=>E.type==="text"?T+E.text.length:T,0),m=this.suggestingMode&&f>0&&f<p&&le.isTailFullyDeletionMarked(o,f),y=typeof h=="string"&&(f===0||f===p),b=this.suggestingMode&&typeof h=="string"&&f>0&&f<p,k=typeof h=="string",S=g?null:b?h:this.suggestingMode&&!y?gt():null,v=b||this.suggestingMode&&!y&&(p===0||f===0||f===p||m),x=f===0&&!(v&&p===0),w=this.suggestingMode&&!k&&S;if(f===0){if(this.transact(()=>{r=G();const B=new I.XmlElement("paragraph");B.setAttribute("id",r);const N=a.getAttribute("heading"),R=a.getAttribute("styleId"),M=N!=null?!0:typeof R=="string"&&/^heading\d/i.test(R);ia(a,B);const O=rt(a,"direction");if((O==="rtl"||O==="ltr")&&B.setAttribute("direction",O),!M){const H=rt(a,"align");H&&B.setAttribute("align",H);const F=a.getAttribute("styleId");F!=null&&B.setAttribute("styleId",F)}const $=rt(a,"borders");if($!=null){const{upper:H,lower:F}=le.splitBordersAttr($);H?B.setAttribute("borders",H):et(B,"borders"),F?a.setAttribute("borders",F):et(a,"borders")}const L=new I.XmlText,D=M?null:yn(n,o,t,u);D&&B.setAttribute("_emptyTextMarks",JSON.stringify(D)),this.suggestionEngine.clearParagraphStructuralSuggestion(a),this.suggestionEngine.clearParagraphStructuralSuggestion(B),k&&h&&this.suggestionEngine.setParagraphStructuralSuggestion(a,"insert",void 0,h,"Insert"),S&&(v?this.suggestionEngine.setParagraphStructuralSuggestion(B,"insert",void 0,S,"Insert"):(this.suggestionEngine.setParagraphStructuralSuggestion(B,"split","before",S),this.suggestionEngine.setParagraphStructuralSuggestion(a,"split","after",S))),B.insert(0,[L]),l.insert(x?c:c+1,[B]),g&&this.suggestionEngine.preserveSequenceAfterParagraphSplit(g,[a,B]),M&&r&&this.applyStylesheetHeadingDefaults(B,{type:"paragraph",id:r,heading:o.heading,styleId:o.styleId,children:[]},n,void 0)}),!r)return null;w&&S&&this.suggestionEngine.saveLiveSuggestion({id:S,type:"block-insert",blockId:r,label:"Insert"});const T={block:k?t.block:this.suggestingMode&&v?r:t.block,offset:0},E={anchor:T,focus:T};return this.setSelectionAfterOperation(E),this.afterOperationRelativeSelection=Y(E,this.ydoc,this.getDocument()),T}if(this.transact(()=>{let T=null;for(let C=0;C<a.length;C++){const j=a.get(C);if(j instanceof I.XmlText){T=j;break}}if(!T||o.type!=="paragraph")return;const E=st(T);let B=0;const N=[];if(!m){for(const C of E)if(C.insert&&typeof C.insert=="string"){const j=C.insert.length;if(B+j<=f)B+=j;else if(B>=f)N.push(C);else{const U=f-B,z=C.insert.slice(U);z&&N.push({insert:z,...C.attributes&&{attributes:C.attributes}}),B=f}}f<T.length&&T.delete(f,T.length-f)}this.suggestionEngine.clearParagraphStructuralSuggestion(a),r=G();const R=new I.XmlElement("paragraph");R.setAttribute("id",r),ia(a,R);const M=rt(a,"align");M&&R.setAttribute("align",M);const O=a.getAttribute("styleId");O!=null&&R.setAttribute("styleId",O);const $=rt(a,"direction");($==="rtl"||$==="ltr")&&R.setAttribute("direction",$);const L=rt(a,"borders");if(L!=null){const{upper:C,lower:j}=le.splitBordersAttr(L);j?R.setAttribute("borders",j):et(R,"borders"),C?a.setAttribute("borders",C):et(a,"borders")}const D=new I.XmlText,H=yn(n,o,t,u),F=o.heading!==void 0&&Rs(n.stylesheet)!==void 0;let X=null;if(F&&N.length>0){const C=n.stylesheet,j=(o.styleId?_o(C,o.styleId):void 0)??Ye(C,o.heading),U=Rs(C);X=Xo(j?.runMarks,U?.runMarks)}if(N.length>0){let C=0;for(const j of N)if(j.insert&&typeof j.insert=="string"){let U=j.attributes||{};if(X){U={...U};for(const[z,tt]of Object.entries(X))tt===!1||tt===void 0?delete U[z]:U[z]=tt}lt(D,C,j.insert,U),C+=j.insert.length}}else H&&R.setAttribute("_emptyTextMarks",JSON.stringify(H));this.suggestionEngine.clearParagraphStructuralSuggestion(R),k&&h&&this.suggestionEngine.setParagraphStructuralSuggestion(a,"insert",void 0,h,"Insert"),S&&(v?this.suggestionEngine.setParagraphStructuralSuggestion(R,"insert",void 0,S,"Insert"):(this.suggestionEngine.setParagraphStructuralSuggestion(R,"split","after",S),this.suggestionEngine.setParagraphStructuralSuggestion(a,"split","before",S))),R.insert(0,[D]),l.insert(c+1,[R]),g&&this.suggestionEngine.preserveSequenceAfterParagraphSplit(g,[a,R]),F&&r&&(this.applyStylesheetHeadingDefaults(R,{type:"paragraph",id:r,heading:o.heading,styleId:o.styleId,children:[]},n,void 0),N.length>0&&R.removeAttribute("_emptyTextMarks"))}),!r)return null;w&&S&&(v?this.suggestionEngine.saveLiveSuggestion({id:S,type:"block-insert",blockId:r,label:"Insert"}):this.suggestionEngine.saveLiveSuggestion({id:S,type:"paragraph-split",blockId:o.id,insertedBlockId:r,beforeBlock:this.suggestionEngine.cloneSuggestionSnapshot(o)}));const A={block:r,offset:0},P={anchor:A,focus:A};return this.setSelectionAfterOperation(P),this.afterOperationRelativeSelection=Y(P,this.ydoc,this.getDocument()),A}applyFormatting(t,e,n,o,r){this.beforeOperationSelection=o;const i=this.getDocument();this.beforeOperationRelativeSelection=Y(o,this.ydoc,i);let a=!1,l=null;const c=[];return this.transact(()=>{const d=this.getYContentFragment(),g=this.collectInlineFormattingRanges(t,e,d,i);if(g.length===0)return;const u=this.suggestingMode?(()=>{let f=null;for(const h of g){if(!h.blockId)return null;const p=this.suggestionEngine.getEnclosingBlockInsertSuggestionIdForBlockId(i,h.blockId);if(!p)return null;if(!f){f=p;continue}if(f!==p)return null}return f})():null;l=this.suggestingMode&&!u?gt():null;t:for(const{yText:f,start:h,end:p}of g){const m=st(f);let y=0;for(const b of m)if(b.insert&&typeof b.insert=="string"){const k=b.insert.length,S=y+k;if(y<p&&S>h&&!(b.attributes||{})[n]){a=!0;break t}y+=k}}for(const{yText:f,start:h,end:p,blockId:m,itemIndex:y}of g){const b=Math.max(0,p-h),k=this.suggestingMode&&l&&b>0?this.collectOverlappingTextSpans(f,h,b):[];if(this.suggestingMode&&l&&b>0&&m)for(const v of k)v.attributes?.insertion||v.attributes?.deletion||c.push({blockId:m,itemIndex:y,start:v.start,end:v.start+v.length,attributes:v.attributes});const S=n==="superscript"&&a?{superscript:!0,subscript:!1}:n==="subscript"&&a?{subscript:!0,superscript:!1}:{[n]:a};if(this.suggestingMode&&l&&b>0){const v=this.suggestionEngine.buildInlineSuggestionMetadataMarks(l,this.getFormattingDescriptionFromMarkKey(n));for(const x of k)x.attributes?.deletion||(at(f,x.start,x.length,S),!x.attributes?.insertion&&at(f,x.start,x.length,{formatChange:!0,...v,suggestionPriorAttributes:Ue(x.attributes)}))}else at(f,h,b,S)}this.suggestingMode&&l&&c.length>0&&this.suggestionEngine.saveLiveSuggestion({id:l,type:"inline-format",label:this.getFormattingDescriptionFromMarkKey(n),spans:c})}),this.setSelectionAfterOperation(r),this.afterOperationRelativeSelection=Y(r,this.ydoc,this.getDocument()),!0}formatRangesWithValue(t,e,n){if(!this.suggestingMode){for(const{yText:a,start:l,end:c}of t){const d=Math.max(0,c-l);d>0&&at(a,l,d,e)}return}const o=gt(),r=this.suggestionEngine.buildInlineSuggestionMetadataMarks(o,n),i=[];for(const{yText:a,start:l,end:c,blockId:d,itemIndex:g}of t){const u=Math.max(0,c-l);if(u===0)continue;const f=this.collectOverlappingTextSpans(a,l,u);for(const h of f)h.attributes?.deletion||!Object.entries(e).some(([p,m])=>{const y=h.attributes?.[p];return m===!1||m===null?y!=null&&y!==!1:y!==m})||(at(a,h.start,h.length,e),!h.attributes?.insertion&&(at(a,h.start,h.length,{formatChange:!0,...r,suggestionPriorAttributes:Ue(h.attributes)}),d&&i.push({blockId:d,itemIndex:g,start:h.start,end:h.start+h.length,attributes:h.attributes??{}})))}i.length>0&&this.suggestionEngine.saveLiveSuggestion({id:o,type:"inline-format",label:n,spans:i})}setFontFamily(t,e,n,o){this.beforeOperationSelection=o;const r=this.getDocument();return this.beforeOperationRelativeSelection=Y(o,this.ydoc,r),this.transact(()=>{const i=this.getYContentFragment(),a=this.collectInlineFormattingRanges(t,e,i,r),l=xt(r,t,e)===0;if(a.length===0){l&&this.updateEmptyTextMarksAtPosition(t,"fontFamily",n,r);return}this.formatRangesWithValue(a,{fontFamily:n??!1},"Font"),l&&this.updateEmptyTextMarksAtPosition(t,"fontFamily",n,r)}),this.setSelectionAfterOperation(o),this.afterOperationRelativeSelection=Y(o,this.ydoc,this.getDocument()),!0}setFontSize(t,e,n,o){this.beforeOperationSelection=o;const r=this.getDocument();return this.beforeOperationRelativeSelection=Y(o,this.ydoc,r),this.transact(()=>{const i=this.getYContentFragment(),a=this.collectInlineFormattingRanges(t,e,i,r),l=xt(r,t,e)===0;if(a.length===0){l&&this.updateEmptyTextMarksAtPosition(t,"fontSize",n,r);return}this.formatRangesWithValue(a,{fontSize:n??!1},"Font Size"),l&&this.updateEmptyTextMarksAtPosition(t,"fontSize",n,r)}),this.setSelectionAfterOperation(o),this.afterOperationRelativeSelection=Y(o,this.ydoc,this.getDocument()),!0}setLetterSpacing(t,e,n,o){this.beforeOperationSelection=o;const r=this.getDocument();return this.beforeOperationRelativeSelection=Y(o,this.ydoc,r),this.transact(()=>{const i=this.getYContentFragment(),a=this.collectInlineFormattingRanges(t,e,i,r),l=xt(r,t,e)===0;if(a.length===0){l&&this.updateEmptyTextMarksAtPosition(t,"letterSpacing",n,r);return}this.formatRangesWithValue(a,{letterSpacing:n??!1},"Letter Spacing"),l&&this.updateEmptyTextMarksAtPosition(t,"letterSpacing",n,r)}),this.setSelectionAfterOperation(o),this.afterOperationRelativeSelection=Y(o,this.ydoc,this.getDocument()),!0}setTextColor(t,e,n,o){this.beforeOperationSelection=o;const r=this.getDocument();return this.beforeOperationRelativeSelection=Y(o,this.ydoc,r),this.transact(()=>{const i=this.getYContentFragment(),a=this.collectInlineFormattingRanges(t,e,i,r),l=xt(r,t,e)===0;if(a.length===0){l&&this.updateEmptyTextMarksAtPosition(t,"color",n,r);return}this.formatRangesWithValue(a,{color:n??!1},"Text Color"),l&&this.updateEmptyTextMarksAtPosition(t,"color",n,r)}),this.setSelectionAfterOperation(o),this.afterOperationRelativeSelection=Y(o,this.ydoc,this.getDocument()),!0}setBackgroundColor(t,e,n,o){const r=lc(n);this.beforeOperationSelection=o;const i=this.getDocument();return this.beforeOperationRelativeSelection=Y(o,this.ydoc,i),this.transact(()=>{const a=this.getYContentFragment(),l=this.collectInlineFormattingRanges(t,e,a,i),c=xt(i,t,e)===0;if(l.length===0){c&&this.updateBackgroundColorEmptyMarksAtPosition(t,r,i);return}this.formatRangesWithValue(l,{backgroundColor:r??null},"Highlight"),c&&this.updateBackgroundColorEmptyMarksAtPosition(t,r,i)}),this.setSelectionAfterOperation(o),this.afterOperationRelativeSelection=Y(o,this.ydoc,this.getDocument()),!0}clearFormatting(t,e,n){this.beforeOperationSelection=n;const o=this.getDocument();this.beforeOperationRelativeSelection=Y(n,this.ydoc,o);let r=!1;return this.transact(()=>{const i=this.getYContentFragment(),a=this.collectInlineFormattingRanges(t,e,i,o),l=this.collectParagraphBlockIdsInRange(t,e,o);a.some(({start:c,end:d})=>d>c)&&(this.formatRangesWithValue(a,js,"Clear Formatting"),r=!0);for(const c of l){const d=Z(this.ydoc,c);if(d)for(const g of $s)rt(d,g)!==void 0&&(et(d,g),r=!0)}xt(o,t,e)===0&&this.clearFormattingEmptyMarksAtPosition(t,o)&&(r=!0)}),this.setSelectionAfterOperation(n),this.afterOperationRelativeSelection=Y(n,this.ydoc,this.getDocument()),r}setLink(t,e,n,o){this.beforeOperationSelection=o;const r=this.getDocument();return this.beforeOperationRelativeSelection=Y(o,this.ydoc,r),this.transact(()=>{const i=this.getYContentFragment(),a=this.collectInlineFormattingRanges(t,e,i,r);if(a.length===0)return;if(!this.suggestingMode){for(const{yText:c,start:d,end:g}of a){const u=Math.max(0,g-d);n?at(c,d,u,{link:n}):at(c,d,u,{link:!1})}return}const l=this.getPendingLinkSuggestionIdForRanges(a);if(l){if(!n&&!this.pendingLinkSuggestionHadPriorLink(a)){this.suggestionEngine.rejectLiveSuggestion(l);return}for(const{yText:c,start:d,end:g}of a){const u=Math.max(0,g-d);u!==0&&at(c,d,u,{link:n??!1})}return}this.formatRangesWithValue(a,{link:n??!1},"Link")}),this.setSelectionAfterOperation(o),this.afterOperationRelativeSelection=Y(o,this.ydoc,this.getDocument()),!0}getPendingLinkSuggestionIdForRanges(t){let e=null;for(const{yText:n,start:o,end:r}of t){const i=Math.max(0,r-o);if(i!==0)for(const a of this.collectOverlappingTextSpans(n,o,i)){const l=a.attributes?.suggestionId;if(!a.attributes?.formatChange||!l)return null;const c=this.suggestionEngine.getLiveSuggestion(l);if(c?.type!=="inline-format"||c.label!=="Link"||e&&e!==l)return null;e=l}}return e}pendingLinkSuggestionHadPriorLink(t){for(const{yText:e,start:n,end:o}of t){const r=Math.max(0,o-n);if(r!==0)for(const i of this.collectOverlappingTextSpans(e,n,r)){const a=i.attributes?.suggestionPriorAttributes;if(typeof a=="string")try{if(JSON.parse(a).link)return!0}catch{}}}return!1}setCodeBlockLanguage(t,e){const n=this.getDocument(),o=W(n,t);if(!o||o.type!=="code")return!1;const r=n.children.findIndex(i=>i.id===t);return r===-1?!1:(this.transact(()=>{const i=this.getYContentFragment().get(r);i instanceof I.XmlElement&&i.nodeName==="code"&&(e?(i.setAttribute("language",e),ac(e)&&(i.getAttribute("renderDiagram")===null&&i.setAttribute("renderDiagram","true"),i.getAttribute("showDiagramSource")===null&&i.setAttribute("showDiagramSource","true"))):i.removeAttribute("language"))}),!0)}setCodeBlockRenderDiagram(t,e){const n=this.getDocument(),o=W(n,t);if(!o||o.type!=="code")return!1;const r=n.children.findIndex(i=>i.id===t);return r===-1?!1:(this.transact(()=>{const i=this.getYContentFragment().get(r);i instanceof I.XmlElement&&i.nodeName==="code"&&(i.setAttribute("renderDiagram",String(e)),e&&i.getAttribute("showDiagramSource")===null&&i.setAttribute("showDiagramSource","true"))}),!0)}setCodeBlockShowDiagramSource(t,e){const n=this.getDocument(),o=W(n,t);if(!o||o.type!=="code")return!1;const r=n.children.findIndex(i=>i.id===t);return r===-1?!1:(this.transact(()=>{const i=this.getYContentFragment().get(r);i instanceof I.XmlElement&&i.nodeName==="code"&&i.setAttribute("showDiagramSource",String(e))}),!0)}setMathBlockContent(t,e){const n=this.getDocument(),o=W(n,t);if(!o||o.type!=="math"&&!ze(o))return!1;const r=ot(this.ydoc,t);return r?(this.transact(()=>{const i=r.yBlock;if(!(i instanceof I.XmlElement))return;const a=ze(o)?"code":"math";if(i.nodeName!==a)return;let l=i.get(0);l instanceof I.XmlText||(l=new I.XmlText,i.insert(0,[l]));const c=l.length;c>0&&l.delete(0,c),l.insert(0,e)}),!0):!1}setMathBlockDisplayMode(t,e){const n=this.getDocument(),o=W(n,t);if(!o||o.type!=="math"&&!ze(o))return!1;const r=ot(this.ydoc,t);return r?(this.transact(()=>{const i=r.yBlock;if(i instanceof I.XmlElement){if(ze(o)&&i.nodeName==="code"){const a=e==="inline"?"latex-inline":"latex";i.setAttribute("language",a),i.getAttribute("renderDiagram")===null&&i.setAttribute("renderDiagram","true"),i.getAttribute("showDiagramSource")===null&&i.setAttribute("showDiagramSource","true");return}i.nodeName==="math"&&i.setAttribute("displayMode",e)}}),!0):!1}setMathBlockAlign(t,e){const n=this.getDocument(),o=W(n,t);if(!o||o.type!=="math"&&!ze(o))return!1;if(ze(o))return!0;const r=n.children.findIndex(i=>i.id===t);return r===-1?!1:(this.transact(()=>{const i=this.getYContentFragment().get(r);i instanceof I.XmlElement&&i.nodeName==="math"&&i.setAttribute("align",e)}),!0)}replaceParagraph(t,e,n,o){this.beforeOperationSelection=n;const r=this.getDocument();return this.beforeOperationRelativeSelection=Y(n,this.ydoc,r),t<0||t>=r.children.length?!1:(r.children[t],this.transact(()=>{const i=this.getYContentFragment(),a=i.get(t),l=a instanceof I.XmlElement?a.getAttribute("id"):void 0,c=new I.XmlElement("paragraph");c.setAttribute("id",e.id||l||G()),e.heading&&c.setAttribute("heading",String(e.heading)),e.align&&c.setAttribute("align",e.align),e.lineSpacing!==void 0&&c.setAttribute("lineSpacing",String(e.lineSpacing)),bn(c,e);{const h=qt(e);h!==void 0&&c.setAttribute("pagination",h)}e.styleId!==void 0&&c.setAttribute("styleId",e.styleId),e.direction!==void 0&&c.setAttribute("direction",e.direction),e.tabStops!==void 0&&c.setAttribute("tabStops",e.tabStops),e.borders!==void 0&&c.setAttribute("borders",e.borders),e.shading!==void 0&&c.setAttribute("shading",e.shading),e.oxmlAttrs!==void 0&&c.setAttribute("oxmlAttrs",e.oxmlAttrs),e.oxmlPPr!==void 0&&c.setAttribute("oxmlPPr",e.oxmlPPr);const d=Ht(e.leftIndent);d!==void 0&&c.setAttribute("leftIndent",String(d));const g=Jt(e.firstLineIndent);g!==void 0&&c.setAttribute("firstLineIndent",String(g));const u=new I.XmlText;let f=0;e.children.forEach(h=>{if(h.type==="text"){const p={...h.marks||{}};lt(u,f,h.text,p),f+=h.text.length}}),c.insert(0,[u]),i.delete(t,1),i.insert(t,[c])}),this.setSelectionAfterOperation(o),this.afterOperationRelativeSelection=Y(o,this.ydoc,this.getDocument()),!0)}pasteParagraphsAsSuggestions(t,e,n,o){let r={block:t.block,offset:t.offset},i={anchor:n.anchor?{...n.anchor}:null,focus:n.focus?{...n.focus}:null},a=!1;const l=()=>{const d=this.getAfterOperationSelection();return d?.focus?{block:d.focus.block,offset:d.focus.offset}:null};let c=null;if(this.transact(()=>{for(let d=0;d<e.length;d++){if(d>0){const g=this.splitParagraph(r,{anchor:r,focus:r});if(!g)return;r=g,i={anchor:r,focus:r}}for(const g of e[d].children){if(g.type!=="text"||g.text.length===0)continue;const u=this.suggestionEngine.stripSuggestionMarksFromTextMark(g.marks)??{};if(!this.insertFormattedText(r,g.text,u,i,{anchor:r,focus:r},o))return;a=!0;const f=l();f&&(r=f),i={anchor:r,focus:r}}}c=r}),!a&&!c)return null;if(c){const d={anchor:c,focus:c};this.setSelectionAfterOperation(d),this.afterOperationRelativeSelection=Y(d,this.ydoc,this.getDocument())}return c}pasteParagraphs(t,e,n,o={}){if(e.length===0||!e.some(b=>b.children.some(k=>k.type==="text"&&k.text.length>0)))return null;const r=de(Ro(this.getDocument(),t,n)?.marks);if(r?.fontFamily===jt&&delete r.fontFamily,r&&(e=e.map(b=>b.type==="paragraph"?{...b,children:b.children.map(k=>k.type==="text"?{...k,marks:{...r,...k.marks??{}}}:k)}:b)),this.suggestingMode)return this.pasteParagraphsAsSuggestions(t,e,n,o.suggestionIdOverride);this.beforeOperationSelection={anchor:n.anchor?{...n.anchor}:null,focus:n.focus?{...n.focus}:null};const i=this.getDocument();this.beforeOperationRelativeSelection=Y(n,this.ydoc,i);let a=null;const l=o.preserveStructure===!0&&e.length>1;let c,d=null,g=null,u=null,f=!1,h=null,p=null;const m=b=>{if(!b.id)return null;let k=0;for(const S of b.children)S.type==="text"&&(k+=S.text.length);return{block:b.id,offset:k}},y=b=>b.id?b:{...b,id:G()};try{this.transact(()=>{const k=n.anchor&&n.focus&&xt(i,n.anchor,n.focus)!==0;let S={block:t.block,offset:t.offset};if(k&&n.anchor&&n.focus){const X={block:t.block,offset:t.offset},C=n.anchor.block===X.block&&n.anchor.offset===X.offset,j=n.focus.block===X.block&&n.focus.offset===X.offset,U=X,z=C?{block:n.focus.block,offset:n.focus.offset}:j?{block:n.anchor.block,offset:n.anchor.offset}:xt(i,n.anchor,n.focus)<=0?{block:n.focus.block,offset:n.focus.offset}:{block:n.anchor.block,offset:n.anchor.offset},tt=this.getParagraphOffsetForPosition(U,i),_=this.getParagraphOffsetForPosition(z,i);tt&&_&&this.arePathsEqual(tt.paragraphPath,_.paragraphPath)&&(d=_.offset);const V=tt?.offset??U.offset;this.deleteSelection({block:U.block,offset:U.offset},{block:z.block,offset:z.offset},{anchor:n.anchor?{block:n.anchor.block,offset:n.anchor.offset}:null,focus:n.focus?{block:n.focus.block,offset:n.focus.offset}:null},{anchor:{block:U.block,offset:U.offset},focus:{block:U.block,offset:U.offset}});const nt=this.getDocument(),J=W(nt,U.block);(J?.type==="paragraph"||J?.type==="list")&&J.id&&(S={block:J.id,offset:V})}const v=d!==null?i:this.getDocument(),x=this.getBlockContextById(v,S.block);if(!x){a=null;return}if(x.block.type==="list"){const X=e[0],C=X.children.filter(j=>j.type==="text").map(j=>j.text).join("");if(C){const j=X.children.find(z=>z.type==="text")?.marks||null,U=this.listOperations.insertTextInListItem(S,C,j);U&&(a=U)}return}if(x.block.type!=="paragraph"){a=null;return}const w=x.block;if(!w||w.type!=="paragraph"){a=null;return}const A=[],P=this.getParagraphOffsetForPosition(S,v)?.offset??0,T=d??P;let E=0;for(let X=0;X<w.children.length;X++){const C=w.children[X];if(C.type==="text"){const j=E;if(E+C.text.length>T){const U=Math.max(0,T-j);U<C.text.length&&A.push({type:"text",text:C.text.substring(U),marks:C.marks})}E+=C.text.length}}const B=A.length>0&&A.some(X=>X.text.length>0);if(f=B,B){let X=0;for(const j of w.children)j.type==="text"&&(X+=j.text.length);const C={block:w.id,offset:X};this.deleteSelection(S,C,{anchor:S,focus:C},{anchor:S,focus:S})}const N=e[0],R=Z(this.ydoc,S.block);if(!R){a=null;return}const M=ct(R);if(!M){a=null;return}if(M.length===0&&N.type==="paragraph"){N.heading!==void 0?R.setAttribute("heading",String(N.heading)):R.removeAttribute("heading"),N.align?R.setAttribute("align",N.align):et(R,"align"),N.lineSpacing!==void 0?R.setAttribute("lineSpacing",String(N.lineSpacing)):et(R,"lineSpacing");for(const j of nl)et(R,j);bn(R,N);{const j=qt(N);j!==void 0?R.setAttribute("pagination",j):et(R,"pagination")}N.styleId!==void 0?R.setAttribute("styleId",N.styleId):R.removeAttribute("styleId"),N.direction!==void 0?R.setAttribute("direction",N.direction):et(R,"direction"),N.tabStops!==void 0?R.setAttribute("tabStops",N.tabStops):et(R,"tabStops"),N.borders!==void 0?R.setAttribute("borders",N.borders):et(R,"borders"),N.shading!==void 0?R.setAttribute("shading",N.shading):et(R,"shading");const X=Ht(N.leftIndent);X!==void 0?R.setAttribute("leftIndent",String(X)):et(R,"leftIndent");const C=Jt(N.firstLineIndent);C!==void 0?R.setAttribute("firstLineIndent",String(C)):et(R,"firstLineIndent")}const O=N.children.filter(X=>X.type==="text"),$=this.insertTextNodes(S,O);if(!$){a=null;return}if(g=$,a=$,e.length===1&&!B){u=$.block;return}const L=ot(this.ydoc,S.block);if(!L)return;const D=L.yParent;let H=L.index+1;if(l){const X=[];let C=null;for(let j=1;j<e.length;j++){const U=y(e[j]);this.insertParagraphInternal(H,U,D),X.push(U.id),H++}if(B){const j={type:"paragraph",id:G(),children:A.map(tt=>({type:"text",text:tt.text,marks:tt.marks?{...tt.marks}:void 0}))};w.heading!==void 0&&(j.heading=w.heading),w.align&&(j.align=w.align),w.direction!==void 0&&(j.direction=w.direction),w.tabStops!==void 0&&(j.tabStops=w.tabStops),w.lineSpacing!==void 0&&(j.lineSpacing=w.lineSpacing),w.spaceBefore!==void 0&&(j.spaceBefore=w.spaceBefore),w.spaceAfter!==void 0&&(j.spaceAfter=w.spaceAfter),w.contextualSpacing!==void 0&&(j.contextualSpacing=w.contextualSpacing),w.keepNext!==void 0&&(j.keepNext=w.keepNext),w.keepLines!==void 0&&(j.keepLines=w.keepLines),w.widowControl!==void 0&&(j.widowControl=w.widowControl);const U=Ht(w.leftIndent);U!==void 0&&(j.leftIndent=U);const z=Jt(w.firstLineIndent);z!==void 0&&(j.firstLineIndent=z),this.insertParagraphInternal(H,j,D),C=j.id,H++}c={insertedParagraphIds:X,remainderParagraphId:C};return}let F=S.block;for(let X=1;X<e.length;X++){const C=y(e[X]);this.insertParagraphInternal(H,C,D),F=C.id,H++}if(u=F,B){const X=e.length>1?D.get(H-1):R;if(X instanceof I.XmlElement){let C=null;for(let j=0;j<X.length;j++){const U=X.get(j);if(U instanceof I.XmlText){C=U;break}}if(C){let j=C.length;h=j,p=F;for(const U of A){if(!U.text.length)continue;const z={...U.marks||{}};C.insert(j,U.text,z),j+=U.text.length}}}}});const b=this.getDocument();if(l&&c){const{insertedParagraphIds:k,remainderParagraphId:S}=c;if(k.length>0){const v=k[k.length-1],x=W(b,v);x&&x.type==="paragraph"?a=m(x):a={block:v,offset:0}}else if(S!==null){const v=W(b,S);v&&v.type==="paragraph"?a=m(v):a={block:S,offset:0}}else g&&(a=g)}else if(!l)if(f&&p!==null&&h!==null)a={block:p,offset:h};else if(f&&g)a=g;else if(u!==null){const k=W(b,u);k&&k.type==="paragraph"?a=m(k):g?a=g:a={block:u,offset:0}}else g&&(a=g);!a&&g&&(a=g)}catch(b){return console.error("Error in pasteParagraphs:",b),null}return a||(a=g??t),a&&(a=this.normalizeCursorPosition(a),this.setSelectionAfterOperation({anchor:a,focus:a}),this.updateAfterOperationRelativeSelection(this.getDocument())),a}normalizeCursorPosition(t){return this.getDocument().children.length,t}replaceDocument(t){return this.undoManager.stopCapturing(),this.transact(()=>{const e=this.getYContentFragment();e.length>0&&e.delete(0,e.length),t.children.forEach(n=>{if(n.type==="placeholder"){const o=new I.XmlElement("placeholder");o.setAttribute("id",n.id||G()),o.setAttribute("height",String(n.height)),e.push([o])}else if(n.type==="image"){const o=n,r=new I.XmlElement("image");r.setAttribute("id",n.id||G()),r.setAttribute("src",o.src),o.sourceUrl&&r.setAttribute("sourceUrl",o.sourceUrl),r.setAttribute("width",String(o.width)),r.setAttribute("height",String(o.height)),o.alt&&r.setAttribute("alt",o.alt),e.push([r])}else if(n.type==="paragraph"){const o=new I.XmlElement("paragraph");o.setAttribute("id",n.id||G()),n.heading&&o.setAttribute("heading",String(n.heading)),n.align&&o.setAttribute("align",n.align),n.lineSpacing!==void 0&&o.setAttribute("lineSpacing",String(n.lineSpacing)),bn(o,n);{const c=qt(n);c!==void 0&&o.setAttribute("pagination",c)}n.styleId!==void 0&&o.setAttribute("styleId",n.styleId),n.direction!==void 0&&o.setAttribute("direction",n.direction),n.tabStops!==void 0&&o.setAttribute("tabStops",n.tabStops),n.borders!==void 0&&o.setAttribute("borders",n.borders),n.shading!==void 0&&o.setAttribute("shading",n.shading);const r=Ht(n.leftIndent);r!==void 0&&o.setAttribute("leftIndent",String(r));const i=Jt(n.firstLineIndent);i!==void 0&&o.setAttribute("firstLineIndent",String(i));const a=new I.XmlText;let l=0;n.children.forEach(c=>{if(c.type==="text"){const d={...c.marks||{}};lt(a,l,c.text,d),l+=c.text.length}}),o.insert(0,[a]),e.push([o])}else if(n.type==="list"){const o=n,r=new I.XmlElement("list");r.setAttribute("id",n.id||G()),r.setAttribute("variant",o.variant),o.startNumber!==void 0&&r.setAttribute("startNumber",String(o.startNumber)),o.numberingChainId&&r.setAttribute("numberingChainId",o.numberingChainId),o.numberingFormat&&r.setAttribute("numberingFormat",o.numberingFormat),o.children.forEach(i=>{const a=new I.XmlElement("list-item");Ce(a,i),a.setAttribute("id",i.id||G()),o.variant==="todo"&&a.setAttribute("checked",String(i.checked??!1)),i.indentLevel!==void 0&&i.indentLevel>0&&a.setAttribute("indentLevel",String(i.indentLevel)),i.direction!==void 0&&a.setAttribute("direction",i.direction);const l=new I.XmlText;let c=0;i.children.forEach(d=>{if(d.type==="text"){const g={...d.marks||{}};l.insert(c,d.text,g),c+=d.text.length}}),a.insert(0,[l]),r.push([a])}),e.push([r])}})}),this.undoManager.clear(),!0}alignNormalizationDirection(t,e){const n=t?.type==="paragraph"?t:void 0,o=Object.prototype.hasOwnProperty.call(e,"direction")?e.direction??void 0:n?.direction;let r="";if(n)for(const i of n.children)r+=i.text??"";return Ds(o,r)}updateParagraphAttributes(t,e,n,o){this.beforeOperationSelection=n;const r=this.getDocument();if(this.beforeOperationRelativeSelection=Y(n,this.ydoc,r),t<0||t>=r.children.length)return!1;(Object.prototype.hasOwnProperty.call(e,"leftIndent")||Object.prototype.hasOwnProperty.call(e,"firstLineIndent"))&&this.ensureParagraphIndentStorageUsesUnits();const i=this.alignNormalizationDirection(r.children[t],e);return this.transact(()=>{const a=this.getYContentFragment().get(t);if(a instanceof I.XmlElement){if(Object.prototype.hasOwnProperty.call(e,"align")&&(e.align===void 0||e.align==="left"&&i==="ltr"?et(a,"align"):a.setAttribute("align",e.align)),Object.prototype.hasOwnProperty.call(e,"heading")){e.heading===void 0?a.removeAttribute("heading"):a.setAttribute("heading",String(e.heading));const l=r.children[t];l&&!this.applyStylesheetHeadingDefaults(a,l,r,e.heading)&&this.clearFontSizeMarksForHeadingChange(l,r)}if(Object.prototype.hasOwnProperty.call(e,"lineSpacing")&&(e.lineSpacing===void 0?et(a,"lineSpacing"):a.setAttribute("lineSpacing",String(e.lineSpacing))),Object.prototype.hasOwnProperty.call(e,"styleId")&&(e.styleId===null||e.styleId===void 0?a.removeAttribute("styleId"):a.setAttribute("styleId",e.styleId)),Object.prototype.hasOwnProperty.call(e,"direction")&&(e.direction===null||e.direction===void 0?et(a,"direction"):a.setAttribute("direction",e.direction)),Object.prototype.hasOwnProperty.call(e,"tabStops")&&(e.tabStops===null||e.tabStops===void 0?et(a,"tabStops"):a.setAttribute("tabStops",e.tabStops)),Object.prototype.hasOwnProperty.call(e,"borders")&&(e.borders===null||e.borders===void 0?et(a,"borders"):a.setAttribute("borders",e.borders)),Object.prototype.hasOwnProperty.call(e,"shading")&&(e.shading===null||e.shading===void 0?et(a,"shading"):a.setAttribute("shading",e.shading)),Object.prototype.hasOwnProperty.call(e,"keepNext")||Object.prototype.hasOwnProperty.call(e,"keepLines")||Object.prototype.hasOwnProperty.call(e,"widowControl")){const l={};vn(l,rt(a,"pagination"));for(const d of["keepNext","keepLines","widowControl"])Object.prototype.hasOwnProperty.call(e,d)&&(e[d]===void 0?delete l[d]:l[d]=e[d]);const c=qt(l);c===void 0?et(a,"pagination"):a.setAttribute("pagination",c)}if(Object.prototype.hasOwnProperty.call(e,"leftIndent")){const l=Ht(e.leftIndent);l===void 0?et(a,"leftIndent"):a.setAttribute("leftIndent",String(l))}if(Object.prototype.hasOwnProperty.call(e,"firstLineIndent")){const l=Jt(e.firstLineIndent);l===void 0?et(a,"firstLineIndent"):a.setAttribute("firstLineIndent",String(l))}}}),this.afterOperationRelativeSelection=Y(o,this.ydoc,this.getDocument()),!0}applyStylesheetHeadingDefaults(t,e,n,o){if(e.type!=="paragraph"||!e.id)return!1;const r=n.stylesheet,i=Ye(r,o);if(!r||!i)return!1;const a=(e.styleId?_o(r,e.styleId):void 0)??Ye(r,e.heading);o!==void 0&&i.styleId.toLowerCase()!=="normal"?t.setAttribute("styleId",i.styleId):t.removeAttribute("styleId");const l=a?.paragraphAttrs??{},c=i.paragraphAttrs??{},d=(p,m)=>Object.prototype.hasOwnProperty.call(p,m),g=["align","lineSpacing","spaceBefore","spaceAfter","contextualSpacing","leftIndent","firstLineIndent","direction","borders","shading","tabStops"];(d(c,"leftIndent")||d(c,"firstLineIndent"))&&(c.leftIndent!==void 0||c.firstLineIndent!==void 0)&&this.ensureParagraphIndentStorageUsesUnits();for(const p of g){if(!d(l,p)&&!d(c,p))continue;const m=c[p];m===void 0||m===!1?et(t,p):t.setAttribute(p,String(m))}const u=["keepNext","keepLines","widowControl"];if(u.some(p=>d(l,p)||d(c,p))){const p={};vn(p,rt(t,"pagination"));for(const y of u)!d(l,y)&&!d(c,y)||(c[y]===void 0?delete p[y]:p[y]=c[y]);const m=qt(p);m===void 0?et(t,"pagination"):t.setAttribute("pagination",m)}const f=Xo(a?.runMarks,i.runMarks),h=e.children.reduce((p,m)=>m.type==="text"?p+m.text.length:p,0);if(h>0){const p=this.getYContentFragment(),m=this.collectInlineFormattingRanges({block:e.id,offset:0},{block:e.id,offset:h},p,n);for(const{yText:y,start:b,end:k}of m){const S=Math.max(0,k-b);S>0&&at(y,b,S,f)}}else wo(t,i.runMarks);return!0}clearFontSizeMarksForHeadingChange(t,e){if(t.type!=="paragraph"||!t.id)return;const n=t.children.reduce((i,a)=>a.type==="text"?i+a.text.length:i,0);if(!t.children.some(i=>i.type==="text"&&i.marks?.fontSize!==void 0))return;if(n===0){this.updateEmptyTextMarksAtPosition({block:t.id,offset:0},"fontSize",void 0,e);return}const o=this.getYContentFragment(),r=this.collectInlineFormattingRanges({block:t.id,offset:0},{block:t.id,offset:n},o,e);for(const{yText:i,start:a,end:l}of r){const c=Math.max(0,l-a);c>0&&at(i,a,c,{fontSize:!1})}}updateParagraphAttributesById(t,e,n,o){const r=W(this.getDocument(),t);if(!r||r.type!=="paragraph"&&r.type!=="list")return!1;const i=Z(this.ydoc,t);if(!i)return!1;this.beforeOperationSelection=n;const a=this.getDocument();this.beforeOperationRelativeSelection=Y(n,this.ydoc,a);const l=Object.prototype.hasOwnProperty.call(e,"leftIndent")||Object.prototype.hasOwnProperty.call(e,"firstLineIndent"),c=this.suggestionEngine.getEnclosingBlockInsertSuggestionIdForBlockId(a,t),d=this.suggestingMode&&!c?gt():null;l&&this.ensureParagraphIndentStorageUsesUnits();const g=this.alignNormalizationDirection(W(a,t)??void 0,e);return this.transact(()=>{if(Object.prototype.hasOwnProperty.call(e,"align")&&(e.align===void 0||e.align==="left"&&g==="ltr"?et(i,"align"):i.setAttribute("align",e.align)),Object.prototype.hasOwnProperty.call(e,"heading")&&(e.heading===void 0?i.removeAttribute("heading"):i.setAttribute("heading",String(e.heading)),this.applyStylesheetHeadingDefaults(i,r,a,e.heading)||this.clearFontSizeMarksForHeadingChange(r,a)),Object.prototype.hasOwnProperty.call(e,"lineSpacing")&&(e.lineSpacing===void 0?et(i,"lineSpacing"):i.setAttribute("lineSpacing",String(e.lineSpacing))),Object.prototype.hasOwnProperty.call(e,"styleId")&&(e.styleId===null||e.styleId===void 0?i.removeAttribute("styleId"):i.setAttribute("styleId",e.styleId)),Object.prototype.hasOwnProperty.call(e,"direction")&&(e.direction===null||e.direction===void 0?et(i,"direction"):i.setAttribute("direction",e.direction)),Object.prototype.hasOwnProperty.call(e,"tabStops")&&(e.tabStops===null||e.tabStops===void 0?et(i,"tabStops"):i.setAttribute("tabStops",e.tabStops)),Object.prototype.hasOwnProperty.call(e,"borders")&&(e.borders===null||e.borders===void 0?et(i,"borders"):i.setAttribute("borders",e.borders)),Object.prototype.hasOwnProperty.call(e,"shading")&&(e.shading===null||e.shading===void 0?et(i,"shading"):i.setAttribute("shading",e.shading)),Object.prototype.hasOwnProperty.call(e,"keepNext")||Object.prototype.hasOwnProperty.call(e,"keepLines")||Object.prototype.hasOwnProperty.call(e,"widowControl")){const u={};vn(u,rt(i,"pagination"));for(const h of["keepNext","keepLines","widowControl"])Object.prototype.hasOwnProperty.call(e,h)&&(e[h]===void 0?delete u[h]:u[h]=e[h]);const f=qt(u);f===void 0?et(i,"pagination"):i.setAttribute("pagination",f)}if(Object.prototype.hasOwnProperty.call(e,"leftIndent")){const u=Ht(e.leftIndent);u===void 0?et(i,"leftIndent"):i.setAttribute("leftIndent",String(u))}if(Object.prototype.hasOwnProperty.call(e,"firstLineIndent")){const u=Jt(e.firstLineIndent);u===void 0?et(i,"firstLineIndent"):i.setAttribute("firstLineIndent",String(u))}this.suggestingMode&&d&&(this.suggestionEngine.clearElementStructuralSuggestion(i),this.suggestionEngine.setElementStructuralSuggestion(i,"change",void 0,d,"Format"),this.suggestionEngine.saveLiveSuggestion({id:d,type:"block-change",blockId:t,beforeBlock:this.suggestionEngine.cloneSuggestionSnapshot(r),label:"Format"}))}),this.afterOperationRelativeSelection=Y(o,this.ydoc,this.getDocument()),!0}updateTocAttributesById(t,e,n,o){const r=W(this.getDocument(),t);if(!r||r.type!=="toc")return!1;const i=Z(this.ydoc,t);return i?(this.beforeOperationSelection=n,this.beforeOperationRelativeSelection=Y(n,this.ydoc,this.getDocument()),this.transact(()=>{Object.prototype.hasOwnProperty.call(e,"fontFamily")&&(e.fontFamily==null||e.fontFamily===""?i.removeAttribute("fontFamily"):i.setAttribute("fontFamily",e.fontFamily)),Object.prototype.hasOwnProperty.call(e,"fontSize")&&(e.fontSize==null?i.removeAttribute("fontSize"):i.setAttribute("fontSize",String(e.fontSize))),Object.prototype.hasOwnProperty.call(e,"color")&&(e.color==null||e.color===""?i.removeAttribute("color"):i.setAttribute("color",e.color))}),this.afterOperationRelativeSelection=Y(o,this.ydoc,this.getDocument()),!0):!1}beginGroup(t){this.batchingUpdates=!0,this.pendingUpdate=null}endGroup(){if(this.undoManager.stopCapturing(),this.batchingUpdates=!1,this.pendingUpdate){const t=this.pendingUpdate;this.pendingUpdate=null,t()}}getHistoryInfo(){return{undoStackSize:this.undoManager.undoStack.length,redoStackSize:this.undoManager.redoStack.length}}clearHistory(){this.undoManager.clear()}extractTextNodesForRange(t,e,n){if(n<=e)return[];const o=[];let r=0;for(const i of t.children){if(i.type!=="text")continue;const a=r,l=r+i.text.length,c=Math.max(e,a),d=Math.min(n,l);if(c<d&&o.push({type:"text",text:i.text.slice(c-a,d-a),marks:this.suggestionEngine.sanitizePreviewMarks(i.marks)}),r=l,r>=n)break}return o}buildParagraphReplacementLiveBlock(t,e,n,o){const r=this.suggestionEngine.buildInlineSuggestionMetadataMarks(n,o),i=(u,f)=>u.map(h=>{const p=this.suggestionEngine.sanitizePreviewMarks(h.marks)??{};return delete p.deletion,delete p.insertion,delete p.formatChange,{type:"text",text:h.text,marks:{...p,...r,[f]:!0,suggestionId:n}}}),a=i(t.children,"deletion"),l=i(e.children,"insertion"),c=a.map(u=>u.text).join(""),d=l.map(u=>u.text).join(""),g=c.length>0&&d.length>0&&!/\s$/.test(c)&&!/^\s/.test(d);return{...e,children:[...a,...g?[{type:"text",text:" "}]:[],...l],structuralSuggestionId:n,structuralSuggestionKind:"change",structuralSuggestionLabel:o}}canBridgeListItemChangeAsInline(t,e){return An.every(n=>t[n]===e[n])&&t.direction===e.direction&&(t.checked??!1)===(e.checked??!1)&&(t.indentLevel??0)===(e.indentLevel??0)}replaceBlockByIdWithoutSelection(t,e,n){const o=n?n.yBlock._item:null,r=n&&!o?.deleted&&n.yParent.get(n.index)===n.yBlock,i=r?null:ot(this.ydoc,t),a=r?n.yParent:i?.yParent,l=r?n.index:i?.index;return!a||l===void 0?!1:(this.transact(()=>{const c=a.get(l);if(e.type==="list"&&c instanceof I.XmlElement&&c.nodeName==="list"){Kr(c,e);return}const d=this.blockToYjsElement(e);a.delete(l,1),a.insert(l,[d])}),!0)}paragraphReplaceShouldStayAtomic(t,e){return!Je(t,e)}resolvePositionAwareInsertionReference(t){const e=[...t.mustBeAfter].reverse().find(r=>typeof r=="string"&&r.length>0);if(e)return{referenceId:e,position:"after"};const n=t.mustBeBefore.find(r=>typeof r=="string"&&r.length>0);if(n)return{referenceId:n,position:"before"};const o=t.baseDoc.children[0]?.id;return o?{referenceId:o,position:"before"}:t.baseDoc.children.length===0?{referenceId:Ve,position:"after"}:null}tryCancelInsertedBlockForRemoveAction(t,e){if(!t?.length)return null;const n=t.length===1?t[0]:void 0,o=n?.arguments;if(n?.name==="remove_block"&&typeof o?.count=="number"&&Number.isInteger(o.count)&&o.count>1){const c=e.children.findIndex(d=>d.id===o.id);if(c<0||c+o.count>e.children.length)return null;t=e.children.slice(c,c+o.count).map(d=>({name:"remove_block",arguments:{id:d.id}}))}const r=this.getDocument(),i=new Set,a=new Set,l=new Set;for(const c of t){if(c.name!=="remove_block")return null;const d=c.arguments;if(typeof d?.id!="string"||d.count!==void 0&&d.count!==1)return null;const g=W(r,d.id)??W(e,d.id),u=this.suggestionEngine.getBlockInsertSuggestionIdForBlock(g),f=u?this.suggestionEngine.getLiveSuggestion(u):void 0;if(!g)return null;if(i.add(d.id),!u){l.add(d.id);continue}if(f?.type!=="block-insert")return null;a.add(u)}for(const c of a){const d=this.suggestionEngine.getLiveSuggestion(c);d?.type==="block-insert"&&d.cleanupTrailingParagraphId&&l.delete(d.cleanupTrailingParagraphId)}if(l.size>0||a.size===0)return null;for(const c of a)if(this.collectStructuralInsertBlockIds(r,c).some(d=>!i.has(d)))return null;return this.suggestionEngine.rejectLiveSuggestions([...a])===0?null:{success:!0,planningSuggestionIds:[],agentFeedback:`Removed pending inserted block${i.size===1?"":"s"} ${[...i].join(", ")}.`}}getActionTargetBlockIds(t,e){if(!t)return[];const n=new Set;for(const o of t){const r=o.arguments&&typeof o.arguments=="object"?o.arguments:null;if(!r||typeof r.id!="string"||r.id.length===0)continue;const i=r.id;if(n.add(i),o.name!=="replace_block")continue;const a=typeof r.count=="number"&&Number.isFinite(r.count)?Math.max(1,Math.floor(r.count)):1;if(a<=1)continue;const l=Cn(e,i);if(!(l<0))for(let c=l+1;c<Math.min(e.children.length,l+a);c++){const d=e.children[c]?.id;d&&n.add(d)}}return Array.from(n)}applyAgentActions(t,e,n){if(e||(e="default-"+Date.now()),t.actions?.some(c=>c.name==="move_blocks")){if(t.actions.length!==1||t.actions[0].name!=="move_blocks")return{success:!1,error:"move_blocks must be the only action in its tool call."};const{block_ids:c,reference_id:d,position:g}=t.actions[0].arguments,u=this.getDocument(),f=m=>{throw new St("invalid_move",m,"validation")};let h,p;try{(!Array.isArray(c)||!c.length||c.length>100||new Set(c).size!==c.length||c.some(_=>typeof _!="string"))&&f("Provide one to 100 unique top-level block IDs in document order."),g!=="before"&&g!=="after"&&f("position must be before or after.");const m=u.children.findIndex(_=>_.id===c[0]),y=u.children.findIndex(_=>_.id===d);(m<0||y<0||c.some((_,V)=>u.children[m+V]?.id!==_))&&f("Source blocks must be contiguous top-level blocks in document order, and the destination must be a current top-level block. Read the current section first.");const b=m+c.length-1;y>=m&&y<=b&&f("The destination is inside the source range; choose a reference block outside the range.");const k=u.children.slice(m,b+1),S=_=>_.type==="text"&&!!_.text||!!_.children?.some(S),v=new Map;for(const _ of u.children){const V=_.structuralSuggestionId??_.suggestionId,nt=_.structuralSuggestionKind??_.diffState;!V||nt!=="insert"&&nt!=="delete"||v.set(V,(v.get(V)??new Set).add(nt))}const x=_=>v.get(_)?.size===2,w=k[0].structuralSuggestionId??k[0].suggestionId;if(w){const _=(J,K)=>(J.structuralSuggestionId??J.suggestionId)===w&&(J.structuralSuggestionKind??J.diffState)===K;let V=!1;const nt=J=>{try{JSON.parse(J.marks?.docxMove??"null")?.wholeBlocks&&J.marks?.suggestionId===w&&(V=!0)}catch{}J.children?.forEach(nt)};if(k.forEach(nt),!k.some(S)&&x(w)&&(V=!0),V&&k.every(J=>_(J,"delete"))){const J=g==="after"?y+1:y-c.length,K=u.children.slice(J,J+c.length);if(K.length===c.length&&K.every(q=>_(q,"insert")))return{success:!0,resultCode:"already_satisfied",suggestionIds:[w],agentFeedback:`This move is already proposed at the requested destination; no additional changes were made. Destination block IDs: ${K.map(q=>q.id).join(", ")}.`};f(`These are the deleted originals of an existing pending Move. To correct that proposal, use its complete current destination range instead: ${u.children.filter(q=>_(q,"insert")).map(q=>q.id).join(", ")}. Do not move or anchor to the deleted originals.`)}}const A=_=>{const V=_.structuralSuggestionId??_.suggestionId;if(!V||(_.structuralSuggestionKind??_.diffState)!=="insert")return null;let nt=!1;const J=q=>{if(q.marks?.comment||q.marks?.deletion||[q.suggestionId,q.structuralSuggestionId,q.marks?.suggestionId].some(Q=>Q&&Q!==V)||q.structuralSuggestionKind&&q.structuralSuggestionKind!=="insert"||q.diffState&&q.diffState!=="insert")return!1;if(q.type==="text"&&q.text){nt=!0;try{const Q=JSON.parse(q.marks?.docxMove??"null");if(q.marks?.suggestionId!==V||!q.marks?.insertion||!Q?.wholeBlocks||Q.role!=="to")return!1}catch{return!1}}return!q.children||q.children.every(J)},K=_.type!=="paragraph"||ql(_);return J(_)&&(nt||K&&x(V))?V:null},P=A(k[0]),T=P&&k.every(_=>A(_)===P)?P:null;if(T){const _=K=>{if(K.type==="text"&&K.text){const q=K.marks,Q=JSON.parse(q.docxMove);if(q.suggestionSource!=="agent"||q.suggestionAuthorName!==(t.agentName??Nt)||Q.name!==`reviseMove-${T}`||q.suggestionAgentConversationId&&q.suggestionAgentConversationId!==t.agentConversationId)return!1}return!K.children||K.children.every(_)},V=k.some(S)?null:this.suggestionEngine.getLiveSuggestion(T),nt=!!V&&V.type==="inline-text"&&V.label==="Move"&&V.source==="agent"&&(V.agentName??Nt)===(t.agentName??Nt)&&(!V.agentConversationId||V.agentConversationId===t.agentConversationId);(!k.every(_)||!k.some(S)&&!nt)&&f("Only this agent's own pending Move can be repositioned. Review imported or other authors' moves first."),u.children.some(K=>(K.structuralSuggestionId??K.suggestionId)===T&&(K.structuralSuggestionKind??K.diffState)==="delete")||f("This pending Move has no original source; it cannot be repositioned safely.");const J=u.children.filter(K=>A(K)===T);(J.length!==k.length||J.some((K,q)=>K.id!==c[q]))&&f("To correct a pending Move, supply its complete destination range in current document order; moving only part would split the linked change."),n?.applyBlockMovesDirectly&&f("An existing tracked Move must be corrected in suggesting mode.")}const E=A(u.children[y]);if(E){const _=u.children[y+(g==="after"?1:-1)];_&&(_.structuralSuggestionId??_.suggestionId)===E&&(_.structuralSuggestionKind??_.diffState)==="insert"&&f("Do not insert inside an existing multi-block Move destination. Anchor before its first block or after its last block.")}const B=new Set,N=_=>{_.id&&B.add(_.id),_.children?.forEach(N)};[...k,u.children[y]].forEach(N),this.getComments().some(_=>_.anchorBlockId&&B.has(_.anchorBlockId))&&f("Moving blocks with anchored comments is not supported yet; no change was made.");for(const _ of this.getLiveSuggestionStore().values())this.suggestionEngine.liveSuggestionRecordTouchesAnyBlock(_,B)&&f("Source or destination has pending tracked changes; inspect those changes before moving it.");const R=_=>{(_.suggestionId||_.structuralSuggestionId||_.diffState||_.marks?.suggestionId||_.marks?.insertion||_.marks?.deletion||_.marks?.docxMove)&&f("Source and destination must have no pending tracked changes. Review them before moving these blocks."),_.marks?.comment&&f("Moving blocks with anchored comments is not supported yet; no change was made."),_.children?.forEach(R)},M=_=>{const V=_.structuralSuggestionId??_.suggestionId;if(V&&(_.structuralSuggestionKind??_.diffState)==="delete")return x(V)?V:null;let nt=null,J=!0;const K=q=>{if(q.type==="text"&&q.text)try{const Q=JSON.parse(q.marks?.docxMove??"null");Q?.wholeBlocks&&Q.role==="from"&&q.marks?.deletion&&(nt??q.marks.suggestionId)===q.marks.suggestionId?nt=q.marks.suggestionId:J=!1}catch{J=!1}q.children?.forEach(K)};return K(_),J?nt:null},O=_=>{const V=M(_);return V?u.children.filter(nt=>A(nt)===V).map(nt=>nt.id):[]},$=(_,V)=>{const nt=O(_);nt.length&&f(`'${_.id}' is the original position of a pending Move; its content now sits at ${nt.map(J=>`'${J}'`).join(", ")}. Use that ID as the ${V}.`)};T||k.forEach(_=>$(_,"block_ids entry")),E||$(u.children[y],"reference_id"),T||k.forEach(R),E||R(u.children[y]);const L=u.children.filter(_=>(_.structuralSuggestionKind??_.diffState)!=="delete"),D=L.findIndex(_=>_.id===c[0]),H=L.findIndex(_=>_.id===d);if(H===D-1&&g==="after"||H===D+c.length&&g==="before")return{success:!0,resultCode:"already_satisfied",...T?{suggestionIds:[T]}:{},agentFeedback:`These blocks are already at the requested position; no additional change was made. Current block IDs: ${c.join(", ")}. Continue with the remaining blocks.`};k.some(_=>_.type==="section-break")&&f("move_blocks cannot move a section break, because that would change the page layout of the surrounding sections. Move the content blocks on either side of the break instead."),p=this.cloneYDoc(this.ydoc),this.agentMoveClientId??(this.agentMoveClientId=p.clientID),p.clientID=this.agentMoveClientId,h=new le(mt(p),()=>{},void 0,p,"agent-move-staging",!0,new an,{canRepairIdentity:()=>!1});const F=h;if(T){F.transact(()=>{const K=F.getYContentFragment(),q=k.map(Q=>Z(p,Q.id).clone());K.delete(m,k.length),K.insert(y-(m<y?k.length:0)+(g==="after"?1:0),q)});const _=F.getDocument().children,V=_.findIndex(K=>K.id===c[0]),nt=_.filter(K=>(K.structuralSuggestionId??K.suggestionId)===T&&(K.structuralSuggestionKind??K.diffState)==="delete");(_[V-1]?.id===nt.at(-1)?.id||_[V+k.length]?.id===nt[0]?.id)&&f("This would put the blocks back at their original source; reject the Move instead of creating a move that goes nowhere."),_.filter(K=>(K.structuralSuggestionKind??K.diffState)!=="delete").at(-1)?.type!=="paragraph"&&f("Correcting this Move would remove the final caret paragraph. Choose a destination that leaves a paragraph at the document end.");const J=I.encodeStateAsUpdate(p,I.encodeStateVector(this.ydoc));return this.runWithUndoGroup("agent-block-move",()=>this.transact(()=>I.applyUpdate(this.ydoc,J,this.origin))),{success:!0,suggestionIds:[T],agentFeedback:`Corrected the destination of the existing tracked Move; its original source and accept/reject behavior are preserved. Destination block IDs remain: ${c.join(", ")}. Independent neighboring moves stay where they were.`}}const X=G(),C=dg(k),j=new Set,U=_=>{_.id&&j.add(_.id),_.children?.forEach(U)};U(u),u.notes?.forEach(U);const z=_=>{if(_.id){for(;j.has(_.id);)_.id=G();j.add(_.id)}_.children?.forEach(z)};C.forEach(z),F.suggestionEngine.withSuggestionMetadata({source:"agent",authorType:"ai",label:"Move",agentName:t.agentName??Nt,commentThreadId:t.commentThreadId,agentModel:t.agentModel,agentConversationId:t.agentConversationId,agentRequestId:t.agentRequestId,agentTurn:t.agentTurn},()=>F.transact(()=>{const _=F.getYContentFragment(),V=(q,Q)=>q instanceof I.XmlText?q.length?(at(q,0,q.length,{...F.suggestionEngine.buildInlineSuggestionMetadataMarks(X,"Move"),...Q==="from"?{deletion:!0}:{insertion:!0}}),q.length):0:q instanceof I.XmlElement&&Ts(q.nodeName)?0:q instanceof I.XmlFragment||q instanceof I.XmlElement?q.toArray().reduce((ut,yt)=>ut+(yt instanceof I.AbstractType?V(yt,Q):0),0):0;let nt=0;for(const q of c){const Q=Z(p,q);nt+=V(Q,"from"),F.suggestionEngine.markDeletedBlockElement(Q,X,"Move")}const J=C.map(q=>F.blockToYjsElement(q));_.insert(y+(g==="after"?1:0),J);for(const q of J)V(q,"to"),F.suggestionEngine.markInsertedBlockElement(q,X,"Move");const K=_.toArray().filter(q=>!(q instanceof I.XmlElement&&(q.getAttribute("structuralSuggestionKind")==="delete"||q.getAttribute("diffState")==="delete"))).at(-1);if(K instanceof I.XmlElement&&K.nodeName!=="paragraph"){const q=F.blockToYjsElement({type:"paragraph",id:G(),children:[{type:"text",text:""}]});_.insert(_.length,[q]),F.suggestionEngine.markInsertedBlockElement(q,X,"Move")}nt?F.completeInternalTextMove([X],[X],X,{wholeBlocks:!0})||f("Unable to link both move halves; no change was made."):F.suggestionEngine.saveLiveSuggestion({id:X,type:"inline-text",label:"Move",anchorBlockId:C[0]?.id})})),n?.applyBlockMovesDirectly&&F.acceptLiveSuggestions([X]);const tt=I.encodeStateAsUpdate(p,I.encodeStateVector(this.ydoc));return this.runWithUndoGroup("agent-block-move",()=>this.transact(()=>I.applyUpdate(this.ydoc,tt,this.origin))),{success:!0,suggestionIds:n?.applyBlockMovesDirectly?[]:[X],agentFeedback:n?.applyBlockMovesDirectly?`Moved ${c.length} block(s). Destination block IDs: ${C.map(_=>_.id).join(", ")}.`:`Moved ${c.length} block(s) as one tracked Move. Destination block IDs: ${C.map(_=>_.id).join(", ")}. Source IDs remain only in the before/review view.${E?` Positioned next to pending Move ${E}; if that move is rejected, these blocks stay where its destination was.`:""}`}}catch(m){return{success:!1,error:m instanceof Error?m.message:String(m),failure:Be(m)}}finally{h?.dispose(),p?.destroy()}}const o=(t.actions??[]).filter(c=>c.name==="insert_footnote");if(o.length>0){const c=[];for(const u of o){const f=u.arguments??{},h=f.id??"",p=(this.getDocument().notes??[]).find(b=>b.id===h||W(b,h));if(p)return sn("footnote_in_note_unsupported",{subject:h},{blockId:h,noteId:p.id});let m;try{m=yc(this,h,f.find??"")}catch(b){return{success:!1,error:b instanceof Error?b.message:String(b),failure:Be(b)}}const y=this.suggestingMode;this.suggestingMode=!0;try{const{result:b}=this.suggestionEngine.withSuggestionMetadata({source:"agent",authorType:"ai",label:f.kind==="endnote"?"Insert endnote":"Insert footnote",agentName:t.agentName??Nt,agentModel:t.agentModel,commentThreadId:t.commentThreadId,agentConversationId:t.agentConversationId,agentRequestId:t.agentRequestId,agentTurn:t.agentTurn,historyOrigin:`live-suggestions:${e}`},()=>this.insertFootnote(m,f.text??"",{anchor:m,focus:m},f.kind==="endnote"?"endnote":"footnote"));if(!b)return{success:!1,error:"insert_footnote: failed to insert"};b.suggestionId&&c.push(b.suggestionId)}finally{this.suggestingMode=y}}const d={...t,actions:(t.actions??[]).filter(u=>u.name!=="insert_footnote")};if(d.actions.length===0)return{success:!0,suggestionIds:c};const g=this.applyAgentActions(d,e,n);return g.success&&(g.suggestionIds=[...g.suggestionIds??[],...c]),g}const r=this.collectPendingNoteReplacements(t.actions??[]);if(r){if("error"in r)return{success:!1,error:r.error};const c=new Map;for(const h of r.edits){const p=c.get(h.blockId)??this.noteBlockText(h.blockId),m=p&&h.find?p.split(h.find).length-1:0;if(p===null||m===0||!h.all&&m>1)return{success:!1,error:m>1?`replace: Found ${m} matches for "${h.find}" in note block '${h.blockId}'. Include more surrounding context so it matches exactly one location.`:`replace: No match found for "${h.find}" in note block '${h.blockId}'.`};c.set(h.blockId,h.all?p.split(h.find).join(h.replace):p.replace(h.find,()=>h.replace))}const d={...t,actions:(t.actions??[]).filter(h=>!r.actions.has(h))},g=d.actions.length>0?this.applyAgentActions(d,e,n):null;if(g&&!g.success)return g;const u=[],f=this.suggestingMode;this.suggestingMode=!0;try{for(const h of r.edits){const{result:p}=this.suggestionEngine.withSuggestionMetadata({source:"agent",authorType:"ai",label:"Replace",agentName:t.agentName??Nt,agentModel:t.agentModel,commentThreadId:t.commentThreadId,agentConversationId:t.agentConversationId,agentRequestId:t.agentRequestId,agentTurn:t.agentTurn,historyOrigin:`live-suggestions:${e}`},()=>this.replaceFootnoteBodyText(h.blockId,h.find,h.replace,h.all));if(!p.success)return{success:!1,error:`replace: ${p.error??`No match found for "${h.find}" in note block '${h.blockId}'.`}${g?" The call's other edits were already applied.":""}`};p.suggestionId&&u.push(p.suggestionId)}}finally{this.suggestingMode=f}return g?(g.suggestionIds=[...g.suggestionIds??[],...u],g):{success:!0,suggestionIds:u,agentFeedback:`Edited ${r.edits.length} replacement(s) in pending footnote text.`}}this.detachedSuggestionStore.getPendingSuggestions().size===0&&this.toolCallHistory.getAllToolCalls().length>0&&this.toolCallHistory.clear();let i;try{i=xu(t,e,this.preprocessorSession,this.getDocument())}catch(c){const d=c instanceof Vr?c:void 0,g=d?Rt(d.action):void 0;return{success:!1,failure:Be(d?.originalError??c),error:c instanceof Error?c.message:String(c),...d?{failedActions:[{actionIndex:d.actionIndex,actionName:d.action.name,error:d.message,failure:Be(d.originalError),sourceEditIndex:g?.sourceEditIndex,sourceEditType:g?.sourceEditType}]}:{}}}if(n?.maxPreprocessedActions!==void 0&&(i.actions?.length??0)>n.maxPreprocessedActions)return{success:!1,error:`This edit expands to ${i.actions.length} tracked changes, above the per-call limit of ${n.maxPreprocessedActions}. Split it into smaller edits, or use replace_document_content/import_document when replacing most of a document.`};const a=gl(t.actions,i.actions);let l;if(i.actions){for(const f of i.actions)if(f.name==="set_title")this.setTitle(f.arguments.title),f.arguments.title;else if(f.name==="set_notes"){const h=f.arguments?.notes,p=typeof h=="string"?h:h==null?"":String(h);this.setNotes(p)}else if(f.name==="set_page_layout"){const h=this.applySetPageLayoutAction(f.arguments??{});if(h.error)return{success:!1,error:`set_page_layout: ${h.error}`}}else if(f.name==="set_header_footer"){const h=this.applySetHeaderFooterAction(f.arguments??{});if(h.error)return{success:!1,error:h.error};l=h.feedback??l}const c={...i,actions:i.actions.filter(f=>f.name!=="set_title"&&f.name!=="set_notes"&&f.name!=="set_page_layout"&&f.name!=="set_header_footer")},d=c.actions.length>=100,g=Date.now(),u=f=>{d&&(`${c.actions.length}${f}`,Date.now()-g)};if(u("preprocessed"),c.actions.length>0){const f=this.suggestionEngine.getLiveSuggestionIds().length>0;let h,p,m,y;if(f){const M=this.suggestionEngine.createLiveSuggestionProjection("accept"),O=this.suggestionEngine.createLiveSuggestionProjection("reject");h=M.doc,p=O.doc,m=this.cloneYDoc(M.ydoc),y=this.cloneYDoc(O.ydoc)}else h=this.getDocument(),p=h,m=this.cloneYDoc(this.ydoc),y=this.cloneYDoc(this.ydoc);const b=h,k=this.tryCancelInsertedBlockForRemoveAction(c.actions,b);if(k)return k;const{anchorsByAction:S,failures:v,alreadySatisfied:x}=ig(m,c.actions,e,b,{rejectUnchangedAction:!0,continueAfterError:!0,canonicalDocument:()=>mt(m),skipContextForFirstAction:!0});u("validated");const w=c.actions.length===1?Rt(c.actions[0])?.styleEffects:void 0;if(v.length>0){const M=O=>`${O.actionName}: ${O.error}`;if(v.length===1){const O=c.actions[0],$=c.actions.length===1&&(O?.name==="replace"||O?.name==="replace_all")&&Array.isArray(O.arguments?.replacements)?O.arguments.replacements.length:0,L=$>1?` None of this call's ${$} replacements were applied; resend the ones that still apply without the failing one.`:"";return{success:!1,error:`Failed operation: ${M(v[0])}${L}`,failedActions:v,failure:v[0]?.failure}}else return{success:!1,error:`Failed operations: ${v.map(M).join("; ")}`,failedActions:v,failure:v[0]?.failure}}if(x)return m.destroy(),y.destroy(),{success:!0,resultCode:"already_satisfied",styleEffects:w,suggestionIds:[],planningSuggestionIds:[],agentFeedback:(c.actions.length===1?dr(c.actions[0]):void 0)??"Verified that the requested state is already satisfied; no document change was needed."};const A=(c.actions.length===1?dr(c.actions[0]):void 0)??gl(t.actions,i.actions,S)??a,P=mt(m);u("materialized validation document");const T=new Set,E=M=>{if(!M)return;T.add(M);const O=W(b,M)??W(P,M);O?.id&&T.add(O.id)};for(const M of S)for(const O of M)typeof O?.paragraphId=="string"&&O.paragraphId.length>0&&E(O.paragraphId);for(const M of c.actions){const O=M?.name,$=M?.arguments;(O==="replace"||O==="replace_all"||O==="replace_many"||O==="replace_block"||O==="remove_block"||O==="set_block_attribute"||O==="clear_block_formatting")&&typeof $?.id=="string"&&$.id.length>0&&E($.id),typeof $?.referenceId=="string"&&$.referenceId.length>0&&E($.referenceId),typeof $?.tableId=="string"&&$.tableId.length>0&&E($.tableId)}const B=Wh(b,c.actions);for(const M of B)T.add(M.currentBlockId),T.add(M.finalBlockId);if(this.suggestionEngine.expandPendingSequenceBlockIds(T),f){const M=new Map;for(const L of this.getDocument().children){const D=L;D.id&&(D.structuralSuggestionKind==="split"||D.structuralSuggestionKind==="merge")&&M.set(D.id,D.structuralSuggestionId??"")}const O=new Set(T);for(const L of S.flat())typeof L?.paragraphId=="string"&&O.add(L.paragraphId);const $=[...new Set([...O].filter(L=>M.has(L)).map(L=>M.get(L)))];if($.length>0)return m.destroy(),y.destroy(),{success:!1,error:`This edit touches a paragraph next to a pending tracked paragraph split or merge (${$.join(", ")}). Accept or reject that change first, then make the edit.`,failure:{code:"pending_paragraph_boundary",phase:"validation",retryable:!1,mutationOutcome:"unchanged",details:{suggestionIds:$}}}}this.toolCallHistory.addToolCalls(c,e);const N=T.size>0||B.length>0?{...T.size>0?{affectedBlockIds:Array.from(T)}:{},...B.length>0?{replacementBlockMatches:B}:{}}:void 0,R=this.suggestionEngine.applyValidatedAgentActionsAsSuggestions({validationFork:m,baseFork:y,flattenOptions:N,toolCallId:e,originalActions:t.actions,processedActions:i.actions,validationAnchorsByAction:S,docBeforeToolCall:b,docAfterToolCall:P,baseDocForSuggestions:p,agentFeedback:A,agentName:t.agentName,agentModel:t.agentModel,commentThreadId:t.commentThreadId,agentConversationId:t.agentConversationId,agentRequestId:t.agentRequestId,agentTurn:t.agentTurn,optimizeStyleFormatting:n?.optimizeStyleFormatting,directMode:n?.directMode});return u("applied live suggestions"),this.materializePendingFootnoteBodies(),{...R,styleEffects:w}}}return{success:!0,planningSuggestionIds:[],agentFeedback:l??a}}getAllOperations(){return[]}onRemoteDocumentChange(t){}insertBlock(t,e,n,o){this.beforeOperationSelection=n;const r=this.suggestingMode?gt():null,i=t.id||G(),a=this.getDocument();if(e<0||e>a.children.length)return!1;const l=te().getHandlerForBlock(t);this.beforeOperationRelativeSelection=l.allowsInternalCursor()?Y(n,this.ydoc,a):null,this.transact(()=>{const d=this.getYContentFragment(),g={...t,id:i};let u;if(g.type==="list"){const f=g,h=new I.XmlElement("list");h.setAttribute("variant",f.variant),f.id&&h.setAttribute("id",f.id),f.startNumber!==void 0&&h.setAttribute("startNumber",String(f.startNumber)),f.numberingChainId&&h.setAttribute("numberingChainId",f.numberingChainId),f.numberingFormat&&h.setAttribute("numberingFormat",f.numberingFormat);const p=[];f.children.forEach(m=>{const y=new I.XmlElement("list-item");Ce(y,m),m.id&&y.setAttribute("id",m.id),m.checked!==void 0&&y.setAttribute("checked",String(m.checked)),m.indentLevel!==void 0&&y.setAttribute("indentLevel",String(m.indentLevel)),m.direction!==void 0&&y.setAttribute("direction",m.direction);const b=new I.XmlText;let k=0;m.children.forEach(S=>{if(S.type==="text"){const v=S.marks?{...S.marks}:void 0;lt(b,k,S.text,v),k+=S.text.length}}),y.insert(0,[b]),p.push(y)}),h.insert(0,p),u=h}else u=l.toYjs(g,this.ydoc);r&&u instanceof I.XmlElement&&(u.setAttribute("id",i),this.suggestionEngine.markInsertedBlockElement(u,r)),d.insert(e,[u])}),this.setSelectionAfterOperation(o),this.afterOperationRelativeSelection=l.allowsInternalCursor()?Y(o,this.ydoc,this.getDocument()):null;const c=this.ensureTrailingParagraph();return r&&this.suggestionEngine.saveLiveSuggestion({id:r,type:"block-insert",blockId:i,label:"Insert",cleanupTrailingParagraphId:c??void 0}),!0}ensureTrailingParagraph(){const t=this.getYContentFragment();if(t.length===0)return null;const e=t.get(t.length-1);if(e instanceof I.XmlElement&&e.nodeName==="paragraph")return null;const n=new I.XmlElement("paragraph"),o=G();n.setAttribute("id",o);const r=new I.XmlText;return n.insert(0,[r]),this.transact(()=>{t.insert(t.length,[n])}),o}getComments(){return Cg(this.kernel)}addComment(t,e,n,o,r){return Bg(this.kernel,t,e,n,o,r)}addCommentToRanges(t,e,n){return Nr(this.kernel,t,e,n)}addBlockComment(t,e,n){return ha(this.kernel,t,e,n)}addCommentForSuggestion(t,e,n){return this.addCommentForSuggestions([t],e,n)}getSuggestionCommentRanges(t){return Pg(this.kernel,t)}addCommentForSuggestions(t,e,n){const o=Array.from(new Set(t)).filter(a=>typeof a=="string"&&a.length>0);if(o.length===0)return null;const r=this.getSuggestionCommentRanges(o).map(({blockId:a,start:l,end:c})=>({blockId:a,start:l,end:c})),i={...n,suggestionId:o[0],...o.length>1?{relatedSuggestionIds:o}:{}};if(r.length>0)return Nr(this.kernel,r,e,i);for(const a of o){const l=this.getLiveSuggestion(a),c=l&&"blockId"in l?l.blockId:l&&"firstBlockId"in l?l.firstBlockId:void 0;if(c)return ha(this.kernel,c,e,i)}return null}replyToComment(t,e,n){return Eg(this.kernel,t,e,n)}relinkCommentSuggestionIds(){return Fg(this.kernel,t=>this.suggestionEngine.canResolveLiveSuggestion(t))}resolveCommentsForSettledSuggestions(t){return Lg(this.kernel,t,e=>this.suggestionEngine.canResolveLiveSuggestion(e))}setCommentResolved(t,e){return Ng(this.kernel,t,e)}deleteComment(t){return Og(this.kernel,t)}isBlockInsideFootnote(t,e){return Rg(t,e)}getFootnotes(){return Dg(this.kernel)}renumberFootnotes(){return Se(this.kernel)}materializePendingFootnoteBodies(){return pa(this.kernel)}addPastedFootnoteBodies(t){const e=this.getYNotesFragment();e.insert(e.length,t.map(n=>this.kernel.blockToYjsElement(n))),this.reconcileFootnotes()}reconcileFootnotes(){$g(this.kernel)}insertFootnote(t,e,n,o="footnote"){return _g(this.kernel,t,e,n,o)}setFootnoteBodyText(t,e){return Xg(this.kernel,t,e)}collectPendingNoteReplacements(t){const e=(this.getDocument().notes??[]).filter(i=>i.structuralSuggestionKind==="insert");if(e.length===0)return null;const n=i=>{for(const a of e){const l=[],c=g=>{g&&typeof g=="object"&&typeof g.id=="string"&&l.push(g),Array.isArray(g?.children)&&g.children.forEach(c)};a.children.forEach(c);const d=l.filter(g=>g.type==="paragraph");if(a.id===i)return d.length===1?d[0].id:null;if(d.some(g=>g.id===i))return i}return null},o=[],r=new Set;for(const i of t){if(i.name!=="replace"&&i.name!=="replace_all")continue;const a=i.arguments??{},l=typeof a.id=="string"?n(a.id):null;if(!l)continue;const c=Array.isArray(a.replacements)?a.replacements:[a];for(const d of c){const g=typeof d.find=="string"?d.find:"",u=typeof d.replace=="string"?d.replace:"";if(!g||/[<>]/.test(g)||/[<>]/.test(u))return{error:"replace: text inside a footnote that is still a pending suggestion can only be edited with plain-text find/replace (no HTML). Use plain text, or accept the footnote first."};o.push({blockId:l,find:g,replace:u,all:i.name==="replace_all"||d.occurrence==="all"||a.occurrence==="all"})}r.add(i)}return o.length>0?{edits:o,actions:r}:null}noteBlockText(t){let e=null;const n=i=>{for(const a of i.toArray()){if(e)return;if(a instanceof I.XmlElement){if(a.getAttribute("id")===t){e=a;return}n(a)}}};if(n(this.getYNotesFragment()),!e)return null;let o="";const r=i=>{if(i instanceof I.XmlText){for(const a of i.toDelta())typeof a.insert=="string"&&!a.attributes?.deletion&&(o+=a.insert);return}for(const a of i.toArray())(a instanceof I.XmlElement||a instanceof I.XmlText)&&r(a)};return r(e),o}replaceFootnoteBodyText(t,e,n,o=!1){return Ug(this.kernel,t,e,n,o)}convertAllNoteKinds(t){return zg(this.kernel,t)}removeFootnote(t){return Wg(this.kernel,t)}blockToYjsElement(t){const e={...t,id:t.id||G()};return e.type==="list"?It(e):te().getHandlerForBlock(e).toYjs(e,this.ydoc)}insertBlockAfterId(t,e,n,o){const r=ot(this.ydoc,e);if(!r)return!1;const{yParent:i,index:a}=r;this.beforeOperationSelection=n;const l=this.suggestingMode?gt():null,c=t.id||G();this.transact(()=>{const g=this.blockToYjsElement(t);l&&g instanceof I.XmlElement&&(g.setAttribute("id",c),this.suggestionEngine.markInsertedBlockElement(g,l)),i.insert(a+1,[g])}),this.setSelectionAfterOperation(o),this.updateAfterOperationRelativeSelection(this.getDocument());const d=this.ensureTrailingParagraph();return l&&this.suggestionEngine.saveLiveSuggestion({id:l,type:"block-insert",blockId:c,label:"Insert",cleanupTrailingParagraphId:d??void 0}),!0}insertBlockBeforeId(t,e,n,o){const r=ot(this.ydoc,e);if(!r)return!1;const{yParent:i,index:a}=r;this.beforeOperationSelection=n;const l=this.suggestingMode?gt():null,c=t.id||G();this.transact(()=>{const g=this.blockToYjsElement(t);l&&g instanceof I.XmlElement&&(g.setAttribute("id",c),this.suggestionEngine.markInsertedBlockElement(g,l)),i.insert(a,[g])}),this.setSelectionAfterOperation(o),this.updateAfterOperationRelativeSelection(this.getDocument());const d=this.ensureTrailingParagraph();return l&&this.suggestionEngine.saveLiveSuggestion({id:l,type:"block-insert",blockId:c,label:"Insert",cleanupTrailingParagraphId:d??void 0}),!0}insertBlockIntoParent(t,e,n,o){const r=ot(this.ydoc,e);if(!r)return!1;const{yBlock:i}=r;if(!(i instanceof I.XmlElement))return!1;const a=i.nodeName;if(!(a==="container"||a==="table-cell"))return!1;this.beforeOperationSelection=n;const l=this.suggestingMode?gt():null,c=t.id||G();return this.transact(()=>{const d=this.blockToYjsElement(t);l&&d instanceof I.XmlElement&&(d.setAttribute("id",c),this.suggestionEngine.markInsertedBlockElement(d,l)),i.insert(0,[d])}),this.setSelectionAfterOperation(o),this.updateAfterOperationRelativeSelection(this.getDocument()),l&&this.suggestionEngine.saveLiveSuggestion({id:l,type:"block-insert",blockId:c,label:"Insert"}),!0}insertBlockAtStart(t,e,n){return this.insertBlock(t,0,e,n)}insertBlockAtEnd(t,e,n){const o=this.getDocument();return this.insertBlock(t,o.children.length,e,n)}updateBlock(t,e,n,o){this.beforeOperationSelection=n;const r=this.getDocument();if(t<0||t>=r.children.length)return!1;const i=r.children[t];if(i.type!==e.type)return console.warn(`[DocumentMutator] updateBlock type mismatch: ${i.type} -> ${e.type}`),!1;const a=te().getHandlerForBlock(e);return this.beforeOperationRelativeSelection=a.allowsInternalCursor()?Y(n,this.ydoc,r):null,Te(this.ydoc)&&Yl(this.ydoc),this.transact(()=>{const l=this.getYContentFragment();if(t<0||t>=l.length)return;const c={...e,id:e.id||i.id||G()},d=l.get(t);if(e.type==="list"&&d instanceof I.XmlElement&&d.nodeName==="list")Kr(d,c);else{const g=c.type==="list"?It(c):a.toYjs(c,this.ydoc);l.delete(t,1),l.insert(t,[g])}}),this.setSelectionAfterOperation(o),this.afterOperationRelativeSelection=a.allowsInternalCursor()?Y(o,this.ydoc,this.getDocument()):null,!0}updateBlockById(t,e,n,o){this.beforeOperationSelection=n;const r=this.getDocument(),i=W(r,t);if(!i)return!1;if(i.type!==e.type)return console.warn(`[DocumentMutator] updateBlockById type mismatch: ${i.type} -> ${e.type}`),!1;const a=ot(this.ydoc,t);if(!a)return!1;const{yParent:l,index:c}=a,d=te().getHandlerForBlock(e),g=this.suggestingMode?gt():null;let u=e,f=null;if(this.suggestingMode&&g&&i.type==="table"&&e.type==="table"){const h=this.suggestionEngine.buildSuggestedTableChange(i,e,g);if(h)u=h.liveBlock,f=h.record;else if(!this.suggestionEngine.hasSameTableGeometry(i,e))return!1}return this.beforeOperationRelativeSelection=d.allowsInternalCursor()?Y(n,this.ydoc,r):null,this.transact(()=>{const h={...u,id:u.id||i.id||G()},p=l.get(c);if(u.type==="list"&&p instanceof I.XmlElement&&p.nodeName==="list")Kr(p,h);else{const m=h.type==="list"?It(h):d.toYjs(h,this.ydoc);l.delete(c,1),l.insert(c,[m])}f&&this.suggestionEngine.saveLiveSuggestion(f)}),this.setSelectionAfterOperation(o),this.afterOperationRelativeSelection=d.allowsInternalCursor()?Y(o,this.ydoc,this.getDocument()):null,!0}replaceParagraphById(t,e,n,o){this.beforeOperationSelection=n;const r=this.getDocument();if(!W(r,t))return!1;const i=ot(this.ydoc,t);if(!i)return!1;const{yBlock:a,yParent:l,index:c}=i;return this.beforeOperationRelativeSelection=Y(n,this.ydoc,r),this.transact(()=>{const d=a instanceof I.XmlElement?a.getAttribute("id"):void 0,g=new I.XmlElement("paragraph");g.setAttribute("id",e.id||d||G()),e.heading&&g.setAttribute("heading",String(e.heading)),e.align&&g.setAttribute("align",e.align),e.lineSpacing!==void 0&&g.setAttribute("lineSpacing",String(e.lineSpacing)),bn(g,e);{const m=qt(e);m!==void 0&&g.setAttribute("pagination",m)}e.styleId!==void 0&&g.setAttribute("styleId",e.styleId),e.direction!==void 0&&g.setAttribute("direction",e.direction),e.tabStops!==void 0&&g.setAttribute("tabStops",e.tabStops),e.borders!==void 0&&g.setAttribute("borders",e.borders),e.shading!==void 0&&g.setAttribute("shading",e.shading),e.oxmlAttrs!==void 0&&g.setAttribute("oxmlAttrs",e.oxmlAttrs),e.oxmlPPr!==void 0&&g.setAttribute("oxmlPPr",e.oxmlPPr);const u=Ht(e.leftIndent);u!==void 0&&g.setAttribute("leftIndent",String(u));const f=Jt(e.firstLineIndent);f!==void 0&&g.setAttribute("firstLineIndent",String(f));const h=new I.XmlText;let p=0;e.children.forEach(m=>{if(m.type==="text"){const y={...m.marks||{}};lt(h,p,m.text,y),p+=m.text.length}}),g.insert(0,[h]),l.delete(c,1),l.insert(c,[g])}),this.setSelectionAfterOperation(o),this.afterOperationRelativeSelection=Y(o,this.ydoc,this.getDocument()),!0}toggleTodoItem(t,e,n,o,r){const i=this.getDocument(),a=i.children[t];if(!a||a.type!=="list"||a.variant!=="todo"||e<0||e>=a.children.length)return!1;this.beforeOperationSelection=o;const l=te().getHandlerForBlock(a);return this.beforeOperationRelativeSelection=l?.allowsInternalCursor()?Y(o,this.ydoc,i):null,this.transact(()=>{const c=this.getYContentFragment().get(t);if(!(c instanceof I.XmlElement))return;let d=0;for(let g=0;g<c.length;g++){const u=c.get(g);if(u instanceof I.XmlElement&&u.nodeName==="list-item"){if(d===e){n?u.setAttribute("checked","true"):u.removeAttribute("checked");return}d++}}}),this.setSelectionAfterOperation(r),this.afterOperationRelativeSelection=l?.allowsInternalCursor()?Y(r,this.ydoc,this.getDocument()):null,!0}toggleTodoItemById(t,e,n,o,r){const i=this.getDocument(),a=W(i,t);if(!a||a.type!=="list"||a.variant!=="todo"||e<0||e>=a.children.length)return!1;const l=ot(this.ydoc,t);if(!l)return!1;const{yBlock:c}=l;this.beforeOperationSelection=o;const d=te().getHandlerForBlock(a);return this.beforeOperationRelativeSelection=d?.allowsInternalCursor()?Y(o,this.ydoc,i):null,this.transact(()=>{if(!(c instanceof I.XmlElement))return;let g=0;for(let u=0;u<c.length;u++){const f=c.get(u);if(f instanceof I.XmlElement&&f.nodeName==="list-item"){if(g===e){n?f.setAttribute("checked","true"):f.removeAttribute("checked");return}g++}}}),this.setSelectionAfterOperation(r),this.afterOperationRelativeSelection=d?.allowsInternalCursor()?Y(r,this.ydoc,this.getDocument()):null,!0}};ul.DEFERRED_IDENTITY_REPAIR_MS=1500;let Co=ul;function gs(s,t,e){const n=o=>o&&o.block===t?{...o,offset:Co.remapOffsetAcrossReplacementNormalization(o.offset,e)}:o;return{anchor:n(s.anchor),focus:n(s.focus)}}const Jh=Object.freeze(Object.defineProperty({__proto__:null,DEFAULT_FONT_FAMILY:jt,DocumentMutator:Co,LARGE_REMOVAL_PENDING_NOTE:dl,MAX_BULK_LIVE_SUGGESTION_RESOLUTION_PASSES:tl,copyMarksForUserInsertion:el,enrichReplaceBlockFeedbackWithChangeSummary:cl,extractTextForChangeSummary:Ot,parseLayeredInsertion:mn,parseSuggestionPriorAttributes:xo,remapSelectionAcrossReplacementNormalization:gs,sanitizeSuggestionPriorAttributes:Ue},Symbol.toStringTag,{value:"Module"}));export{Co as D,an as P,xi as a,On as b,hi as c,Zo as d,kt as e,ba as f,qc as g,Kc as h,ir as i,Oc as j,ai as k,or as l,Ee as m,mc as n,Gs as o,bc as p,Qo as q,on as r,Ge as s,qn as t,Uo as u,Ys as v,ii as w,ra as x,Jh as y};
|