texlite 0.8.4 → 0.9.0

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.
Files changed (65) hide show
  1. package/DESIGN.md +75 -8
  2. package/OPERATIONS.md +19 -2
  3. package/dist/client/assets/{AdminUsers-CqOmV9rq.js → AdminUsers-3CHb5012.js} +1 -1
  4. package/dist/client/assets/{CitationLibraryDialog-BmWFXTW2.js → CitationLibraryDialog-zPpsUhWJ.js} +1 -1
  5. package/dist/client/assets/Dashboard-CWfSLzD3.js +2 -0
  6. package/dist/client/assets/{GitDialog-BCfSHuMB.js → GitDialog-BUU2U_LV.js} +2 -2
  7. package/dist/client/assets/HistoryDialog-B6aopsrw.js +7 -0
  8. package/dist/client/assets/{LatexEditor-DSopAHbC.js → LatexEditor-CM445Tk0.js} +1 -1
  9. package/dist/client/assets/{PdfPreview-BDkU20jP.js → PdfPreview-BFVNczSk.js} +1 -1
  10. package/dist/client/assets/{ProjectIconPickerDialog-GAd8HGOx.js → ProjectIconPickerDialog-Cf0zBf8u.js} +1 -1
  11. package/dist/client/assets/{ProjectNavigationDialogs-BTLcRY7i.js → ProjectNavigationDialogs-TPbe11iR.js} +1 -1
  12. package/dist/client/assets/{ProjectSettings-BJWTkoZq.js → ProjectSettings-CDQvIlQ4.js} +1 -1
  13. package/dist/client/assets/ProjectWorkspace-C6GrvKN6.js +27 -0
  14. package/dist/client/assets/SelectionHistoryDialog-CyE0_YDs.js +3 -0
  15. package/dist/client/assets/{SystemMetricsDialog-C9P4TSQl.js → SystemMetricsDialog-CuqHPUnn.js} +1 -1
  16. package/dist/client/assets/{TagManagementDialog-LYbib36_.js → TagManagementDialog-gRLM3lLx.js} +1 -1
  17. package/dist/client/assets/{WordCountDialog-BFg0GeJy.js → WordCountDialog-B4PI0vEk.js} +1 -1
  18. package/dist/client/assets/check-BXvzrdoz.js +1 -0
  19. package/dist/client/assets/chevron-left-BB5MYb7g.js +1 -0
  20. package/dist/client/assets/hard-drive-6uYFyezl.js +1 -0
  21. package/dist/client/assets/index-BRT5O-Hg.js +5 -0
  22. package/dist/client/assets/index-C0t11tlT.js +14 -0
  23. package/dist/client/assets/index-DXWp2bzM.css +1 -0
  24. package/dist/client/assets/{key-round-BaIj7Jch.js → key-round-DOAxDSfz.js} +1 -1
  25. package/dist/client/assets/minimize-2-BWtbag2I.js +1 -0
  26. package/dist/client/assets/{minus-Beso_n-6.js → minus-9eVJnugf.js} +1 -1
  27. package/dist/client/assets/{plus-BfEC7mzf.js → plus-BGXipRoG.js} +1 -1
  28. package/dist/client/assets/{refresh-cw-FZs9MtoA.js → refresh-cw-Dvp3O90f.js} +1 -1
  29. package/dist/client/assets/{search-DL2UGvdj.js → search-b1ORp1k8.js} +1 -1
  30. package/dist/client/assets/{sigma-CSRwPPkk.js → sigma-Bk0_MzWi.js} +1 -1
  31. package/dist/client/assets/{spellCheck-L9gD2d1M.js → spellCheck-BJjWgnef.js} +1 -1
  32. package/dist/client/assets/{tags-CjkWzXqX.js → tags-JAkbmWns.js} +1 -1
  33. package/dist/client/assets/{type-D1mmDdLM.js → type-CE2DYkPH.js} +1 -1
  34. package/dist/client/assets/{user-plus-YJ3ftuL5.js → user-plus-CKalKSsw.js} +1 -1
  35. package/dist/client/assets/x-Bq29njHL.js +1 -0
  36. package/dist/client/index.html +2 -2
  37. package/dist/server/app.js +45 -4
  38. package/dist/server/cli.js +4 -0
  39. package/dist/server/collaboration.js +219 -7
  40. package/dist/server/commentMentions.js +139 -0
  41. package/dist/server/config.js +9 -2
  42. package/dist/server/db.js +59 -0
  43. package/dist/server/editHistory.js +411 -0
  44. package/dist/server/editHistoryRetry.js +90 -0
  45. package/dist/server/history.js +136 -20
  46. package/dist/server/historyRetention.js +37 -0
  47. package/dist/server/i18n.js +4 -0
  48. package/dist/server/index.js +6 -0
  49. package/dist/server/logRotation.js +82 -0
  50. package/dist/server/pm2.js +7 -0
  51. package/dist/server/routes/comments.js +107 -16
  52. package/dist/server/routes/projectHistory.js +93 -7
  53. package/dist/server/routes/projectShared.js +2 -1
  54. package/dist/server/routes/projects.js +3 -1
  55. package/package.json +1 -1
  56. package/texlite.config.example.json +4 -1
  57. package/dist/client/assets/Dashboard-BfN2bCgZ.js +0 -2
  58. package/dist/client/assets/HistoryDialog-BtQhyTr9.js +0 -5
  59. package/dist/client/assets/ProjectWorkspace-WLYA7BSv.js +0 -27
  60. package/dist/client/assets/check-bnimQPun.js +0 -1
  61. package/dist/client/assets/chevron-left-DNM7mhNi.js +0 -1
  62. package/dist/client/assets/hard-drive-CF3WDfkG.js +0 -1
  63. package/dist/client/assets/index-CzVDvC5h.js +0 -14
  64. package/dist/client/assets/index-RjUuWk8F.css +0 -1
  65. package/dist/client/assets/x-BDSEosRE.js +0 -1
@@ -1,27 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/spellCheck-L9gD2d1M.js","assets/index-CzVDvC5h.js","assets/react-BVUjbTTn.js","assets/index-RjUuWk8F.css","assets/LatexEditor-DSopAHbC.js","assets/editor-CiK7TK0p.js","assets/check-bnimQPun.js","assets/x-BDSEosRE.js","assets/search-DL2UGvdj.js","assets/user-plus-YJ3ftuL5.js","assets/refresh-cw-FZs9MtoA.js","assets/CitationLibraryDialog-BmWFXTW2.js","assets/citationLibrary-ZeQPCv5O.js","assets/plus-BfEC7mzf.js","assets/chevron-left-DNM7mhNi.js","assets/tags-CjkWzXqX.js","assets/GitDialog-BCfSHuMB.js","assets/key-round-BaIj7Jch.js","assets/minus-Beso_n-6.js","assets/HistoryDialog-BtQhyTr9.js","assets/hard-drive-CF3WDfkG.js","assets/ProjectNavigationDialogs-BTLcRY7i.js","assets/ProjectSettings-BJWTkoZq.js","assets/type-D1mmDdLM.js","assets/sigma-CSRwPPkk.js","assets/WordCountDialog-BFg0GeJy.js"])))=>i.map(i=>d[i]);
2
- import{c as Re,f as ie,g as ce,A as pi,n as xd,l as Sd,r as kd,_ as vt,S as Cd,b as nt,i as as,h as na,C as ds,M as Ht,d as sa,j as jd}from"./index-CzVDvC5h.js";import{r as f,u as We,j as o,P as ur,d as Fi,e as vd}from"./react-BVUjbTTn.js";import{C as Ed}from"./check-bnimQPun.js";import{A as Dd,U as mi,B as _d,G as Td,M as Ld,X as Rn,F as Rd,e as rl,f as Ad,a as Nd,C as Od,b as Fd,T as Yt,c as ra,d as zn,L as Md,h as $t,S as gi,D as Ks,P as il,g as ol}from"./x-BDSEosRE.js";import{S as $d}from"./search-DL2UGvdj.js";import{U as Id}from"./user-plus-YJ3ftuL5.js";import{R as Pd}from"./refresh-cw-FZs9MtoA.js";const Ud=Re("AlignLeft",[["path",{d:"M15 12H3",key:"6jk70r"}],["path",{d:"M17 18H3",key:"1amg6g"}],["path",{d:"M21 6H3",key:"1jwq7v"}]]);const ia=Re("ChevronDown",[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]]);const zd=Re("CircleCheck",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]);const Mi=Re("CircleX",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]]);const ll=Re("Columns2",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M12 3v18",key:"108xh3"}]]);const wi=Re("Eraser",[["path",{d:"m7 21-4.3-4.3c-1-1-1-2.5 0-3.4l9.6-9.6c1-1 2.5-1 3.4 0l5.6 5.6c1 1 1 2.5 0 3.4L13 21",key:"182aya"}],["path",{d:"M22 21H7",key:"t4ddhn"}],["path",{d:"m5 11 9 9",key:"1mo9qw"}]]);const Bd=Re("FilePlus2",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"1pf5j1"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M3 15h6",key:"4e2qda"}],["path",{d:"M6 12v6",key:"1u72j0"}]]);const oa=Re("GripVertical",[["circle",{cx:"9",cy:"12",r:"1",key:"1vctgf"}],["circle",{cx:"9",cy:"5",r:"1",key:"hp0tcf"}],["circle",{cx:"9",cy:"19",r:"1",key:"fkjjf6"}],["circle",{cx:"15",cy:"12",r:"1",key:"1tmaij"}],["circle",{cx:"15",cy:"5",r:"1",key:"19l28e"}],["circle",{cx:"15",cy:"19",r:"1",key:"f4zoj3"}]]);const al=Re("Hash",[["line",{x1:"4",x2:"20",y1:"9",y2:"9",key:"4lhtct"}],["line",{x1:"4",x2:"20",y1:"15",y2:"15",key:"vyu0kd"}],["line",{x1:"10",x2:"8",y1:"3",y2:"21",key:"1ggp8o"}],["line",{x1:"16",x2:"14",y1:"3",y2:"21",key:"weycgp"}]]);const qd=Re("Keyboard",[["path",{d:"M10 8h.01",key:"1r9ogq"}],["path",{d:"M12 12h.01",key:"1mp3jc"}],["path",{d:"M14 8h.01",key:"1primd"}],["path",{d:"M16 12h.01",key:"1l6xoz"}],["path",{d:"M18 8h.01",key:"emo2bl"}],["path",{d:"M6 8h.01",key:"x9i8wu"}],["path",{d:"M7 16h10",key:"wp8him"}],["path",{d:"M8 12h.01",key:"czm47f"}],["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}]]);const cl=Re("Move",[["path",{d:"M12 2v20",key:"t6zp3m"}],["path",{d:"m15 19-3 3-3-3",key:"11eu04"}],["path",{d:"m19 9 3 3-3 3",key:"1mg7y2"}],["path",{d:"M2 12h20",key:"9i4pu4"}],["path",{d:"m5 9-3 3 3 3",key:"j64kie"}],["path",{d:"m9 5 3-3 3 3",key:"l8vdw6"}]]);const la=Re("PackageOpen",[["path",{d:"M12 22v-9",key:"x3hkom"}],["path",{d:"M15.17 2.21a1.67 1.67 0 0 1 1.63 0L21 4.57a1.93 1.93 0 0 1 0 3.36L8.82 14.79a1.655 1.655 0 0 1-1.64 0L3 12.43a1.93 1.93 0 0 1 0-3.36z",key:"2ntwy6"}],["path",{d:"M20 13v3.87a2.06 2.06 0 0 1-1.11 1.83l-6 3.08a1.93 1.93 0 0 1-1.78 0l-6-3.08A2.06 2.06 0 0 1 4 16.87V13",key:"1pmm1c"}],["path",{d:"M21 12.43a1.93 1.93 0 0 0 0-3.36L8.83 2.2a1.64 1.64 0 0 0-1.63 0L3 4.57a1.93 1.93 0 0 0 0 3.36l12.18 6.86a1.636 1.636 0 0 0 1.63 0z",key:"12ttoo"}]]);const aa=Re("PanelLeftClose",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"m16 15-3-3 3-3",key:"14y99z"}]]);const Wd=Re("PanelLeftOpen",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"m14 9 3 3-3 3",key:"8010ee"}]]);const Vd=Re("PanelLeft",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]]);const Hd=Re("PanelRight",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]]);const Kd=Re("Play",[["polygon",{points:"6 3 20 12 6 21 6 3",key:"1oa8hb"}]]);const Jd=Re("Reply",[["polyline",{points:"9 17 4 12 9 7",key:"hvgpf2"}],["path",{d:"M20 18v-2a4 4 0 0 0-4-4H4",key:"5vmcpk"}]]);const Gd=Re("RotateCcw",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]]);const ul=Re("Save",[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]]);const Yd=Re("Send",[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]]);const Xd=Re("Settings",[["path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z",key:"1qme2f"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]),yi=[{id:"jetbrains",labelKey:"projectSettings.fontJetBrains",stack:'"JetBrains Mono", ui-monospace, monospace'},{id:"source-code",labelKey:"projectSettings.fontSourceCode",stack:'"Source Code Pro", ui-monospace, monospace'},{id:"ibm-plex",labelKey:"projectSettings.fontIbmPlex",stack:'"IBM Plex Mono", ui-monospace, monospace'},{id:"fira-code",labelKey:"projectSettings.fontFiraCode",stack:'"Fira Code", ui-monospace, monospace'},{id:"iosevka",labelKey:"projectSettings.fontIosevka",stack:'"Iosevka", ui-monospace, monospace'}],gt={font:"jetbrains",fontSize:14,lineHeight:1.65,lineWrapping:!0,spellCheck:!0,mathPreviewOnHover:!1,vimMode:!1,formatOnCompile:!1,texFmtConfig:"",openFilesInTabs:!1},Qd="texlite-editor-preferences";function ca(t,e){return`${Qd}:${encodeURIComponent(t)}:${encodeURIComponent(e)}`}function Tw(t){return yi.find(e=>e.id===t)?.stack??yi[0].stack}function dl(t,e){try{const n=JSON.parse(localStorage.getItem(ca(t,e))??"{}");return{font:yi.some(s=>s.id===n.font)?n.font:gt.font,fontSize:[12,13,14,15,16,18,20].includes(Number(n.fontSize))?Number(n.fontSize):gt.fontSize,lineHeight:[1.45,1.65,1.85].includes(Number(n.lineHeight))?Number(n.lineHeight):gt.lineHeight,lineWrapping:typeof n.lineWrapping=="boolean"?n.lineWrapping:gt.lineWrapping,spellCheck:typeof n.spellCheck=="boolean"?n.spellCheck:gt.spellCheck,mathPreviewOnHover:typeof n.mathPreviewOnHover=="boolean"?n.mathPreviewOnHover:gt.mathPreviewOnHover,vimMode:typeof n.vimMode=="boolean"?n.vimMode:gt.vimMode,formatOnCompile:typeof n.formatOnCompile=="boolean"?n.formatOnCompile:gt.formatOnCompile,texFmtConfig:typeof n.texFmtConfig=="string"&&n.texFmtConfig.length<=16*1024?n.texFmtConfig:gt.texFmtConfig,openFilesInTabs:typeof n.openFilesInTabs=="boolean"?n.openFilesInTabs:gt.openFilesInTabs}}catch{return gt}}function Zd(t,e,n){localStorage.setItem(ca(t,e),JSON.stringify(n))}function eh(){let t={status:"loading",error:""};const e=new Set,n=(s,r="")=>{if(!(t.status===s&&t.error===r)){t={status:s,error:r};for(const i of e)i()}};return{getSnapshot:()=>t,subscribe:s=>(e.add(s),()=>e.delete(s)),loading:()=>n("loading"),working:()=>n("working"),failed:s=>n("error",s instanceof Error?s.message:String(s))}}const Kt=eh(),th=/\.(?:tex|bib|cls|sty)$/i,ua=3e4;let wt=null,Js=!1,cn=null,nh=1;const hn=new Map,Gs=[];let An=null,is=null;class ot extends Error{constructor(e,n){super(n),this.kind=e,this.name="TexFmtError"}kind}function Jr(t){return t instanceof ot}function Mt(t){wt?.terminate(),wt=null,Js=!1,cn!==null&&window.clearTimeout(cn),cn=null,An=null,Gs.length=0,is=null,Kt.failed(t);for(const e of hn.values())e.timeout!==null&&window.clearTimeout(e.timeout),e.reject(t);hn.clear()}function cs(){if(An!==null||Gs.length===0)return;let t;try{t=sh()}catch(s){Mt(s instanceof ot?s:new ot("load","The bundled tex-fmt formatter could not be loaded."));return}if(!Js)return;const e=Gs.shift();if(e===void 0)return;const n=hn.get(e);if(!n){cs();return}An=e,n.timeout=window.setTimeout(()=>{An===e&&Mt(new ot("result","The formatter did not respond within 30 seconds."))},ua);try{t.postMessage({...n.request,id:e})}catch{Mt(new ot("load","The formatter worker could not receive the source."))}}function sh(){if(wt)return wt;if(typeof Worker>"u"){const t=new ot("load","This browser does not support formatter workers.");throw Kt.failed(t),t}Kt.loading();try{wt=new Worker(new URL("/assets/latexFormatterWorker-DYkYtcFy.js",import.meta.url),{type:"module",name:"texlite-latex-formatter"}),cn=window.setTimeout(()=>{Js||Mt(new ot("load","The formatter did not finish loading within 30 seconds."))},ua)}catch{const t=new ot("load","The bundled tex-fmt formatter could not be loaded.");throw Kt.failed(t),t}return wt.onmessage=t=>{const e=t.data;if(e&&"type"in e){e.type==="ready"&&(Js=!0,cn!==null&&window.clearTimeout(cn),cn=null,cs());return}if(!e||typeof e.id!="number"){Mt(new ot("result","The formatter worker returned an invalid response."));return}const n=hn.get(e.id);if(n)if(hn.delete(e.id),n.timeout!==null&&window.clearTimeout(n.timeout),An===e.id&&(An=null),e.ok)Kt.working(),n.resolve(e.result),cs();else{const s=new ot(e.kind,e.message);e.kind==="format"?(Kt.working(),n.reject(s),cs()):(n.reject(s),Mt(s))}},wt.onerror=()=>{Mt(new ot("load","The bundled tex-fmt formatter could not be loaded."))},wt.onmessageerror=()=>{Mt(new ot("result","The formatter worker returned an unreadable response."))},wt}function $i(t){const e=nh++;return new Promise((n,s)=>{hn.set(e,{request:t,resolve:n,reject:s,timeout:null}),Gs.push(e),cs()})}function rh(t,e=""){return $i({action:"format",source:t,config:e})}async function ih(){wt&&Kt.getSnapshot().status==="working"||(is||(is=$i({action:"probe"}).then(()=>{}).finally(()=>{is=null})),await is)}async function Lw(){(wt||hn.size)&&Mt(new ot("load","The formatter runtime was reloaded.")),Kt.loading(),await ih()}function Is(t){return th.test(t)}function oh(t){return t.match(/(?:\r?\n)+$/)?.[0]??""}function lh(t,e){const n=oh(t),l=(n?t.slice(0,-n.length):t).split(/\r?\n/).find(u=>u.trim())?.match(/^[\t ]*/)?.[0]??"",a=e.replace(/(?:\r?\n)+$/,"");return`${l?a.split(`
3
- `).map(u=>u&&`${l}${u}`).join(`
4
- `):a}${n}`}async function Gr(t,e,n=0){return $i({action:"diff",source:t,formatted:e,baseOffset:n})}function ah(t,e=null){const n=hl(t),r=e==="succeeded"||e===null&&uh(t)?[]:fl(n.filter(pl)),i=hl(ch(t));return{warnings:fl(i.filter(a=>!pl(a)&&dh(a))),errors:r}}function hl(t){return t.split(`
5
- `).map(e=>e.trim()).filter(Boolean)}function fl(t){return[...new Set(t)]}function ch(t){const e=/^Running ['"][^\n]*(?:pdf|xe|lua)latex(?:\s|['"])[^\n]*$/gim;let n=-1;for(const s of t.matchAll(e))n=s.index;return n>=0?t.slice(n):t}function uh(t){return/Latexmk: All targets .* are up-to-date/i.test(t)&&/Output written on .*\.pdf/i.test(t)}function pl(t){return/^!\s/.test(t)||/(?:^|:\s)(?:LaTeX|Package|Class|pdfTeX|XeTeX|LuaTeX)?\s*Error:/i.test(t)||/^Latexmk:.*(?:\bErrors?,|did not complete making targets|failure)/i.test(t)||/^Collected error summary/i.test(t)||/\b(?:fatal error|emergency stop|undefined control sequence|no output pdf|no pages of output)\b/i.test(t)||/\b(?:bibtex|biber) errors?:/i.test(t)||/^error, and then rerun latexmk/i.test(t)}function dh(t){return/\bwarnings?\b|overfull|underfull|badness/i.test(t)}function hh(t){return t instanceof Error&&t.name==="AbortError"}function fh({projectId:t,activeFile:e,permission:n,revision:s,selection:r,save:i,onError:l,onAdded:a}){const[c,u]=f.useState([]),[h,d]=f.useState(null),[p,w]=f.useState(!1),[g,S]=f.useState(""),y=f.useRef(null),C=f.useRef(e),_=f.useRef(i),q=f.useRef(l),Y=f.useRef(a);C.current=e,_.current=i,q.current=l,Y.current=a;const K=async Q=>{y.current?.abort();const D=new AbortController;y.current=D;try{const x=await ie(`/api/projects/${t}/comments?path=${encodeURIComponent(Q)}`,{signal:D.signal});C.current===Q&&u(x.comments)}catch(x){!hh(x)&&C.current===Q&&u([])}finally{y.current===D&&(y.current=null)}};return f.useEffect(()=>{d(null)},[t,e]),f.useEffect(()=>(e?K(e):u([]),()=>{y.current?.abort(),y.current=null}),[t,e,s]),{comments:c,focusComment:h,setFocusComment:d,commentOpen:p,setCommentOpen:w,commentText:g,setCommentText:S,addComment:async()=>{if(!(!g.trim()||!e))try{if(n!=="read"&&!await _.current())return;await ie(`/api/projects/${t}/comments`,{method:"POST",body:JSON.stringify({path:e,content:g,...r})}),await K(e),w(!1),S(""),Y.current()}catch(Q){q.current(ce(Q))}},toggleComment:async Q=>{try{await ie(`/api/projects/${t}/comments/${Q.id}`,{method:"PATCH",body:JSON.stringify({resolved:!Q.resolved})}),await K(e)}catch(D){q.current(ce(D))}},replyToComment:async(Q,D)=>{try{return await ie(`/api/projects/${t}/comments/${Q.id}/replies`,{method:"POST",body:JSON.stringify({content:D})}),await K(e),!0}catch(x){return q.current(ce(x)),!1}},editComment:async(Q,D)=>{try{return await ie(`/api/projects/${t}/comments/${Q.id}`,{method:"PATCH",body:JSON.stringify({content:D})}),await K(e),!0}catch(x){return q.current(ce(x)),!1}},deleteComment:async Q=>{try{return await ie(`/api/projects/${t}/comments/${Q.id}`,{method:"DELETE"}),await K(e),d(D=>D?.id===Q.id?null:D),!0}catch(D){return q.current(ce(D)),!1}},editCommentReply:async(Q,D,x)=>{try{return await ie(`/api/projects/${t}/comments/${Q.id}/replies/${D}`,{method:"PATCH",body:JSON.stringify({content:x})}),await K(e),!0}catch(z){return q.current(ce(z)),!1}},deleteCommentReply:async(Q,D)=>{try{return await ie(`/api/projects/${t}/comments/${Q.id}/replies/${D}`,{method:"DELETE"}),await K(e),!0}catch(x){return q.current(ce(x)),!1}}}}const tt=()=>new Map,bi=t=>{const e=tt();return t.forEach((n,s)=>{e.set(s,n)}),e},Et=(t,e,n)=>{let s=t.get(e);return s===void 0&&t.set(e,s=n()),s},ph=(t,e)=>{const n=[];for(const[s,r]of t)n.push(e(r,s));return n},mh=(t,e)=>{for(const[n,s]of t)if(e(s,n))return!0;return!1},Xt=()=>new Set,Yr=t=>t[t.length-1],gh=(t,e)=>{for(let n=0;n<e.length;n++)t.push(e[n])},Pt=Array.from,Ii=(t,e)=>{for(let n=0;n<t.length;n++)if(!e(t[n],n,t))return!1;return!0},Pi=(t,e)=>{for(let n=0;n<t.length;n++)if(e(t[n],n,t))return!0;return!1},wh=(t,e)=>{const n=new Array(t);for(let s=0;s<t;s++)n[s]=e(s,n);return n},Bn=Array.isArray;class Ui{constructor(){this._observers=tt()}on(e,n){return Et(this._observers,e,Xt).add(n),n}once(e,n){const s=(...r)=>{this.off(e,s),n(...r)};this.on(e,s)}off(e,n){const s=this._observers.get(e);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(e))}emit(e,n){return Pt((this._observers.get(e)||tt()).values()).forEach(s=>s(...n))}destroy(){this._observers=tt()}}class da{constructor(){this._observers=tt()}on(e,n){Et(this._observers,e,Xt).add(n)}once(e,n){const s=(...r)=>{this.off(e,s),n(...r)};this.on(e,s)}off(e,n){const s=this._observers.get(e);s!==void 0&&(s.delete(n),s.size===0&&this._observers.delete(e))}emit(e,n){return Pt((this._observers.get(e)||tt()).values()).forEach(s=>s(...n))}destroy(){this._observers=tt()}}const bt=Math.floor,qs=Math.abs,zi=(t,e)=>t<e?t:e,gn=(t,e)=>t>e?t:e,yh=Math.pow,ha=t=>t!==0?t<0:1/t<0,ml=1,gl=2,Xr=4,Qr=8,hs=32,It=64,lt=128,dr=31,xi=63,dn=127,bh=2147483647,Ys=Number.MAX_SAFE_INTEGER,wl=Number.MIN_SAFE_INTEGER,xh=Number.isInteger||(t=>typeof t=="number"&&isFinite(t)&&bt(t)===t),fa=String.fromCharCode,Sh=t=>t.toLowerCase(),kh=/^\s*/g,Ch=t=>t.replace(kh,""),jh=/([A-Z])/g,yl=(t,e)=>Ch(t.replace(jh,n=>`${e}${Sh(n)}`)),vh=t=>{const e=unescape(encodeURIComponent(t)),n=e.length,s=new Uint8Array(n);for(let r=0;r<n;r++)s[r]=e.codePointAt(r);return s},fs=typeof TextEncoder<"u"?new TextEncoder:null,Eh=t=>fs.encode(t),Dh=fs?Eh:vh;let us=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});us&&us.decode(new Uint8Array).length===1&&(us=null);const _h=(t,e)=>wh(e,()=>t).join("");class ks{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const Le=()=>new ks,Bi=t=>{let e=t.cpos;for(let n=0;n<t.bufs.length;n++)e+=t.bufs[n].length;return e},me=t=>{const e=new Uint8Array(Bi(t));let n=0;for(let s=0;s<t.bufs.length;s++){const r=t.bufs[s];e.set(r,n),n+=r.length}return e.set(new Uint8Array(t.cbuf.buffer,0,t.cpos),n),e},Th=(t,e)=>{const n=t.cbuf.length;n-t.cpos<e&&(t.bufs.push(new Uint8Array(t.cbuf.buffer,0,t.cpos)),t.cbuf=new Uint8Array(gn(n,e)*2),t.cpos=0)},Ue=(t,e)=>{const n=t.cbuf.length;t.cpos===n&&(t.bufs.push(t.cbuf),t.cbuf=new Uint8Array(n*2),t.cpos=0),t.cbuf[t.cpos++]=e},Si=Ue,P=(t,e)=>{for(;e>dn;)Ue(t,lt|dn&e),e=bt(e/128);Ue(t,dn&e)},qi=(t,e)=>{const n=ha(e);for(n&&(e=-e),Ue(t,(e>xi?lt:0)|(n?It:0)|xi&e),e=bt(e/64);e>0;)Ue(t,(e>dn?lt:0)|dn&e),e=bt(e/128)},ki=new Uint8Array(3e4),Lh=ki.length/3,Rh=(t,e)=>{if(e.length<Lh){const n=fs.encodeInto(e,ki).written||0;P(t,n);for(let s=0;s<n;s++)Ue(t,ki[s])}else Te(t,Dh(e))},Ah=(t,e)=>{const n=unescape(encodeURIComponent(e)),s=n.length;P(t,s);for(let r=0;r<s;r++)Ue(t,n.codePointAt(r))},qe=fs&&fs.encodeInto?Rh:Ah,hr=(t,e)=>{const n=t.cbuf.length,s=t.cpos,r=zi(n-s,e.length),i=e.length-r;t.cbuf.set(e.subarray(0,r),s),t.cpos+=r,i>0&&(t.bufs.push(t.cbuf),t.cbuf=new Uint8Array(gn(n*2,i)),t.cbuf.set(e.subarray(r)),t.cpos=i)},Te=(t,e)=>{P(t,e.byteLength),hr(t,e)},Wi=(t,e)=>{Th(t,e);const n=new DataView(t.cbuf.buffer,t.cpos,e);return t.cpos+=e,n},Nh=(t,e)=>Wi(t,4).setFloat32(0,e,!1),Oh=(t,e)=>Wi(t,8).setFloat64(0,e,!1),Fh=(t,e)=>Wi(t,8).setBigInt64(0,e,!1),bl=new DataView(new ArrayBuffer(4)),Mh=t=>(bl.setFloat32(0,t),bl.getFloat32(0)===t),ps=(t,e)=>{switch(typeof e){case"string":Ue(t,119),qe(t,e);break;case"number":xh(e)&&qs(e)<=bh?(Ue(t,125),qi(t,e)):Mh(e)?(Ue(t,124),Nh(t,e)):(Ue(t,123),Oh(t,e));break;case"bigint":Ue(t,122),Fh(t,e);break;case"object":if(e===null)Ue(t,126);else if(Bn(e)){Ue(t,117),P(t,e.length);for(let n=0;n<e.length;n++)ps(t,e[n])}else if(e instanceof Uint8Array)Ue(t,116),Te(t,e);else{Ue(t,118);const n=Object.keys(e);P(t,n.length);for(let s=0;s<n.length;s++){const r=n[s];qe(t,r),ps(t,e[r])}}break;case"boolean":Ue(t,e?120:121);break;default:Ue(t,127)}};class xl extends ks{constructor(e){super(),this.w=e,this.s=null,this.count=0}write(e){this.s===e?this.count++:(this.count>0&&P(this,this.count-1),this.count=1,this.w(this,e),this.s=e)}}const Sl=t=>{t.count>0&&(qi(t.encoder,t.count===1?t.s:-t.s),t.count>1&&P(t.encoder,t.count-2))};class Ws{constructor(){this.encoder=new ks,this.s=0,this.count=0}write(e){this.s===e?this.count++:(Sl(this),this.count=1,this.s=e)}toUint8Array(){return Sl(this),me(this.encoder)}}const kl=t=>{if(t.count>0){const e=t.diff*2+(t.count===1?0:1);qi(t.encoder,e),t.count>1&&P(t.encoder,t.count-2)}};class Zr{constructor(){this.encoder=new ks,this.s=0,this.count=0,this.diff=0}write(e){this.diff===e-this.s?(this.s=e,this.count++):(kl(this),this.count=1,this.diff=e-this.s,this.s=e)}toUint8Array(){return kl(this),me(this.encoder)}}class $h{constructor(){this.sarr=[],this.s="",this.lensE=new Ws}write(e){this.s+=e,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(e.length)}toUint8Array(){const e=new ks;return this.sarr.push(this.s),this.s="",qe(e,this.sarr.join("")),hr(e,this.lensE.toUint8Array()),me(e)}}const xt=t=>new Error(t),yt=()=>{throw xt("Method unimplemented")},at=()=>{throw xt("Unexpected case")},pa=xt("Unexpected end of array"),ma=xt("Integer out of Range");class fr{constructor(e){this.arr=e,this.pos=0}}const en=t=>new fr(t),Ci=t=>t.pos!==t.arr.length,Ih=(t,e)=>{const n=new Uint8Array(t.arr.buffer,t.pos+t.arr.byteOffset,e);return t.pos+=e,n},Ye=t=>Ih(t,ee(t)),qn=t=>t.arr[t.pos++],ee=t=>{let e=0,n=1;const s=t.arr.length;for(;t.pos<s;){const r=t.arr[t.pos++];if(e=e+(r&dn)*n,n*=128,r<lt)return e;if(e>Ys)throw ma}throw pa},Vi=t=>{let e=t.arr[t.pos++],n=e&xi,s=64;const r=(e&It)>0?-1:1;if((e&lt)===0)return r*n;const i=t.arr.length;for(;t.pos<i;){if(e=t.arr[t.pos++],n=n+(e&dn)*s,s*=128,e<lt)return r*n;if(n>Ys)throw ma}throw pa},Ph=t=>{let e=ee(t);if(e===0)return"";{let n=String.fromCodePoint(qn(t));if(--e<100)for(;e--;)n+=String.fromCodePoint(qn(t));else for(;e>0;){const s=e<1e4?e:1e4,r=t.arr.subarray(t.pos,t.pos+s);t.pos+=s,n+=String.fromCodePoint.apply(null,r),e-=s}return decodeURIComponent(escape(n))}},Uh=t=>us.decode(Ye(t)),je=us?Uh:Ph,Hi=(t,e)=>{const n=new DataView(t.arr.buffer,t.arr.byteOffset+t.pos,e);return t.pos+=e,n},zh=t=>Hi(t,4).getFloat32(0,!1),Bh=t=>Hi(t,8).getFloat64(0,!1),qh=t=>Hi(t,8).getBigInt64(0,!1),Wh=[t=>{},t=>null,Vi,zh,Bh,qh,t=>!1,t=>!0,je,t=>{const e=ee(t),n={};for(let s=0;s<e;s++){const r=je(t);n[r]=ms(t)}return n},t=>{const e=ee(t),n=[];for(let s=0;s<e;s++)n.push(ms(t));return n},Ye],ms=t=>Wh[127-qn(t)](t);class Cl extends fr{constructor(e,n){super(e),this.reader=n,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),Ci(this)?this.count=ee(this)+1:this.count=-1),this.count--,this.s}}class Vs extends fr{constructor(e){super(e),this.s=0,this.count=0}read(){if(this.count===0){this.s=Vi(this);const e=ha(this.s);this.count=1,e&&(this.s=-this.s,this.count=ee(this)+2)}return this.count--,this.s}}class ei extends fr{constructor(e){super(e),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const e=Vi(this),n=e&1;this.diff=bt(e/2),this.count=1,n&&(this.count=ee(this)+2)}return this.s+=this.diff,this.count--,this.s}}class Vh{constructor(e){this.decoder=new Vs(e),this.str=je(this.decoder),this.spos=0}read(){const e=this.spos+this.decoder.read(),n=this.str.slice(this.spos,e);return this.spos=e,n}}const Hh=crypto.getRandomValues.bind(crypto),ga=()=>Hh(new Uint32Array(1))[0],Kh="10000000-1000-4000-8000"+-1e11,Jh=()=>Kh.replace(/[018]/g,t=>(t^ga()&15>>t/4).toString(16)),Qt=Date.now,Wn=t=>new Promise(t);Promise.all.bind(Promise);const jl=t=>t===void 0?null:t;class Gh{constructor(){this.map=new Map}setItem(e,n){this.map.set(e,n)}getItem(e){return this.map.get(e)}}let wa=new Gh,Ki=!0;try{typeof localStorage<"u"&&localStorage&&(wa=localStorage,Ki=!1)}catch{}const ya=wa,Yh=t=>Ki||addEventListener("storage",t),Xh=t=>Ki||removeEventListener("storage",t),gs=Symbol("Equality"),ba=(t,e)=>t===e||!!t?.[gs]?.(e)||!1,Qh=t=>typeof t=="object",Zh=Object.assign,ef=Object.keys,tf=(t,e)=>{for(const n in t)e(t[n],n)},nf=(t,e)=>{const n=[];for(const s in t)n.push(e(t[s],s));return n},Xs=t=>ef(t).length,sf=t=>{for(const e in t)return!1;return!0},Cs=(t,e)=>{for(const n in t)if(!e(t[n],n))return!1;return!0},Ji=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),rf=(t,e)=>t===e||Xs(t)===Xs(e)&&Cs(t,(n,s)=>(n!==void 0||Ji(e,s))&&ba(e[s],n)),of=Object.freeze,xa=t=>{for(const e in t){const n=t[e];(typeof n=="object"||typeof n=="function")&&xa(t[e])}return of(t)},Gi=(t,e,n=0)=>{try{for(;n<t.length;n++)t[n](...e)}finally{n<t.length&&Gi(t,e,n+1)}},lf=t=>t,Nn=(t,e)=>{if(t===e)return!0;if(t==null||e==null||t.constructor!==e.constructor&&(t.constructor||Object)!==(e.constructor||Object))return!1;if(t[gs]!=null)return t[gs](e);switch(t.constructor){case ArrayBuffer:t=new Uint8Array(t),e=new Uint8Array(e);case Uint8Array:{if(t.byteLength!==e.byteLength)return!1;for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;break}case Set:{if(t.size!==e.size)return!1;for(const n of t)if(!e.has(n))return!1;break}case Map:{if(t.size!==e.size)return!1;for(const n of t.keys())if(!e.has(n)||!Nn(t.get(n),e.get(n)))return!1;break}case void 0:case Object:if(Xs(t)!==Xs(e))return!1;for(const n in t)if(!Ji(t,n)||!Nn(t[n],e[n]))return!1;break;case Array:if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(!Nn(t[n],e[n]))return!1;break;default:return!1}return!0},af=(t,e)=>e.includes(t);var Sa={};const Zt=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]",ka=typeof window<"u"&&typeof document<"u"&&!Zt;let kt;const cf=()=>{if(kt===void 0)if(Zt){kt=tt();const t=process.argv;let e=null;for(let n=0;n<t.length;n++){const s=t[n];s[0]==="-"?(e!==null&&kt.set(e,""),e=s):e!==null&&(kt.set(e,s),e=null)}e!==null&&kt.set(e,"")}else typeof location=="object"?(kt=tt(),(location.search||"?").slice(1).split("&").forEach(t=>{if(t.length!==0){const[e,n]=t.split("=");kt.set(`--${yl(e,"-")}`,n),kt.set(`-${yl(e,"-")}`,n)}})):kt=tt();return kt},ji=t=>cf().has(t),Qs=t=>jl(Zt?Sa[t.toUpperCase().replaceAll("-","_")]:ya.getItem(t)),Ca=t=>ji("--"+t)||Qs(t)!==null,uf=Ca("production"),df=Zt&&af(Sa.FORCE_COLOR,["true","1","2"]),hf=df||!ji("--no-colors")&&!Ca("no-color")&&(!Zt||process.stdout.isTTY)&&(!Zt||ji("--color")||Qs("COLORTERM")!==null||(Qs("TERM")||"").includes("color")),ja=t=>new Uint8Array(t),ff=(t,e,n)=>new Uint8Array(t,e,n),pf=t=>new Uint8Array(t),mf=t=>{let e="";for(let n=0;n<t.byteLength;n++)e+=fa(t[n]);return btoa(e)},gf=t=>Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("base64"),wf=t=>{const e=atob(t),n=ja(e.length);for(let s=0;s<e.length;s++)n[s]=e.charCodeAt(s);return n},yf=t=>{const e=Buffer.from(t,"base64");return ff(e.buffer,e.byteOffset,e.byteLength)},bf=ka?mf:gf,xf=ka?wf:yf,Sf=t=>{const e=ja(t.byteLength);return e.set(t),e};class kf{constructor(e,n){this.left=e,this.right=n}}const Ft=(t,e)=>new kf(t,e),Cf=(t,e)=>t.forEach(n=>e(n.left,n.right)),vl=t=>t.next()>=.5,ti=(t,e,n)=>bt(t.next()*(n+1-e)+e),va=(t,e,n)=>bt(t.next()*(n+1-e)+e),Yi=(t,e,n)=>va(t,e,n),jf=t=>fa(Yi(t,97,122)),vf=(t,e=0,n=20)=>{const s=Yi(t,e,n);let r="";for(let i=0;i<s;i++)r+=jf(t);return r},ni=(t,e)=>e[Yi(t,0,e.length-1)],Ef=Symbol("0schema");class Df{constructor(){this._rerrs=[]}extend(e,n,s,r=null){this._rerrs.push({path:e,expected:n,has:s,message:r})}toString(){const e=[];for(let n=this._rerrs.length-1;n>0;n--){const s=this._rerrs[n];e.push(_h(" ",(this._rerrs.length-n)*2)+`${s.path!=null?`[${s.path}] `:""}${s.has} doesn't match ${s.expected}. ${s.message}`)}return e.join(`
6
- `)}}const vi=(t,e)=>t===e?!0:t==null||e==null||t.constructor!==e.constructor?!1:t[gs]?ba(t,e):Bn(t)?Ii(t,n=>Pi(e,s=>vi(n,s))):Qh(t)?Cs(t,(n,s)=>vi(n,e[s])):!1;class Ze{static _dilutes=!1;extends(e){let[n,s]=[this.shape,e.shape];return this.constructor._dilutes&&([s,n]=[n,s]),vi(n,s)}equals(e){return this.constructor===e.constructor&&Nn(this.shape,e.shape)}[Ef](){return!0}[gs](e){return this.equals(e)}validate(e){return this.check(e)}check(e,n){yt()}get nullable(){return Xn(this,yr)}get optional(){return new _a(this)}cast(e){return El(e,this),e}expect(e){return El(e,this),e}}class Xi extends Ze{constructor(e,n){super(),this.shape=e,this._c=n}check(e,n=void 0){const s=e?.constructor===this.shape&&(this._c==null||this._c(e));return!s&&n?.extend(null,this.shape.name,e?.constructor.name,e?.constructor!==this.shape?"Constructor match failed":"Check failed"),s}}const Fe=(t,e=null)=>new Xi(t,e);Fe(Xi);class Qi extends Ze{constructor(e){super(),this.shape=e}check(e,n){const s=this.shape(e);return!s&&n?.extend(null,"custom prop",e?.constructor.name,"failed to check custom prop"),s}}const Be=t=>new Qi(t);Fe(Qi);class pr extends Ze{constructor(e){super(),this.shape=e}check(e,n){const s=this.shape.some(r=>r===e);return!s&&n?.extend(null,this.shape.join(" | "),e.toString()),s}}const mr=(...t)=>new pr(t),Ea=Fe(pr),_f=RegExp.escape||(t=>t.replace(/[().|&,$^[\]]/g,e=>"\\"+e)),Da=t=>{if(Vn.check(t))return[_f(t)];if(Ea.check(t))return t.shape.map(e=>e+"");if($a.check(t))return["[+-]?\\d+.?\\d*"];if(Ia.check(t))return[".*"];if(Zs.check(t))return t.shape.map(Da).flat(1);at()};class Tf extends Ze{constructor(e){super(),this.shape=e,this._r=new RegExp("^"+e.map(Da).map(n=>`(${n.join("|")})`).join("")+"$")}check(e,n){const s=this._r.exec(e)!=null;return!s&&n?.extend(null,this._r.toString(),e.toString(),"String doesn't match string template."),s}}Fe(Tf);const Lf=Symbol("optional");class _a extends Ze{constructor(e){super(),this.shape=e}check(e,n){const s=e===void 0||this.shape.check(e);return!s&&n?.extend(null,"undefined (optional)","()"),s}get[Lf](){return!0}}const Rf=Fe(_a);class Af extends Ze{check(e,n){return n?.extend(null,"never",typeof e),!1}}Fe(Af);class gr extends Ze{constructor(e,n=!1){super(),this.shape=e,this._isPartial=n}static _dilutes=!0;get partial(){return new gr(this.shape,!0)}check(e,n){return e==null?(n?.extend(null,"object","null"),!1):Cs(this.shape,(s,r)=>{const i=this._isPartial&&!Ji(e,r)||s.check(e[r],n);return!i&&n?.extend(r.toString(),s.toString(),typeof e[r],"Object property does not match"),i})}}const Nf=t=>new gr(t),Of=Fe(gr),Ff=Be(t=>t!=null&&(t.constructor===Object||t.constructor==null));class Ta extends Ze{constructor(e,n){super(),this.shape={keys:e,values:n}}check(e,n){return e!=null&&Cs(e,(s,r)=>{const i=this.shape.keys.check(r,n);return!i&&n?.extend(r+"","Record",typeof e,i?"Key doesn't match schema":"Value doesn't match value"),i&&this.shape.values.check(s,n)})}}const La=(t,e)=>new Ta(t,e),Mf=Fe(Ta);class Ra extends Ze{constructor(e){super(),this.shape=e}check(e,n){return e!=null&&Cs(this.shape,(s,r)=>{const i=s.check(e[r],n);return!i&&n?.extend(r.toString(),"Tuple",typeof s),i})}}const $f=(...t)=>new Ra(t);Fe(Ra);class Aa extends Ze{constructor(e){super(),this.shape=e.length===1?e[0]:new Zi(e)}check(e,n){const s=Bn(e)&&Ii(e,r=>this.shape.check(r));return!s&&n?.extend(null,"Array",""),s}}const Na=(...t)=>new Aa(t),If=Fe(Aa),Pf=Be(t=>Bn(t));class Oa extends Ze{constructor(e,n){super(),this.shape=e,this._c=n}check(e,n){const s=e instanceof this.shape&&(this._c==null||this._c(e));return!s&&n?.extend(null,this.shape.name,e?.constructor.name),s}}const Uf=(t,e=null)=>new Oa(t,e);Fe(Oa);const zf=Uf(Ze);class Bf extends Ze{constructor(e){super(),this.len=e.length-1,this.args=$f(...e.slice(-1)),this.res=e[this.len]}check(e,n){const s=e.constructor===Function&&e.length<=this.len;return!s&&n?.extend(null,"function",typeof e),s}}const qf=Fe(Bf),Wf=Be(t=>typeof t=="function");class Vf extends Ze{constructor(e){super(),this.shape=e}check(e,n){const s=Ii(this.shape,r=>r.check(e,n));return!s&&n?.extend(null,"Intersectinon",typeof e),s}}Fe(Vf,t=>t.shape.length>0);class Zi extends Ze{static _dilutes=!0;constructor(e){super(),this.shape=e}check(e,n){const s=Pi(this.shape,r=>r.check(e,n));return n?.extend(null,"Union",typeof e),s}}const Xn=(...t)=>t.findIndex(e=>Zs.check(e))>=0?Xn(...t.map(e=>ws(e)).map(e=>Zs.check(e)?e.shape:[e]).flat(1)):t.length===1?t[0]:new Zi(t),Zs=Fe(Zi),Fa=()=>!0,er=Be(Fa),Hf=Fe(Qi,t=>t.shape===Fa),eo=Be(t=>typeof t=="bigint"),Kf=Be(t=>t===eo),Ma=Be(t=>typeof t=="symbol");Be(t=>t===Ma);const On=Be(t=>typeof t=="number"),$a=Be(t=>t===On),Vn=Be(t=>typeof t=="string"),Ia=Be(t=>t===Vn),wr=Be(t=>typeof t=="boolean"),Jf=Be(t=>t===wr),Pa=mr(void 0);Fe(pr,t=>t.shape.length===1&&t.shape[0]===void 0);mr(void 0);const yr=mr(null),Gf=Fe(pr,t=>t.shape.length===1&&t.shape[0]===null);Fe(Uint8Array);Fe(Xi,t=>t.shape===Uint8Array);const Yf=Xn(On,Vn,yr,Pa,eo,wr,Ma);(()=>{const t=Na(er),e=La(Vn,er),n=Xn(On,Vn,yr,wr,t,e);return t.shape=n,e.shape.values=n,n})();const ws=t=>{if(zf.check(t))return t;if(Ff.check(t)){const e={};for(const n in t)e[n]=ws(t[n]);return Nf(e)}else{if(Pf.check(t))return Xn(...t.map(ws));if(Yf.check(t))return mr(t);if(Wf.check(t))return Fe(t)}at()},El=uf?()=>{}:(t,e)=>{const n=new Df;if(!e.check(t,n))throw xt(`Expected value to be of type ${e.constructor.name}.
7
- ${n.toString()}`)};class Xf{constructor(e){this.patterns=[],this.$state=e}if(e,n){return this.patterns.push({if:ws(e),h:n}),this}else(e){return this.if(er,e)}done(){return(e,n)=>{for(let s=0;s<this.patterns.length;s++){const r=this.patterns[s];if(r.if.check(e))return r.h(e,n)}throw xt("Unhandled pattern")}}}const Qf=t=>new Xf(t),Ua=Qf(er).if($a,(t,e)=>ti(e,wl,Ys)).if(Ia,(t,e)=>vf(e)).if(Jf,(t,e)=>vl(e)).if(Kf,(t,e)=>BigInt(ti(e,wl,Ys))).if(Zs,(t,e)=>En(e,ni(e,t.shape))).if(Of,(t,e)=>{const n={};for(const s in t.shape){let r=t.shape[s];if(Rf.check(r)){if(vl(e))continue;r=r.shape}n[s]=Ua(r,e)}return n}).if(If,(t,e)=>{const n=[],s=va(e,0,42);for(let r=0;r<s;r++)n.push(En(e,t.shape));return n}).if(Ea,(t,e)=>ni(e,t.shape)).if(Gf,(t,e)=>null).if(qf,(t,e)=>{const n=En(e,t.res);return()=>n}).if(Hf,(t,e)=>En(e,ni(e,[On,Vn,yr,Pa,eo,wr,Na(On),La(Xn("a","b","c"),On)]))).if(Mf,(t,e)=>{const n={},s=ti(e,0,3);for(let r=0;r<s;r++){const i=En(e,t.shape.keys),l=En(e,t.shape.values);n[i]=l}return n}).done(),En=(t,e)=>Ua(ws(e),t),Dt=typeof document<"u"?document:{},Zf=t=>Dt.createElement(t),ep=()=>Dt.createDocumentFragment();Be(t=>t.nodeType===cp);const tp=t=>Dt.createTextNode(t);typeof DOMParser<"u"&&new DOMParser;const np=(t,e)=>(Cf(e,(n,s)=>{s===!1?t.removeAttribute(n):s===!0?t.setAttribute(n,""):t.setAttribute(n,s)}),t),sp=t=>{const e=ep();for(let n=0;n<t.length;n++)za(e,t[n]);return e},rp=(t,e)=>(za(t,sp(e)),t),Rw=(t,e=[],n=[])=>rp(np(Zf(t),e),n);Be(t=>t.nodeType===op);const Aw=tp;Be(t=>t.nodeType===lp);const ip=t=>ph(t,(e,n)=>`${n}:${e};`).join(""),za=(t,e)=>t.appendChild(e),op=Dt.ELEMENT_NODE,lp=Dt.TEXT_NODE;Dt.CDATA_SECTION_NODE;Dt.COMMENT_NODE;const ap=Dt.DOCUMENT_NODE;Dt.DOCUMENT_TYPE_NODE;const cp=Dt.DOCUMENT_FRAGMENT_NODE;Be(t=>t.nodeType===ap);const Ut=Symbol,Ba=Ut(),qa=Ut(),up=Ut(),dp=Ut(),hp=Ut(),Wa=Ut(),fp=Ut(),to=Ut(),pp=Ut(),mp=t=>{t.length===1&&t[0]?.constructor===Function&&(t=t[0]());const e=[],n=[];let s=0;for(;s<t.length;s++){const r=t[s];if(r===void 0)break;if(r.constructor===String||r.constructor===Number)e.push(r);else if(r.constructor===Object)break}for(s>0&&n.push(e.join(""));s<t.length;s++){const r=t[s];r instanceof Symbol||n.push(r)}return n},gp={[Ba]:Ft("font-weight","bold"),[qa]:Ft("font-weight","normal"),[up]:Ft("color","blue"),[hp]:Ft("color","green"),[dp]:Ft("color","grey"),[Wa]:Ft("color","red"),[fp]:Ft("color","purple"),[to]:Ft("color","orange"),[pp]:Ft("color","black")},wp=t=>{t.length===1&&t[0]?.constructor===Function&&(t=t[0]());const e=[],n=[],s=tt();let r=[],i=0;for(;i<t.length;i++){const l=t[i],a=gp[l];if(a!==void 0)s.set(a.left,a.right);else{if(l===void 0)break;if(l.constructor===String||l.constructor===Number){const c=ip(s);i>0||c.length>0?(e.push("%c"+l),n.push(c)):e.push(l)}else break}}for(i>0&&(r=n,r.unshift(e.join("")));i<t.length;i++){const l=t[i];l instanceof Symbol||r.push(l)}return r},Va=hf?wp:mp,yp=(...t)=>{console.log(...Va(t)),Ka.forEach(e=>e.print(t))},Ha=(...t)=>{console.warn(...Va(t)),t.unshift(to),Ka.forEach(e=>e.print(t))},Ka=Xt(),Ja=t=>({[Symbol.iterator](){return this},next:t}),bp=(t,e)=>Ja(()=>{let n;do n=t.next();while(!n.done&&!e(n.value));return n}),si=(t,e)=>Ja(()=>{const{done:n,value:s}=t.next();return{done:n,value:n?void 0:e(s)}});class br{constructor(e,n){this.clock=e,this.len=n}}class Qn{constructor(){this.clients=new Map}}const Hn=(t,e,n)=>e.clients.forEach((s,r)=>{const i=t.doc.store.clients.get(r);if(i!=null){const l=i[i.length-1],a=l.id.clock+l.length;for(let c=0,u=s[c];c<s.length&&u.clock<a;u=s[++c])cc(t,i,u.clock,u.len,n)}}),xp=(t,e)=>{let n=0,s=t.length-1;for(;n<=s;){const r=bt((n+s)/2),i=t[r],l=i.clock;if(l<=e){if(e<l+i.len)return r;n=r+1}else s=r-1}return null},js=(t,e)=>{const n=t.clients.get(e.client);return n!==void 0&&xp(n,e.clock)!==null},no=t=>{t.clients.forEach(e=>{e.sort((r,i)=>r.clock-i.clock);let n,s;for(n=1,s=1;n<e.length;n++){const r=e[s-1],i=e[n];r.clock+r.len>=i.clock?e[s-1]=new br(r.clock,gn(r.len,i.clock+i.len-r.clock)):(s<n&&(e[s]=i),s++)}e.length=s})},Ei=t=>{const e=new Qn;for(let n=0;n<t.length;n++)t[n].clients.forEach((s,r)=>{if(!e.clients.has(r)){const i=s.slice();for(let l=n+1;l<t.length;l++)gh(i,t[l].clients.get(r)||[]);e.clients.set(r,i)}});return no(e),e},ys=(t,e,n,s)=>{Et(t.clients,e,()=>[]).push(new br(n,s))},Sp=()=>new Qn,kp=t=>{const e=Sp();return t.clients.forEach((n,s)=>{const r=[];for(let i=0;i<n.length;i++){const l=n[i];if(l.deleted){const a=l.id.clock;let c=l.length;if(i+1<n.length)for(let u=n[i+1];i+1<n.length&&u.deleted;u=n[++i+1])c+=u.length;r.push(new br(a,c))}}r.length>0&&e.clients.set(s,r)}),e},Zn=(t,e)=>{P(t.restEncoder,e.clients.size),Pt(e.clients.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{t.resetDsCurVal(),P(t.restEncoder,n);const r=s.length;P(t.restEncoder,r);for(let i=0;i<r;i++){const l=s[i];t.writeDsClock(l.clock),t.writeDsLen(l.len)}})},so=t=>{const e=new Qn,n=ee(t.restDecoder);for(let s=0;s<n;s++){t.resetDsCurVal();const r=ee(t.restDecoder),i=ee(t.restDecoder);if(i>0){const l=Et(e.clients,r,()=>[]);for(let a=0;a<i;a++)l.push(new br(t.readDsClock(),t.readDsLen()))}}return e},Dl=(t,e,n)=>{const s=new Qn,r=ee(t.restDecoder);for(let i=0;i<r;i++){t.resetDsCurVal();const l=ee(t.restDecoder),a=ee(t.restDecoder),c=n.clients.get(l)||[],u=Ae(n,l);for(let h=0;h<a;h++){const d=t.readDsClock(),p=d+t.readDsLen();if(d<u){u<p&&ys(s,l,u,p-u);let w=Ct(c,d),g=c[w];for(!g.deleted&&g.id.clock<d&&(c.splice(w+1,0,ar(e,g,d-g.id.clock)),w++);w<c.length&&(g=c[w++],g.id.clock<p);)g.deleted||(p<g.id.clock+g.length&&c.splice(w,0,ar(e,g,p-g.id.clock)),g.delete(e))}else ys(s,l,d,p-d)}}if(s.clients.size>0){const i=new fn;return P(i.restEncoder,0),Zn(i,s),i.toUint8Array()}return null},Ga=ga;class wn extends Ui{constructor({guid:e=Jh(),collectionid:n=null,gc:s=!0,gcFilter:r=()=>!0,meta:i=null,autoLoad:l=!1,shouldLoad:a=!0}={}){super(),this.gc=s,this.gcFilter=r,this.clientID=Ga(),this.guid=e,this.collectionid=n,this.share=new Map,this.store=new lc,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=a,this.autoLoad=l,this.meta=i,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=Wn(u=>{this.on("load",()=>{this.isLoaded=!0,u(this)})});const c=()=>Wn(u=>{const h=d=>{(d===void 0||d===!0)&&(this.off("sync",h),u())};this.on("sync",h)});this.on("sync",u=>{u===!1&&this.isSynced&&(this.whenSynced=c()),this.isSynced=u===void 0||u===!0,this.isSynced&&!this.isLoaded&&this.emit("load",[this])}),this.whenSynced=c()}load(){const e=this._item;e!==null&&!this.shouldLoad&&ge(e.parent.doc,n=>{n.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(Pt(this.subdocs).map(e=>e.guid))}transact(e,n=null){return ge(this,e,n)}get(e,n=ze){const s=Et(this.share,e,()=>{const i=new n;return i._integrate(this,null),i}),r=s.constructor;if(n!==ze&&r!==n)if(r===ze){const i=new n;i._map=s._map,s._map.forEach(l=>{for(;l!==null;l=l.left)l.parent=i}),i._start=s._start;for(let l=i._start;l!==null;l=l.right)l.parent=i;return i._length=s._length,this.share.set(e,i),i._integrate(this,null),i}else throw new Error(`Type with the name ${e} has already been defined with a different constructor`);return s}getArray(e=""){return this.get(e,$n)}getText(e=""){return this.get(e,Gn)}getMap(e=""){return this.get(e,Jn)}getXmlElement(e=""){return this.get(e,Yn)}getXmlFragment(e=""){return this.get(e,pn)}toJSON(){const e={};return this.share.forEach((n,s)=>{e[s]=n.toJSON()}),e}destroy(){this.isDestroyed=!0,Pt(this.subdocs).forEach(n=>n.destroy());const e=this._item;if(e!==null){this._item=null;const n=e.content;n.doc=new wn({guid:this.guid,...n.opts,shouldLoad:!1}),n.doc._item=e,ge(e.parent.doc,s=>{const r=n.doc;e.deleted||s.subdocsAdded.add(r),s.subdocsRemoved.add(this)},null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}}class Ya{constructor(e){this.restDecoder=e}resetDsCurVal(){}readDsClock(){return ee(this.restDecoder)}readDsLen(){return ee(this.restDecoder)}}class Xa extends Ya{readLeftID(){return se(ee(this.restDecoder),ee(this.restDecoder))}readRightID(){return se(ee(this.restDecoder),ee(this.restDecoder))}readClient(){return ee(this.restDecoder)}readInfo(){return qn(this.restDecoder)}readString(){return je(this.restDecoder)}readParentInfo(){return ee(this.restDecoder)===1}readTypeRef(){return ee(this.restDecoder)}readLen(){return ee(this.restDecoder)}readAny(){return ms(this.restDecoder)}readBuf(){return Sf(Ye(this.restDecoder))}readJSON(){return JSON.parse(je(this.restDecoder))}readKey(){return je(this.restDecoder)}}class Cp{constructor(e){this.dsCurrVal=0,this.restDecoder=e}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=ee(this.restDecoder),this.dsCurrVal}readDsLen(){const e=ee(this.restDecoder)+1;return this.dsCurrVal+=e,e}}class Kn extends Cp{constructor(e){super(e),this.keys=[],ee(e),this.keyClockDecoder=new ei(Ye(e)),this.clientDecoder=new Vs(Ye(e)),this.leftClockDecoder=new ei(Ye(e)),this.rightClockDecoder=new ei(Ye(e)),this.infoDecoder=new Cl(Ye(e),qn),this.stringDecoder=new Vh(Ye(e)),this.parentInfoDecoder=new Cl(Ye(e),qn),this.typeRefDecoder=new Vs(Ye(e)),this.lenDecoder=new Vs(Ye(e))}readLeftID(){return new Fn(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new Fn(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return this.parentInfoDecoder.read()===1}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return ms(this.restDecoder)}readBuf(){return Ye(this.restDecoder)}readJSON(){return ms(this.restDecoder)}readKey(){const e=this.keyClockDecoder.read();if(e<this.keys.length)return this.keys[e];{const n=this.stringDecoder.read();return this.keys.push(n),n}}}class Qa{constructor(){this.restEncoder=Le()}toUint8Array(){return me(this.restEncoder)}resetDsCurVal(){}writeDsClock(e){P(this.restEncoder,e)}writeDsLen(e){P(this.restEncoder,e)}}class vs extends Qa{writeLeftID(e){P(this.restEncoder,e.client),P(this.restEncoder,e.clock)}writeRightID(e){P(this.restEncoder,e.client),P(this.restEncoder,e.clock)}writeClient(e){P(this.restEncoder,e)}writeInfo(e){Si(this.restEncoder,e)}writeString(e){qe(this.restEncoder,e)}writeParentInfo(e){P(this.restEncoder,e?1:0)}writeTypeRef(e){P(this.restEncoder,e)}writeLen(e){P(this.restEncoder,e)}writeAny(e){ps(this.restEncoder,e)}writeBuf(e){Te(this.restEncoder,e)}writeJSON(e){qe(this.restEncoder,JSON.stringify(e))}writeKey(e){qe(this.restEncoder,e)}}class Za{constructor(){this.restEncoder=Le(),this.dsCurrVal=0}toUint8Array(){return me(this.restEncoder)}resetDsCurVal(){this.dsCurrVal=0}writeDsClock(e){const n=e-this.dsCurrVal;this.dsCurrVal=e,P(this.restEncoder,n)}writeDsLen(e){e===0&&at(),P(this.restEncoder,e-1),this.dsCurrVal+=e}}class fn extends Za{constructor(){super(),this.keyMap=new Map,this.keyClock=0,this.keyClockEncoder=new Zr,this.clientEncoder=new Ws,this.leftClockEncoder=new Zr,this.rightClockEncoder=new Zr,this.infoEncoder=new xl(Si),this.stringEncoder=new $h,this.parentInfoEncoder=new xl(Si),this.typeRefEncoder=new Ws,this.lenEncoder=new Ws}toUint8Array(){const e=Le();return P(e,0),Te(e,this.keyClockEncoder.toUint8Array()),Te(e,this.clientEncoder.toUint8Array()),Te(e,this.leftClockEncoder.toUint8Array()),Te(e,this.rightClockEncoder.toUint8Array()),Te(e,me(this.infoEncoder)),Te(e,this.stringEncoder.toUint8Array()),Te(e,me(this.parentInfoEncoder)),Te(e,this.typeRefEncoder.toUint8Array()),Te(e,this.lenEncoder.toUint8Array()),hr(e,me(this.restEncoder)),me(e)}writeLeftID(e){this.clientEncoder.write(e.client),this.leftClockEncoder.write(e.clock)}writeRightID(e){this.clientEncoder.write(e.client),this.rightClockEncoder.write(e.clock)}writeClient(e){this.clientEncoder.write(e)}writeInfo(e){this.infoEncoder.write(e)}writeString(e){this.stringEncoder.write(e)}writeParentInfo(e){this.parentInfoEncoder.write(e?1:0)}writeTypeRef(e){this.typeRefEncoder.write(e)}writeLen(e){this.lenEncoder.write(e)}writeAny(e){ps(this.restEncoder,e)}writeBuf(e){Te(this.restEncoder,e)}writeJSON(e){ps(this.restEncoder,e)}writeKey(e){const n=this.keyMap.get(e);n===void 0?(this.keyClockEncoder.write(this.keyClock++),this.stringEncoder.write(e)):this.keyClockEncoder.write(n)}}const jp=(t,e,n,s)=>{s=gn(s,e[0].id.clock);const r=Ct(e,s);P(t.restEncoder,e.length-r),t.writeClient(n),P(t.restEncoder,s);const i=e[r];i.write(t,s-i.id.clock);for(let l=r+1;l<e.length;l++)e[l].write(t,0)},ro=(t,e,n)=>{const s=new Map;n.forEach((r,i)=>{Ae(e,i)>r&&s.set(i,r)}),xr(e).forEach((r,i)=>{n.has(i)||s.set(i,0)}),P(t.restEncoder,s.size),Pt(s.entries()).sort((r,i)=>i[0]-r[0]).forEach(([r,i])=>{jp(t,e.clients.get(r),r,i)})},vp=(t,e)=>{const n=tt(),s=ee(t.restDecoder);for(let r=0;r<s;r++){const i=ee(t.restDecoder),l=new Array(i),a=t.readClient();let c=ee(t.restDecoder);n.set(a,{i:0,refs:l});for(let u=0;u<i;u++){const h=t.readInfo();switch(dr&h){case 0:{const d=t.readLen();l[u]=new ut(se(a,c),d),c+=d;break}case 10:{const d=ee(t.restDecoder);l[u]=new dt(se(a,c),d),c+=d;break}default:{const d=(h&(It|lt))===0,p=new be(se(a,c),null,(h&lt)===lt?t.readLeftID():null,null,(h&It)===It?t.readRightID():null,d?t.readParentInfo()?e.get(t.readString()):t.readLeftID():null,d&&(h&hs)===hs?t.readString():null,Tc(t,h));l[u]=p,c+=p.length}}}}return n},Ep=(t,e,n)=>{const s=[];let r=Pt(n.keys()).sort((w,g)=>w-g);if(r.length===0)return null;const i=()=>{if(r.length===0)return null;let w=n.get(r[r.length-1]);for(;w.refs.length===w.i;)if(r.pop(),r.length>0)w=n.get(r[r.length-1]);else return null;return w};let l=i();if(l===null)return null;const a=new lc,c=new Map,u=(w,g)=>{const S=c.get(w);(S==null||S>g)&&c.set(w,g)};let h=l.refs[l.i++];const d=new Map,p=()=>{for(const w of s){const g=w.id.client,S=n.get(g);S?(S.i--,a.clients.set(g,S.refs.slice(S.i)),n.delete(g),S.i=0,S.refs=[]):a.clients.set(g,[w]),r=r.filter(y=>y!==g)}s.length=0};for(;;){if(h.constructor!==dt){const g=Et(d,h.id.client,()=>Ae(e,h.id.client))-h.id.clock;if(g<0)s.push(h),u(h.id.client,h.id.clock-1),p();else{const S=h.getMissing(t,e);if(S!==null){s.push(h);const y=n.get(S)||{refs:[],i:0};if(y.refs.length===y.i)u(S,Ae(e,S)),p();else{h=y.refs[y.i++];continue}}else(g===0||g<h.length)&&(h.integrate(t,g),d.set(h.id.client,h.id.clock+h.length))}}if(s.length>0)h=s.pop();else if(l!==null&&l.i<l.refs.length)h=l.refs[l.i++];else{if(l=i(),l===null)break;h=l.refs[l.i++]}}if(a.clients.size>0){const w=new fn;return ro(w,a,new Map),P(w.restEncoder,0),{missing:c,update:w.toUint8Array()}}return null},Dp=(t,e)=>ro(t,e.doc.store,e.beforeState),_p=(t,e,n,s=new Kn(t))=>ge(e,r=>{r.local=!1;let i=!1;const l=r.doc,a=l.store,c=vp(s,l),u=Ep(r,a,c),h=a.pendingStructs;if(h){for(const[p,w]of h.missing)if(w<Ae(a,p)){i=!0;break}if(u){for(const[p,w]of u.missing){const g=h.missing.get(p);(g==null||g>w)&&h.missing.set(p,w)}h.update=nr([h.update,u.update])}}else a.pendingStructs=u;const d=Dl(s,r,a);if(a.pendingDs){const p=new Kn(en(a.pendingDs));ee(p.restDecoder);const w=Dl(p,r,a);d&&w?a.pendingDs=nr([d,w]):a.pendingDs=d||w}else a.pendingDs=d;if(i){const p=a.pendingStructs.update;a.pendingStructs=null,ec(r.doc,p)}},n,!1),ec=(t,e,n,s=Kn)=>{const r=en(e);_p(r,t,n,new s(r))},tc=(t,e,n)=>ec(t,e,n,Xa),Tp=(t,e,n=new Map)=>{ro(t,e.store,n),Zn(t,kp(e.store))},Lp=(t,e=new Uint8Array([0]),n=new fn)=>{const s=nc(e);Tp(n,t,s);const r=[n.toUint8Array()];if(t.store.pendingDs&&r.push(t.store.pendingDs),t.store.pendingStructs&&r.push(Gp(t.store.pendingStructs.update,e)),r.length>1){if(n.constructor===vs)return Kp(r.map((i,l)=>l===0?i:Xp(i)));if(n.constructor===fn)return nr(r)}return r[0]},io=(t,e)=>Lp(t,e,new vs),Rp=t=>{const e=new Map,n=ee(t.restDecoder);for(let s=0;s<n;s++){const r=ee(t.restDecoder),i=ee(t.restDecoder);e.set(r,i)}return e},nc=t=>Rp(new Ya(en(t))),sc=(t,e)=>(P(t.restEncoder,e.size),Pt(e.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{P(t.restEncoder,n),P(t.restEncoder,s)}),t),Ap=(t,e)=>sc(t,xr(e.store)),Np=(t,e=new Za)=>(t instanceof Map?sc(e,t):Ap(e,t),e.toUint8Array()),Op=t=>Np(t,new Qa);class Fp{constructor(){this.l=[]}}const _l=()=>new Fp,Tl=(t,e)=>t.l.push(e),Ll=(t,e)=>{const n=t.l,s=n.length;t.l=n.filter(r=>e!==r),s===t.l.length&&console.error("[yjs] Tried to remove event handler that doesn't exist.")},rc=(t,e,n)=>Gi(t.l,[e,n]);class Fn{constructor(e,n){this.client=e,this.clock=n}}const Ln=(t,e)=>t===e||t!==null&&e!==null&&t.client===e.client&&t.clock===e.clock,se=(t,e)=>new Fn(t,e),ic=t=>{for(const[e,n]of t.doc.share.entries())if(n===t)return e;throw at()},tr=(t,e)=>{for(;e!==null;){if(e.parent===t)return!0;e=e.parent._item}return!1};class oc{constructor(e,n,s,r=0){this.type=e,this.tname=n,this.item=s,this.assoc=r}}const Nw=t=>{const e={};return t.type&&(e.type=t.type),t.tname&&(e.tname=t.tname),t.item&&(e.item=t.item),t.assoc!=null&&(e.assoc=t.assoc),e},Ow=t=>new oc(t.type==null?null:se(t.type.client,t.type.clock),t.tname??null,t.item==null?null:se(t.item.client,t.item.clock),t.assoc==null?0:t.assoc);class Mp{constructor(e,n,s=0){this.type=e,this.index=n,this.assoc=s}}const $p=(t,e,n=0)=>new Mp(t,e,n),Ps=(t,e,n)=>{let s=null,r=null;return t._item===null?r=ic(t):s=se(t._item.id.client,t._item.id.clock),new oc(s,r,e,n)},Fw=(t,e,n=0)=>{let s=t._start;if(n<0){if(e===0)return Ps(t,null,n);e--}for(;s!==null;){if(!s.deleted&&s.countable){if(s.length>e)return Ps(t,se(s.id.client,s.id.clock+e),n);e-=s.length}if(s.right===null&&n<0)return Ps(t,s.lastId,n);s=s.right}return Ps(t,null,n)},Ip=(t,e)=>{const n=Mn(t,e),s=e.clock-n.id.clock;return{item:n,diff:s}},Mw=(t,e,n=!0)=>{const s=e.store,r=t.item,i=t.type,l=t.tname,a=t.assoc;let c=null,u=0;if(r!==null){if(Ae(s,r.client)<=r.clock)return null;const h=n?Li(s,r):Ip(s,r),d=h.item;if(!(d instanceof be))return null;if(c=d.parent,c._item===null||!c._item.deleted){u=d.deleted||!d.countable?0:h.diff+(a>=0?0:1);let p=d.left;for(;p!==null;)!p.deleted&&p.countable&&(u+=p.length),p=p.left}}else{if(l!==null)c=e.get(l);else if(i!==null){if(Ae(s,i.client)<=i.clock)return null;const{item:h}=n?Li(s,i):{item:Mn(s,i)};if(h instanceof be&&h.content instanceof _t)c=h.content.type;else return null}else throw at();a>=0?u=c._length:u=0}return $p(c,u,t.assoc)},$w=(t,e)=>t===e||t!==null&&e!==null&&t.tname===e.tname&&Ln(t.item,e.item)&&Ln(t.type,e.type)&&t.assoc===e.assoc,_n=(t,e)=>e===void 0?!t.deleted:e.sv.has(t.id.client)&&(e.sv.get(t.id.client)||0)>t.id.clock&&!js(e.ds,t.id),Di=(t,e)=>{const n=Et(t.meta,Di,Xt),s=t.doc.store;n.has(e)||(e.sv.forEach((r,i)=>{r<Ae(s,i)&&et(t,se(i,r))}),Hn(t,e.ds,r=>{}),n.add(e))};class lc{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const xr=t=>{const e=new Map;return t.clients.forEach((n,s)=>{const r=n[n.length-1];e.set(s,r.id.clock+r.length)}),e},Ae=(t,e)=>{const n=t.clients.get(e);if(n===void 0)return 0;const s=n[n.length-1];return s.id.clock+s.length},ac=(t,e)=>{let n=t.clients.get(e.id.client);if(n===void 0)n=[],t.clients.set(e.id.client,n);else{const s=n[n.length-1];if(s.id.clock+s.length!==e.id.clock)throw at()}n.push(e)},Ct=(t,e)=>{let n=0,s=t.length-1,r=t[s],i=r.id.clock;if(i===e)return s;let l=bt(e/(i+r.length-1)*s);for(;n<=s;){if(r=t[l],i=r.id.clock,i<=e){if(e<i+r.length)return l;n=l+1}else s=l-1;l=bt((n+s)/2)}throw at()},Pp=(t,e)=>{const n=t.clients.get(e.client);return n[Ct(n,e.clock)]},Mn=Pp,_i=(t,e,n)=>{const s=Ct(e,n),r=e[s];return r.id.clock<n&&r instanceof be?(e.splice(s+1,0,ar(t,r,n-r.id.clock)),s+1):s},et=(t,e)=>{const n=t.doc.store.clients.get(e.client);return n[_i(t,n,e.clock)]},Rl=(t,e,n)=>{const s=e.clients.get(n.client),r=Ct(s,n.clock),i=s[r];return n.clock!==i.id.clock+i.length-1&&i.constructor!==ut&&s.splice(r+1,0,ar(t,i,n.clock-i.id.clock+1)),i},Up=(t,e,n)=>{const s=t.clients.get(e.id.client);s[Ct(s,e.id.clock)]=n},cc=(t,e,n,s,r)=>{if(s===0)return;const i=n+s;let l=_i(t,e,n),a;do a=e[l++],i<a.id.clock+a.length&&_i(t,e,i),r(a);while(l<e.length&&e[l].id.clock<i)};class zp{constructor(e,n,s){this.doc=e,this.deleteSet=new Qn,this.beforeState=xr(e.store),this.afterState=new Map,this.changed=new Map,this.changedParentTypes=new Map,this._mergeStructs=[],this.origin=n,this.meta=new Map,this.local=s,this.subdocsAdded=new Set,this.subdocsRemoved=new Set,this.subdocsLoaded=new Set,this._needFormattingCleanup=!1}}const Al=(t,e)=>e.deleteSet.clients.size===0&&!mh(e.afterState,(n,s)=>e.beforeState.get(s)!==n)?!1:(no(e.deleteSet),Dp(t,e),Zn(t,e.deleteSet),!0),Nl=(t,e,n)=>{const s=e._item;(s===null||s.id.clock<(t.beforeState.get(s.id.client)||0)&&!s.deleted)&&Et(t.changed,e,Xt).add(n)},Hs=(t,e)=>{let n=t[e],s=t[e-1],r=e;for(;r>0;n=s,s=t[--r-1]){if(s.deleted===n.deleted&&s.constructor===n.constructor&&s.mergeWith(n)){n instanceof be&&n.parentSub!==null&&n.parent._map.get(n.parentSub)===n&&n.parent._map.set(n.parentSub,s);continue}break}const i=e-r;return i&&t.splice(e+1-i,i),i},Bp=(t,e,n)=>{for(const[s,r]of t.clients.entries()){const i=e.clients.get(s);for(let l=r.length-1;l>=0;l--){const a=r[l],c=a.clock+a.len;for(let u=Ct(i,a.clock),h=i[u];u<i.length&&h.id.clock<c;h=i[++u]){const d=i[u];if(a.clock+a.len<=d.id.clock)break;d instanceof be&&d.deleted&&!d.keep&&n(d)&&d.gc(e,!1)}}}},qp=(t,e)=>{t.clients.forEach((n,s)=>{const r=e.clients.get(s);for(let i=n.length-1;i>=0;i--){const l=n[i],a=zi(r.length-1,1+Ct(r,l.clock+l.len-1));for(let c=a,u=r[c];c>0&&u.id.clock>=l.clock;u=r[c])c-=1+Hs(r,c)}})},uc=(t,e)=>{if(e<t.length){const n=t[e],s=n.doc,r=s.store,i=n.deleteSet,l=n._mergeStructs;try{no(i),n.afterState=xr(n.doc.store),s.emit("beforeObserverCalls",[n,s]);const a=[];n.changed.forEach((c,u)=>a.push(()=>{(u._item===null||!u._item.deleted)&&u._callObserver(n,c)})),a.push(()=>{n.changedParentTypes.forEach((c,u)=>{u._dEH.l.length>0&&(u._item===null||!u._item.deleted)&&(c=c.filter(h=>h.target._item===null||!h.target._item.deleted),c.forEach(h=>{h.currentTarget=u,h._path=null}),c.sort((h,d)=>h.path.length-d.path.length),a.push(()=>{rc(u._dEH,c,n)}))}),a.push(()=>s.emit("afterTransaction",[n,s])),a.push(()=>{n._needFormattingCleanup&&dm(n)})}),Gi(a,[])}finally{s.gc&&Bp(i,r,s.gcFilter),qp(i,r),n.afterState.forEach((h,d)=>{const p=n.beforeState.get(d)||0;if(p!==h){const w=r.clients.get(d),g=gn(Ct(w,p),1);for(let S=w.length-1;S>=g;)S-=1+Hs(w,S)}});for(let h=l.length-1;h>=0;h--){const{client:d,clock:p}=l[h].id,w=r.clients.get(d),g=Ct(w,p);g+1<w.length&&Hs(w,g+1)>1||g>0&&Hs(w,g)}if(!n.local&&n.afterState.get(s.clientID)!==n.beforeState.get(s.clientID)&&(yp(to,Ba,"[yjs] ",qa,Wa,"Changed the client-id because another client seems to be using it."),s.clientID=Ga()),s.emit("afterTransactionCleanup",[n,s]),s._observers.has("update")){const h=new vs;Al(h,n)&&s.emit("update",[h.toUint8Array(),n.origin,s,n])}if(s._observers.has("updateV2")){const h=new fn;Al(h,n)&&s.emit("updateV2",[h.toUint8Array(),n.origin,s,n])}const{subdocsAdded:a,subdocsLoaded:c,subdocsRemoved:u}=n;(a.size>0||u.size>0||c.size>0)&&(a.forEach(h=>{h.clientID=s.clientID,h.collectionid==null&&(h.collectionid=s.collectionid),s.subdocs.add(h)}),u.forEach(h=>s.subdocs.delete(h)),s.emit("subdocs",[{loaded:c,added:a,removed:u},s,n]),u.forEach(h=>h.destroy())),t.length<=e+1?(s._transactionCleanups=[],s.emit("afterAllTransactions",[s,t])):uc(t,e+1)}}},ge=(t,e,n=null,s=!0)=>{const r=t._transactionCleanups;let i=!1,l=null;t._transaction===null&&(i=!0,t._transaction=new zp(t,n,s),r.push(t._transaction),r.length===1&&t.emit("beforeAllTransactions",[t]),t.emit("beforeTransaction",[t._transaction,t]));try{l=e(t._transaction)}finally{if(i){const a=t._transaction===r[0];t._transaction=null,a&&uc(r,0)}}return l};class Wp{constructor(e,n){this.insertions=n,this.deletions=e,this.meta=new Map}}const Ol=(t,e,n)=>{Hn(t,n.deletions,s=>{s instanceof be&&e.scope.some(r=>r===t.doc||tr(r,s))&&po(s,!1)})},Fl=(t,e,n)=>{let s=null;const r=t.doc,i=t.scope;ge(r,a=>{for(;e.length>0&&t.currStackItem===null;){const c=r.store,u=e.pop(),h=new Set,d=[];let p=!1;Hn(a,u.insertions,w=>{if(w instanceof be){if(w.redone!==null){let{item:g,diff:S}=Li(c,w.id);S>0&&(g=et(a,se(g.id.client,g.id.clock+S))),w=g}!w.deleted&&i.some(g=>g===a.doc||tr(g,w))&&d.push(w)}}),Hn(a,u.deletions,w=>{w instanceof be&&i.some(g=>g===a.doc||tr(g,w))&&!js(u.insertions,w.id)&&h.add(w)}),h.forEach(w=>{p=_c(a,w,h,u.insertions,t.ignoreRemoteMapChanges,t)!==null||p});for(let w=d.length-1;w>=0;w--){const g=d[w];t.deleteFilter(g)&&(g.delete(a),p=!0)}t.currStackItem=p?u:null}a.changed.forEach((c,u)=>{c.has(null)&&u._searchMarker&&(u._searchMarker.length=0)}),s=a},t);const l=t.currStackItem;if(l!=null){const a=s.changedParentTypes;t.emit("stack-item-popped",[{stackItem:l,type:n,changedParentTypes:a,origin:t},t]),t.currStackItem=null}return l};class Vp extends Ui{constructor(e,{captureTimeout:n=500,captureTransaction:s=c=>!0,deleteFilter:r=()=>!0,trackedOrigins:i=new Set([null]),ignoreRemoteMapChanges:l=!1,doc:a=Bn(e)?e[0].doc:e instanceof wn?e:e.doc}={}){super(),this.scope=[],this.doc=a,this.addToScope(e),this.deleteFilter=r,i.add(this),this.trackedOrigins=i,this.captureTransaction=s,this.undoStack=[],this.redoStack=[],this.undoing=!1,this.redoing=!1,this.currStackItem=null,this.lastChange=0,this.ignoreRemoteMapChanges=l,this.captureTimeout=n,this.afterTransactionHandler=c=>{if(!this.captureTransaction(c)||!this.scope.some(y=>c.changedParentTypes.has(y)||y===this.doc)||!this.trackedOrigins.has(c.origin)&&(!c.origin||!this.trackedOrigins.has(c.origin.constructor)))return;const u=this.undoing,h=this.redoing,d=u?this.redoStack:this.undoStack;u?this.stopCapturing():h||this.clear(!1,!0);const p=new Qn;c.afterState.forEach((y,C)=>{const _=c.beforeState.get(C)||0,q=y-_;q>0&&ys(p,C,_,q)});const w=Qt();let g=!1;if(this.lastChange>0&&w-this.lastChange<this.captureTimeout&&d.length>0&&!u&&!h){const y=d[d.length-1];y.deletions=Ei([y.deletions,c.deleteSet]),y.insertions=Ei([y.insertions,p])}else d.push(new Wp(c.deleteSet,p)),g=!0;!u&&!h&&(this.lastChange=w),Hn(c,c.deleteSet,y=>{y instanceof be&&this.scope.some(C=>C===c.doc||tr(C,y))&&po(y,!0)});const S=[{stackItem:d[d.length-1],origin:c.origin,type:u?"redo":"undo",changedParentTypes:c.changedParentTypes},this];g?this.emit("stack-item-added",S):this.emit("stack-item-updated",S)},this.doc.on("afterTransaction",this.afterTransactionHandler),this.doc.on("destroy",()=>{this.destroy()})}addToScope(e){const n=new Set(this.scope);e=Bn(e)?e:[e],e.forEach(s=>{n.has(s)||(n.add(s),(s instanceof ze?s.doc!==this.doc:s!==this.doc)&&Ha("[yjs#509] Not same Y.Doc"),this.scope.push(s))})}addTrackedOrigin(e){this.trackedOrigins.add(e)}removeTrackedOrigin(e){this.trackedOrigins.delete(e)}clear(e=!0,n=!0){(e&&this.canUndo()||n&&this.canRedo())&&this.doc.transact(s=>{e&&(this.undoStack.forEach(r=>Ol(s,this,r)),this.undoStack=[]),n&&(this.redoStack.forEach(r=>Ol(s,this,r)),this.redoStack=[]),this.emit("stack-cleared",[{undoStackCleared:e,redoStackCleared:n}])})}stopCapturing(){this.lastChange=0}undo(){this.undoing=!0;let e;try{e=Fl(this,this.undoStack,"undo")}finally{this.undoing=!1}return e}redo(){this.redoing=!0;let e;try{e=Fl(this,this.redoStack,"redo")}finally{this.redoing=!1}return e}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}destroy(){this.trackedOrigins.delete(this),this.doc.off("afterTransaction",this.afterTransactionHandler),super.destroy()}}function*Hp(t){const e=ee(t.restDecoder);for(let n=0;n<e;n++){const s=ee(t.restDecoder),r=t.readClient();let i=ee(t.restDecoder);for(let l=0;l<s;l++){const a=t.readInfo();if(a===10){const c=ee(t.restDecoder);yield new dt(se(r,i),c),i+=c}else if((dr&a)!==0){const c=(a&(It|lt))===0,u=new be(se(r,i),null,(a&lt)===lt?t.readLeftID():null,null,(a&It)===It?t.readRightID():null,c?t.readParentInfo()?t.readString():t.readLeftID():null,c&&(a&hs)===hs?t.readString():null,Tc(t,a));yield u,i+=u.length}else{const c=t.readLen();yield new ut(se(r,i),c),i+=c}}}}class oo{constructor(e,n){this.gen=Hp(e),this.curr=null,this.done=!1,this.filterSkips=n,this.next()}next(){do this.curr=this.gen.next().value||null;while(this.filterSkips&&this.curr!==null&&this.curr.constructor===dt);return this.curr}}class lo{constructor(e){this.currClient=0,this.startClock=0,this.written=0,this.encoder=e,this.clientStructs=[]}}const Kp=t=>nr(t,Xa,vs),Jp=(t,e)=>{if(t.constructor===ut){const{client:n,clock:s}=t.id;return new ut(se(n,s+e),t.length-e)}else if(t.constructor===dt){const{client:n,clock:s}=t.id;return new dt(se(n,s+e),t.length-e)}else{const n=t,{client:s,clock:r}=n.id;return new be(se(s,r+e),null,se(s,r+e-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(e))}},nr=(t,e=Kn,n=fn)=>{if(t.length===1)return t[0];const s=t.map(h=>new e(en(h)));let r=s.map(h=>new oo(h,!0)),i=null;const l=new n,a=new lo(l);for(;r=r.filter(p=>p.curr!==null),r.sort((p,w)=>{if(p.curr.id.client===w.curr.id.client){const g=p.curr.id.clock-w.curr.id.clock;return g===0?p.curr.constructor===w.curr.constructor?0:p.curr.constructor===dt?1:-1:g}else return w.curr.id.client-p.curr.id.client}),r.length!==0;){const h=r[0],d=h.curr.id.client;if(i!==null){let p=h.curr,w=!1;for(;p!==null&&p.id.clock+p.length<=i.struct.id.clock+i.struct.length&&p.id.client>=i.struct.id.client;)p=h.next(),w=!0;if(p===null||p.id.client!==d||w&&p.id.clock>i.struct.id.clock+i.struct.length)continue;if(d!==i.struct.id.client)Jt(a,i.struct,i.offset),i={struct:p,offset:0},h.next();else if(i.struct.id.clock+i.struct.length<p.id.clock)if(i.struct.constructor===dt)i.struct.length=p.id.clock+p.length-i.struct.id.clock;else{Jt(a,i.struct,i.offset);const g=p.id.clock-i.struct.id.clock-i.struct.length;i={struct:new dt(se(d,i.struct.id.clock+i.struct.length),g),offset:0}}else{const g=i.struct.id.clock+i.struct.length-p.id.clock;g>0&&(i.struct.constructor===dt?i.struct.length-=g:p=Jp(p,g)),i.struct.mergeWith(p)||(Jt(a,i.struct,i.offset),i={struct:p,offset:0},h.next())}}else i={struct:h.curr,offset:0},h.next();for(let p=h.curr;p!==null&&p.id.client===d&&p.id.clock===i.struct.id.clock+i.struct.length&&p.constructor!==dt;p=h.next())Jt(a,i.struct,i.offset),i={struct:p,offset:0}}i!==null&&(Jt(a,i.struct,i.offset),i=null),ao(a);const c=s.map(h=>so(h)),u=Ei(c);return Zn(l,u),l.toUint8Array()},Gp=(t,e,n=Kn,s=fn)=>{const r=nc(e),i=new s,l=new lo(i),a=new n(en(t)),c=new oo(a,!1);for(;c.curr;){const h=c.curr,d=h.id.client,p=r.get(d)||0;if(c.curr.constructor===dt){c.next();continue}if(h.id.clock+h.length>p)for(Jt(l,h,gn(p-h.id.clock,0)),c.next();c.curr&&c.curr.id.client===d;)Jt(l,c.curr,0),c.next();else for(;c.curr&&c.curr.id.client===d&&c.curr.id.clock+c.curr.length<=p;)c.next()}ao(l);const u=so(a);return Zn(i,u),i.toUint8Array()},dc=t=>{t.written>0&&(t.clientStructs.push({written:t.written,restEncoder:me(t.encoder.restEncoder)}),t.encoder.restEncoder=Le(),t.written=0)},Jt=(t,e,n)=>{t.written>0&&t.currClient!==e.id.client&&dc(t),t.written===0&&(t.currClient=e.id.client,t.encoder.writeClient(e.id.client),P(t.encoder.restEncoder,e.id.clock+n)),e.write(t.encoder,n),t.written++},ao=t=>{dc(t);const e=t.encoder.restEncoder;P(e,t.clientStructs.length);for(let n=0;n<t.clientStructs.length;n++){const s=t.clientStructs[n];P(e,s.written),hr(e,s.restEncoder)}},Yp=(t,e,n,s)=>{const r=new n(en(t)),i=new oo(r,!1),l=new s,a=new lo(l);for(let u=i.curr;u!==null;u=i.next())Jt(a,e(u),0);ao(a);const c=so(r);return Zn(l,c),l.toUint8Array()},Xp=t=>Yp(t,lf,Kn,vs),Ml="You must not compute changes after the event-handler fired.";class Sr{constructor(e,n){this.target=e,this.currentTarget=e,this.transaction=n,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||(this._path=Qp(this.currentTarget,this.target))}deletes(e){return js(this.transaction.deleteSet,e.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw xt(Ml);const e=new Map,n=this.target;this.transaction.changed.get(n).forEach(r=>{if(r!==null){const i=n._map.get(r);let l,a;if(this.adds(i)){let c=i.left;for(;c!==null&&this.adds(c);)c=c.left;if(this.deletes(i))if(c!==null&&this.deletes(c))l="delete",a=Yr(c.content.getContent());else return;else c!==null&&this.deletes(c)?(l="update",a=Yr(c.content.getContent())):(l="add",a=void 0)}else if(this.deletes(i))l="delete",a=Yr(i.content.getContent());else return;e.set(r,{action:l,oldValue:a})}}),this._keys=e}return this._keys}get delta(){return this.changes.delta}adds(e){return e.id.clock>=(this.transaction.beforeState.get(e.id.client)||0)}get changes(){let e=this._changes;if(e===null){if(this.transaction.doc._transactionCleanups.length===0)throw xt(Ml);const n=this.target,s=Xt(),r=Xt(),i=[];if(e={added:s,deleted:r,delta:i,keys:this.keys},this.transaction.changed.get(n).has(null)){let a=null;const c=()=>{a&&i.push(a)};for(let u=n._start;u!==null;u=u.right)u.deleted?this.deletes(u)&&!this.adds(u)&&((a===null||a.delete===void 0)&&(c(),a={delete:0}),a.delete+=u.length,r.add(u)):this.adds(u)?((a===null||a.insert===void 0)&&(c(),a={insert:[]}),a.insert=a.insert.concat(u.content.getContent()),s.add(u)):((a===null||a.retain===void 0)&&(c(),a={retain:0}),a.retain+=u.length);a!==null&&a.retain===void 0&&c()}this._changes=e}return e}}const Qp=(t,e)=>{const n=[];for(;e._item!==null&&e!==t;){if(e._item.parentSub!==null)n.unshift(e._item.parentSub);else{let s=0,r=e._item.parent._start;for(;r!==e._item&&r!==null;)!r.deleted&&r.countable&&(s+=r.length),r=r.right;n.unshift(s)}e=e._item.parent}return n},Xe=()=>{Ha("Invalid access: Add Yjs type to a document before reading data.")},hc=80;let co=0;class Zp{constructor(e,n){e.marker=!0,this.p=e,this.index=n,this.timestamp=co++}}const em=t=>{t.timestamp=co++},fc=(t,e,n)=>{t.p.marker=!1,t.p=e,e.marker=!0,t.index=n,t.timestamp=co++},tm=(t,e,n)=>{if(t.length>=hc){const s=t.reduce((r,i)=>r.timestamp<i.timestamp?r:i);return fc(s,e,n),s}else{const s=new Zp(e,n);return t.push(s),s}},kr=(t,e)=>{if(t._start===null||e===0||t._searchMarker===null)return null;const n=t._searchMarker.length===0?null:t._searchMarker.reduce((i,l)=>qs(e-i.index)<qs(e-l.index)?i:l);let s=t._start,r=0;for(n!==null&&(s=n.p,r=n.index,em(n));s.right!==null&&r<e;){if(!s.deleted&&s.countable){if(e<r+s.length)break;r+=s.length}s=s.right}for(;s.left!==null&&r>e;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);for(;s.left!==null&&s.left.id.client===s.id.client&&s.left.id.clock+s.left.length===s.id.clock;)s=s.left,!s.deleted&&s.countable&&(r-=s.length);return n!==null&&qs(n.index-r)<s.parent.length/hc?(fc(n,s,r),n):tm(t._searchMarker,s,r)},bs=(t,e,n)=>{for(let s=t.length-1;s>=0;s--){const r=t[s];if(n>0){let i=r.p;for(i.marker=!1;i&&(i.deleted||!i.countable);)i=i.left,i&&!i.deleted&&i.countable&&(r.index-=i.length);if(i===null||i.marker===!0){t.splice(s,1);continue}r.p=i,i.marker=!0}(e<r.index||n>0&&e===r.index)&&(r.index=gn(e,r.index+n))}},Cr=(t,e,n)=>{const s=t,r=e.changedParentTypes;for(;Et(r,t,()=>[]).push(n),t._item!==null;)t=t._item.parent;rc(s._eH,n,e)};class ze{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=_l(),this._dEH=_l(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(e,n){this.doc=e,this._item=n}_copy(){throw yt()}clone(){throw yt()}_write(e){}get _first(){let e=this._start;for(;e!==null&&e.deleted;)e=e.right;return e}_callObserver(e,n){!e.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(e){Tl(this._eH,e)}observeDeep(e){Tl(this._dEH,e)}unobserve(e){Ll(this._eH,e)}unobserveDeep(e){Ll(this._dEH,e)}toJSON(){}}const pc=(t,e,n)=>{t.doc??Xe(),e<0&&(e=t._length+e),n<0&&(n=t._length+n);let s=n-e;const r=[];let i=t._start;for(;i!==null&&s>0;){if(i.countable&&!i.deleted){const l=i.content.getContent();if(l.length<=e)e-=l.length;else{for(let a=e;a<l.length&&s>0;a++)r.push(l[a]),s--;e=0}}i=i.right}return r},mc=t=>{t.doc??Xe();const e=[];let n=t._start;for(;n!==null;){if(n.countable&&!n.deleted){const s=n.content.getContent();for(let r=0;r<s.length;r++)e.push(s[r])}n=n.right}return e},xs=(t,e)=>{let n=0,s=t._start;for(t.doc??Xe();s!==null;){if(s.countable&&!s.deleted){const r=s.content.getContent();for(let i=0;i<r.length;i++)e(r[i],n++,t)}s=s.right}},gc=(t,e)=>{const n=[];return xs(t,(s,r)=>{n.push(e(s,r,t))}),n},nm=t=>{let e=t._start,n=null,s=0;return{[Symbol.iterator](){return this},next:()=>{if(n===null){for(;e!==null&&e.deleted;)e=e.right;if(e===null)return{done:!0,value:void 0};n=e.content.getContent(),s=0,e=e.right}const r=n[s++];return n.length<=s&&(n=null),{done:!1,value:r}}}},wc=(t,e)=>{t.doc??Xe();const n=kr(t,e);let s=t._start;for(n!==null&&(s=n.p,e-=n.index);s!==null;s=s.right)if(!s.deleted&&s.countable){if(e<s.length)return s.content.getContent()[e];e-=s.length}},sr=(t,e,n,s)=>{let r=n;const i=t.doc,l=i.clientID,a=i.store,c=n===null?e._start:n.right;let u=[];const h=()=>{u.length>0&&(r=new be(se(l,Ae(a,l)),r,r&&r.lastId,c,c&&c.id,e,null,new mn(u)),r.integrate(t,0),u=[])};s.forEach(d=>{if(d===null)u.push(d);else switch(d.constructor){case Number:case Object:case Boolean:case Array:case String:u.push(d);break;default:switch(h(),d.constructor){case Uint8Array:case ArrayBuffer:r=new be(se(l,Ae(a,l)),r,r&&r.lastId,c,c&&c.id,e,null,new Es(new Uint8Array(d))),r.integrate(t,0);break;case wn:r=new be(se(l,Ae(a,l)),r,r&&r.lastId,c,c&&c.id,e,null,new Ds(d)),r.integrate(t,0);break;default:if(d instanceof ze)r=new be(se(l,Ae(a,l)),r,r&&r.lastId,c,c&&c.id,e,null,new _t(d)),r.integrate(t,0);else throw new Error("Unexpected content type in insert operation")}}}),h()},yc=()=>xt("Length exceeded!"),bc=(t,e,n,s)=>{if(n>e._length)throw yc();if(n===0)return e._searchMarker&&bs(e._searchMarker,n,s.length),sr(t,e,null,s);const r=n,i=kr(e,n);let l=e._start;for(i!==null&&(l=i.p,n-=i.index,n===0&&(l=l.prev,n+=l&&l.countable&&!l.deleted?l.length:0));l!==null;l=l.right)if(!l.deleted&&l.countable){if(n<=l.length){n<l.length&&et(t,se(l.id.client,l.id.clock+n));break}n-=l.length}return e._searchMarker&&bs(e._searchMarker,r,s.length),sr(t,e,l,s)},sm=(t,e,n)=>{let r=(e._searchMarker||[]).reduce((i,l)=>l.index>i.index?l:i,{index:0,p:e._start}).p;if(r)for(;r.right;)r=r.right;return sr(t,e,r,n)},xc=(t,e,n,s)=>{if(s===0)return;const r=n,i=s,l=kr(e,n);let a=e._start;for(l!==null&&(a=l.p,n-=l.index);a!==null&&n>0;a=a.right)!a.deleted&&a.countable&&(n<a.length&&et(t,se(a.id.client,a.id.clock+n)),n-=a.length);for(;s>0&&a!==null;)a.deleted||(s<a.length&&et(t,se(a.id.client,a.id.clock+s)),a.delete(t),s-=a.length),a=a.right;if(s>0)throw yc();e._searchMarker&&bs(e._searchMarker,r,-i+s)},rr=(t,e,n)=>{const s=e._map.get(n);s!==void 0&&s.delete(t)},uo=(t,e,n,s)=>{const r=e._map.get(n)||null,i=t.doc,l=i.clientID;let a;if(s==null)a=new mn([s]);else switch(s.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:a=new mn([s]);break;case Uint8Array:a=new Es(s);break;case wn:a=new Ds(s);break;default:if(s instanceof ze)a=new _t(s);else throw new Error("Unexpected content type")}new be(se(l,Ae(i.store,l)),r,r&&r.lastId,null,null,e,n,a).integrate(t,0)},ho=(t,e)=>{t.doc??Xe();const n=t._map.get(e);return n!==void 0&&!n.deleted?n.content.getContent()[n.length-1]:void 0},Sc=t=>{const e={};return t.doc??Xe(),t._map.forEach((n,s)=>{n.deleted||(e[s]=n.content.getContent()[n.length-1])}),e},kc=(t,e)=>{t.doc??Xe();const n=t._map.get(e);return n!==void 0&&!n.deleted},rm=(t,e)=>{const n={};return t._map.forEach((s,r)=>{let i=s;for(;i!==null&&(!e.sv.has(i.id.client)||i.id.clock>=(e.sv.get(i.id.client)||0));)i=i.left;i!==null&&_n(i,e)&&(n[r]=i.content.getContent()[i.length-1])}),n},Us=t=>(t.doc??Xe(),bp(t._map.entries(),e=>!e[1].deleted));class im extends Sr{}class $n extends ze{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(e){const n=new $n;return n.push(e),n}_integrate(e,n){super._integrate(e,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new $n}clone(){const e=new $n;return e.insert(0,this.toArray().map(n=>n instanceof ze?n.clone():n)),e}get length(){return this.doc??Xe(),this._length}_callObserver(e,n){super._callObserver(e,n),Cr(this,e,new im(this,e))}insert(e,n){this.doc!==null?ge(this.doc,s=>{bc(s,this,e,n)}):this._prelimContent.splice(e,0,...n)}push(e){this.doc!==null?ge(this.doc,n=>{sm(n,this,e)}):this._prelimContent.push(...e)}unshift(e){this.insert(0,e)}delete(e,n=1){this.doc!==null?ge(this.doc,s=>{xc(s,this,e,n)}):this._prelimContent.splice(e,n)}get(e){return wc(this,e)}toArray(){return mc(this)}slice(e=0,n=this.length){return pc(this,e,n)}toJSON(){return this.map(e=>e instanceof ze?e.toJSON():e)}map(e){return gc(this,e)}forEach(e){xs(this,e)}[Symbol.iterator](){return nm(this)}_write(e){e.writeTypeRef(Lm)}}const om=t=>new $n;class lm extends Sr{constructor(e,n,s){super(e,n),this.keysChanged=s}}class Jn extends ze{constructor(e){super(),this._prelimContent=null,e===void 0?this._prelimContent=new Map:this._prelimContent=new Map(e)}_integrate(e,n){super._integrate(e,n),this._prelimContent.forEach((s,r)=>{this.set(r,s)}),this._prelimContent=null}_copy(){return new Jn}clone(){const e=new Jn;return this.forEach((n,s)=>{e.set(s,n instanceof ze?n.clone():n)}),e}_callObserver(e,n){Cr(this,e,new lm(this,e,n))}toJSON(){this.doc??Xe();const e={};return this._map.forEach((n,s)=>{if(!n.deleted){const r=n.content.getContent()[n.length-1];e[s]=r instanceof ze?r.toJSON():r}}),e}get size(){return[...Us(this)].length}keys(){return si(Us(this),e=>e[0])}values(){return si(Us(this),e=>e[1].content.getContent()[e[1].length-1])}entries(){return si(Us(this),e=>[e[0],e[1].content.getContent()[e[1].length-1]])}forEach(e){this.doc??Xe(),this._map.forEach((n,s)=>{n.deleted||e(n.content.getContent()[n.length-1],s,this)})}[Symbol.iterator](){return this.entries()}delete(e){this.doc!==null?ge(this.doc,n=>{rr(n,this,e)}):this._prelimContent.delete(e)}set(e,n){return this.doc!==null?ge(this.doc,s=>{uo(s,this,e,n)}):this._prelimContent.set(e,n),n}get(e){return ho(this,e)}has(e){return kc(this,e)}clear(){this.doc!==null?ge(this.doc,e=>{this.forEach(function(n,s,r){rr(e,r,s)})}):this._prelimContent.clear()}_write(e){e.writeTypeRef(Rm)}}const am=t=>new Jn,Gt=(t,e)=>t===e||typeof t=="object"&&typeof e=="object"&&t&&e&&rf(t,e);class Ti{constructor(e,n,s,r){this.left=e,this.right=n,this.index=s,this.currentAttributes=r}forward(){this.right===null&&at(),this.right.content.constructor===Ie?this.right.deleted||es(this.currentAttributes,this.right.content):this.right.deleted||(this.index+=this.right.length),this.left=this.right,this.right=this.right.right}}const $l=(t,e,n)=>{for(;e.right!==null&&n>0;)e.right.content.constructor===Ie?e.right.deleted||es(e.currentAttributes,e.right.content):e.right.deleted||(n<e.right.length&&et(t,se(e.right.id.client,e.right.id.clock+n)),e.index+=e.right.length,n-=e.right.length),e.left=e.right,e.right=e.right.right;return e},zs=(t,e,n,s)=>{const r=new Map,i=s?kr(e,n):null;if(i){const l=new Ti(i.p.left,i.p,i.index,r);return $l(t,l,n-i.index)}else{const l=new Ti(null,e._start,0,r);return $l(t,l,n)}},Cc=(t,e,n,s)=>{for(;n.right!==null&&(n.right.deleted===!0||n.right.content.constructor===Ie&&Gt(s.get(n.right.content.key),n.right.content.value));)n.right.deleted||s.delete(n.right.content.key),n.forward();const r=t.doc,i=r.clientID;s.forEach((l,a)=>{const c=n.left,u=n.right,h=new be(se(i,Ae(r.store,i)),c,c&&c.lastId,u,u&&u.id,e,null,new Ie(a,l));h.integrate(t,0),n.right=h,n.forward()})},es=(t,e)=>{const{key:n,value:s}=e;s===null?t.delete(n):t.set(n,s)},jc=(t,e)=>{for(;t.right!==null;){if(!(t.right.deleted||t.right.content.constructor===Ie&&Gt(e[t.right.content.key]??null,t.right.content.value)))break;t.forward()}},vc=(t,e,n,s)=>{const r=t.doc,i=r.clientID,l=new Map;for(const a in s){const c=s[a],u=n.currentAttributes.get(a)??null;if(!Gt(u,c)){l.set(a,u);const{left:h,right:d}=n;n.right=new be(se(i,Ae(r.store,i)),h,h&&h.lastId,d,d&&d.id,e,null,new Ie(a,c)),n.right.integrate(t,0),n.forward()}}return l},ri=(t,e,n,s,r)=>{n.currentAttributes.forEach((p,w)=>{r[w]===void 0&&(r[w]=null)});const i=t.doc,l=i.clientID;jc(n,r);const a=vc(t,e,n,r),c=s.constructor===String?new jt(s):s instanceof ze?new _t(s):new yn(s);let{left:u,right:h,index:d}=n;e._searchMarker&&bs(e._searchMarker,n.index,c.getLength()),h=new be(se(l,Ae(i.store,l)),u,u&&u.lastId,h,h&&h.id,e,null,c),h.integrate(t,0),n.right=h,n.index=d,n.forward(),Cc(t,e,n,a)},Il=(t,e,n,s,r)=>{const i=t.doc,l=i.clientID;jc(n,r);const a=vc(t,e,n,r);e:for(;n.right!==null&&(s>0||a.size>0&&(n.right.deleted||n.right.content.constructor===Ie));){if(!n.right.deleted)switch(n.right.content.constructor){case Ie:{const{key:c,value:u}=n.right.content,h=r[c];if(h!==void 0){if(Gt(h,u))a.delete(c);else{if(s===0)break e;a.set(c,u)}n.right.delete(t)}else n.currentAttributes.set(c,u);break}default:s<n.right.length&&et(t,se(n.right.id.client,n.right.id.clock+s)),s-=n.right.length;break}n.forward()}if(s>0){let c="";for(;s>0;s--)c+=`
8
- `;n.right=new be(se(l,Ae(i.store,l)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,e,null,new jt(c)),n.right.integrate(t,0),n.forward()}Cc(t,e,n,a)},Ec=(t,e,n,s,r)=>{let i=e;const l=tt();for(;i&&(!i.countable||i.deleted);){if(!i.deleted&&i.content.constructor===Ie){const u=i.content;l.set(u.key,u)}i=i.right}let a=0,c=!1;for(;e!==i;){if(n===e&&(c=!0),!e.deleted){const u=e.content;if(u.constructor===Ie){const{key:h,value:d}=u,p=s.get(h)??null;(l.get(h)!==u||p===d)&&(e.delete(t),a++,!c&&(r.get(h)??null)===d&&p!==d&&(p===null?r.delete(h):r.set(h,p))),!c&&!e.deleted&&es(r,u)}}e=e.right}return a},cm=(t,e)=>{for(;e&&e.right&&(e.right.deleted||!e.right.countable);)e=e.right;const n=new Set;for(;e&&(e.deleted||!e.countable);){if(!e.deleted&&e.content.constructor===Ie){const s=e.content.key;n.has(s)?e.delete(t):n.add(s)}e=e.left}},um=t=>{let e=0;return ge(t.doc,n=>{let s=t._start,r=t._start,i=tt();const l=bi(i);for(;r;)r.deleted===!1&&(r.content.constructor===Ie?es(l,r.content):(e+=Ec(n,s,r,i,l),i=bi(l),s=r)),r=r.right}),e},dm=t=>{const e=new Set,n=t.doc;for(const[s,r]of t.afterState.entries()){const i=t.beforeState.get(s)||0;r!==i&&cc(t,n.store.clients.get(s),i,r,l=>{!l.deleted&&l.content.constructor===Ie&&l.constructor!==ut&&e.add(l.parent)})}ge(n,s=>{Hn(t,t.deleteSet,r=>{if(r instanceof ut||!r.parent._hasFormatting||e.has(r.parent))return;const i=r.parent;r.content.constructor===Ie?e.add(i):cm(s,r)});for(const r of e)um(r)})},Pl=(t,e,n)=>{const s=n,r=bi(e.currentAttributes),i=e.right;for(;n>0&&e.right!==null;){if(e.right.deleted===!1)switch(e.right.content.constructor){case _t:case yn:case jt:n<e.right.length&&et(t,se(e.right.id.client,e.right.id.clock+n)),n-=e.right.length,e.right.delete(t);break}e.forward()}i&&Ec(t,i,e.right,r,e.currentAttributes);const l=(e.left||e.right).parent;return l._searchMarker&&bs(l._searchMarker,e.index,-s+n),e};class hm extends Sr{constructor(e,n,s){super(e,n),this.childListChanged=!1,this.keysChanged=new Set,s.forEach(r=>{r===null?this.childListChanged=!0:this.keysChanged.add(r)})}get changes(){if(this._changes===null){const e={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=e}return this._changes}get delta(){if(this._delta===null){const e=this.target.doc,n=[];ge(e,s=>{const r=new Map,i=new Map;let l=this.target._start,a=null;const c={};let u="",h=0,d=0;const p=()=>{if(a!==null){let w=null;switch(a){case"delete":d>0&&(w={delete:d}),d=0;break;case"insert":(typeof u=="object"||u.length>0)&&(w={insert:u},r.size>0&&(w.attributes={},r.forEach((g,S)=>{g!==null&&(w.attributes[S]=g)}))),u="";break;case"retain":h>0&&(w={retain:h},sf(c)||(w.attributes=Zh({},c))),h=0;break}w&&n.push(w),a=null}};for(;l!==null;){switch(l.content.constructor){case _t:case yn:this.adds(l)?this.deletes(l)||(p(),a="insert",u=l.content.getContent()[0],p()):this.deletes(l)?(a!=="delete"&&(p(),a="delete"),d+=1):l.deleted||(a!=="retain"&&(p(),a="retain"),h+=1);break;case jt:this.adds(l)?this.deletes(l)||(a!=="insert"&&(p(),a="insert"),u+=l.content.str):this.deletes(l)?(a!=="delete"&&(p(),a="delete"),d+=l.length):l.deleted||(a!=="retain"&&(p(),a="retain"),h+=l.length);break;case Ie:{const{key:w,value:g}=l.content;if(this.adds(l)){if(!this.deletes(l)){const S=r.get(w)??null;Gt(S,g)?g!==null&&l.delete(s):(a==="retain"&&p(),Gt(g,i.get(w)??null)?delete c[w]:c[w]=g)}}else if(this.deletes(l)){i.set(w,g);const S=r.get(w)??null;Gt(S,g)||(a==="retain"&&p(),c[w]=S)}else if(!l.deleted){i.set(w,g);const S=c[w];S!==void 0&&(Gt(S,g)?S!==null&&l.delete(s):(a==="retain"&&p(),g===null?delete c[w]:c[w]=g))}l.deleted||(a==="insert"&&p(),es(r,l.content));break}}l=l.right}for(p();n.length>0;){const w=n[n.length-1];if(w.retain!==void 0&&w.attributes===void 0)n.pop();else break}}),this._delta=n}return this._delta}}class Gn extends ze{constructor(e){super(),this._pending=e!==void 0?[()=>this.insert(0,e)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??Xe(),this._length}_integrate(e,n){super._integrate(e,n);try{this._pending.forEach(s=>s())}catch(s){console.error(s)}this._pending=null}_copy(){return new Gn}clone(){const e=new Gn;return e.applyDelta(this.toDelta()),e}_callObserver(e,n){super._callObserver(e,n);const s=new hm(this,e,n);Cr(this,e,s),!e.local&&this._hasFormatting&&(e._needFormattingCleanup=!0)}toString(){this.doc??Xe();let e="",n=this._start;for(;n!==null;)!n.deleted&&n.countable&&n.content.constructor===jt&&(e+=n.content.str),n=n.right;return e}toJSON(){return this.toString()}applyDelta(e,{sanitize:n=!0}={}){this.doc!==null?ge(this.doc,s=>{const r=new Ti(null,this._start,0,new Map);for(let i=0;i<e.length;i++){const l=e[i];if(l.insert!==void 0){const a=!n&&typeof l.insert=="string"&&i===e.length-1&&r.right===null&&l.insert.slice(-1)===`
9
- `?l.insert.slice(0,-1):l.insert;(typeof a!="string"||a.length>0)&&ri(s,this,r,a,l.attributes||{})}else l.retain!==void 0?Il(s,this,r,l.retain,l.attributes||{}):l.delete!==void 0&&Pl(s,r,l.delete)}}):this._pending.push(()=>this.applyDelta(e))}toDelta(e,n,s){this.doc??Xe();const r=[],i=new Map,l=this.doc;let a="",c=this._start;function u(){if(a.length>0){const d={};let p=!1;i.forEach((g,S)=>{p=!0,d[S]=g});const w={insert:a};p&&(w.attributes=d),r.push(w),a=""}}const h=()=>{for(;c!==null;){if(_n(c,e)||n!==void 0&&_n(c,n))switch(c.content.constructor){case jt:{const d=i.get("ychange");e!==void 0&&!_n(c,e)?(d===void 0||d.user!==c.id.client||d.type!=="removed")&&(u(),i.set("ychange",s?s("removed",c.id):{type:"removed"})):n!==void 0&&!_n(c,n)?(d===void 0||d.user!==c.id.client||d.type!=="added")&&(u(),i.set("ychange",s?s("added",c.id):{type:"added"})):d!==void 0&&(u(),i.delete("ychange")),a+=c.content.str;break}case _t:case yn:{u();const d={insert:c.content.getContent()[0]};if(i.size>0){const p={};d.attributes=p,i.forEach((w,g)=>{p[g]=w})}r.push(d);break}case Ie:_n(c,e)&&(u(),es(i,c.content));break}c=c.right}u()};return e||n?ge(l,d=>{e&&Di(d,e),n&&Di(d,n),h()},"cleanup"):h(),r}insert(e,n,s){if(n.length<=0)return;const r=this.doc;r!==null?ge(r,i=>{const l=zs(i,this,e,!s);s||(s={},l.currentAttributes.forEach((a,c)=>{s[c]=a})),ri(i,this,l,n,s)}):this._pending.push(()=>this.insert(e,n,s))}insertEmbed(e,n,s){const r=this.doc;r!==null?ge(r,i=>{const l=zs(i,this,e,!s);ri(i,this,l,n,s||{})}):this._pending.push(()=>this.insertEmbed(e,n,s||{}))}delete(e,n){if(n===0)return;const s=this.doc;s!==null?ge(s,r=>{Pl(r,zs(r,this,e,!0),n)}):this._pending.push(()=>this.delete(e,n))}format(e,n,s){if(n===0)return;const r=this.doc;r!==null?ge(r,i=>{const l=zs(i,this,e,!1);l.right!==null&&Il(i,this,l,n,s)}):this._pending.push(()=>this.format(e,n,s))}removeAttribute(e){this.doc!==null?ge(this.doc,n=>{rr(n,this,e)}):this._pending.push(()=>this.removeAttribute(e))}setAttribute(e,n){this.doc!==null?ge(this.doc,s=>{uo(s,this,e,n)}):this._pending.push(()=>this.setAttribute(e,n))}getAttribute(e){return ho(this,e)}getAttributes(){return Sc(this)}_write(e){e.writeTypeRef(Am)}}const fm=t=>new Gn;class ii{constructor(e,n=()=>!0){this._filter=n,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc??Xe()}[Symbol.iterator](){return this}next(){let e=this._currentNode,n=e&&e.content&&e.content.type;if(e!==null&&(!this._firstCall||e.deleted||!this._filter(n)))do if(n=e.content.type,!e.deleted&&(n.constructor===Yn||n.constructor===pn)&&n._start!==null)e=n._start;else for(;e!==null;){const s=e.next;if(s!==null){e=s;break}else e.parent===this._root?e=null:e=e.parent._item}while(e!==null&&(e.deleted||!this._filter(e.content.type)));return this._firstCall=!1,e===null?{value:void 0,done:!0}:(this._currentNode=e,{value:e.content.type,done:!1})}}class pn extends ze{constructor(){super(),this._prelimContent=[]}get firstChild(){const e=this._first;return e?e.content.getContent()[0]:null}_integrate(e,n){super._integrate(e,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new pn}clone(){const e=new pn;return e.insert(0,this.toArray().map(n=>n instanceof ze?n.clone():n)),e}get length(){return this.doc??Xe(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(e){return new ii(this,e)}querySelector(e){e=e.toUpperCase();const s=new ii(this,r=>r.nodeName&&r.nodeName.toUpperCase()===e).next();return s.done?null:s.value}querySelectorAll(e){return e=e.toUpperCase(),Pt(new ii(this,n=>n.nodeName&&n.nodeName.toUpperCase()===e))}_callObserver(e,n){Cr(this,e,new gm(this,n,e))}toString(){return gc(this,e=>e.toString()).join("")}toJSON(){return this.toString()}toDOM(e=document,n={},s){const r=e.createDocumentFragment();return s!==void 0&&s._createAssociation(r,this),xs(this,i=>{r.insertBefore(i.toDOM(e,n,s),null)}),r}insert(e,n){this.doc!==null?ge(this.doc,s=>{bc(s,this,e,n)}):this._prelimContent.splice(e,0,...n)}insertAfter(e,n){if(this.doc!==null)ge(this.doc,s=>{const r=e&&e instanceof ze?e._item:e;sr(s,this,r,n)});else{const s=this._prelimContent,r=e===null?0:s.findIndex(i=>i===e)+1;if(r===0&&e!==null)throw xt("Reference item not found");s.splice(r,0,...n)}}delete(e,n=1){this.doc!==null?ge(this.doc,s=>{xc(s,this,e,n)}):this._prelimContent.splice(e,n)}toArray(){return mc(this)}push(e){this.insert(this.length,e)}unshift(e){this.insert(0,e)}get(e){return wc(this,e)}slice(e=0,n=this.length){return pc(this,e,n)}forEach(e){xs(this,e)}_write(e){e.writeTypeRef(Om)}}const pm=t=>new pn;class Yn extends pn{constructor(e="UNDEFINED"){super(),this.nodeName=e,this._prelimAttrs=new Map}get nextSibling(){const e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){const e=this._item?this._item.prev:null;return e?e.content.type:null}_integrate(e,n){super._integrate(e,n),this._prelimAttrs.forEach((s,r)=>{this.setAttribute(r,s)}),this._prelimAttrs=null}_copy(){return new Yn(this.nodeName)}clone(){const e=new Yn(this.nodeName),n=this.getAttributes();return tf(n,(s,r)=>{e.setAttribute(r,s)}),e.insert(0,this.toArray().map(s=>s instanceof ze?s.clone():s)),e}toString(){const e=this.getAttributes(),n=[],s=[];for(const a in e)s.push(a);s.sort();const r=s.length;for(let a=0;a<r;a++){const c=s[a];n.push(c+'="'+e[c]+'"')}const i=this.nodeName.toLocaleLowerCase(),l=n.length>0?" "+n.join(" "):"";return`<${i}${l}>${super.toString()}</${i}>`}removeAttribute(e){this.doc!==null?ge(this.doc,n=>{rr(n,this,e)}):this._prelimAttrs.delete(e)}setAttribute(e,n){this.doc!==null?ge(this.doc,s=>{uo(s,this,e,n)}):this._prelimAttrs.set(e,n)}getAttribute(e){return ho(this,e)}hasAttribute(e){return kc(this,e)}getAttributes(e){return e?rm(this,e):Sc(this)}toDOM(e=document,n={},s){const r=e.createElement(this.nodeName),i=this.getAttributes();for(const l in i){const a=i[l];typeof a=="string"&&r.setAttribute(l,a)}return xs(this,l=>{r.appendChild(l.toDOM(e,n,s))}),s!==void 0&&s._createAssociation(r,this),r}_write(e){e.writeTypeRef(Nm),e.writeKey(this.nodeName)}}const mm=t=>new Yn(t.readKey());class gm extends Sr{constructor(e,n,s){super(e,s),this.childListChanged=!1,this.attributesChanged=new Set,n.forEach(r=>{r===null?this.childListChanged=!0:this.attributesChanged.add(r)})}}class ir extends Jn{constructor(e){super(),this.hookName=e}_copy(){return new ir(this.hookName)}clone(){const e=new ir(this.hookName);return this.forEach((n,s)=>{e.set(s,n)}),e}toDOM(e=document,n={},s){const r=n[this.hookName];let i;return r!==void 0?i=r.createDom(this):i=document.createElement(this.hookName),i.setAttribute("data-yjs-hook",this.hookName),s!==void 0&&s._createAssociation(i,this),i}_write(e){e.writeTypeRef(Fm),e.writeKey(this.hookName)}}const wm=t=>new ir(t.readKey());class or extends Gn{get nextSibling(){const e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){const e=this._item?this._item.prev:null;return e?e.content.type:null}_copy(){return new or}clone(){const e=new or;return e.applyDelta(this.toDelta()),e}toDOM(e=document,n,s){const r=e.createTextNode(this.toString());return s!==void 0&&s._createAssociation(r,this),r}toString(){return this.toDelta().map(e=>{const n=[];for(const r in e.attributes){const i=[];for(const l in e.attributes[r])i.push({key:l,value:e.attributes[r][l]});i.sort((l,a)=>l.key<a.key?-1:1),n.push({nodeName:r,attrs:i})}n.sort((r,i)=>r.nodeName<i.nodeName?-1:1);let s="";for(let r=0;r<n.length;r++){const i=n[r];s+=`<${i.nodeName}`;for(let l=0;l<i.attrs.length;l++){const a=i.attrs[l];s+=` ${a.key}="${a.value}"`}s+=">"}s+=e.insert;for(let r=n.length-1;r>=0;r--)s+=`</${n[r].nodeName}>`;return s}).join("")}toJSON(){return this.toString()}_write(e){e.writeTypeRef(Mm)}}const ym=t=>new or;class fo{constructor(e,n){this.id=e,this.length=n}get deleted(){throw yt()}mergeWith(e){return!1}write(e,n,s){throw yt()}integrate(e,n){throw yt()}}const bm=0;class ut extends fo{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor!==e.constructor?!1:(this.length+=e.length,!0)}integrate(e,n){n>0&&(this.id.clock+=n,this.length-=n),ac(e.doc.store,this)}write(e,n){e.writeInfo(bm),e.writeLen(this.length-n)}getMissing(e,n){return null}}class Es{constructor(e){this.content=e}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new Es(this.content)}splice(e){throw yt()}mergeWith(e){return!1}integrate(e,n){}delete(e){}gc(e){}write(e,n){e.writeBuf(this.content)}getRef(){return 3}}const xm=t=>new Es(t.readBuf());class Ss{constructor(e){this.len=e}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new Ss(this.len)}splice(e){const n=new Ss(this.len-e);return this.len=e,n}mergeWith(e){return this.len+=e.len,!0}integrate(e,n){ys(e.deleteSet,n.id.client,n.id.clock,this.len),n.markDeleted()}delete(e){}gc(e){}write(e,n){e.writeLen(this.len-n)}getRef(){return 1}}const Sm=t=>new Ss(t.readLen()),Dc=(t,e)=>new wn({guid:t,...e,shouldLoad:e.shouldLoad||e.autoLoad||!1});class Ds{constructor(e){e._item&&console.error("This document was already integrated as a sub-document. You should create a second instance instead with the same guid."),this.doc=e;const n={};this.opts=n,e.gc||(n.gc=!1),e.autoLoad&&(n.autoLoad=!0),e.meta!==null&&(n.meta=e.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new Ds(Dc(this.doc.guid,this.opts))}splice(e){throw yt()}mergeWith(e){return!1}integrate(e,n){this.doc._item=n,e.subdocsAdded.add(this.doc),this.doc.shouldLoad&&e.subdocsLoaded.add(this.doc)}delete(e){e.subdocsAdded.has(this.doc)?e.subdocsAdded.delete(this.doc):e.subdocsRemoved.add(this.doc)}gc(e){}write(e,n){e.writeString(this.doc.guid),e.writeAny(this.opts)}getRef(){return 9}}const km=t=>new Ds(Dc(t.readString(),t.readAny()));class yn{constructor(e){this.embed=e}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new yn(this.embed)}splice(e){throw yt()}mergeWith(e){return!1}integrate(e,n){}delete(e){}gc(e){}write(e,n){e.writeJSON(this.embed)}getRef(){return 5}}const Cm=t=>new yn(t.readJSON());class Ie{constructor(e,n){this.key=e,this.value=n}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new Ie(this.key,this.value)}splice(e){throw yt()}mergeWith(e){return!1}integrate(e,n){const s=n.parent;s._searchMarker=null,s._hasFormatting=!0}delete(e){}gc(e){}write(e,n){e.writeKey(this.key),e.writeJSON(this.value)}getRef(){return 6}}const jm=t=>new Ie(t.readKey(),t.readJSON());class lr{constructor(e){this.arr=e}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new lr(this.arr)}splice(e){const n=new lr(this.arr.slice(e));return this.arr=this.arr.slice(0,e),n}mergeWith(e){return this.arr=this.arr.concat(e.arr),!0}integrate(e,n){}delete(e){}gc(e){}write(e,n){const s=this.arr.length;e.writeLen(s-n);for(let r=n;r<s;r++){const i=this.arr[r];e.writeString(i===void 0?"undefined":JSON.stringify(i))}}getRef(){return 2}}const vm=t=>{const e=t.readLen(),n=[];for(let s=0;s<e;s++){const r=t.readString();r==="undefined"?n.push(void 0):n.push(JSON.parse(r))}return new lr(n)},Em=Qs("node_env")==="development";class mn{constructor(e){this.arr=e,Em&&xa(e)}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new mn(this.arr)}splice(e){const n=new mn(this.arr.slice(e));return this.arr=this.arr.slice(0,e),n}mergeWith(e){return this.arr=this.arr.concat(e.arr),!0}integrate(e,n){}delete(e){}gc(e){}write(e,n){const s=this.arr.length;e.writeLen(s-n);for(let r=n;r<s;r++){const i=this.arr[r];e.writeAny(i)}}getRef(){return 8}}const Dm=t=>{const e=t.readLen(),n=[];for(let s=0;s<e;s++)n.push(t.readAny());return new mn(n)};class jt{constructor(e){this.str=e}getLength(){return this.str.length}getContent(){return this.str.split("")}isCountable(){return!0}copy(){return new jt(this.str)}splice(e){const n=new jt(this.str.slice(e));this.str=this.str.slice(0,e);const s=this.str.charCodeAt(e-1);return s>=55296&&s<=56319&&(this.str=this.str.slice(0,e-1)+"�",n.str="�"+n.str.slice(1)),n}mergeWith(e){return this.str+=e.str,!0}integrate(e,n){}delete(e){}gc(e){}write(e,n){e.writeString(n===0?this.str:this.str.slice(n))}getRef(){return 4}}const _m=t=>new jt(t.readString()),Tm=[om,am,fm,mm,pm,wm,ym],Lm=0,Rm=1,Am=2,Nm=3,Om=4,Fm=5,Mm=6;class _t{constructor(e){this.type=e}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new _t(this.type._copy())}splice(e){throw yt()}mergeWith(e){return!1}integrate(e,n){this.type._integrate(e.doc,n)}delete(e){let n=this.type._start;for(;n!==null;)n.deleted?n.id.clock<(e.beforeState.get(n.id.client)||0)&&e._mergeStructs.push(n):n.delete(e),n=n.right;this.type._map.forEach(s=>{s.deleted?s.id.clock<(e.beforeState.get(s.id.client)||0)&&e._mergeStructs.push(s):s.delete(e)}),e.changed.delete(this.type)}gc(e){let n=this.type._start;for(;n!==null;)n.gc(e,!0),n=n.right;this.type._start=null,this.type._map.forEach(s=>{for(;s!==null;)s.gc(e,!0),s=s.left}),this.type._map=new Map}write(e,n){this.type._write(e)}getRef(){return 7}}const $m=t=>new _t(Tm[t.readTypeRef()](t)),Li=(t,e)=>{let n=e,s=0,r;do s>0&&(n=se(n.client,n.clock+s)),r=Mn(t,n),s=n.clock-r.id.clock,n=r.redone;while(n!==null&&r instanceof be);return{item:r,diff:s}},po=(t,e)=>{for(;t!==null&&t.keep!==e;)t.keep=e,t=t.parent._item},ar=(t,e,n)=>{const{client:s,clock:r}=e.id,i=new be(se(s,r+n),e,se(s,r+n-1),e.right,e.rightOrigin,e.parent,e.parentSub,e.content.splice(n));return e.deleted&&i.markDeleted(),e.keep&&(i.keep=!0),e.redone!==null&&(i.redone=se(e.redone.client,e.redone.clock+n)),e.right=i,i.right!==null&&(i.right.left=i),t._mergeStructs.push(i),i.parentSub!==null&&i.right===null&&i.parent._map.set(i.parentSub,i),e.length=n,i},Ul=(t,e)=>Pi(t,n=>js(n.deletions,e)),_c=(t,e,n,s,r,i)=>{const l=t.doc,a=l.store,c=l.clientID,u=e.redone;if(u!==null)return et(t,u);let h=e.parent._item,d=null,p;if(h!==null&&h.deleted===!0){if(h.redone===null&&(!n.has(h)||_c(t,h,n,s,r,i)===null))return null;for(;h.redone!==null;)h=et(t,h.redone)}const w=h===null?e.parent:h.content.type;if(e.parentSub===null){for(d=e.left,p=e;d!==null;){let C=d;for(;C!==null&&C.parent._item!==h;)C=C.redone===null?null:et(t,C.redone);if(C!==null&&C.parent._item===h){d=C;break}d=d.left}for(;p!==null;){let C=p;for(;C!==null&&C.parent._item!==h;)C=C.redone===null?null:et(t,C.redone);if(C!==null&&C.parent._item===h){p=C;break}p=p.right}}else{if(p=null,e.right&&!r){for(d=e;d!==null&&d.right!==null&&(d.right.redone||js(s,d.right.id)||Ul(i.undoStack,d.right.id)||Ul(i.redoStack,d.right.id));)for(d=d.right;d.redone;)d=et(t,d.redone);if(d&&d.right!==null)return null}else d=w._map.get(e.parentSub)||null;d!==null&&d.parent._item!==h&&(d=w._map.get(e.parentSub)||null)}const g=Ae(a,c),S=se(c,g),y=new be(S,d,d&&d.lastId,p,p&&p.id,w,e.parentSub,e.content.copy());return e.redone=S,po(y,!0),y.integrate(t,0),y};class be extends fo{constructor(e,n,s,r,i,l,a,c){super(e,c.getLength()),this.origin=s,this.left=n,this.right=r,this.rightOrigin=i,this.parent=l,this.parentSub=a,this.redone=null,this.content=c,this.info=this.content.isCountable()?gl:0}set marker(e){(this.info&Qr)>0!==e&&(this.info^=Qr)}get marker(){return(this.info&Qr)>0}get keep(){return(this.info&ml)>0}set keep(e){this.keep!==e&&(this.info^=ml)}get countable(){return(this.info&gl)>0}get deleted(){return(this.info&Xr)>0}set deleted(e){this.deleted!==e&&(this.info^=Xr)}markDeleted(){this.info|=Xr}getMissing(e,n){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=Ae(n,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=Ae(n,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===Fn&&this.id.client!==this.parent.client&&this.parent.clock>=Ae(n,this.parent.client))return this.parent.client;if(this.origin&&(this.left=Rl(e,n,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=et(e,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===ut||this.right&&this.right.constructor===ut)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===be?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===be&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===Fn){const s=Mn(n,this.parent);s.constructor===ut?this.parent=null:this.parent=s.content.type}return null}integrate(e,n){if(n>0&&(this.id.clock+=n,this.left=Rl(e,e.doc.store,se(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(n),this.length-=n),this.parent){if(!this.left&&(!this.right||this.right.left!==null)||this.left&&this.left.right!==this.right){let s=this.left,r;if(s!==null)r=s.right;else if(this.parentSub!==null)for(r=this.parent._map.get(this.parentSub)||null;r!==null&&r.left!==null;)r=r.left;else r=this.parent._start;const i=new Set,l=new Set;for(;r!==null&&r!==this.right;){if(l.add(r),i.add(r),Ln(this.origin,r.origin)){if(r.id.client<this.id.client)s=r,i.clear();else if(Ln(this.rightOrigin,r.rightOrigin))break}else if(r.origin!==null&&l.has(Mn(e.doc.store,r.origin)))i.has(Mn(e.doc.store,r.origin))||(s=r,i.clear());else break;r=r.right}this.left=s}if(this.left!==null){const s=this.left.right;this.right=s,this.left.right=this}else{let s;if(this.parentSub!==null)for(s=this.parent._map.get(this.parentSub)||null;s!==null&&s.left!==null;)s=s.left;else s=this.parent._start,this.parent._start=this;this.right=s}this.right!==null?this.right.left=this:this.parentSub!==null&&(this.parent._map.set(this.parentSub,this),this.left!==null&&this.left.delete(e)),this.parentSub===null&&this.countable&&!this.deleted&&(this.parent._length+=this.length),ac(e.doc.store,this),this.content.integrate(e,this),Nl(e,this.parent,this.parentSub),(this.parent._item!==null&&this.parent._item.deleted||this.parentSub!==null&&this.right!==null)&&this.delete(e)}else new ut(this.id,this.length).integrate(e,0)}get next(){let e=this.right;for(;e!==null&&e.deleted;)e=e.right;return e}get prev(){let e=this.left;for(;e!==null&&e.deleted;)e=e.left;return e}get lastId(){return this.length===1?this.id:se(this.id.client,this.id.clock+this.length-1)}mergeWith(e){if(this.constructor===e.constructor&&Ln(e.origin,this.lastId)&&this.right===e&&Ln(this.rightOrigin,e.rightOrigin)&&this.id.client===e.id.client&&this.id.clock+this.length===e.id.clock&&this.deleted===e.deleted&&this.redone===null&&e.redone===null&&this.content.constructor===e.content.constructor&&this.content.mergeWith(e.content)){const n=this.parent._searchMarker;return n&&n.forEach(s=>{s.p===e&&(s.p=this,!this.deleted&&this.countable&&(s.index-=this.length))}),e.keep&&(this.keep=!0),this.right=e.right,this.right!==null&&(this.right.left=this),this.length+=e.length,!0}return!1}delete(e){if(!this.deleted){const n=this.parent;this.countable&&this.parentSub===null&&(n._length-=this.length),this.markDeleted(),ys(e.deleteSet,this.id.client,this.id.clock,this.length),Nl(e,n,this.parentSub),this.content.delete(e)}}gc(e,n){if(!this.deleted)throw at();this.content.gc(e),n?Up(e,this,new ut(this.id,this.length)):this.content=new Ss(this.length)}write(e,n){const s=n>0?se(this.id.client,this.id.clock+n-1):this.origin,r=this.rightOrigin,i=this.parentSub,l=this.content.getRef()&dr|(s===null?0:lt)|(r===null?0:It)|(i===null?0:hs);if(e.writeInfo(l),s!==null&&e.writeLeftID(s),r!==null&&e.writeRightID(r),s===null&&r===null){const a=this.parent;if(a._item!==void 0){const c=a._item;if(c===null){const u=ic(a);e.writeParentInfo(!0),e.writeString(u)}else e.writeParentInfo(!1),e.writeLeftID(c.id)}else a.constructor===String?(e.writeParentInfo(!0),e.writeString(a)):a.constructor===Fn?(e.writeParentInfo(!1),e.writeLeftID(a)):at();i!==null&&e.writeString(i)}this.content.write(e,n)}}const Tc=(t,e)=>Im[e&dr](t),Im=[()=>{at()},Sm,vm,xm,_m,Cm,jm,$m,Dm,km,()=>{at()}],Pm=10;class dt extends fo{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor!==e.constructor?!1:(this.length+=e.length,!0)}integrate(e,n){at()}write(e,n){e.writeInfo(Pm),P(e.restEncoder,this.length-n)}getMissing(e,n){return null}}const Lc=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:{},Rc="__ $YJS$ __";Lc[Rc]===!0&&console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438");Lc[Rc]=!0;function Um(t){for(let e=0;e<t.length;e+=1)t[e]=Math.floor(Math.random()*256);return t}function zm(t){t[6]=t[6]&15|64,t[8]=t[8]&63|128;const e=Array.from(t,n=>n.toString(16).padStart(2,"0")).join("");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}function Ri(t=globalThis.crypto){if(typeof t?.randomUUID=="function")return t.randomUUID();const e=new Uint8Array(16),n=typeof t?.getRandomValues=="function"?t.getRandomValues(e):Um(e);return zm(n)}const Ac=new Map;class Bm{constructor(e){this.room=e,this.onmessage=null,this._onChange=n=>n.key===e&&this.onmessage!==null&&this.onmessage({data:xf(n.newValue||"")}),Yh(this._onChange)}postMessage(e){ya.setItem(this.room,bf(pf(e)))}close(){Xh(this._onChange)}}const qm=typeof BroadcastChannel>"u"?Bm:BroadcastChannel,mo=t=>Et(Ac,t,()=>{const e=Xt(),n=new qm(t);return n.onmessage=s=>e.forEach(r=>r(s.data,"broadcastchannel")),{bc:n,subs:e}}),Wm=(t,e)=>(mo(t).subs.add(e),e),Vm=(t,e)=>{const n=mo(t),s=n.subs.delete(e);return s&&n.subs.size===0&&(n.bc.close(),Ac.delete(t)),s},Tn=(t,e,n=null)=>{const s=mo(t);s.bc.postMessage(e),s.subs.forEach(r=>r(e,n))},Nc=0,go=1,Oc=2,cr=(t,e)=>{P(t,Nc);const n=Op(e);Te(t,n)},Fc=(t,e,n)=>{P(t,go),Te(t,io(e,n))},Hm=(t,e,n)=>Fc(e,n,Ye(t)),Mc=(t,e,n,s)=>{try{tc(e,Ye(t),n)}catch(r){s?.(r),console.error("Caught error while handling a Yjs update",r)}},Km=(t,e)=>{P(t,Oc),Te(t,e)},Jm=Mc,Gm=(t,e,n,s,r)=>{const i=ee(t);switch(i){case Nc:Hm(t,e,n);break;case go:Mc(t,n,s,r);break;case Oc:Jm(t,n,s,r);break;default:throw new Error("Unknown message type")}return i},Ym=0,Xm=(t,e,n)=>{ee(t)===Ym&&n(e,je(t))},oi=3e4;class Qm extends da{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{const n=Qt();this.getLocalState()!==null&&oi/2<=n-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());const s=[];this.meta.forEach((r,i)=>{i!==this.clientID&&oi<=n-r.lastUpdated&&this.states.has(i)&&s.push(i)}),s.length>0&&wo(this,s,"timeout")},bt(oi/10)),e.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(e){const n=this.clientID,s=this.meta.get(n),r=s===void 0?0:s.clock+1,i=this.states.get(n);e===null?this.states.delete(n):this.states.set(n,e),this.meta.set(n,{clock:r,lastUpdated:Qt()});const l=[],a=[],c=[],u=[];e===null?u.push(n):i==null?e!=null&&l.push(n):(a.push(n),Nn(i,e)||c.push(n)),(l.length>0||c.length>0||u.length>0)&&this.emit("change",[{added:l,updated:c,removed:u},"local"]),this.emit("update",[{added:l,updated:a,removed:u},"local"])}setLocalStateField(e,n){const s=this.getLocalState();s!==null&&this.setLocalState({...s,[e]:n})}getStates(){return this.states}}const wo=(t,e,n)=>{const s=[];for(let r=0;r<e.length;r++){const i=e[r];if(t.states.has(i)){if(t.states.delete(i),i===t.clientID){const l=t.meta.get(i);t.meta.set(i,{clock:l.clock+1,lastUpdated:Qt()})}s.push(i)}}s.length>0&&(t.emit("change",[{added:[],updated:[],removed:s},n]),t.emit("update",[{added:[],updated:[],removed:s},n]))},In=(t,e,n=t.states)=>{const s=e.length,r=Le();P(r,s);for(let i=0;i<s;i++){const l=e[i],a=n.get(l)||null,c=t.meta.get(l).clock;P(r,l),P(r,c),qe(r,JSON.stringify(a))}return me(r)},Zm=(t,e,n)=>{const s=en(e),r=Qt(),i=[],l=[],a=[],c=[],u=ee(s);for(let h=0;h<u;h++){const d=ee(s);let p=ee(s);const w=JSON.parse(je(s)),g=t.meta.get(d),S=t.states.get(d),y=g===void 0?0:g.clock;(y<p||y===p&&w===null&&t.states.has(d))&&(w===null?d===t.clientID&&t.getLocalState()!=null?p++:t.states.delete(d):t.states.set(d,w),t.meta.set(d,{clock:p,lastUpdated:r}),g===void 0&&w!==null?i.push(d):g!==void 0&&w===null?c.push(d):w!==null&&(Nn(w,S)||a.push(d),l.push(d)))}(i.length>0||a.length>0||c.length>0)&&t.emit("change",[{added:i,updated:a,removed:c},n]),(i.length>0||l.length>0||c.length>0)&&t.emit("update",[{added:i,updated:l,removed:c},n])},eg=t=>nf(t,(e,n)=>`${encodeURIComponent(n)}=${encodeURIComponent(e)}`).join("&"),un=0,$c=3,Pn=1,tg=2,_s=[];_s[un]=(t,e,n,s,r)=>{P(t,un);const i=Gm(e,t,n.doc,n);s&&i===go&&!n.synced&&(n.synced=!0)};_s[$c]=(t,e,n,s,r)=>{P(t,Pn),Te(t,In(n.awareness,Array.from(n.awareness.getStates().keys())))};_s[Pn]=(t,e,n,s,r)=>{Zm(n.awareness,Ye(e),n)};_s[tg]=(t,e,n,s,r)=>{Xm(e,n.doc,(i,l)=>ng(n,l))};const zl=3e4,ng=(t,e)=>console.warn(`Permission denied to access ${t.url}.
10
- ${e}`),Ic=(t,e,n)=>{const s=en(e),r=Le(),i=ee(s),l=t.messageHandlers[i];return l?l(r,s,t,n,i):console.error("Unable to compute message"),r},Ai=(t,e,n)=>{e===t.ws&&(t.emit("connection-close",[n,t]),t.ws=null,e.close(),t.wsconnecting=!1,t.wsconnected?(t.wsconnected=!1,t.synced=!1,wo(t.awareness,Array.from(t.awareness.getStates().keys()).filter(s=>s!==t.doc.clientID),t),t.emit("status",[{status:"disconnected"}])):t.wsUnsuccessfulReconnects++,setTimeout(Pc,zi(yh(2,t.wsUnsuccessfulReconnects)*100,t.maxBackoffTime),t))},Pc=t=>{if(t.shouldConnect&&t.ws===null){const e=new t._WS(t.url,t.protocols);e.binaryType="arraybuffer",t.ws=e,t.wsconnecting=!0,t.wsconnected=!1,t.synced=!1,e.onmessage=n=>{t.wsLastMessageReceived=Qt();const s=Ic(t,new Uint8Array(n.data),!0);Bi(s)>1&&e.send(me(s))},e.onerror=n=>{t.emit("connection-error",[n,t])},e.onclose=n=>{Ai(t,e,n)},e.onopen=()=>{t.wsLastMessageReceived=Qt(),t.wsconnecting=!1,t.wsconnected=!0,t.wsUnsuccessfulReconnects=0,t.emit("status",[{status:"connected"}]);const n=Le();if(P(n,un),cr(n,t.doc),e.send(me(n)),t.awareness.getLocalState()!==null){const s=Le();P(s,Pn),Te(s,In(t.awareness,[t.doc.clientID])),e.send(me(s))}},t.emit("status",[{status:"connecting"}])}},li=(t,e)=>{const n=t.ws;t.wsconnected&&n&&n.readyState===n.OPEN&&n.send(e),t.bcconnected&&Tn(t.bcChannel,e,t)};class sg extends Ui{constructor(e,n,s,{connect:r=!0,awareness:i=new Qm(s),params:l={},protocols:a=[],WebSocketPolyfill:c=WebSocket,resyncInterval:u=-1,maxBackoffTime:h=2500,disableBc:d=!1}={}){for(super();e[e.length-1]==="/";)e=e.slice(0,e.length-1);this.serverUrl=e,this.bcChannel=e+"/"+n,this.maxBackoffTime=h,this.params=l,this.protocols=a,this.roomname=n,this.doc=s,this._WS=c,this.awareness=i,this.wsconnected=!1,this.wsconnecting=!1,this.bcconnected=!1,this.disableBc=d,this.wsUnsuccessfulReconnects=0,this.messageHandlers=_s.slice(),this._synced=!1,this.ws=null,this.wsLastMessageReceived=0,this.shouldConnect=r,this._resyncInterval=0,u>0&&(this._resyncInterval=setInterval(()=>{if(this.ws&&this.ws.readyState===WebSocket.OPEN){const p=Le();P(p,un),cr(p,s),this.ws.send(me(p))}},u)),this._bcSubscriber=(p,w)=>{if(w!==this){const g=Ic(this,new Uint8Array(p),!1);Bi(g)>1&&Tn(this.bcChannel,me(g),this)}},this._updateHandler=(p,w)=>{if(w!==this){const g=Le();P(g,un),Km(g,p),li(this,me(g))}},this.doc.on("update",this._updateHandler),this._awarenessUpdateHandler=({added:p,updated:w,removed:g},S)=>{const y=p.concat(w).concat(g),C=Le();P(C,Pn),Te(C,In(i,y)),li(this,me(C))},this._exitHandler=()=>{wo(this.awareness,[s.clientID],"app closed")},Zt&&typeof process<"u"&&process.on("exit",this._exitHandler),i.on("update",this._awarenessUpdateHandler),this._checkInterval=setInterval(()=>{this.wsconnected&&zl<Qt()-this.wsLastMessageReceived&&Ai(this,this.ws,null)},zl/10),r&&this.connect()}get url(){const e=eg(this.params);return this.serverUrl+"/"+this.roomname+(e.length===0?"":"?"+e)}get synced(){return this._synced}set synced(e){this._synced!==e&&(this._synced=e,this.emit("synced",[e]),this.emit("sync",[e]))}destroy(){this._resyncInterval!==0&&clearInterval(this._resyncInterval),clearInterval(this._checkInterval),this.disconnect(),Zt&&typeof process<"u"&&process.off("exit",this._exitHandler),this.awareness.off("update",this._awarenessUpdateHandler),this.doc.off("update",this._updateHandler),super.destroy()}connectBc(){if(this.disableBc)return;this.bcconnected||(Wm(this.bcChannel,this._bcSubscriber),this.bcconnected=!0);const e=Le();P(e,un),cr(e,this.doc),Tn(this.bcChannel,me(e),this);const n=Le();P(n,un),Fc(n,this.doc),Tn(this.bcChannel,me(n),this);const s=Le();P(s,$c),Tn(this.bcChannel,me(s),this);const r=Le();P(r,Pn),Te(r,In(this.awareness,[this.doc.clientID])),Tn(this.bcChannel,me(r),this)}disconnectBc(){const e=Le();P(e,Pn),Te(e,In(this.awareness,[this.doc.clientID],new Map)),li(this,me(e)),this.bcconnected&&(Vm(this.bcChannel,this._bcSubscriber),this.bcconnected=!1)}disconnect(){this.shouldConnect=!1,this.disconnectBc(),this.ws!==null&&Ai(this,this.ws,null)}connect(){this.shouldConnect=!0,!this.wsconnected&&this.ws===null&&(Pc(this),this.connectBc())}}const bn=t=>Wn((e,n)=>{t.onerror=s=>n(new Error(s.target.error)),t.onsuccess=s=>e(s.target.result)}),rg=(t,e)=>Wn((n,s)=>{const r=indexedDB.open(t);r.onupgradeneeded=i=>e(i.target.result),r.onerror=i=>s(xt(i.target.error)),r.onsuccess=i=>{const l=i.target.result;l.onversionchange=()=>{l.close()},n(l)}}),ig=t=>bn(indexedDB.deleteDatabase(t)),og=(t,e)=>e.forEach(n=>t.createObjectStore.apply(t,n)),os=(t,e,n="readwrite")=>{const s=t.transaction(e,n);return e.map(r=>pg(s,r))},Uc=(t,e)=>bn(t.count(e)),lg=(t,e)=>bn(t.get(e)),zc=(t,e)=>bn(t.delete(e)),ag=(t,e,n)=>bn(t.put(e,n)),Ni=(t,e)=>bn(t.add(e)),cg=(t,e,n)=>bn(t.getAll(e,n)),ug=(t,e,n)=>{let s=null;return fg(t,e,r=>(s=r,!1),n).then(()=>s)},dg=(t,e=null)=>ug(t,e,"prev"),hg=(t,e)=>Wn((n,s)=>{t.onerror=s,t.onsuccess=async r=>{const i=r.target.result;if(i===null||await e(i)===!1)return n();i.continue()}}),fg=(t,e,n,s="next")=>hg(t.openKeyCursor(e,s),r=>n(r.key)),pg=(t,e)=>t.objectStore(e),mg=(t,e)=>IDBKeyRange.upperBound(t,e),gg=(t,e)=>IDBKeyRange.lowerBound(t,e),ai="custom",Bc="updates",qc=500,Wc=(t,e=()=>{},n=()=>{})=>{const[s]=os(t.db,[Bc]);return cg(s,gg(t._dbref,!1)).then(r=>{t._destroyed||(e(s),ge(t.doc,()=>{r.forEach(i=>tc(t.doc,i))},t,!1),n(s))}).then(()=>dg(s).then(r=>{t._dbref=r+1})).then(()=>Uc(s).then(r=>{t._dbsize=r})).then(()=>s)},wg=(t,e=!0)=>Wc(t).then(n=>{(e||t._dbsize>=qc)&&Ni(n,io(t.doc)).then(()=>zc(n,mg(t._dbref,!0))).then(()=>Uc(n).then(s=>{t._dbsize=s}))});class yg extends da{constructor(e,n){super(),this.doc=n,this.name=e,this._dbref=0,this._dbsize=0,this._destroyed=!1,this.db=null,this.synced=!1,this._db=rg(e,s=>og(s,[["updates",{autoIncrement:!0}],["custom"]])),this.whenSynced=Wn(s=>this.on("synced",()=>s(this))),this._db.then(s=>{this.db=s,Wc(this,l=>Ni(l,io(n)),()=>{if(this._destroyed)return this;this.synced=!0,this.emit("synced",[this])})}),this._storeTimeout=1e3,this._storeTimeoutId=null,this._storeUpdate=(s,r)=>{if(this.db&&r!==this){const[i]=os(this.db,[Bc]);Ni(i,s),++this._dbsize>=qc&&(this._storeTimeoutId!==null&&clearTimeout(this._storeTimeoutId),this._storeTimeoutId=setTimeout(()=>{wg(this,!1),this._storeTimeoutId=null},this._storeTimeout))}},n.on("update",this._storeUpdate),this.destroy=this.destroy.bind(this),n.on("destroy",this.destroy)}destroy(){return this._storeTimeoutId&&clearTimeout(this._storeTimeoutId),this.doc.off("update",this._storeUpdate),this.doc.off("destroy",this.destroy),this._destroyed=!0,this._db.then(e=>{e.close()})}clearData(){return this.destroy().then(()=>{ig(this.name)})}get(e){return this._db.then(n=>{const[s]=os(n,[ai],"readonly");return lg(s,e)})}set(e,n){return this._db.then(s=>{const[r]=os(s,[ai]);return ag(r,n,e)})}del(e){return this._db.then(n=>{const[s]=os(n,[ai]);return zc(s,e)})}}const Bl=[["#1677c8","#1677c833"],["#d65745","#d6574533"],["#16866a","#16866a33"],["#9a58b5","#9a58b533"],["#d27b18","#d27b1833"],["#3f7d20","#3f7d2033"],["#be3e7b","#be3e7b33"],["#4964c6","#4964c633"],["#8a6a14","#8a6a1433"],["#087f8c","#087f8c33"]],ql=4,Wl=5,bg=6,xg=7,Sg=8,ci=9,ui=3,kg=6e4,Cg=720*60*60*1e3,jg=15e3,vg=5*6e4;function Eg(t){if(!t||typeof t!="object")return null;const e=t,n=e.requestedBy;return typeof e.mainFile!="string"||typeof e.runId!="string"||!["queued","running","succeeded","failed","cleaned"].includes(e.status??"")||e.status==="cleaned"&&e.cleanMode!=="cache"&&e.cleanMode!=="artifacts"||e.stale!==void 0&&typeof e.stale!="boolean"||typeof e.updatedAt!="string"||!n||typeof n.id!="string"||typeof n.username!="string"||typeof n.name!="string"?null:e}function Vl(t){if(!t||typeof t!="object"||Array.isArray(t))return{};const e={};for(const[n,s]of Object.entries(t)){const r=Eg(s);r&&r.mainFile===n&&(e[n]=r)}return e}function Dg(t,e,n){return t<=n&&e<=n}function Hl(t,e,n){const s=r=>r>0&&n-r<=vg;return{recoverable:t.some(r=>r.tabId===e||!s(r.activeAt)),otherActive:t.some(r=>r.tabId!==e&&s(r.activeAt))}}class _g{constructor(e,n){this.projectId=e,this.user=n;const s=window.location.protocol==="https:"?"wss:":"ws:";this.draftTabId=Ag(`texlite:collaboration-tab:${n.id}:${e}`);const r=this.readOwnWritableDraftMarker();this.draftGeneration=r?.generation??0,this.draftUpdatedAt=r?.updatedAt??0,this.draftMarkerPresent=r!==null,this.markDraftTabInactive=()=>this.setOwnDraftActivity(!1),this.markDraftTabActive=()=>this.resumeOwnDraftActivity(),window.addEventListener("pagehide",this.markDraftTabInactive),window.addEventListener("pageshow",this.markDraftTabActive),r&&(this.setOwnDraftActivity(!0),this.startDraftHeartbeat()),this.persistence=new yg(`texlite:${n.id}:${e}`,this.doc),this.localDraftTransactionObserver=l=>{if(l.local){for(const[a,c]of this.doc.share)if(a.startsWith("source:")&&(l.changed.has(c)||l.changedParentTypes.has(c))){this.markWritableDraft();return}}},this.doc.on("afterTransaction",this.localDraftTransactionObserver),this.persistence.on("synced",()=>{this.localDraftReady=!0;for(const l of this.draftListeners)l()}),this.provider=new sg(`${s}//${window.location.host}/api/collaboration`,e,this.doc,{connect:!1,disableBc:!0,maxBackoffTime:2500}),this.awareness=this.provider.awareness;const i=this.doc.getMap("texlite:meta");this.metaObserver=(l,a)=>{a.origin===this.provider&&l.keysChanged.has("compileStates")&&(this.authoritativeCompileStates=null,this.notifyCompileStateListeners())},i.observe(this.metaObserver),this.provider.messageHandlers[ql]=(l,a)=>{const c=je(a),u=this.flushRequests.get(c);if(!u)return;const h=ee(a)===1,d=ee(a),p=je(a),w=ee(a),g=[];for(let S=0;S<w;S++)g.push(je(a));if(window.clearTimeout(u.timer),this.flushRequests.delete(c),h)this.clearOwnWritableDraftMarker(u.draftGeneration),u.resolve({revision:d,persistedAt:p,ok:!0,failedPaths:[]});else{const S=Object.assign(new Error(g.length?`保存失败:${g.join(", ")}`:"源码保存到服务器磁盘失败"),{failedPaths:g});u.reject(S)}},this.provider.messageHandlers[Wl]=(l,a)=>{const c=je(a),u=this.epochStorageKey(),h=Kl(u),d=/^([0-9]+):/.exec(c)?.[1]??null,p=h?/^([0-9]+):/.exec(h)?.[1]??null:null,w=!this.epoch&&d===String(ui)&&p!==null&&p!==d;if((this.epoch&&this.epoch!==c||h&&h!==c)&&!w){this.provider.disconnect(),this.rejectFlushes(new Error("Collaboration state changed"));const _=c.endsWith(":reload")||d!==null&&d!==String(ui),q=()=>{di(u,c.replace(/:reload$/,"")),window.location.reload()};if(_)for(const Y of this.protocolUpgradeListeners)Y();else this.persistence.clearData().then(()=>{this.clearWritableDraftMarkers(),q()});return}this.epoch=c,di(u,c);const g=this.provider.ws;if(!g||g.readyState!==WebSocket.OPEN)return;const S=Le();P(S,Wl),qe(S,c),P(S,ui),g.send(me(S));const y=Le();P(y,0),cr(y,this.doc),g.send(me(y));const C=Le();P(C,1),Te(C,In(this.awareness,[this.doc.clientID])),g.send(me(C))},this.provider.messageHandlers[xg]=(l,a)=>{const c=je(a),u=je(a);if(c!==this.user.id)return;if(u==="revoked"){this.rejectFlushes(new Error("Project access revoked")),this.provider.disconnect();for(const d of this.permissionListeners)d("revoked",this.permission);return}if(u!=="read"&&u!=="edit"&&u!=="owner")return;const h=this.permission;if(this.setPermission(u),h!==u){u==="read"&&this.rejectFlushes(new Error("Project permission changed to read-only"));for(const d of this.permissionListeners)d(u,h)}},this.provider.messageHandlers[bg]=(l,a)=>{je(a)},this.provider.messageHandlers[Sg]=(l,a)=>{let c={};try{c=Vl(JSON.parse(je(a)))}catch{}this.authoritativeCompileStates=c,this.notifyCompileStateListeners()},this.provider.messageHandlers[ci]=(l,a)=>{const c=je(a),u=je(a),h=je(a),d=je(a),p=je(a),w=je(a);if(c==="state"){const S=Ci(a)?je(a):"",y=Ci(a)?je(a):"",C=Number(p);if(!S||!Number.isFinite(C)||C<=Date.now())this.removeFormatLeaseState(h),this.notifyFormatLeaseListeners(null);else{const _={path:h,holderUserId:S,holderName:y,expiresAt:C};this.formatLeaseStatesByPath.set(h,_);const q=this.formatLeaseExpiryTimers.get(h);q!==void 0&&window.clearTimeout(q);const Y=window.setTimeout(()=>{const K=this.formatLeaseStatesByPath.get(h);!K||K.expiresAt>Date.now()||(this.removeFormatLeaseState(h),this.notifyFormatLeaseListeners(null))},Math.max(0,C-Date.now())+25);this.formatLeaseExpiryTimers.set(h,Y),this.notifyFormatLeaseListeners(_)}return}const g=this.formatLeaseRequests.get(u);g&&(window.clearTimeout(g.timer),this.formatLeaseRequests.delete(u),c==="denied"?g.reject(new Error(w||"Format lease request was denied")):g.resolve({status:c,filePath:h,token:d,expiresAt:Number(p)}))},this.provider.on("status",({status:l})=>{l==="disconnected"&&(this.authoritativeCompileStates=null,this.notifyCompileStateListeners(),this.rejectFlushes(new Error("Collaboration connection closed")),this.rejectFormatLeaseRequests(new Error("Collaboration connection closed")),this.clearFormatLeaseStates())}),this.updateLocalAwareness()}projectId;user;doc=new wn;provider;awareness;persistence;permission="read";activeFile="";epoch=null;destroyed=!1;localDraftReady=!1;draftListeners=new Set;permissionListeners=new Set;protocolUpgradeListeners=new Set;compileStateListeners=new Set;flushRequests=new Map;formatLeaseRequests=new Map;formatLeaseListeners=new Set;formatLeaseStatesByPath=new Map;formatLeaseExpiryTimers=new Map;draftTabId;draftGeneration=0;draftUpdatedAt=0;draftMarkerPresent=!1;draftHeartbeatTimer=null;markDraftTabInactive;markDraftTabActive;undoManagers=new Map;authoritativeCompileStates=null;metaObserver;localDraftTransactionObserver;connect(){this.destroyed||(this.provider.connect(),this.updateLocalAwareness())}getText(e){return this.doc.getText(`source:${e}`)}getUndoManager(e){const n=this.undoManagers.get(e);if(n)return n;const s=new Vp(this.getText(e));return this.undoManagers.set(e,s),s}applyTextEdits(e,n){if(this.permission==="read")throw new Error("Read-only collaborators cannot edit source files");const s=this.getText(e);let r=0;for(const i of n){if(!Number.isInteger(i.from)||!Number.isInteger(i.to)||i.from<r||i.to<i.from||i.to>s.length)throw new RangeError("Invalid collaborative text edits");r=i.to}this.doc.transact(()=>{for(let i=n.length-1;i>=0;i-=1){const l=n[i];l.to>l.from&&s.delete(l.from,l.to-l.from),l.replacement&&s.insert(l.from,l.replacement)}})}get meta(){return this.doc.getMap("texlite:meta")}compileStates(){return this.authoritativeCompileStates??Vl(this.meta.get("compileStates"))}onCompileStates(e){return this.compileStateListeners.add(e),()=>this.compileStateListeners.delete(e)}get synced(){return this.provider.synced}get connected(){return this.provider.wsconnected}get draftReady(){return this.localDraftReady}get currentPermission(){return this.permission}onDraftReady(e){return this.draftListeners.add(e),this.localDraftReady&&e(),()=>this.draftListeners.delete(e)}onPermissionChanged(e){return this.permissionListeners.add(e),()=>this.permissionListeners.delete(e)}onProtocolUpgrade(e){return this.protocolUpgradeListeners.add(e),()=>this.protocolUpgradeListeners.delete(e)}async discardLocalDraft(){return this.hasOtherWritableDraft?!1:(await this.persistence.clearData(),this.localDraftReady=!1,this.clearWritableDraftMarkers(),!0)}get hasWritableDraft(){const e=this.readWritableDraftMarkers();return Hl(e.map(({tabId:n,marker:s})=>({tabId:n,activeAt:s.activeAt})),this.draftTabId,Date.now()).recoverable}get hasOtherWritableDraft(){const e=this.readWritableDraftMarkers();return Hl(e.map(({tabId:n,marker:s})=>({tabId:n,activeAt:s.activeAt})),this.draftTabId,Date.now()).otherActive}setPermission(e,n=!1){const s=this.permission;if(this.permission=e,e==="read"&&(s!=="read"&&this.rejectFlushes(new Error("Project permission changed to read-only")),this.destroyUndoManagers(),this.clearFormatLeaseStates()),this.updateLocalAwareness(),n&&s!==e)for(const r of this.permissionListeners)r(e,s)}setActiveFile(e){this.activeFile!==e&&(this.activeFile=e,this.awareness.setLocalStateField("cursor",null),this.updateLocalAwareness())}sessions(){const e=[];return this.awareness.getStates().forEach((n,s)=>{const r=n?.user;!r||typeof r.id!="string"||typeof r.name!="string"||e.push({clientId:s,userId:r.id,username:typeof r.username=="string"?r.username:r.name,name:r.name,color:typeof r.color=="string"?r.color:"#1677c8",colorLight:typeof r.colorLight=="string"?r.colorLight:"#1677c833",permission:r.permission==="owner"||r.permission==="edit"?r.permission:"read",filePath:typeof n.filePath=="string"?n.filePath:"",editing:!!n.cursor,local:s===this.doc.clientID})}),e.sort((n,s)=>Number(s.local)-Number(n.local)||n.name.localeCompare(s.name))}flush(){const e=this.provider.ws;if(!this.provider.synced||!e||e.readyState!==WebSocket.OPEN)return Promise.reject(new Error("Collaboration connection is unavailable"));const n=Ri(),s=this.draftGeneration,r=Le();return P(r,ql),qe(r,n),new Promise((i,l)=>{const a=window.setTimeout(()=>{this.flushRequests.delete(n),l(new Error("Collaboration save timed out"))},5e3);this.flushRequests.set(n,{resolve:i,reject:l,timer:a,draftGeneration:s}),e.send(me(r))})}onFormatLeaseState(e){this.formatLeaseListeners.add(e);for(const n of this.formatLeaseStatesByPath.values())e(n);return()=>this.formatLeaseListeners.delete(e)}formatLeaseStates(){const e=Date.now();for(const[n,s]of this.formatLeaseStatesByPath)s.expiresAt<=e&&this.removeFormatLeaseState(n);return[...this.formatLeaseStatesByPath.values()]}async acquireFormatLease(e){if(this.permission==="read")throw new Error("Formatting requires write permission");const n=await this.requestFormatLease("acquire",e);if(n.status!=="grant"||!n.token||!Number.isFinite(n.expiresAt))throw new Error("Format lease was not granted");let s=n.token,r=n.expiresAt,i=!1;const l=async()=>{if(i)throw new Error("Format lease has already been released");const c=await this.requestFormatLease("renew",e,s);if(c.status!=="renewed"||!Number.isFinite(c.expiresAt))throw new Error("Format lease renewal failed");s=c.token||s,r=c.expiresAt};return{path:e,get token(){return s},get expiresAt(){return r},confirm:l,renew:l,release:async()=>{if(i)return;i=!0;const c=this.provider.ws;if(!(!c||c.readyState!==WebSocket.OPEN))try{await this.requestFormatLease("release",e,s)}catch{}}}}reconnect(){this.destroyed||(this.rejectFlushes(new Error("Collaboration connection reset")),this.provider.disconnect(),this.provider.connect(),this.updateLocalAwareness())}destroy(){this.destroyed=!0,this.setOwnDraftActivity(!1),this.stopDraftHeartbeat(),window.removeEventListener("pagehide",this.markDraftTabInactive),window.removeEventListener("pageshow",this.markDraftTabActive),this.rejectFlushes(new Error("Collaboration connection closed")),this.provider.destroy(),this.persistence.destroy(),this.draftListeners.clear(),this.protocolUpgradeListeners.clear(),this.compileStateListeners.clear(),this.rejectFormatLeaseRequests(new Error("Collaboration connection closed")),this.clearFormatLeaseStates(),this.formatLeaseListeners.clear(),this.meta.unobserve(this.metaObserver),this.doc.off("afterTransaction",this.localDraftTransactionObserver),this.destroyUndoManagers(),this.doc.destroy()}destroyUndoManagers(){for(const e of this.undoManagers.values())e.destroy();this.undoManagers.clear()}notifyCompileStateListeners(){for(const e of this.compileStateListeners)e()}rejectFlushes(e){for(const n of this.flushRequests.values())window.clearTimeout(n.timer),n.reject(e);this.flushRequests.clear()}requestFormatLease(e,n,s=""){const r=this.provider.ws;if(!this.provider.synced||!r||r.readyState!==WebSocket.OPEN)return Promise.reject(new Error("Collaboration connection is unavailable"));const i=Ri(),l=Le();return P(l,ci),qe(l,e),qe(l,i),qe(l,n),qe(l,s),new Promise((a,c)=>{const u=window.setTimeout(()=>{if(this.formatLeaseRequests.delete(i),e==="acquire"){const h=this.provider.ws;if(h?.readyState===WebSocket.OPEN){const d=Le();P(d,ci),qe(d,"cancel"),qe(d,i),qe(d,n),qe(d,""),h.send(me(d))}}c(new Error("Format lease request timed out"))},e==="acquire"?kg:5e3);this.formatLeaseRequests.set(i,{resolve:a,reject:c,timer:u}),r.send(me(l))})}rejectFormatLeaseRequests(e){for(const n of this.formatLeaseRequests.values())window.clearTimeout(n.timer),n.reject(e);this.formatLeaseRequests.clear()}clearFormatLeaseStates(){for(const e of this.formatLeaseExpiryTimers.values())window.clearTimeout(e);this.formatLeaseExpiryTimers.clear(),this.formatLeaseStatesByPath.size&&(this.formatLeaseStatesByPath.clear(),this.notifyFormatLeaseListeners(null))}removeFormatLeaseState(e){const n=this.formatLeaseExpiryTimers.get(e);n!==void 0&&window.clearTimeout(n),this.formatLeaseExpiryTimers.delete(e),this.formatLeaseStatesByPath.delete(e)}notifyFormatLeaseListeners(e){for(const n of this.formatLeaseListeners)n(e)}updateLocalAwareness(){const[e,n]=Bl[Math.abs(this.doc.clientID)%Bl.length];this.awareness.setLocalStateField("user",{id:this.user.id,username:this.user.username,name:this.user.displayName,color:e,colorLight:n,permission:this.permission,sessionId:String(this.doc.clientID)}),this.awareness.setLocalStateField("filePath",this.activeFile)}epochStorageKey(){return`texlite:collaboration-epoch:${this.user.id}:${this.projectId}`}writableDraftStoragePrefix(){return`texlite:collaboration-writable:${this.user.id}:${this.projectId}:`}ownWritableDraftStorageKey(){return`${this.writableDraftStoragePrefix()}${this.draftTabId}`}markWritableDraft(){this.draftGeneration+=1,this.draftUpdatedAt=Date.now(),this.draftMarkerPresent||this.writeOwnWritableDraftMarker(!0),this.startDraftHeartbeat()}clearWritableDraftMarkers(){for(const{key:e}of this.readWritableDraftMarkers())rs(e);this.draftMarkerPresent=!1,this.stopDraftHeartbeat(),rs(this.writableDraftStoragePrefix().slice(0,-1))}clearOwnWritableDraftMarker(e){const n=this.readOwnWritableDraftMarker();!n||!Dg(n.generation,this.draftGeneration,e)||(rs(this.ownWritableDraftStorageKey()),this.draftMarkerPresent=!1,this.stopDraftHeartbeat())}readOwnWritableDraftMarker(){return this.readWritableDraftMarker(this.ownWritableDraftStorageKey())}readWritableDraftMarkers(){const e=this.writableDraftStoragePrefix(),n=[];for(const s of Tg()){if(!s.startsWith(e))continue;const r=this.readWritableDraftMarker(s);r&&n.push({key:s,tabId:s.slice(e.length),marker:r})}return n}readWritableDraftMarker(e){const n=Kl(e);if(!n)return null;try{const s=JSON.parse(n);if(!s||typeof s!="object"||Array.isArray(s))return null;const r=s,i=Date.now();if(!Number.isInteger(r.generation)||(r.generation??0)<0||typeof r.updatedAt!="number"||!Number.isFinite(r.updatedAt)||r.updatedAt<=0||i-r.updatedAt>Cg)return rs(e),null;const l=typeof r.activeAt=="number"&&Number.isFinite(r.activeAt)?Math.max(0,r.activeAt):0;return{generation:r.generation,updatedAt:r.updatedAt,activeAt:l}}catch{return rs(e),null}}writeOwnWritableDraftMarker(e){if(!this.draftMarkerPresent&&this.draftUpdatedAt<=0)return;const n={generation:this.draftGeneration,updatedAt:this.draftUpdatedAt||Date.now(),activeAt:e?Date.now():0};di(this.ownWritableDraftStorageKey(),JSON.stringify(n)),this.draftMarkerPresent=!0}setOwnDraftActivity(e){this.draftMarkerPresent&&(this.writeOwnWritableDraftMarker(e),e?this.startDraftHeartbeat():this.stopDraftHeartbeat())}resumeOwnDraftActivity(){const e=this.readOwnWritableDraftMarker();if(!e){this.draftMarkerPresent=!1,this.stopDraftHeartbeat();return}this.draftGeneration=Math.max(this.draftGeneration,e.generation),this.draftUpdatedAt=e.updatedAt,this.draftMarkerPresent=!0,this.setOwnDraftActivity(!0)}startDraftHeartbeat(){this.draftHeartbeatTimer!==null||!this.draftMarkerPresent||(this.draftHeartbeatTimer=window.setInterval(()=>{this.writeOwnWritableDraftMarker(!0)},jg))}stopDraftHeartbeat(){this.draftHeartbeatTimer!==null&&(window.clearInterval(this.draftHeartbeatTimer),this.draftHeartbeatTimer=null)}}function Kl(t){try{return window.localStorage.getItem(t)}catch{return null}}function di(t,e){try{window.localStorage.setItem(t,e)}catch{}}function rs(t){try{window.localStorage.removeItem(t)}catch{}}function Tg(){try{const t=[];for(let e=0;e<window.localStorage.length;e+=1){const n=window.localStorage.key(e);n&&t.push(n)}return t}catch{return[]}}function Lg(t){try{return window.sessionStorage.getItem(t)}catch{return null}}function Rg(t,e){try{window.sessionStorage.setItem(t,e)}catch{}}function Ag(t){const e=Lg(t);if(e)return e;const n=Ri();return Rg(t,n),n}function Ng(t,e){return Array.from(t.trim()||e.trim()||"?")[0]?.toLocaleUpperCase()??"?"}function Og(t){if(!t||typeof t!="object")return!1;const e=t;return(e.kind==="update"||e.kind==="move"||e.kind==="delete")&&typeof e.revision=="string"}function Fg(t,e,n,s,r,i){const[l]=f.useState(()=>new _g(t,e)),[a,c]=f.useState("connecting"),[u,h]=f.useState(!1),[d,p]=f.useState([]),[w,g]=f.useState(null),[S,y]=f.useState(null),[C,_]=f.useState(""),[q,Y]=f.useState(""),[K,W]=f.useState([]),[T,I]=f.useState(!1),[X,B]=f.useState(s),[V,O]=f.useState(null),[Q,D]=f.useState(!1),x=f.useRef(n),z=f.useRef(i),we=f.useRef(r);x.current=n,z.current=i,we.current=r,f.useEffect(()=>{const fe=l.compileStates();g(fe[n]??null)},[n,l]),f.useEffect(()=>{const fe=()=>p(l.sessions()),Se=()=>{h(!1),p([]),g(null),y(null),_(""),Y(""),W([]),z.current()},v=({status:le})=>{c(le),le!=="connected"&&Se()},oe=le=>{h(le),le||Se()},ne=()=>{c("disconnected"),Se()},A=()=>{const le=l.meta.get("filesEvent");Og(le)&&y(le);const pe=l.meta.get("commentsRevision");typeof pe=="string"&&_(pe);const Pe=l.meta.get("dictionaryRevision");typeof Pe=="string"&&Y(Pe);const Qe=l.compileStates();g(Qe[x.current]??null)},U=()=>{const le=l.compileStates();g(le[x.current]??null)};l.awareness.on("change",fe),l.provider.on("status",v),l.provider.on("sync",oe),l.provider.on("connection-close",ne),l.provider.on("connection-error",ne),l.meta.observe(A);const F=l.onCompileStates(U),Ee=l.onProtocolUpgrade(()=>{D(!0),c("disconnected"),Se()}),re=()=>W(l.formatLeaseStates()),ke=l.onFormatLeaseState(re),Me=()=>{if(!we.current||l.currentPermission!=="read")return;const le=l.hasWritableDraft,pe=l.hasOtherWritableDraft;!le&&!pe||O({previous:"edit",localDraftReady:le,otherTabDraft:pe})},Ve=l.onDraftReady(()=>{I(!0),Me()}),He=l.onPermissionChanged((le,pe)=>{if(le==="revoked"){c("disconnected"),h(!1),z.current();return}B(le),le==="read"&&pe!=="read"?O({previous:pe,localDraftReady:l.hasWritableDraft,otherTabDraft:l.hasOtherWritableDraft}):le!=="read"&&O(null)});return fe(),A(),c(l.connected?"connected":"connecting"),h(l.synced),()=>{l.awareness.off("change",fe),l.provider.off("status",v),l.provider.off("sync",oe),l.provider.off("connection-close",ne),l.provider.off("connection-error",ne),l.meta.unobserve(A),F(),Ee(),ke(),Ve(),He(),l.destroy()}},[l]),f.useEffect(()=>{r&&l.connect()},[l,r]),f.useEffect(()=>{l.setPermission(s),B(s),r&&s==="read"&&(l.hasWritableDraft||l.hasOtherWritableDraft)?O({previous:"edit",localDraftReady:l.hasWritableDraft,otherTabDraft:l.hasOtherWritableDraft}):s!=="read"&&O(null)},[l,s,r]);const ae=V!==null;return f.useEffect(()=>{if(!ae)return;const fe=()=>{if(l.currentPermission!=="read")return;const v=l.hasWritableDraft,oe=l.hasOtherWritableDraft;O(ne=>!ne||ne.localDraftReady===v&&ne.otherTabDraft===oe?ne:{...ne,localDraftReady:v,otherTabDraft:oe})};fe();const Se=window.setInterval(fe,2e3);return()=>window.clearInterval(Se)},[l,ae]),{collaboration:l,status:a,synced:u,activeSessions:d,compileState:w,setCompileState:g,formatLeaseStates:K,filesEvent:S,commentsRevision:C,dictionaryRevision:q,localDraftReady:T,permission:X,protocolUpgradeRequired:Q,reconnect:()=>{Q||(c("connecting"),h(!1),p([]),g(null),W([]),l.reconnect())},permissionDowngrade:V,dismissPermissionDowngrade:()=>O(null),discardLocalDraft:async()=>await l.discardLocalDraft()?(O(null),window.location.reload(),!0):(O(Se=>Se&&{...Se,otherTabDraft:!0}),!1)}}function Jl(t){return t?.status==="succeeded"?"succeeded":t?.log.includes("Compilation was cancelled.")?"cancelled":t?.status==="failed"?"failed":null}function ln(t){return t instanceof Error&&t.name==="AbortError"}function Mg(t){return t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement}function $g({projectId:t,project:e,mainFile:n,resolveCompileMainFile:s,getCurrentMainFile:r,initialLatest:i,collaborationSynced:l,sharedState:a,onSharedState:c,save:u,loadOutline:h,onPreviewTab:d,onError:p,onCompileStart:w,onCompileSuccess:g,onPdfChanged:S}){const{t:y}=We(),[C,_]=f.useState(""),[q,Y]=f.useState(!0),[K,W]=f.useState(null),[T,I]=f.useState("full"),[X,B]=f.useState(""),[V,O]=f.useState(null),[Q,D]=f.useState(null),[x,z]=f.useState([]),[we,ae]=f.useState(null),[xe,he]=f.useState(!1),[ve,fe]=f.useState(!1),[Se,v]=f.useState(()=>new Set),[oe,ne]=f.useState(()=>new Set),[A,U]=f.useState(""),F=f.useRef(n),Ee=f.useRef(""),re=f.useRef(null),ke=f.useRef(null),Me=f.useRef(null),Ve=f.useRef(i),He=f.useRef(!1),le=f.useRef(null),pe=f.useRef(null),Pe=f.useRef(new Set),Qe=f.useRef(new Map),zt=f.useRef(null),Tt=f.useRef(()=>{}),E=f.useRef({onSharedState:c,save:u,loadOutline:h,onPreviewTab:d,onError:p,onCompileStart:w,onCompileSuccess:g,onPdfChanged:S,resolveCompileMainFile:s,getCurrentMainFile:r});F.current=n,E.current={onSharedState:c,save:u,loadOutline:h,onPreviewTab:d,onError:p,onCompileStart:w,onCompileSuccess:g,onPdfChanged:S,resolveCompileMainFile:s,getCurrentMainFile:r};const te=()=>E.current.getCurrentMainFile?.()||F.current,ye=R=>{zt.current!==R&&(zt.current=R,E.current.onCompileSuccess())},Ke=async(R,$)=>{$||(le.current?.abort(),le.current=new AbortController,$=le.current.signal);try{const L=R?`?mainFile=${encodeURIComponent(R)}`:"",Z=await ie(`/api/projects/${t}/compile/artifacts${L}`,{signal:$});F.current===R&&(z(Z.artifacts),ae(null))}catch(L){!ln(L)&&F.current===R&&(z([]),ae(null))}finally{le.current?.signal===$&&(le.current=null)}};f.useEffect(()=>{if(re.current?.abort(),!n){Y(!1),_(""),W(null),I("full"),B(""),O(null),D(null),z([]),ae(null),Me.current=null,E.current.onPdfChanged();return}Me.current?.mainFile!==n&&(Me.current=null);const R=new AbortController;re.current=R,Y(!0),B(""),O(null),D(null),C&&n&&Ee.current===n||(_(""),W(null),I("full")),z([]),ae(null),E.current.onPdfChanged();let L=null;const Z=`?mainFile=${encodeURIComponent(n)}`,ft=He.current?null:Ve.current;ft&&(He.current=!0);const N=()=>ie(`/api/projects/${t}/compile/latest${Z}`,{signal:R.signal}),M=ft?ft.then(ue=>ue.mainFile!==n?N():ue,()=>N()):N();let st=!1;const Lt=()=>{if(st||R.signal.aborted||!n)return;st=!0;const ue=new AbortController;Pe.current.add(ue),Ke(n,ue.signal).finally(()=>{Pe.current.delete(ue)}),E.current.loadOutline(R.signal,n).catch(()=>{})};return M.then(ue=>{if(R.signal.aborted||n&&ue.mainFile!==F.current)return;const Je=Me.current;Je&&Je.mainFile===n&&ue.latestRun?.id!==Je.runId||(B(ue.latestRun?.log??""),O(ue.latestRun?.diagnostics??null),D(Jl(ue.latestRun)),n&&ue.latestRun?.requestedBy&&(ue.latestRun.status==="queued"||ue.latestRun.status==="running")&&E.current.onSharedState({mainFile:n,runId:ue.latestRun.id,status:ue.latestRun.status,requestedBy:ue.latestRun.requestedBy,updatedAt:new Date().toISOString()}),ue.pdfUrl&&(Ee.current=ue.mainFile,_(ue.pdfUrl),W(ue.pdfCompiledAt),I(ue.pdfLoadingMode??"full"),E.current.onPreviewTab("pdf")))}).catch(ue=>{!ln(ue)&&F.current===n&&E.current.onError(ce(ue))}).finally(()=>{re.current===R&&(re.current=null),R.signal.aborted||(Y(!1),L=window.setTimeout(Lt,0))}),()=>{L!==null&&window.clearTimeout(L),R.abort(),pe.current?.abort();for(const ue of Pe.current)ue.abort();Pe.current.clear()}},[t,n]),f.useEffect(()=>{if(!(!a||a.mainFile!==n||a.status!=="cleaned"||!a.cleanMode)){re.current?.abort(),ke.current?.abort(),le.current?.abort(),pe.current?.abort();for(const R of Pe.current)R.abort();Pe.current.clear(),a.cleanMode==="artifacts"?(Me.current=null,B(""),O(null),D(null),_(""),W(null),I("full"),z([]),ae(null),E.current.onPdfChanged(),E.current.onPreviewTab("pdf"),U(y("editor.cleanArtifactsComplete"))):U(y("editor.cleanCacheComplete"))}},[a?.runId,a?.status,a?.cleanMode,a?.mainFile,n,y]),f.useEffect(()=>{!n||a?.mainFile===n&&(a.status==="queued"||a.status==="running")||ne(R=>{if(!R.has(n))return R;const $=new Set(R);return $.delete(n),$})},[n,a?.mainFile,a?.status]),f.useEffect(()=>{if(!a||a.mainFile!==n||a.status!=="succeeded"&&a.status!=="failed")return;let R=!1;ke.current?.abort(),pe.current?.abort();const $=new AbortController;return ke.current=$,Y(!0),ie(`/api/projects/${t}/compile/latest?mainFile=${encodeURIComponent(n)}`,{signal:$.signal}).then(L=>{R||L.mainFile!==F.current||L.latestRun?.id!==a.runId||(B(L.latestRun.log),O(L.latestRun.diagnostics),D(Jl(L.latestRun)),a.status==="succeeded"&&a.stale&&U(y("editor.compileSnapshotStale")),a.status==="succeeded"&&L.pdfUrl?(Me.current={mainFile:n,runId:a.runId},E.current.onPdfChanged(),_(L.pdfUrl),W(L.pdfCompiledAt),I(L.pdfLoadingMode??"full"),E.current.onPreviewTab("pdf"),ye(a.runId),Ke(n)):a.status==="failed"&&E.current.onPreviewTab(L.latestRun.diagnostics.errors.length?"errors":"log"))}).catch(L=>{!ln(L)&&!R&&E.current.onError(ce(L))}).finally(()=>{ke.current===$&&(ke.current=null),R||Y(!1)}),()=>{R=!0,$.abort(),ke.current===$&&(ke.current=null)}},[a?.runId,a?.status,a?.mainFile,a?.stale,n,t,y]);const _e=async()=>{if(!e||e.permission==="read"||!l)return;const R=E.current.resolveCompileMainFile?.()||te();if(!R||Qe.current.has(R)||a?.mainFile===R&&(a.status==="queued"||a.status==="running"))return;v(L=>new Set([...L,R])),E.current.onCompileStart(),U(""),pe.current?.abort(),pe.current=null,B(""),O(null),D(null),E.current.onPreviewTab(C?"pdf":"log");const $=new AbortController;Qe.current.set(R,$);try{if(!await E.current.save())return;const L=await ie(`/api/projects/${t}/compile`,{method:"POST",signal:$.signal,body:JSON.stringify({mainFile:R})});if(L.mainFile!==R||te()!==R)return;B(L.log),O(L.diagnostics),D(L.cancelled?"cancelled":L.ok?"succeeded":"failed"),L.cancelled&&U(y("compileControls.cancelled")),L.skipped&&U(y("editor.upToDate")),L.ok&&L.stale&&U(y("editor.compileSnapshotStale")),L.pdfUrl?(L.ok&&(Me.current={mainFile:R,runId:L.runId}),E.current.onPdfChanged(),_(L.pdfUrl),W(L.pdfCompiledAt),I(L.pdfLoadingMode??"full"),E.current.onPreviewTab("pdf"),L.ok&&(L.skipped?E.current.onCompileSuccess():ye(L.runId))):E.current.onPreviewTab(L.diagnostics.errors.length?"errors":"log")}catch(L){!ln(L)&&te()===R&&E.current.onError(ce(L))}finally{Qe.current.get(R)===$&&(Qe.current.delete(R),v(L=>{const Z=new Set(L);return Z.delete(R),Z}),ne(L=>{if(!L.has(R))return L;const Z=new Set(L);return Z.delete(R),Z}))}},de=async()=>{if(!e||e.permission==="read"||!l)return;const R=te();if(R){ne($=>new Set([...$,R]));try{(await ie(`/api/projects/${t}/compile/cancel`,{method:"POST",body:JSON.stringify({mainFile:R})})).cancelled||ne(L=>{const Z=new Set(L);return Z.delete(R),Z})}catch($){ne(L=>{const Z=new Set(L);return Z.delete(R),Z}),!ln($)&&te()===R&&E.current.onError(ce($))}}},ht=async R=>{if(!e||e.permission==="read"||!l||ve)return;const $=te();if(!(!$||Qe.current.has($)||a?.mainFile===$&&(a.status==="queued"||a.status==="running"))){fe(!0),re.current?.abort(),ke.current?.abort(),le.current?.abort(),pe.current?.abort();try{if((await ie(`/api/projects/${t}/compile/clean`,{method:"POST",body:JSON.stringify({mainFile:$,mode:R})})).mainFile!==$||te()!==$)return;E.current.onSharedState(null),R==="artifacts"&&(Me.current=null,B(""),O(null),D(null),_(""),W(null),I("full"),z([]),ae(null),E.current.onPdfChanged()),U(y(R==="cache"?"editor.cleanCacheComplete":"editor.cleanArtifactsComplete"))}catch(L){!ln(L)&&te()===$&&E.current.onError(ce(L))}finally{fe(!1)}}};Tt.current=()=>{_e()},f.useEffect(()=>{if(!A)return;const R=window.setTimeout(()=>U(""),3e3);return()=>window.clearTimeout(R)},[A]),f.useEffect(()=>{const R=$=>{if(!(!($.ctrlKey||$.metaKey)||$.key.toLocaleLowerCase()!=="s")){if(Mg($.target)){$.preventDefault();return}$.preventDefault(),$.stopPropagation(),$.repeat||Tt.current()}};return window.addEventListener("keydown",R,!0),()=>window.removeEventListener("keydown",R,!0)},[]),f.useEffect(()=>()=>{re.current?.abort(),ke.current?.abort(),le.current?.abort(),pe.current?.abort();for(const R of Pe.current)R.abort();Pe.current.clear();for(const R of Qe.current.values())R.abort();Qe.current.clear()},[]);const Ne=async R=>{if(!R.viewable)return;pe.current?.abort();const $=new AbortController;pe.current=$,he(!0);try{const L=await ie(`/api/projects/${t}/compile/artifacts?mainFile=${encodeURIComponent(n)}&path=${encodeURIComponent(R.path)}`,{signal:$.signal});!$.signal.aborted&&pe.current===$&&F.current===n&&ae(L)}catch(L){ln(L)||E.current.onError(ce(L))}finally{pe.current===$&&(pe.current=null,he(!1))}};return{pdfUrl:C,pdfCompiledAt:K,pdfLoadingMode:T,pdfLoading:q,compileLog:X,compileDiagnostics:V,compileOutcome:Q,artifacts:x,artifactPreview:we,artifactLoading:xe,editorNotice:A,localCompiling:Se.has(n),cancelling:oe.has(n),cleaning:ve,compile:_e,cancelCompile:de,cleanCompile:ht,viewArtifact:Ne}}const Oi=10*1024*1024,Ig=new Set([".png",".jpg",".jpeg",".gif",".webp",".svg",".bmp",".ico",".avif",".pdf",".zip",".gz",".bz2",".xz",".tar",".rar",".7z",".doc",".docx",".xls",".xlsx",".ppt",".pptx",".odt",".ods",".odp",".mp3",".mp4",".wav",".ogg",".webm",".mov",".avi",".wasm",".exe",".bin",".so",".dll",".class",".jar"]);function Gl(t){return t instanceof Error&&t.name==="AbortError"}function ls(t){const e=t.split("/").filter(Boolean);return e.pop(),e.map((n,s)=>e.slice(0,s+1).join("/"))}function an(t,e){return!!(t&&e)&&(e===t||e.startsWith(`${t}/`))}function Pg(t){const e=`.${t.split(".").at(-1)?.toLocaleLowerCase()??""}`;return!Ig.has(e)}function Un(t){return/(?:\.(?:tex|bib|sty|cls|txt|md)|latexmkrc)$/i.test(t)}function Yl(t){const e=t.split(".").at(-1)?.toLocaleLowerCase()??"";return e==="pdf"?"pdf":["png","jpg","jpeg","gif","webp","svg","bmp","ico","avif"].includes(e)?"image":Pg(t)?"text":"unsupported"}function Ug(t,e){return`/api/projects/${t}/file/raw?path=${encodeURIComponent(e)}`}function zg({projectId:t,site:e,activeFile:n,dirty:s,save:r,onError:i,onProject:l,onActiveFile:a,onActiveMainFile:c,onRootDocuments:u}){const{t:h}=We(),[d,p]=f.useState([]),[w,g]=f.useState(!1),[S,y]=f.useState(""),[C,_]=f.useState(null),[q,Y]=f.useState(!1),[K,W]=f.useState(!1),[T,I]=f.useState(""),[X,B]=f.useState(""),[V,O]=f.useState(""),[Q,D]=f.useState(new Set),[x,z]=f.useState(null),[we,ae]=f.useState(""),[xe,he]=f.useState(""),[ve,fe]=f.useState(null),[Se,v]=f.useState(!1),[oe,ne]=f.useState(null),[A,U]=f.useState(!1),F=f.useRef(null),Ee=f.useRef(null),re=async(E={})=>{F.current?.abort(),F.current=null;const te=E.signal?null:new AbortController;te&&(F.current=te);try{const ye=await ie(`/api/projects/${t}/files`,{signal:E.signal??te?.signal});return(!E.isCurrent||E.isCurrent())&&p(ye.files),ye.files}catch(ye){if(!Gl(ye))throw ye;return}finally{te&&F.current===te&&(F.current=null)}},ke=async()=>{if(!(!S.trim()||S.trim().endsWith("/"))){B("");try{await ie(`/api/projects/${t}/file`,{method:"POST",body:JSON.stringify({path:S,content:""})}),await re(),a(S),D(E=>new Set([...E,...ls(S)])),g(!1),y("")}catch(E){B(ce(E))}}},Me=async()=>{if(!T.trim())return;B("");const E=V?`${V}/${T.trim()}`:T.trim();try{const te=await ie(`/api/projects/${t}/folders`,{method:"POST",body:JSON.stringify({path:E})});await re(),D(ye=>new Set([...ye,...ls(te.path),te.path])),O(te.path),W(!1),I("")}catch(te){B(ce(te))}},Ve=async(E,te=new Set,ye=V)=>{if(!E.length)return;const Ke=e.maxUploadSizeMB;if(E.find(Z=>Z.size>Ke*1024*1024))return i(h("errors.fileTooLarge",{size:Ke}));const de=ye,ht=E.map(Z=>de?`${de}/${Z.name}`:Z.name),Ne=new Map;for(const Z of ht)Ne.set(Z,(Ne.get(Z)??0)+1);const R=[...Ne.entries()].filter(([,Z])=>Z>1).map(([Z])=>Z);if(R.length)return i(h("errors.duplicateUploadNames",{files:R.join(", ")}));const $=new Set(d.map(Z=>Z.path)),L=[...new Set(ht.filter(Z=>$.has(Z)&&!te.has(Z)))];if(L.length){ne({files:E,directory:de,collisions:L});return}ne(null),U(!0);try{const Z=new URLSearchParams;de&&Z.set("directory",de);let ft="";for(const[N,M]of E.entries()){const st=ht[N];Z.delete("overwrite"),te.has(st)&&Z.set("overwrite","1");const Lt=Z.toString()?`?${Z.toString()}`:"",ue=new FormData;ue.append("file",M);try{const Je=await ie(`/api/projects/${t}/upload${Lt}`,{method:"POST",body:ue});typeof Je.path=="string"&&Un(Je.path)&&(ft=Je.path)}catch(Je){if(Je instanceof pi&&Je.status===409&&!te.has(st)&&Je.code==="FILE_EXISTS"){N>0&&await re(),ne({files:E.slice(N),directory:de,collisions:[st]});return}throw Je}}await re(),ft&&a(ft)}catch(Z){i(ce(Z))}finally{U(!1)}},He=async E=>{await Ve(Array.from(E.target.files??[])),E.target.value=""},le=async E=>{Ee.current?.abort(),Ee.current=null,Y(!1);const te=Ug(t,E.path);if((E.size??0)>Oi){_({path:E.path,kind:"large",size:E.size??0,url:te});return}const ye=Yl(E.path);if(ye!=="text"){_({path:E.path,kind:ye,size:E.size??0,url:te});return}_({path:E.path,kind:ye,size:E.size??0,url:te,content:""}),Y(!0);const Ke=new AbortController;Ee.current=Ke;try{let _e;try{_e=await fetch(te,{signal:Ke.signal})}catch(Ne){throw xd(Ne)}const de=_e.headers.get("content-type")??"";if(!_e.ok){let Ne=null;try{Ne=de.includes("application/json")?await _e.json():await _e.text()}catch{}throw new pi(Sd(Ne,_e.status),_e.status,kd(Ne))}const ht=await _e.text();_(Ne=>Ne?.path===E.path?{...Ne,content:ht}:Ne)}catch(_e){Gl(_e)||(_(null),i(ce(_e)))}finally{Ee.current===Ke&&(Ee.current=null,Y(!1))}},pe=E=>{const te=Yl(E.path),ye=e.maxCollaborativeFileSizeMB*1024*1024;(E.size??0)>Oi||Un(E.path)&&(E.size??0)>ye||te!=="text"||!Un(E.path)?le(E):a(E.path)},Pe=async()=>{if(!x)return;const E=we.trim();if(E){B("");try{if(!await r())return;const te=await ie(`/api/projects/${t}/path`,{method:"PATCH",body:JSON.stringify({source:x.path,destinationDirectory:xe,destinationName:E})}),ye=de=>de===x.path?te.path:de.startsWith(`${x.path}/`)?`${te.path}${de.slice(x.path.length)}`:de;a(de=>ye(de)),c(de=>ye(de)),u(de=>new Set([...de].map(ye))),O(de=>de&&ye(de));const[Ke,_e]=await Promise.all([ie(`/api/projects/${t}/files`),ie(`/api/projects/${t}`)]);p(Ke.files),l(_e.project),D(de=>new Set([...de,...ls(te.path),xe].filter(Boolean))),z(null),ae(""),he("")}catch(te){B(ce(te))}}},Qe=async()=>{if(ve){B("");try{if(s&&!await r())return;await ie(`/api/projects/${t}/file?path=${encodeURIComponent(ve.path)}`,{method:"DELETE"}),fe(null)}catch(E){B(ce(E))}}};f.useEffect(()=>()=>{F.current?.abort(),Ee.current?.abort()},[]),f.useEffect(()=>{Ee.current?.abort(),Ee.current=null,Y(!1)},[n]);const zt=d.filter(E=>E.type==="directory"),Tt=d.filter(E=>ls(E.path).every(te=>Q.has(te)));return{files:d,setFiles:p,loadFiles:re,newFileOpen:w,setNewFileOpen:g,newFilePath:S,setNewFilePath:y,resourcePreview:C,setResourcePreview:_,resourcePreviewLoading:q,setResourcePreviewLoading:Y,newFolderOpen:K,setNewFolderOpen:W,newFolderName:T,setNewFolderName:I,fileDialogError:X,setFileDialogError:B,selectedFolder:V,setSelectedFolder:O,expandedFolders:Q,setExpandedFolders:D,moveEntry:x,setMoveEntry:z,moveName:we,setMoveName:ae,moveDestination:xe,setMoveDestination:he,deleteEntry:ve,setDeleteEntry:fe,fileDragActive:Se,setFileDragActive:v,uploadConflict:oe,setUploadConflict:ne,uploadingFiles:A,directoryEntries:zt,visibleEntries:Tt,createFile:ke,createFolder:Me,uploadFiles:Ve,upload:He,openFile:pe,movePath:Pe,removePath:Qe}}function Bg({active:t,projectId:e,activeFile:n,content:s,dictionaryWords:r}){const[i,l]=f.useState([]),[a,c]=f.useState(""),[u,h]=f.useState(""),[d,p]=f.useState(0),[w,g]=f.useState(null),[S,y]=f.useState(null),[C,_]=f.useState(!1),[q,Y]=f.useState(0),K=f.useRef(0),W=f.useRef(!1),T=f.useRef(!1),I=f.useRef(s),X=f.useRef(n),B=f.useRef(0);I.current=s,X.current=n,T.current=C,f.useEffect(()=>{l([]),c(""),h(""),g(null),y(null),_(!1)},[n,r]),f.useEffect(()=>{y(null),_(!1)},[e]),f.useEffect(()=>{p(D=>i.length?Math.min(D,i.length-1):0)},[i]),f.useEffect(()=>{const D=++K.current;if(!t||!n){l([]),c(""),h(""),g(null);return}if(S){l([]),c(""),h("");return}const x=s,z=n;let we=!1;const ae=window.setTimeout(()=>{y(null),(async()=>{try{const{lintLatex:xe,isHarperLintSupersededError:he}=await vt(async()=>{const{lintLatex:fe,isHarperLintSupersededError:Se}=await import("./spellCheck-L9gD2d1M.js");return{lintLatex:fe,isHarperLintSupersededError:Se}},__vite__mapDeps([0,1,2,3]));if(we||D!==K.current||I.current!==x||X.current!==z)return;let ve;try{ve=await xe(e,z,x,r)}catch(fe){if(he(fe))return;throw fe}if(we||D!==K.current||I.current!==x||X.current!==z)return;W.current=!1,_(!1),l(ve),c(x),h(z),p(0),g(null)}catch(xe){if(we||D!==K.current||I.current!==x||X.current!==z)return;l([]),c(""),h(""),y(xe instanceof Error?xe.message:String(xe));const he=W.current;W.current=!1,_(he?T.current:!1)}})()},700);return()=>{we=!0,window.clearTimeout(ae)}},[t,e,n,s,r,q,S]),f.useEffect(()=>{if(!S||!t)return;let D=!1;const x=()=>{D||(D=!0,W.current=!0,y(null),Y(we=>we+1))},z=window.setTimeout(x,15e3);return window.addEventListener("online",x,{once:!0}),()=>{window.clearTimeout(z),window.removeEventListener("online",x)}},[S,t]);const V=u===n&&a===s,O=f.useMemo(()=>V?{total:i.length,unique:new Set(i.map(D=>`${D.kind}:${D.word.toLocaleLowerCase("en-US")}`)).size}:null,[V,i]);return{issues:V?i:[],jump:V?w:null,index:d,summary:O,jumpToIssue:D=>{if(!i.length)return;const x=Math.max(0,Math.min(D,i.length-1)),z=i[x];p(x),g({from:z.from,to:z.to,nonce:++B.current})},error:C?null:S,nativeFallback:t&&!!S,retry:()=>{W.current=!1,y(null),_(!1),Y(D=>D+1)},dismissError:()=>{W.current=!1,_(!0)}}}function Xl(t){return t instanceof Error&&t.name==="AbortError"}function qg({projectId:t,mainFile:e,activeFile:n,onActiveFile:s,onError:r,onShowPdf:i}){const[l,a]=f.useState(null),[c,u]=f.useState(null),[h,d]=f.useState(null),p=f.useRef(null),w=f.useRef(0),g=f.useRef(n),S=f.useRef(s),y=f.useRef(r),C=f.useRef(i),_=T=>T===e&&/\.tex$/i.test(T);g.current=n,S.current=s,y.current=r,C.current=i,f.useEffect(()=>(p.current?.abort(),p.current=null,a(null),u(null),d(null),()=>p.current?.abort()),[t,e]);const q=(T,I,X)=>{d({path:T,line:I,column:X,nonce:++w.current}),g.current!==T&&S.current(T)},Y=async(T,I,X,B={})=>{if(!_(T))return;p.current?.abort();const V=new AbortController;p.current=V;try{const O=await ie(`/api/projects/${t}/sync/pdf?mainFile=${encodeURIComponent(e)}&path=${encodeURIComponent(T)}&line=${I}&column=${X}`,{signal:V.signal});if(p.current!==V||!O)return;a({...O,nonce:++w.current}),C.current()}catch(O){!Xl(O)&&!B.silent&&y.current(ce(O))}finally{p.current===V&&(p.current=null)}},K=async(T,I,X)=>{if(!_(g.current))return;const B=g.current;p.current?.abort();const V=new AbortController;p.current=V;try{const O=await ie(`/api/projects/${t}/sync/source?mainFile=${encodeURIComponent(e)}&page=${T}&x=${I}&y=${X}`,{signal:V.signal});if(p.current!==V||g.current!==B||!_(g.current))return;q(O.path,O.line,O.column)}catch(O){Xl(O)||y.current(ce(O))}finally{p.current===V&&(p.current=null)}};return{pdfTarget:l,pdfViewport:c,sourceJump:h,setPdfViewport:u,clearPdfViewport:()=>u(null),jumpToSource:q,syncSourceToPdf:Y,syncPdfToSource:K,syncVisiblePdfToSource:()=>{c&&K(c.page,c.x,c.y)}}}function Vc(t,e){return`texlite.workspaceLayout:${encodeURIComponent(t)}:${encodeURIComponent(e)}`}function Ql(t,e){try{const n=window.localStorage.getItem(Vc(t,e));if(n==="editor-pdf"||n==="editor-only"||n==="pdf-only")return n}catch{}return"editor-pdf"}function Wg(t,e){const[n,s]=f.useState(()=>Ql(t,e));return f.useEffect(()=>{s(Ql(t,e))},[t,e]),{workspaceLayout:n,setWorkspaceLayout:i=>{s(i);try{window.localStorage.setItem(Vc(t,e),i)}catch{}}}}function Zl(t){const n=t.split(/(?<=\n)/).map(s=>{for(let r=0;r<s.length;r+=1){if(s[r]!=="%")continue;let i=0;for(let l=r-1;l>=0&&s[l]==="\\";l-=1)i+=1;if(i%2===0)return s.slice(0,r)+(s.endsWith(`
11
- `)?`
12
- `:"")}return s}).join("").replace(/\\verb\*?([^\s]).*?\1/g,"").replace(/\\begin\{(?:verbatim\*?|Verbatim|lstlisting|minted)\}(?:\[[^\]]*\])?[\s\S]*?\\end\{(?:verbatim\*?|Verbatim|lstlisting|minted)\}/g,"");return/\\documentclass\s*(?:\[[^\]]*\]\s*)?\{/.test(n)}function Vg({sessions:t,status:e}){const{t:n}=We(),[s,r]=f.useState(!1),i=Math.max(0,t.length-5),l=s&&i>0,a=l?t:t.slice(0,5);return f.useEffect(()=>{t.length<=5&&r(!1)},[t.length]),t.length<=1?null:o.jsxs("div",{className:`collaboration-presence collaboration-${e}`,title:n(`editor.collaboration.${e}`),children:[o.jsx("span",{className:"collaboration-status-dot","aria-label":n(`editor.collaboration.${e}`)}),o.jsxs("div",{className:"collaboration-avatars","aria-label":n("editor.collaboration.activeSessions",{count:t.length}),children:[a.map(c=>{const u=c.editing?n("editor.collaboration.editing"):n("editor.collaboration.viewing"),h=c.permission==="read"?n("common.readOnly"):n("common.readWrite"),d=n("editor.collaboration.sessionTooltip",{name:c.name,username:c.username,file:c.filePath||n("editor.collaboration.joining"),activity:u,permission:h});return o.jsxs("span",{className:`collaboration-avatar${c.editing?" editing":""}${c.local?" local":""}`,style:{"--session-color":c.color},title:d,"aria-label":d,tabIndex:0,children:[Ng(c.name,c.username),o.jsxs("span",{className:"collaboration-avatar-tooltip",role:"tooltip",children:[o.jsx("strong",{children:c.name}),o.jsxs("span",{children:["@",c.username]}),o.jsxs("small",{children:[c.filePath||n("editor.collaboration.joining")," · ",u," · ",h]})]})]},c.clientId)}),i>0&&o.jsx("button",{type:"button",className:"collaboration-avatar collaboration-avatar-overflow","aria-expanded":l,"aria-label":l?n("editor.collaboration.showFewerSessions"):n("editor.collaboration.showMoreSessions",{count:i}),title:l?n("editor.collaboration.showFewerSessions"):n("editor.collaboration.showMoreSessions",{count:i}),onClick:()=>r(c=>!c),children:l?"−":`+${i}`})]})]})}function Hg({value:t,onChange:e}){const{t:n}=We(),[s,r]=f.useState(!1),i=f.useRef(null),l=[{value:"editor-pdf",icon:ll},{value:"editor-only",icon:Vd},{value:"pdf-only",icon:Hd}];return f.useEffect(()=>{if(!s)return;const a=u=>{i.current?.contains(u.target)||r(!1)},c=u=>{u.key==="Escape"&&r(!1)};return document.addEventListener("pointerdown",a),document.addEventListener("keydown",c),()=>{document.removeEventListener("pointerdown",a),document.removeEventListener("keydown",c)}},[s]),o.jsxs("div",{className:"layout-menu",ref:i,children:[o.jsxs("button",{type:"button",className:`layout-trigger${s?" active":""}`,"aria-haspopup":"menu","aria-expanded":s,title:n("editor.layout.current",{layout:n(`editor.layout.${t}.name`)}),onClick:()=>r(a=>!a),children:[o.jsx(ll,{size:15}),o.jsxs("span",{children:[o.jsx("small",{children:n("editor.layout.label")}),n(`editor.layout.${t}.name`)]}),o.jsx(ia,{size:13})]}),s&&o.jsxs("div",{className:"layout-popover",role:"menu","aria-label":n("editor.layout.label"),children:[o.jsx("div",{className:"layout-popover-title",children:n("editor.layout.choose")}),l.map(a=>{const c=a.icon,u=a.value===t;return o.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":u,className:`layout-option${u?" selected":""}`,onClick:()=>{e(a.value),r(!1)},children:[o.jsx(c,{size:19}),o.jsxs("span",{children:[o.jsx("strong",{children:n(`editor.layout.${a.value}.name`)}),o.jsx("small",{children:n(`editor.layout.${a.value}.description`)})]}),u&&o.jsx(Ed,{size:16})]},a.value)})]})]})}function Kg({site:t,project:e,activeFile:n,saveStateLabel:s,editorPreferences:r,activeSessions:i,collaborationStatus:l,reconnectCollaboration:a,protocolUpgradeRequired:c,showEditor:u,filesCollapsed:h,toggleFilesPanel:d,workspaceLayout:p,changeWorkspaceLayout:w,onBack:g,onShare:S,showCitationLibrary:y,citationLibraryOpen:C,onCitationLibrary:_,onHistory:q,onGit:Y,canManageGit:K,formatting:W,readOnly:T,collaborationSynced:I,canFormat:X,activeFormatLease:B,onFormatFile:V,onFormatSelection:O,hasSelection:Q,onAddComment:D,onToggleComments:x,commentsOpen:z,unresolvedCommentCount:we,hasActiveFile:ae,onToggleSettings:xe,settingsOpen:he,compileBusy:ve,sharedCompiling:fe,localCompiling:Se,cancelling:v,compileState:oe,onCompile:ne,onCancelCompile:A}){const{t:U}=We();return o.jsxs("header",{className:"editor-topbar",children:[o.jsx("button",{className:"back",title:U("editor.backToProjects"),"aria-label":U("editor.backToProjects"),onClick:g,children:o.jsx(Dd,{size:18})}),o.jsx("a",{className:"brand-link compact-brand-link",href:"/","aria-label":t.siteName,onClick:F=>{F.preventDefault(),g()},children:o.jsx(Cd,{siteName:t.siteName,compact:!0})}),o.jsxs("div",{className:"project-heading",children:[o.jsx("strong",{children:e.name}),o.jsxs("small",{children:[n," · ",s]})]}),r.vimMode&&o.jsxs("span",{className:"vim-status-badge",title:U("editor.vimOnHint"),children:[o.jsx(qd,{size:14}),U("editor.vimOn")]}),o.jsx(Vg,{sessions:i,status:l}),l==="disconnected"&&!c&&o.jsxs("div",{className:"collaboration-recovery",role:"status",children:[o.jsx("span",{children:U("editor.collaboration.disconnected")}),o.jsx("button",{type:"button",onClick:a,children:U("editor.collaboration.reconnect")})]}),o.jsxs("div",{className:"editor-actions",children:[u&&o.jsxs("button",{className:h?"":"active",onClick:d,children:[h?o.jsx(Wd,{size:15}):o.jsx(aa,{size:15}),U("common.files")]}),o.jsx(Hg,{value:p,onChange:w}),o.jsxs("button",{onClick:S,children:[o.jsx(mi,{size:15}),U("projectSettings.share")]}),y&&o.jsxs("button",{className:C?"active":"",onClick:_,children:[o.jsx(_d,{size:15}),U("citationLibrary.title")]}),o.jsxs("div",{className:"version-action",role:"group","aria-label":U("common.version"),children:[o.jsxs("div",{className:"version-action-label",children:[o.jsx(Td,{size:14}),o.jsx("span",{children:U("common.version")})]}),o.jsxs("div",{className:"version-action-options",children:[o.jsx("button",{type:"button",className:"version-action-history",title:U("history.title"),onClick:q,children:U("history.title")}),o.jsx("button",{type:"button",className:"version-action-git",title:U(K?"git.title":"git.ownerOnly"),disabled:!K,onClick:Y,children:"Git"})]})]}),u&&e.permission!=="read"&&X&&o.jsxs("div",{className:"format-action",role:"group","aria-label":U("editor.format"),"aria-busy":W,children:[o.jsxs("div",{className:"format-action-label",children:[o.jsx(Ud,{size:14}),o.jsx("span",{children:U("editor.format")})]}),o.jsxs("div",{className:"format-action-options",children:[o.jsx("button",{type:"button",className:"format-action-file",title:U("editor.formatFileHint"),onMouseDown:F=>F.preventDefault(),onClick:V,disabled:W||B||!I,children:U("editor.formatFile")}),o.jsx("button",{type:"button",className:"format-action-selected",title:U(Q?"editor.formatSelection":"editor.formatSelectionHint"),onMouseDown:F=>F.preventDefault(),onClick:O,disabled:W||B||!I||!Q,children:U("editor.formatSelected")})]})]}),o.jsxs("div",{className:"comments-action",role:"group","aria-label":U("common.comments"),children:[o.jsxs("div",{className:"comments-action-label",children:[o.jsx(Ld,{size:14}),o.jsx("span",{children:U("common.comments")})]}),o.jsxs("div",{className:"comments-action-options",children:[o.jsx("button",{type:"button",className:"comments-action-add",title:U("editor.addComment"),"aria-label":U("editor.addComment"),onMouseDown:F=>F.preventDefault(),onClick:D,disabled:!ae,children:U("editor.commentsAdd")}),o.jsxs("button",{type:"button",className:`comments-action-all${z?" active":""}`,title:U("editor.commentsAll"),onClick:x,children:[U("editor.commentsAll")," ",we||""]})]})]}),o.jsxs("button",{className:he?"active":"",onClick:xe,children:[o.jsx(Xd,{size:15}),U("common.settings")]}),fe||Se?o.jsxs("button",{className:"compile cancel-compile",title:U("compileControls.cancel"),onClick:A,disabled:v||W||T||!I,children:[v?o.jsx(nt,{className:"spin",size:15}):o.jsx(Rn,{size:15}),U(v?"compileControls.cancelling":"compileControls.cancel")]}):o.jsxs("button",{className:"compile",title:U("editor.compileShortcut"),onClick:ne,disabled:ve||W||T||!I,children:[ve?o.jsx(nt,{className:"spin",size:15}):o.jsx(Kd,{size:15}),U("editor.compile",{engine:e.engine})]})]})]})}function Jg({project:t,filesPanel:e,files:n,visibleEntries:s,activeFile:r,activeMainFile:i,rootDocuments:l,selectedFolder:a,expandedFolders:c,fileDragActive:u,uploadingFiles:h,readOnly:d,editorFontSize:p,outline:w,sourceCursorStore:g,wordCountBusy:S,hasSelection:y,uploadInput:C,setSelectedFolder:_,setExpandedFolders:q,setMoveEntry:Y,setMoveName:K,setMoveDestination:W,setDeleteEntry:T,setFileDialogError:I,setNewFolderName:X,setNewFolderOpen:B,setNewFilePath:V,setNewFileOpen:O,setQuickOpen:Q,setProjectSearchOpen:D,setFileDragActive:x,setFilesCollapsed:z,toggleFilesPanel:we,uploadFiles:ae,upload:xe,openFile:he,jumpToSource:ve,syncSourceToPdf:fe,onWordCount:Se}){const{t:v}=We(),[oe,ne]=f.useState(!1);return o.jsx(ur,{id:"files",order:1,ref:e,defaultSize:16,minSize:12,maxSize:30,collapsible:!0,collapsedSize:0,onCollapse:()=>z(!0),onExpand:()=>z(!1),children:o.jsxs("aside",{className:"left-panel",children:[o.jsxs("section",{className:`files-panel${u?" drop-active":""}`,onDragEnter:A=>{A.dataTransfer.types.includes("Files")&&(A.preventDefault(),!d&&!h&&x(!0))},onDragOver:A=>{A.dataTransfer.types.includes("Files")&&(A.preventDefault(),A.dataTransfer.dropEffect=d||h?"none":"copy")},onDragLeave:A=>{A.currentTarget.contains(A.relatedTarget)||x(!1)},onDrop:A=>{A.preventDefault(),x(!1),!d&&!h&&ae(Array.from(A.dataTransfer.files))},children:[o.jsxs("div",{className:"panel-title",children:[o.jsx("button",{className:"file-size-toggle",type:"button","aria-pressed":oe,title:v(oe?"editor.hideFileSizes":"editor.showFileSizes"),onClick:()=>ne(A=>!A),children:v("common.files")}),o.jsxs("span",{className:"file-tools",children:[o.jsx("button",{"aria-label":v("navigation.quickOpen"),title:`${v("navigation.quickOpen")} (Ctrl/Cmd+P)`,onClick:()=>Q(!0),children:o.jsx(Rd,{size:15})}),o.jsx("button",{"aria-label":v("navigation.projectSearch"),title:`${v("navigation.projectSearch")} (Ctrl/Cmd+Shift+F)`,onClick:()=>D(!0),children:o.jsx($d,{size:15})}),!d&&o.jsxs(o.Fragment,{children:[o.jsx("button",{disabled:h,"aria-label":v("editor.uploadAttachment"),title:v("editor.uploadTo",{folder:a||v("editor.projectRoot")}),onClick:()=>C.current?.click(),children:o.jsx(rl,{size:15})}),o.jsx("button",{"aria-label":v("editor.newFolder"),title:v("editor.newFolder"),onClick:()=>{X(""),B(!0)},children:o.jsx(Ad,{size:15})}),o.jsx("button",{"aria-label":v("editor.newFile"),title:v("editor.newFile"),onClick:()=>{V(a?`${a}/`:""),O(!0)},children:o.jsx(Bd,{size:15})}),o.jsx("input",{ref:C,type:"file",multiple:!0,hidden:!0,onChange:A=>{xe(A)}})]}),o.jsx("button",{"aria-label":v("editor.collapseFiles"),title:v("editor.collapseFiles"),onClick:we,children:o.jsx(aa,{size:15})})]})]}),u&&o.jsxs("div",{className:"file-drop-overlay",children:[o.jsx(rl,{size:24}),o.jsx("strong",{children:v("editor.dropFiles")}),o.jsx("span",{children:v("editor.uploadTo",{folder:a||v("editor.projectRoot")})})]}),o.jsxs("div",{className:"file-list",style:{fontSize:`${p}px`},children:[o.jsx("div",{className:`file-entry folder-entry root-entry${a===""?" selected":""}`,children:o.jsxs("button",{className:"file-entry-main",onClick:()=>_(""),children:[o.jsx(Nd,{size:15}),o.jsx("span",{children:v("editor.projectRoot")})]})}),s.map(A=>{const U=A.path.split("/").length-1,F=A.path.split("/").at(-1),Ee=c.has(A.path),re=l.has(A.path),ke=i===A.path,Me=A.path!==t.mainFile&&!t.mainFile.startsWith(`${A.path}/`);return A.type==="directory"?o.jsxs("div",{className:`file-entry folder-entry${a===A.path?" selected":""}`,style:{paddingLeft:`${U*13+5}px`},children:[o.jsxs("button",{className:"file-entry-main",title:A.path,onClick:()=>{_(A.path),q(Ve=>{const He=new Set(Ve);return He.has(A.path)?He.delete(A.path):He.add(A.path),He})},children:[Ee?o.jsx(ia,{size:13}):o.jsx(Od,{size:13}),o.jsx(Fd,{size:14}),o.jsx("span",{children:F})]}),!d&&o.jsxs(o.Fragment,{children:[o.jsx("button",{className:"file-entry-action",title:v("editor.move"),"aria-label":v("editor.move"),onClick:()=>{Y(A),K(F??""),W("")},children:o.jsx(cl,{size:13})}),Me&&o.jsx("button",{className:"file-entry-action danger-text",title:v("editor.deletePath"),"aria-label":v("editor.deletePath"),onClick:()=>{T(A),I("")},children:o.jsx(Yt,{size:13})})]})]},A.path):o.jsxs("div",{className:`file-entry${r===A.path?" active":""}${re?" root-document":""}${ke?" compile-target":""}`,style:{paddingLeft:`${U*13+18}px`},children:[o.jsxs("button",{className:"file-entry-main",title:ke?v("editor.currentMainDocument",{path:A.path}):re?v("editor.mainDocumentCandidate",{path:A.path}):A.path,onClick:()=>he(A),children:[re?o.jsx(ra,{size:13}):o.jsx(zn,{size:13}),o.jsx("span",{children:F}),ke&&o.jsx("small",{children:v("editor.currentMainShort")})]}),oe&&typeof A.size=="number"&&o.jsx("span",{className:"file-entry-size",title:`${A.size.toLocaleString()} B`,children:Yg(A.size)}),!d&&o.jsxs(o.Fragment,{children:[o.jsx("button",{className:"file-entry-action",title:v("editor.move"),"aria-label":v("editor.move"),onClick:()=>{Y(A),K(F??""),W("")},children:o.jsx(cl,{size:13})}),Me&&o.jsx("button",{className:"file-entry-action danger-text",title:v("editor.deletePath"),"aria-label":v("editor.deletePath"),onClick:()=>{T(A),I("")},children:o.jsx(Yt,{size:13})})]})]},A.path)})]})]}),o.jsx(Gg,{outline:w,activeFile:r,activeMainFile:i,sourceCursorStore:g,wordCountBusy:S,hasSelection:y,jumpToSource:ve,syncSourceToPdf:fe,onWordCount:Se})]})})}function Gg({outline:t,activeFile:e,activeMainFile:n,sourceCursorStore:s,wordCountBusy:r,hasSelection:i,jumpToSource:l,syncSourceToPdf:a,onWordCount:c}){const{t:u}=We(),h=f.useSyncExternalStore(s.subscribe,s.getOutlineLine,s.getOutlineLine);return o.jsxs("section",{className:"outline-panel",children:[o.jsxs("div",{className:"panel-title",children:[o.jsxs("span",{className:"outline-heading",children:[o.jsx(Md,{size:14}),u("common.outline")]}),o.jsxs("span",{className:"word-count-actions",role:"group","aria-label":u("editor.wordCountTitle"),children:[o.jsxs("button",{type:"button",title:u("editor.wordCountFullHint"),onClick:()=>c("full"),disabled:r||!n,children:[r?o.jsx(nt,{className:"spin",size:12}):o.jsx(al,{size:12}),u("editor.wordCountFull")]}),o.jsxs("button",{type:"button",title:u("editor.wordCountSelectionHint"),onClick:()=>c("selection"),disabled:r||!i,children:[r?o.jsx(nt,{className:"spin",size:12}):o.jsx(al,{size:12}),u("editor.wordCountSelection")]})]})]}),o.jsxs("div",{className:"outline",children:[t.map((d,p)=>o.jsxs("button",{className:`outline-item${e===d.path&&h===d.line?" current":""}`,title:`${d.path}:${d.line}`,onClick:()=>{l(d.path,d.line,1),a(d.path,d.line,1)},children:[o.jsx("span",{className:"outline-guides","aria-hidden":!0,style:{width:`${d.level*12}px`}}),o.jsx("small",{children:d.path===e?d.line:d.path.split("/").at(-1)}),o.jsx("span",{className:"outline-title",children:d.title})]},`${d.path}-${d.line}-${p}`)),t.length===0&&o.jsx("p",{className:"muted padded",children:u("editor.noOutline")})]})]})}function Yg(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:t<1024*1024*1024?`${(t/1024/1024).toFixed(1)} MB`:`${(t/1024/1024/1024).toFixed(1)} GB`}const Xg=f.lazy(()=>vt(()=>import("./LatexEditor-DSopAHbC.js"),__vite__mapDeps([4,2,5,1,3,6,7,8,9,10])).then(t=>({default:t.LatexEditor})));function Qg({project:t,activeFile:e,activeMainFile:n,openTabs:s,content:r,loadedFile:i,readOnly:l,comments:a,focusComment:c,editorPreferences:u,completionIndex:h,nativeSpellCheck:d,spellCheckIssues:p,spellCheckJump:w,sourceJump:g,collaborativeText:S,collaborationAwareness:y,undoManager:C,editorNotice:_,activateTab:q,closeTab:Y,handleTabKeyDown:K,updateEditorContent:W,setSelection:T,onCommentClick:I,onSpellCheckReplace:X,onCursor:B}){const{t:V}=We();return o.jsx(ur,{id:"source",order:2,defaultSize:42,minSize:22,children:o.jsxs("main",{className:"source-panel",children:[u.openFilesInTabs&&s.length>0&&o.jsx("div",{className:"editor-tabs-bar",role:"tablist","aria-label":V("editor.openFiles"),children:o.jsx("div",{className:"editor-tabs-scroll",children:s.map((O,Q)=>{const D=O===e,x=O===(n||t.mainFile),z=O.split("/").at(-1)||O;return o.jsxs("div",{className:`editor-tab-item${D?" active":""}`,role:"presentation",children:[o.jsxs("button",{id:`editor-tab-${encodeURIComponent(O)}`,type:"button",role:"tab","aria-selected":D,"aria-controls":"editor-source-content",tabIndex:D?0:-1,className:`editor-tab${D?" active":""}${x?" main-tab":""}`,onClick:()=>q(O),onKeyDown:we=>K(we,Q),title:O,children:[o.jsx("span",{className:"editor-tab-icon",children:x?o.jsx(ra,{size:13}):o.jsx(zn,{size:13})}),o.jsx("span",{className:"editor-tab-title",children:z}),x&&o.jsx("small",{className:"editor-tab-badge",children:V("editor.currentMainShort")})]}),o.jsx("button",{type:"button",className:"editor-tab-close",title:V("common.close"),"aria-label":`${V("common.close")} ${z}`,onClick:()=>Y(O),children:o.jsx(Rn,{size:12})})]},O)})})}),o.jsxs("div",{id:"editor-source-content",className:"editor-content-container",children:[o.jsx(f.Suspense,{fallback:o.jsxs("div",{className:"preview-empty",children:[o.jsx(nt,{className:"spin",size:22}),o.jsx("span",{children:V("common.loading")})]}),children:o.jsx(Xg,{value:r,filePath:e,readOnly:l,comments:a,focusComment:c,preferences:u,nativeSpellCheck:d,completionIndex:h,spellCheckIssues:p,spellCheckJump:w,jumpTo:i===e&&g?.path===e?g:null,searchRequest:0,collaboration:S?{text:S,awareness:y,undoManager:l?void 0:C}:void 0,onChange:W,onSelection:T,onCommentClick:I,onSpellCheckReplace:X,onCursor:B},e)}),_&&o.jsx("div",{className:"editor-centered-notice",role:"status","aria-live":"polite",children:_})]})]})})}function ea({diagnostics:t,files:e,empty:n,tone:s,onJump:r}){const{t:i}=We(),l=s==="error"?Mi:$t;return t.length?o.jsx("div",{className:`compile-diagnostic-list compile-${s}`,children:t.map((a,c)=>{const u=tw(a.file,e),h=!!(u&&a.line);return o.jsxs("button",{type:"button",disabled:!h,className:"compile-diagnostic-row",onClick:()=>{u&&a.line&&r(u,a.line,a.column??1)},children:[o.jsx(l,{size:15}),o.jsxs("span",{children:[o.jsx("strong",{children:a.message}),o.jsxs("small",{children:[a.phase,u?` · ${u}${a.line?`:${a.line}`:""}`:a.line?` · ${i("editor.lineNumber",{line:a.line})}`:""]})]})]},`${a.phase}-${a.file??""}-${a.line??0}-${c}`)})}):o.jsxs("div",{className:`compile-empty compile-${s}`,children:[o.jsx(l,{size:26}),o.jsx("span",{children:n})]})}function hi({lines:t,empty:e,tone:n="log"}){const s=n==="error"?Mi:n==="warning"?$t:gi;return t.length?o.jsx("pre",{className:`compile-output compile-${n}`,children:t.join(`
13
- `)}):o.jsxs("div",{className:`compile-empty compile-${n}`,children:[o.jsx(s,{size:26}),o.jsx("span",{children:e})]})}function Zg({projectId:t,mainFile:e,artifacts:n,preview:s,loading:r,onView:i}){const{t:l}=We(),a=c=>`/api/projects/${t}/compile/artifacts?mainFile=${encodeURIComponent(e)}&path=${encodeURIComponent(c)}&download=1`;return n.length?o.jsxs("div",{className:"artifact-browser",children:[o.jsx("div",{className:"artifact-list",children:n.map(c=>o.jsxs("div",{className:`artifact-row${s?.path===c.path?" active":""}`,children:[o.jsxs("button",{type:"button",disabled:!c.viewable,title:c.viewable?l("editor.viewArtifact"):l("editor.downloadToView"),onClick:()=>i(c),children:[o.jsx(zn,{size:14}),o.jsxs("span",{children:[o.jsx("strong",{children:c.path}),o.jsx("small",{children:nw(c.size)})]})]}),o.jsx("a",{href:a(c.path),title:l("editor.downloadArtifact"),"aria-label":l("editor.downloadArtifact"),children:o.jsx(Ks,{size:14})})]},c.path))}),o.jsx("div",{className:"artifact-preview",children:r?o.jsxs("div",{className:"compile-empty",children:[o.jsx(nt,{className:"spin",size:24}),o.jsx("span",{children:l("common.loading")})]}):s?o.jsxs(o.Fragment,{children:[o.jsxs("header",{children:[o.jsx("strong",{children:s.path}),o.jsxs("a",{href:a(s.path),children:[o.jsx(Ks,{size:13}),l("projects.download")]})]}),o.jsx("pre",{children:s.content})]}):o.jsxs("div",{className:"compile-empty",children:[o.jsx(zn,{size:24}),o.jsx("span",{children:l("editor.selectArtifact")})]})})]}):o.jsxs("div",{className:"compile-empty",children:[o.jsx(la,{size:26}),o.jsx("span",{children:l("editor.noArtifacts")})]})}function ew({mainFile:t,disabled:e,cleaning:n,onCleanCache:s,onCleanArtifacts:r}){const{t:i}=We();return o.jsxs("div",{className:"compile-clean-panel",children:[o.jsxs("div",{className:"compile-clean-intro",children:[o.jsx($t,{size:28}),o.jsxs("div",{children:[o.jsx("strong",{children:i("editor.cleanTitle")}),o.jsx("p",{children:i("editor.cleanDescription",{file:t})})]})]}),o.jsxs("div",{className:"compile-clean-actions",children:[o.jsxs("article",{children:[o.jsx("div",{className:"compile-clean-action-icon",children:o.jsx(wi,{size:19})}),o.jsxs("div",{children:[o.jsx("strong",{children:i("editor.cleanCache")}),o.jsx("p",{children:i("editor.cleanCacheDescription")}),o.jsxs("button",{type:"button",disabled:e||n,onClick:s,children:[n?o.jsx(nt,{className:"spin",size:14}):o.jsx(wi,{size:14}),i("editor.cleanCache")]})]})]}),o.jsxs("article",{className:"danger",children:[o.jsx("div",{className:"compile-clean-action-icon",children:o.jsx(Yt,{size:19})}),o.jsxs("div",{children:[o.jsx("strong",{children:i("editor.cleanArtifacts")}),o.jsx("p",{children:i("editor.cleanArtifactsDescription")}),o.jsxs("button",{type:"button",className:"danger",disabled:e||n,onClick:r,children:[n?o.jsx(nt,{className:"spin",size:14}):o.jsx(Yt,{size:14}),i("editor.cleanArtifacts")]})]})]})]})]})}function tw(t,e){if(!t)return null;const n=e.filter(a=>a.type==="file").map(a=>a.path),s=t.replaceAll("\\","/").replace(/^\.\//,"");if(n.includes(s))return s;const r=n.filter(a=>s.endsWith(`/${a}`));if(r.length===1)return r[0];const i=s.split("/").at(-1),l=n.filter(a=>a.split("/").at(-1)===i);return l.length===1?l[0]:null}function nw(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/1024/1024).toFixed(1)} MB`}const sw=f.lazy(()=>na().then(t=>({default:t.PdfPreview})));function rw({projectId:t,activeMainFile:e,previewTab:n,diagnosticTab:s,pdfUrl:r,pdfLoadingMode:i,pdfLoading:l,pdfCompiledAt:a,pdfCompiledLabel:c,pdfTargetLabel:u,pdfDownloadUrl:h,pdfTarget:d,pdfViewport:p,activeFile:w,compileBusy:g,compileLog:S,compileDiagnostics:y,compileMessages:C,artifacts:_,artifactPreview:q,artifactLoading:Y,cleaning:K,readOnly:W,collaborationSynced:T,workspaceLayout:I,showSyncResize:X,diagnosticCount:B,selectPreviewTab:V,changeWorkspaceLayout:O,onSetNotice:Q,onSetPdfViewport:D,syncVisiblePdfToSource:x,syncCurrentSourceToPdf:z,syncPdfToSource:we,canSyncWithPdf:ae,files:xe,jumpToSource:he,onSetCleanMode:ve,cleanCompile:fe,viewArtifact:Se}){const{t:v}=We();return o.jsxs(o.Fragment,{children:[X&&o.jsxs(Fi,{className:"resize-handle sync-resize-handle",children:[o.jsx(oa,{className:"resize-grip",size:12}),o.jsxs("span",{className:"sync-direction-buttons",onPointerDown:oe=>oe.stopPropagation(),children:[o.jsx("button",{disabled:!p||!ae,title:v(ae?"editor.showInSource":"editor.syncTexOnlyForMain"),"aria-label":v("editor.showInSource"),onClick:()=>{if(!ae){Q(v("editor.syncTexOnlyForMain"));return}x()},children:o.jsx("span",{"aria-hidden":!0,children:"←"})}),o.jsx("button",{disabled:!w||!r||!ae,title:v(ae?"editor.showInPdf":"editor.syncTexOnlyForMain"),"aria-label":v("editor.showInPdf"),onClick:()=>{if(!ae){Q(v("editor.syncTexOnlyForMain"));return}z()},children:o.jsx("span",{"aria-hidden":!0,children:"→"})})]})]}),o.jsx(ur,{id:"preview",order:3,defaultSize:42,minSize:22,children:o.jsxs("section",{className:"preview-panel",children:[o.jsxs("div",{className:"preview-tabs",children:[o.jsxs("div",{className:"preview-tab-list",role:"tablist","aria-label":v("editor.outputTabs"),children:[o.jsxs("button",{role:"tab","aria-selected":n==="pdf",className:`pdf-tab${n==="pdf"?" active":""}`,onClick:()=>V("pdf"),title:a?v("editor.pdfCompiledAtFor",{file:e,time:new Date(a).toLocaleString(as.resolvedLanguage)}):v("editor.currentMainDocument",{path:e}),children:[o.jsx(zn,{size:16}),o.jsxs("span",{className:"pdf-tab-label",children:["PDF · ",u,c&&o.jsx("small",{children:c})]})]}),o.jsxs("button",{role:"tab","aria-selected":n==="diagnostics",className:`diagnostics-tab${n==="diagnostics"?" active":""}`,onClick:()=>V("diagnostics"),children:[o.jsx(gi,{size:14}),v("editor.outputTabs"),o.jsx("span",{children:B})]})]}),h&&o.jsxs("a",{className:"pdf-download-top",href:h,download:!0,title:v("editor.downloadPdf"),"aria-label":v("editor.downloadPdf"),children:[o.jsx(Ks,{size:15}),o.jsx("span",{children:v("editor.downloadPdf")})]})]}),n==="diagnostics"&&o.jsxs("div",{className:"preview-subtabs",role:"tablist","aria-label":v("editor.outputTabs"),children:[o.jsxs("button",{role:"tab","aria-selected":s==="log",className:s==="log"?"active":"",onClick:()=>V("log"),children:[o.jsx(gi,{size:13}),v("editor.log")]}),o.jsxs("button",{role:"tab","aria-selected":s==="warnings",className:s==="warnings"?"active":"",onClick:()=>V("warnings"),children:[o.jsx($t,{size:13}),v("editor.warnings"),o.jsx("span",{children:C.warnings.length})]}),o.jsxs("button",{role:"tab","aria-selected":s==="errors",className:s==="errors"?"active":"",onClick:()=>V("errors"),children:[o.jsx(Mi,{size:13}),v("editor.errors"),o.jsx("span",{children:C.errors.length})]}),o.jsxs("button",{role:"tab","aria-selected":s==="artifacts",className:s==="artifacts"?"active":"",onClick:()=>V("artifacts"),children:[o.jsx(la,{size:13}),v("editor.artifacts"),o.jsx("span",{children:_.length})]}),o.jsxs("button",{role:"tab","aria-selected":s==="clean",className:s==="clean"?"active":"",onClick:()=>V("clean"),children:[o.jsx(wi,{size:13}),v("editor.clean")]})]}),o.jsxs("div",{className:`preview-content preview-${n} ${n==="diagnostics"?`preview-${s}`:""}`,children:[n==="pdf"&&(r?o.jsx(f.Suspense,{fallback:o.jsxs("div",{className:"pdf-loading-state",role:"status","aria-live":"polite",children:[o.jsx(nt,{className:"spin",size:24}),o.jsx("span",{children:v("editor.loadingPdf")})]}),children:o.jsx(sw,{url:r,loadingMode:i,target:d,compiling:g,onViewportLocation:(oe,ne,A)=>D({page:oe,x:ne,y:A}),onDoubleClickLocation:(oe,ne,A)=>{if(D({page:oe,x:ne,y:A}),!ae){Q(v("editor.syncTexOnlyForMain"));return}we(oe,ne,A)}})}):l?o.jsxs("div",{className:"pdf-loading-state",role:"status","aria-live":"polite",children:[o.jsx(nt,{className:"spin",size:24}),o.jsx("span",{children:v("editor.loadingPdf")})]}):o.jsxs("div",{className:"preview-empty",children:[o.jsx(zn,{size:28}),o.jsx("strong",{children:v("editor.preview")}),o.jsx("span",{children:v("editor.previewHint")})]})),n==="diagnostics"&&s==="log"&&o.jsx(hi,{lines:S?S.split(`
14
- `):[],empty:v(g?"editor.compiling":"editor.noLog")}),n==="diagnostics"&&s==="warnings"&&(y?o.jsx(ea,{tone:"warning",diagnostics:y.warnings,files:xe,empty:v("editor.noWarnings"),onJump:(oe,ne,A)=>{I==="pdf-only"&&O("editor-pdf"),he(oe,ne,A)}}):o.jsx(hi,{tone:"warning",lines:C.warnings,empty:v("editor.noWarnings")})),n==="diagnostics"&&s==="errors"&&(y?o.jsx(ea,{tone:"error",diagnostics:y.errors,files:xe,empty:v("editor.noErrors"),onJump:(oe,ne,A)=>{I==="pdf-only"&&O("editor-pdf"),he(oe,ne,A)}}):o.jsx(hi,{tone:"error",lines:C.errors,empty:v("editor.noErrors")})),n==="diagnostics"&&s==="artifacts"&&o.jsx(Zg,{projectId:t,mainFile:e,artifacts:_,preview:q,loading:Y,onView:oe=>{Se(oe)}}),n==="diagnostics"&&s==="clean"&&o.jsx(ew,{mainFile:e,disabled:W||!T||g,cleaning:K,onCleanCache:()=>ve("cache"),onCleanArtifacts:()=>ve("artifacts")})]})]})})]})}function fi(t,e){!(t.ctrlKey||t.metaKey)||t.key!=="Enter"||t.nativeEvent.isComposing||(t.preventDefault(),t.stopPropagation(),e())}function iw({comment:t,currentUserId:e,onFocus:n,onToggle:s,onReply:r,onEdit:i,onDelete:l,onEditReply:a,onDeleteReply:c}){const{t:u}=We(),[h,d]=f.useState(!1),[p,w]=f.useState(""),[g,S]=f.useState(!1),[y,C]=f.useState(t.content),[_,q]=f.useState(!1),[Y,K]=f.useState(null),[W,T]=f.useState(""),[I,X]=f.useState(null),B=async x=>{x?.preventDefault(),p.trim()&&await r(p)&&(w(""),d(!1))},V=async x=>{x?.preventDefault(),y.trim()&&await i(y)&&S(!1)},O=async x=>{x?.preventDefault(),!(!Y||!W.trim())&&await a(Y,W)&&K(null)},Q=t.authorUsername,D=x=>new Date(x).toLocaleString(as.resolvedLanguage);return o.jsxs(o.Fragment,{children:[o.jsxs("article",{className:`comment-thread${t.resolved?" resolved":""}${t.orphaned?" orphaned":""}`,onClick:()=>{window.getSelection()?.toString()||n()},children:[o.jsxs("header",{className:"comment-header",children:[o.jsxs("span",{className:"comment-author",children:[o.jsx("strong",{children:t.authorDisplayName??Q??u("editor.deletedUser")}),Q&&o.jsxs("small",{children:["@",Q]})]}),o.jsxs("span",{className:"comment-times",children:[o.jsx("time",{dateTime:t.createdAt,title:new Date(t.createdAt).toISOString(),children:D(t.createdAt)}),t.editedAt&&o.jsx("small",{children:u("editor.editedAt",{time:D(t.editedAt)})})]})]}),o.jsx("div",{className:"comment-location",children:t.orphaned?u("editor.orphaned"):u("editor.line",{line:t.startLine})}),t.selectedText&&o.jsx("blockquote",{className:"comment-selected-text",children:t.selectedText}),g?o.jsxs("form",{className:"comment-reply-form comment-edit-form",onSubmit:x=>{V(x)},onClick:x=>x.stopPropagation(),children:[o.jsx("textarea",{autoFocus:!0,rows:4,value:y,onChange:x=>C(x.target.value),onKeyDown:x=>fi(x,V)}),o.jsxs("div",{children:[o.jsx("button",{type:"button",onClick:()=>S(!1),children:u("common.cancel")}),o.jsxs("button",{className:"primary",type:"submit",disabled:!y.trim(),children:[o.jsx(ul,{size:13}),u("editor.saveChanges")]})]})]}):o.jsx("p",{className:"comment-content",children:t.content}),t.replies.length>0&&o.jsx("div",{className:"comment-replies",children:t.replies.map(x=>o.jsxs("div",{className:"comment-reply",children:[o.jsxs("header",{children:[o.jsxs("span",{className:"comment-author",children:[o.jsx("strong",{children:x.authorDisplayName??x.authorUsername??u("editor.deletedUser")}),x.authorUsername&&o.jsxs("small",{children:["@",x.authorUsername]})]}),o.jsxs("span",{className:"comment-times",children:[o.jsx("time",{dateTime:x.createdAt,title:new Date(x.createdAt).toISOString(),children:D(x.createdAt)}),x.editedAt&&o.jsx("small",{children:u("editor.editedAt",{time:D(x.editedAt)})})]})]}),Y===x.id?o.jsxs("form",{className:"comment-reply-form comment-edit-form",onSubmit:z=>{O(z)},onClick:z=>z.stopPropagation(),children:[o.jsx("textarea",{autoFocus:!0,rows:3,value:W,onChange:z=>T(z.target.value),onKeyDown:z=>fi(z,O)}),o.jsxs("div",{children:[o.jsx("button",{type:"button",onClick:()=>K(null),children:u("common.cancel")}),o.jsxs("button",{className:"primary",type:"submit",disabled:!W.trim(),children:[o.jsx(ul,{size:13}),u("editor.saveChanges")]})]})]}):o.jsx("p",{className:"comment-content",children:x.content}),x.authorId===e&&Y!==x.id&&o.jsxs("div",{className:"comment-owner-actions",children:[o.jsx("button",{title:u("editor.editReply"),"aria-label":u("editor.editReply"),onClick:z=>{z.stopPropagation(),K(x.id),T(x.content)},children:o.jsx(il,{size:12})}),o.jsx("button",{className:"danger-text",title:u("editor.deleteReply"),"aria-label":u("editor.deleteReply"),onClick:z=>{z.stopPropagation(),X(x.id)},children:o.jsx(Yt,{size:12})})]})]},x.id))}),o.jsxs("div",{className:"comment-actions",children:[o.jsxs("button",{className:"resolve",onClick:x=>{x.stopPropagation(),s()},children:[t.resolved?o.jsx(Gd,{size:13}):o.jsx(zd,{size:13}),t.resolved?u("editor.reopen"):u("editor.resolve")]}),o.jsxs("button",{className:"reply-action",onClick:x=>{x.stopPropagation(),d(z=>!z)},children:[o.jsx(Jd,{size:13}),u("editor.reply")]}),t.authorId===e&&!g&&o.jsxs("span",{className:"comment-owner-actions",children:[o.jsx("button",{title:u("editor.editComment"),"aria-label":u("editor.editComment"),onClick:x=>{x.stopPropagation(),C(t.content),S(!0)},children:o.jsx(il,{size:13})}),o.jsx("button",{className:"danger-text",title:u("editor.deleteComment"),"aria-label":u("editor.deleteComment"),onClick:x=>{x.stopPropagation(),q(!0)},children:o.jsx(Yt,{size:13})})]})]}),h&&o.jsxs("form",{className:"comment-reply-form",onSubmit:x=>{B(x)},onClick:x=>x.stopPropagation(),children:[o.jsx("textarea",{autoFocus:!0,rows:3,value:p,placeholder:u("editor.replyPlaceholder"),onChange:x=>w(x.target.value),onKeyDown:x=>fi(x,B)}),o.jsxs("div",{children:[o.jsx("button",{type:"button",onClick:()=>{d(!1),w("")},children:u("common.cancel")}),o.jsxs("button",{className:"primary",type:"submit",disabled:!p.trim(),children:[o.jsx(Yd,{size:13}),u("editor.sendReply")]})]})]})]}),o.jsx(ds,{open:_,title:u("editor.deleteCommentTitle"),description:u("editor.deleteCommentDescription",{count:t.replies.length}),confirmLabel:u("common.delete"),danger:!0,onCancel:()=>q(!1),onConfirm:()=>{l().then(x=>{x&&q(!1)})}}),o.jsx(ds,{open:!!I,title:u("editor.deleteReplyTitle"),description:u("editor.deleteReplyDescription"),confirmLabel:u("common.delete"),danger:!0,onCancel:()=>X(null),onConfirm:()=>{I&&c(I).then(x=>{x&&X(null)})}})]})}function ow({open:t,onOpenChange:e,project:n,projectId:s}){const{t:r}=We(),[i,l]=f.useState([]),[a,c]=f.useState([]),[u,h]=f.useState(""),[d,p]=f.useState("read"),[w,g]=f.useState(null),[S,y]=f.useState(""),C=n.permission==="owner",_=async()=>{try{const[T,I]=await Promise.all([ie(`/api/projects/${s}/members`),ie("/api/users")]);l(T.members),c(I.users.filter(X=>X.id!==n.ownerId))}catch(T){y(ce(T))}};f.useEffect(()=>{t&&_()},[t,s]);const q=async()=>{if(u)try{await ie(`/api/projects/${s}/members/${u}`,{method:"PUT",body:JSON.stringify({permission:d})}),h(""),p("read"),await _()}catch(T){y(ce(T))}},Y=async(T,I)=>{try{await ie(`/api/projects/${s}/members/${T.id}`,{method:"PUT",body:JSON.stringify({permission:I})}),await _()}catch(X){y(ce(X))}},K=async()=>{if(w)try{await ie(`/api/projects/${s}/members/${w.id}`,{method:"DELETE"}),g(null),await _()}catch(T){y(ce(T))}},W=a.filter(T=>!i.some(I=>I.id===T.id));return o.jsxs(o.Fragment,{children:[o.jsx(Ht,{open:t,wide:!0,title:r("projectSettings.share"),description:r("projectSettings.shareDescription"),onOpenChange:e,footer:o.jsx("button",{onClick:()=>e(!1),children:r("common.close")}),children:o.jsxs("div",{className:"share-dialog",children:[S&&o.jsx("p",{className:"error",children:S}),o.jsxs("div",{className:"share-owner",children:[o.jsx(mi,{size:17}),o.jsxs("span",{children:[o.jsx("small",{children:r("projects.owner")}),o.jsx("strong",{children:n.ownerDisplayName??n.ownerUsername})]})]}),C&&o.jsxs("div",{className:"share-add",children:[o.jsxs("label",{className:"form-field",children:[r("common.user"),o.jsxs("select",{value:u,onChange:T=>h(T.target.value),children:[o.jsx("option",{value:"",children:r("projectSettings.chooseUser")}),W.map(T=>o.jsx("option",{value:T.id,children:T.displayName??T.username},T.id))]})]}),o.jsxs("label",{className:"form-field",children:[r("common.permission"),o.jsxs("select",{value:d,onChange:T=>p(T.target.value),children:[o.jsx("option",{value:"read",children:r("common.readOnly")}),o.jsx("option",{value:"edit",children:r("common.readWrite")})]})]}),o.jsxs("button",{className:"primary icon-button",disabled:!u,onClick:()=>{q()},children:[o.jsx(Id,{size:15}),r("projectSettings.addMember")]})]}),o.jsxs("div",{className:"shared-members-heading",children:[o.jsx("strong",{children:r("projectSettings.members")}),o.jsx("span",{children:i.length})]}),o.jsxs("div",{className:"shared-members",children:[i.map(T=>o.jsxs("div",{className:"shared-member",children:[o.jsxs("span",{className:"member-identity",children:[o.jsx("span",{className:"member-avatar",children:(T.displayName??T.username).slice(0,1).toLocaleUpperCase()}),o.jsxs("span",{children:[o.jsx("strong",{children:T.displayName??T.username}),o.jsxs("small",{children:["@",T.username]})]})]}),o.jsxs("span",{className:"member-controls",children:[o.jsxs("select",{"aria-label":r("common.permission"),disabled:!C,value:T.permission,onChange:I=>{Y(T,I.target.value)},children:[o.jsx("option",{value:"read",children:r("common.readOnly")}),o.jsx("option",{value:"edit",children:r("common.readWrite")})]}),C&&o.jsx("button",{className:"icon-only danger-text",title:r("common.remove"),"aria-label":r("common.remove"),onClick:()=>g(T),children:o.jsx(Yt,{size:15})})]})]},T.id)),i.length===0&&o.jsxs("div",{className:"share-empty",children:[o.jsx(mi,{size:24}),o.jsx("span",{children:r("projectSettings.noMembers")})]})]})]})}),o.jsx(ds,{open:!!w,title:r("projectSettings.removeTitle"),description:r("projectSettings.removeDescription",{username:w?.username??""}),confirmLabel:r("common.remove"),danger:!0,onCancel:()=>g(null),onConfirm:()=>{K()}})]})}const lw=f.lazy(()=>vt(()=>import("./CitationLibraryDialog-BmWFXTW2.js"),__vite__mapDeps([11,2,1,3,12,7,13,6,8,14,15])).then(t=>({default:t.CitationLibraryDialog}))),aw=f.lazy(()=>vt(()=>import("./GitDialog-BCfSHuMB.js"),__vite__mapDeps([16,2,1,3,7,17,18,13,6,8,9,10])).then(t=>({default:t.GitDialog}))),cw=f.lazy(()=>vt(()=>import("./HistoryDialog-BtQhyTr9.js"),__vite__mapDeps([19,2,1,3,20,7,6,8,9,10])).then(t=>({default:t.HistoryDialog}))),uw=f.lazy(()=>vt(()=>import("./ProjectNavigationDialogs-BTLcRY7i.js"),__vite__mapDeps([21,2,1,3,8,7,6])).then(t=>({default:t.ProjectSearchDialog}))),dw=f.lazy(()=>vt(()=>import("./ProjectNavigationDialogs-BTLcRY7i.js"),__vite__mapDeps([21,2,1,3,8,7,6])).then(t=>({default:t.QuickOpenDialog})));function hw({user:t,project:e,projectId:n,activeFile:s,content:r,maxCitationBibtexBytes:i,files:l,directoryEntries:a,readOnly:c,workspaceLayout:u,changeWorkspaceLayout:h,resourcePreview:d,resourcePreviewLoading:p,setResourcePreview:w,setResourcePreviewLoading:g,uploadConflict:S,setUploadConflict:y,uploadFiles:C,cleanMode:_,setCleanMode:q,cleanCompile:Y,newFileOpen:K,setNewFileOpen:W,newFilePath:T,setNewFilePath:I,newFolderOpen:X,setNewFolderOpen:B,newFolderName:V,setNewFolderName:O,selectedFolder:Q,fileDialogError:D,setFileDialogError:x,createFile:z,createFolder:we,moveEntry:ae,setMoveEntry:xe,moveName:he,setMoveName:ve,moveDestination:fe,setMoveDestination:Se,movePath:v,deleteEntry:oe,setDeleteEntry:ne,deleteActiveSessions:A,removePath:U,commentOpen:F,setCommentOpen:Ee,selection:re,commentText:ke,setCommentText:Me,addComment:Ve,shareOpen:He,setShareOpen:le,citationLibraryOpen:pe,setCitationLibraryOpen:Pe,insertCitationAtCursor:Qe,quickOpen:zt,setQuickOpen:Tt,projectSearchOpen:E,setProjectSearchOpen:te,openFile:ye,jumpToSource:Ke,historyOpen:_e,setHistoryOpen:de,gitOpen:ht,setGitOpen:Ne,save:R,permissionDowngrade:$,permissionDowngradeBusy:L,dismissPermissionDowngrade:Z,discardPermissionDraft:ft}){const{t:N}=We();return o.jsxs(o.Fragment,{children:[$&&o.jsx(Ht,{open:!0,title:N("editor.collaboration.permissionDowngradeTitle"),description:$.localDraftReady&&$.otherTabDraft?N("editor.collaboration.permissionDowngradeMultipleDrafts"):$.otherTabDraft?N("editor.collaboration.permissionDowngradeOtherTab"):$.localDraftReady?N("editor.collaboration.permissionDowngradeDescription",{previous:N("common.readWrite")}):N("editor.collaboration.permissionDowngradeNoDraft"),onOpenChange:M=>{!M&&!L&&Z()},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",disabled:L,onClick:Z,children:$.localDraftReady?N("editor.collaboration.permissionDowngradeKeep"):N("common.close")}),!$.otherTabDraft&&o.jsxs("button",{type:"button",className:"danger",disabled:L,onClick:()=>{ft()},children:[L?o.jsx(nt,{className:"spin",size:14}):$.localDraftReady?o.jsx(Yt,{size:14}):o.jsx(Pd,{size:14}),$.localDraftReady?N("editor.collaboration.permissionDowngradeDiscard"):N("editor.collaboration.permissionDowngradeReload")]})]}),children:o.jsx("div",{})}),o.jsxs(Ht,{open:!!d,extraWide:d?.kind==="image"||d?.kind==="pdf"||d?.kind==="text",title:d?.path??"",description:d?.kind==="large"?N("editor.resourceTooLarge",{size:fw(d.size),limit:`${Oi/1024/1024} MB`}):N(`editor.resourcePreview.${d?.kind??"text"}`),onOpenChange:M=>{M||(w(null),g(!1))},footer:d&&o.jsxs("a",{className:"primary resource-download",href:`${d.url}&download=1`,download:!0,children:[o.jsx(Ks,{size:14}),N("editor.downloadResource")]}),children:[d?.kind==="large"&&o.jsxs("div",{className:"resource-preview-message",children:[o.jsx(ol,{size:34}),o.jsx("strong",{children:N("editor.resourceTooLargeTitle")}),o.jsx("span",{children:N("editor.resourceTooLargeDescription")})]}),d?.kind==="unsupported"&&o.jsxs("div",{className:"resource-preview-message",children:[o.jsx(ol,{size:34}),o.jsx("strong",{children:N("editor.resourceUnsupportedTitle")}),o.jsx("span",{children:N("editor.resourceUnsupportedDescription")})]}),d?.kind==="image"&&o.jsx("div",{className:"resource-image-wrap",children:o.jsx("img",{className:"resource-image",src:d.url,alt:d.path})}),d?.kind==="pdf"&&o.jsx("iframe",{className:"resource-pdf",src:d.url,title:d.path}),d?.kind==="text"&&(p?o.jsxs("div",{className:"resource-preview-message",children:[o.jsx(nt,{className:"spin",size:24}),o.jsx("span",{children:N("common.loading")})]}):o.jsx("pre",{className:"resource-text",children:d.content}))]}),o.jsx(ds,{open:!!S,title:N("editor.uploadOverwriteTitle"),description:N("editor.uploadOverwriteDescription",{files:S?.collisions.join(", ")??""}),confirmLabel:N("editor.uploadOverwrite"),danger:!0,onCancel:()=>y(null),onConfirm:()=>{const M=S;y(null),M&&C(M.files,new Set(M.collisions),M.directory)}}),o.jsx(ds,{open:!!_,title:N(_==="cache"?"editor.cleanCacheConfirmTitle":"editor.cleanArtifactsConfirmTitle"),description:N(_==="cache"?"editor.cleanCacheConfirmDescription":"editor.cleanArtifactsConfirmDescription"),confirmLabel:N("editor.cleanConfirm"),danger:_==="artifacts",onCancel:()=>q(null),onConfirm:()=>{const M=_;q(null),M&&Y(M)}}),o.jsx(Ht,{open:K,title:N("editor.newFile"),description:N("editor.newFileDescription"),onOpenChange:M=>{W(M),M||x("")},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>W(!1),children:N("common.cancel")}),o.jsx("button",{className:"primary",onClick:()=>{z()},children:N("common.create")})]}),children:o.jsxs(o.Fragment,{children:[D&&o.jsx("p",{className:"error dialog-error",children:D}),o.jsxs("label",{className:"form-field",children:[N("editor.filePath"),o.jsx("input",{autoFocus:!0,value:T,onChange:M=>I(M.target.value),onKeyDown:M=>{M.key==="Enter"&&!M.nativeEvent.isComposing&&(M.preventDefault(),z())}})]})]})}),o.jsx(Ht,{open:X,title:N("editor.newFolder"),description:N("editor.folderDestination",{folder:Q||N("editor.projectRoot")}),onOpenChange:M=>{B(M),M||x("")},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>B(!1),children:N("common.cancel")}),o.jsx("button",{className:"primary",onClick:()=>{we()},children:N("common.create")})]}),children:o.jsxs(o.Fragment,{children:[D&&o.jsx("p",{className:"error dialog-error",children:D}),o.jsxs("label",{className:"form-field",children:[N("editor.folderName"),o.jsx("input",{autoFocus:!0,value:V,onChange:M=>O(M.target.value),onKeyDown:M=>{M.key==="Enter"&&we()}})]})]})}),o.jsx(Ht,{open:!!ae,title:N("editor.moveTitle",{name:ae?.path.split("/").at(-1)??""}),description:N("editor.moveDescription"),onOpenChange:M=>{M||(xe(null),ve(""),x(""))},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>xe(null),children:N("common.cancel")}),o.jsx("button",{className:"primary",disabled:!he.trim(),onClick:()=>{v()},children:N("editor.moveApply")})]}),children:o.jsxs(o.Fragment,{children:[D&&o.jsx("p",{className:"error dialog-error",children:D}),o.jsxs("label",{className:"form-field",children:[N("editor.pathName"),o.jsx("input",{autoFocus:!0,value:he,onChange:M=>ve(M.target.value),onKeyDown:M=>{M.key==="Enter"&&v()}})]}),o.jsxs("label",{className:"form-field",children:[N("editor.destinationFolder"),o.jsxs("select",{value:fe,onChange:M=>Se(M.target.value),children:[o.jsx("option",{value:"",children:N("editor.projectRoot")}),a.filter(M=>ae?.type!=="directory"||M.path!==ae.path&&!M.path.startsWith(`${ae.path}/`)).map(M=>o.jsx("option",{value:M.path,children:M.path},M.path))]})]})]})}),o.jsx(Ht,{open:!!oe,title:N("editor.deletePathTitle",{name:oe?.path.split("/").at(-1)??""}),description:A.length?N("editor.deletePathActiveDescription",{path:oe?.path??"",users:[...new Set(A.map(M=>M.name))].join(", ")}):N("editor.deletePathDescription",{path:oe?.path??""}),onOpenChange:M=>{M||(ne(null),x(""))},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>ne(null),children:N("common.cancel")}),o.jsx("button",{className:"danger",onClick:()=>{U()},children:N("common.delete")})]}),children:o.jsxs(o.Fragment,{children:[D&&o.jsx("p",{className:"error dialog-error",children:D}),A.length>0&&o.jsxs("p",{className:"warning",children:[o.jsx($t,{size:15}),N("editor.deletePathWillClose")]})]})}),o.jsxs(Ht,{open:F,title:N("editor.addComment"),description:re.selectedText?N("editor.commentDescription",{count:re.endOffset-re.startOffset}):N("editor.pointComment"),onOpenChange:Ee,footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>Ee(!1),children:N("common.cancel")}),o.jsx("button",{className:"primary",onClick:()=>{Ve()},children:N("editor.addComment")})]}),children:[o.jsxs("label",{className:"form-field",children:[N("editor.commentContent"),o.jsx("textarea",{autoFocus:!0,rows:5,value:ke,onChange:M=>Me(M.target.value),onKeyDown:M=>{(M.ctrlKey||M.metaKey)&&M.key==="Enter"&&!M.nativeEvent.isComposing&&(M.preventDefault(),M.stopPropagation(),Ve())}})]}),re.selectedText&&o.jsx("blockquote",{className:"selection-preview",children:re.selectedText})]}),o.jsx(ow,{open:He,onOpenChange:le,project:e,projectId:n}),pe&&o.jsx(sa,{title:N("citationLibrary.title"),onClose:()=>Pe(!1),children:o.jsx(lw,{open:!0,onOpenChange:Pe,currentFile:s,currentSource:r,readOnly:c,currentUserId:t.id,maxBibtexBytes:i,onInsert:Qe})}),zt&&o.jsx(f.Suspense,{fallback:null,children:o.jsx(dw,{open:!0,files:l,onOpenChange:Tt,onOpenFile:M=>{const st=l.find(Lt=>Lt.path===M);st&&ye(st)}})}),E&&o.jsx(f.Suspense,{fallback:null,children:o.jsx(uw,{open:!0,project:e,onOpenChange:te,onJump:(M,st,Lt)=>{u==="pdf-only"&&h("editor-pdf"),Ke(M,st,Lt)}})}),_e&&o.jsx(f.Suspense,{fallback:null,children:o.jsx(cw,{open:!0,onOpenChange:de,project:e,onBeforeMutation:e.permission==="read"?async()=>!0:R})}),e.ownerId===t.id&&ht&&o.jsx(f.Suspense,{fallback:null,children:o.jsx(aw,{open:!0,onOpenChange:Ne,project:e,onBeforeMutation:R})})]})}function fw(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/1024/1024).toFixed(1)} MB`}const pw=f.lazy(()=>vt(()=>import("./ProjectSettings-BJWTkoZq.js"),__vite__mapDeps([22,2,1,3,7,23,24,14,10,6,8,9])).then(t=>({default:t.ProjectSettings})));function mw({sidePanel:t,onClose:e,project:n,projectId:s,site:r,files:i,currentUserId:l,comments:a,onFocusComment:c,onToggleComment:u,onReplyComment:h,onEditComment:d,onDeleteComment:p,onEditCommentReply:w,onDeleteCommentReply:g,dictionaryWords:S,onDictionaryChange:y,editorPreferences:C,onEditorPreferences:_,spellCheckCount:q,spellCheckUniqueCount:Y,spellCheckIndex:K,onSpellCheckNavigate:W,onProject:T}){const{t:I}=We();return t?o.jsxs(o.Fragment,{children:[o.jsx(Fi,{className:"resize-handle"}),o.jsx(ur,{id:"context",order:4,defaultSize:20,minSize:15,maxSize:38,children:o.jsxs("aside",{className:"context-panel",children:[t==="comments"&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"drawer-title",children:[o.jsx("strong",{children:I("editor.sourceComments")}),o.jsx("button",{"aria-label":I("common.close"),onClick:e,children:o.jsx(Rn,{size:17})})]}),o.jsxs("div",{className:"comments",children:[a.map(X=>o.jsx(iw,{comment:X,currentUserId:l,onFocus:()=>c(X),onToggle:()=>{u(X)},onReply:B=>h(X,B),onEdit:B=>d(X,B),onDelete:()=>p(X),onEditReply:(B,V)=>w(X,B,V),onDeleteReply:B=>g(X,B)},X.id)),a.length===0&&o.jsx("p",{className:"muted padded",children:I("editor.noComments")})]})]}),t==="settings"&&o.jsx(jd,{onClose:e,children:o.jsx(pw,{onClose:e,project:n,projectId:s,site:r,files:i,dictionaryWords:S,onDictionaryChange:y,editorPreferences:C,onEditorPreferences:_,spellCheckCount:q,spellCheckUniqueCount:Y,spellCheckIndex:K,onSpellCheckNavigate:W,onProject:T})})]})})]}):null}function gw(t){if(typeof globalThis.requestAnimationFrame=="function"){const n=globalThis.requestAnimationFrame(t);return()=>globalThis.cancelAnimationFrame(n)}const e=globalThis.setTimeout(t,0);return()=>globalThis.clearTimeout(e)}function ww(){let t={line:1,column:1,offset:0},e=t.line,n=null,s=null;const r=new Set,i=()=>{for(const c of r)c()},l=()=>{s=null;const c=n;n=null,!(c===null||c===e)&&(e=c,i())},a=c=>{n=c,s===null&&(s=gw(l))};return{getCursor:()=>t,getOutlineLine:()=>e,subscribe:c=>(r.add(c),()=>r.delete(c)),update:(c,u,h)=>{t.line===c&&t.column===u&&t.offset===h||(t={line:c,column:u,offset:h},(c!==e||s!==null)&&a(c))},reset:()=>{s?.(),s=null,n=null,t={line:1,column:1,offset:0},e!==1&&(e=1,i())},dispose:()=>{s?.(),s=null,n=null}}}const yw=f.lazy(()=>vt(()=>import("./WordCountDialog-BFg0GeJy.js"),__vite__mapDeps([25,2,1,3,23,7,6,8,9,10])).then(t=>({default:t.WordCountDialog})));let Bs=null;function ta(){return Bs||(Bs=vt(()=>import("./citationLibrary-ZeQPCv5O.js"),[]).catch(t=>{throw Bs=null,t})),Bs}function Dn(t){return t instanceof Error&&t.name==="AbortError"}const bw=300;function xw({site:t,user:e,projectId:n,preload:s,onBack:r}){const{t:i}=We(),[l,a]=f.useState(null),[c,u]=f.useState(!1),[h,d]=f.useState([]),[p,w]=f.useState(null),[g,S]=f.useState([]),[y,C]=f.useState(""),[_,q]=f.useState(""),[Y,K]=f.useState(new Set),[W,T]=f.useState(""),[I,X]=f.useState({filePath:"",content:""}),[B,V]=f.useState(""),[O,Q]=f.useState(!1),[D,x]=f.useState("editor.saved"),[z,we]=f.useState(null),ae=f.useRef(z);ae.current=z;const xe=f.useRef(null);xe.current||(xe.current=ww());const he=xe.current,[ve,fe]=f.useState("pdf"),[Se,v]=f.useState("log"),oe=m=>{if(m==="pdf"){fe("pdf");return}if(m==="diagnostics"){fe("diagnostics");return}v(m),fe("diagnostics")},{workspaceLayout:ne,setWorkspaceLayout:A}=Wg(e.id,n),[U,F]=f.useState(""),[Ee,re]=f.useState(""),[ke,Me]=f.useState({selectedText:"",startOffset:0,endOffset:0}),Ve=f.useRef({selectedText:"",startOffset:0,endOffset:0}),He=m=>{const b=Ve.current;b.selectedText===m.selectedText&&b.startOffset===m.startOffset&&b.endOffset===m.endOffset||(Ve.current=m,Me(m))},[le,pe]=f.useState(null),[Pe,Qe]=f.useState(!1),[zt,Tt]=f.useState(!1),[E,te]=f.useState(!1),[ye,Ke]=f.useState(!1),[_e,de]=f.useState(!1),[ht,Ne]=f.useState(null),[R,$]=f.useState(!1),[L,Z]=f.useState(!1),[ft,N]=f.useState(!1),[M,st]=f.useState("full"),[Lt,ue]=f.useState(""),[Je,jr]=f.useState(!1),[Hc,vr]=f.useState(""),[Kc,Er]=f.useState(null),[Ts,xn]=f.useState(!1),[tn,Rt]=f.useState(null),[Dr,At]=f.useState(""),[Jc,_r]=f.useState(!1),[rt,yo]=f.useState(()=>dl(e.id,n)),[Sn,Ls]=f.useState([]),Bt=f.useRef([]);Bt.current=Sn;const Gc=f.useRef(null),Rs=f.useRef(null),As=f.useRef(0),Tr=f.useRef(0),Ce=f.useRef(""),St=f.useRef(""),bo=f.useRef(0),nn=f.useRef(null),sn=f.useRef(null),rn=f.useRef(null),kn=f.useRef(null),Cn=f.useRef(null),Nt=f.useRef(!1),qt=f.useRef(null),xo=f.useRef(r);xo.current=r,St.current=_,f.useEffect(()=>{if(!Ee)return;const m=window.setTimeout(()=>re(""),3e3);return()=>window.clearTimeout(m)},[Ee]);const Yc=f.useCallback((m,b,j=0)=>{he.update(m,b,j)},[he]);f.useEffect(()=>()=>he.dispose(),[he]);const Ns=m=>{const b=Bt.current,j=m(b);j!==b&&(Bt.current=j,Ls(j))};f.useEffect(()=>{Bt.current=[],Ls([]),Rt(null),At(""),Cn.current?.abort(),Cn.current=null,N(!1),jr(!1),vr(""),Er(null)},[n]);const So=m=>{const b=Bt.current,j=b.indexOf(m);if(j<0)return;const k=b.filter(G=>G!==m);if(Bt.current=k,Ls(k),Ce.current!==m)return;const J=k.length>0?k[Math.min(j,k.length-1)]:l?.mainFile??"";C(J)},{collaboration:De,status:Os,synced:Ge,activeSessions:ko,formatLeaseStates:Xc,compileState:on,setCompileState:Co,filesEvent:Oe,commentsRevision:Qc,dictionaryRevision:jo,localDraftReady:vo,permission:Lr,reconnect:Zc,protocolUpgradeRequired:Eo,permissionDowngrade:eu,dismissPermissionDowngrade:tu,discardLocalDraft:nu}=Fg(n,e,_,l?.permission??"read",c,()=>x("editor.offlineDraft")),{pdfTarget:su,pdfViewport:ru,sourceJump:iu,setPdfViewport:ou,clearPdfViewport:Do,jumpToSource:Rr,syncSourceToPdf:Ar,syncPdfToSource:lu,syncVisiblePdfToSource:au}=qg({projectId:n,mainFile:_,activeFile:y,onActiveFile:C,onError:F,onShowPdf:()=>oe("pdf")}),it=Bg({active:!!(l&&y&&Ge&&rt.spellCheck),projectId:n,activeFile:y,content:W,dictionaryWords:h});f.useEffect(()=>{yo(dl(e.id,n))},[e.id,n]);const Nr=m=>{T(m)};f.useEffect(()=>{if(!y||B!==y){X(k=>k.filePath||k.content?{filePath:"",content:""}:k);return}const m=y,b=W,j=window.setTimeout(()=>{X(k=>k.filePath===m&&k.content===b?k:{filePath:m,content:b})},bw);return()=>window.clearTimeout(j)},[y,B,W]),f.useEffect(()=>{if(Ce.current=y,he.reset(),He({selectedText:"",startOffset:0,endOffset:0}),!rt.openFilesInTabs){Bt.current.length>0&&(Bt.current=[],Ls([]));return}y&&Ns(m=>m.includes(y)?m:[...m,y])},[y,rt.openFilesInTabs,n,he]),f.useEffect(()=>{if(!O)return;const m=b=>{b.preventDefault(),b.returnValue=""};return window.addEventListener("beforeunload",m),()=>window.removeEventListener("beforeunload",m)},[O]),f.useEffect(()=>{if(Os!=="disconnected")return;const m=new AbortController;return ie(`/api/projects/${n}`,{signal:m.signal}).then(({project:b})=>{m.signal.aborted||(a(b),F(""))}).catch(b=>{if(!Dn(b)){if(b instanceof pi&&[401,403,404].includes(b.status)){F(ce(b)),xo.current();return}F(i("errors.collaborationUnavailable"))}}),()=>m.abort()},[Os,n,i]);const Or=async(m={})=>{nn.current?.abort(),nn.current=null;const b=m.signal?null:new AbortController;b&&(nn.current=b);try{const j=await ie(`/api/projects/${n}/completions`,{signal:m.signal??b?.signal});(!m.isCurrent||m.isCurrent())&&w(j.index)}catch(j){if(Dn(j))return;(!m.isCurrent||m.isCurrent())&&w(null)}finally{b&&nn.current===b&&(nn.current=null)}},Fr=async(m={},b=St.current)=>{sn.current?.abort(),sn.current=null;const j=m.signal?null:new AbortController;j&&(sn.current=j);try{const k=b?`?mainFile=${encodeURIComponent(b)}`:"",J=await ie(`/api/projects/${n}/outline${k}`,{signal:m.signal??j?.signal});(!m.isCurrent||m.isCurrent())&&S(J.outline)}catch(k){!Dn(k)&&(!m.isCurrent||m.isCurrent())&&S([])}finally{j&&sn.current===j&&(sn.current=null)}},_o=async(m={})=>{rn.current?.abort(),rn.current=null;const b=m.signal?null:new AbortController;b&&(rn.current=b);try{const j=await ie(`/api/projects/${n}/dictionary`,{signal:m.signal??b?.signal});(!m.isCurrent||m.isCurrent())&&d(j.words)}catch(j){if(Dn(j))return;(!m.isCurrent||m.isCurrent())&&d([])}finally{b&&rn.current===b&&(rn.current=null)}};f.useEffect(()=>{let m=!1;const b=++bo.current,j=new AbortController,k=()=>!m&&bo.current===b;let J=!1;a(null),Ro([]),S([]),C(""),q(""),K(new Set),T(""),V(""),Co(null),Do(),w(null),d([]),na();const G=(s?.projectId===n?s.project:ie(`/api/projects/${n}`,{signal:j.signal})).then($e=>{k()&&(J=!0,a($e.project),C($e.project.mainFile),q($e.project.mainFile),K(new Set),Po(new Set(ls($e.project.mainFile))))}).catch($e=>{k()&&F(ce($e))}),H=ie(`/api/projects/${n}/files`,{signal:j.signal}).then($e=>{k()&&Ro($e.files)}).catch($e=>{k()&&F(ce($e))});let ct=null;return Promise.allSettled([G,H]).then(()=>{!k()||!J||(ct=window.setTimeout(()=>{k()&&Promise.all([Or({signal:j.signal,isCurrent:k}),_o({signal:j.signal,isCurrent:k})])},0))}),()=>{m=!0,ct!==null&&window.clearTimeout(ct),j.abort(),nn.current?.abort(),nn.current=null,sn.current?.abort(),sn.current=null,rn.current?.abort(),rn.current=null,kn.current?.abort(),kn.current=null}},[n,s]),f.useEffect(()=>{jo&&_o()},[jo,n]),f.useEffect(()=>{!l||Os!=="connected"||Lr===l.permission||a(m=>m&&{...m,permission:Lr})},[Lr,l?.permission]),f.useEffect(()=>{if(!Oe)return;const m=Oe.kind==="delete"&&!!Oe.path&&an(Oe.path,Ce.current),b=Oe.kind==="delete"&&!!Oe.path&&an(Oe.path,St.current);if(Oe.kind==="move"&&Oe.source&&Oe.destination){const k=Oe.source,J=Oe.destination,G=H=>H===k?J:H.startsWith(`${k}/`)?`${J}${H.slice(k.length)}`:H;C(H=>G(H)),q(H=>G(H)),K(H=>new Set([...H].map(G))),$r(H=>H&&G(H)),Ns(H=>H.map(G))}m&&(C(""),V(""),Nr(""),re(i("editor.fileDeletedByCollaborator",{path:Oe.path}))),Oe.kind==="delete"&&Oe.path&&(K(k=>new Set([...k].filter(J=>!an(Oe.path,J)))),$r(k=>an(Oe.path,k)?"":k),Oo(k=>k&&an(Oe.path,k.path)?null:k),Ns(k=>k.filter(J=>!an(Oe.path,J)))),kn.current?.abort();const j=new AbortController;kn.current=j,Promise.all([fu({signal:j.signal}),ie(`/api/projects/${n}`,{signal:j.signal})]).then(([k,J])=>{if(a(J.project),b&&q(J.project.mainFile),m&&k){const G=k.find(H=>H.type==="file"&&H.path===J.project.mainFile)??k.find(H=>H.type==="file"&&Un(H.path));C(G?.path??"")}Or({signal:j.signal}),Fr({signal:j.signal},b?J.project.mainFile:St.current)}).catch(k=>{Dn(k)}).finally(()=>{kn.current===j&&(kn.current=null)})},[Oe?.revision]),f.useEffect(()=>{if(De.setActiveFile(y),!y)return;V(""),x("editor.loading");const m=De.getText(y),b=(j,k)=>{Nr(m.toString()),V(y),k?.local&&l?.permission!=="read"?(As.current+=1,Q(!0),x("editor.pending")):As.current<=Tr.current&&x(ae.current?"editor.savedAt":"editor.saved")};return m.observe(b),(Ge||vo)&&b(),()=>{m.unobserve(b)}},[y,De,Ge,vo,l?.permission]);const Fs=async()=>{if(!Ge)throw new Error("Collaboration is not synchronized");const m=As.current,b=await De.flush();return Tr.current=Math.max(Tr.current,m),we(b.persistedAt),/\.tex$/i.test(Ce.current)&&Fr(),As.current===m?(Q(!1),x("editor.savedAt")):x("editor.pending"),b};f.useEffect(()=>{if(!O||!y)return;if(!Ge){x("editor.offlineDraft");return}x("editor.pending");const m=window.setTimeout(()=>{x("editor.saving"),Fs().catch(()=>{x(De.connected?"editor.saveFailed":"editor.offlineDraft")})},750);return()=>window.clearTimeout(m)},[W,O,y,Ge]);const ts=async()=>{if(!l||l.permission==="read"||!Ge||!y)return!1;x("editor.saving");try{return await Fs(),Or(),!0}catch(m){return x("editor.saveFailed"),F(ce(m)||i("errors.collaborationUnavailable")),!1}},cu=async m=>{if(!l||Je)return;const b=m==="full"?St.current||l.mainFile:Ce.current,j=m==="selection"?Ve.current.selectedText:"";if(!b)return;if(m==="selection"&&(!j.trim()||!/\.(?:tex|sty|cls)$/i.test(b))){re(i("editor.wordCountSelectionEmpty"));return}Cn.current?.abort();const k=new AbortController;Cn.current=k,st(m),ue(b),Er(null),vr(""),N(!0),jr(!0);try{if(m==="full"&&O&&l.permission!=="read"&&!await ts())throw new Error(i("editor.wordCountSaveRequired"));const J=m==="selection"?{mode:m,path:b,source:j}:{mode:m,mainFile:b},G=await ie(`/api/projects/${n}/word-count`,{method:"POST",body:JSON.stringify(J),signal:k.signal});if(k.signal.aborted)return;Er(G)}catch(J){if(Dn(J))return;k.signal.aborted||vr(ce(J))}finally{Cn.current===k&&(Cn.current=null,jr(!1))}},Mr=async(m,b,j=rt.texFmtConfig)=>{if(/\.bib$/i.test(m)){const J=await ta();try{return{formatted:J.formatBibtex(b,t.maxCitationBibtexBytes),diagnostics:""}}catch(G){throw G instanceof J.BibtexFormatError?G.kind==="too-large"?new Error(i("citationLibrary.fileTooLarge",{size:J.citationBibtexLimitLabel(t.maxCitationBibtexBytes)})):new Error(i("citationLibrary.fileInvalid")):G}}const k=await rh(b,j);return{formatted:k.output,diagnostics:k.logs.trim()}},To=async m=>{if(!l||l.permission==="read"||!Ge||Nt.current||!Is(Ce.current))return;const b=Ce.current,j=De.getText(b);Nt.current=!0,xn(!0);let k=()=>{};const J=new Promise(H=>{k=H});qt.current=J,At("");let G=null;try{G=await De.acquireFormatLease(b);const H=j.toString(),{formatted:ct,diagnostics:$e}=await Mr(b,H,m);if(Ce.current!==b||j.toString()!==H){F(i("editor.formatSourceChanged"));return}await G.confirm();const mt=await Gr(H,ct);if(Ce.current!==b||j.toString()!==H){F(i("editor.formatSourceChanged"));return}if(await G.confirm(),Ce.current!==b||j.toString()!==H){F(i("editor.formatSourceChanged"));return}mt.length&&De.applyTextEdits(b,mt),mt.length&&await Fs(),Rt(null),At($e),F(""),re(i("editor.formatFileComplete"))}catch(H){Jr(H)?(Rt({action:"file",kind:H.kind,detail:H.message}),F("")):F(i("editor.formatFileFailed",{message:ce(H)}))}finally{G&&await G.release(),Nt.current=!1,xn(!1),k(),qt.current===J&&(qt.current=null)}},uu=async()=>{if(!rt.formatOnCompile||!l||l.permission==="read"||!Ge||!Is(Ce.current)||Nt.current)return;const m=Ce.current,b=De.getText(m);Nt.current=!0,xn(!0),At("");let j=null;try{j=await De.acquireFormatLease(m);const k=b.toString(),{formatted:J,diagnostics:G}=await Mr(m,k);await j.confirm();const H=await Gr(k,J);if(Ce.current!==m||b.toString()!==k)throw new Error(i("editor.formatSourceChanged"));if(await j.confirm(),Ce.current!==m||b.toString()!==k)throw new Error(i("editor.formatSourceChanged"));H.length&&De.applyTextEdits(m,H),H.length&&await De.flush(),Rt(null),At(G)}catch(k){Jr(k)?(Rt({action:"file",kind:k.kind,detail:k.message}),F("")):F(i("editor.formatFailedContinue",{message:ce(k)}))}finally{j&&await j.release(),Nt.current=!1,xn(!1)}},du=async()=>(qt.current&&await qt.current,await uu(),ts()),Lo=async m=>{if(!l||l.permission==="read"||!Ge||Nt.current||!Is(Ce.current))return;const b=Ve.current;if(!b.selectedText.trim()){re(i("editor.formatSelectionRequired"));return}const j=Ce.current,{startOffset:k,endOffset:J,selectedText:G}=b,H=De.getText(j);if(H.toString().slice(k,J)!==G){F(i("editor.formatSelectionChanged"));return}Nt.current=!0,xn(!0);let ct=()=>{};const $e=new Promise(Ot=>{ct=Ot});qt.current=$e,At("");let mt=null;try{if(mt=await De.acquireFormatLease(j),H.toString().slice(k,J)!==G){F(i("editor.formatSelectionChanged"));return}const vn=await Mr(j,G,m),bd=lh(G,vn.formatted);await mt.confirm();const Kr=await Gr(G,bd,k);if(Ce.current!==j||H.toString().slice(k,J)!==G){F(i("editor.formatSelectionChanged"));return}if(await mt.confirm(),Ce.current!==j||H.toString().slice(k,J)!==G){F(i("editor.formatSelectionChanged"));return}Kr.length&&De.applyTextEdits(j,Kr),Kr.length&&await Fs(),Rt(null),At(vn.diagnostics),F(""),re(i("editor.formatSelectionComplete"))}catch(Ot){Jr(Ot)?(Rt({action:"selection",kind:Ot.kind,detail:Ot.message}),F("")):F(i("editor.formatFailed",{message:ce(Ot)}))}finally{mt&&await mt.release(),Nt.current=!1,xn(!1),ct(),qt.current===$e&&(qt.current=null)}},hu=async m=>{const b=Ce.current;if(!/\.bib$/i.test(b)||l?.permission==="read"||!Ge)return re(i("citationLibrary.importRequiresWrite")),!1;const j=De.getText(b);let k;try{k=await ta()}catch(vn){return F(ce(vn)),!1}if(Ce.current!==b||!Ge)return!1;const J=j.toString(),G=k.parseBibEntriesResult(J,t.maxCitationBibtexBytes);if(G.status==="too-large")return re(i("citationLibrary.fileTooLarge",{size:k.citationBibtexLimitLabel(t.maxCitationBibtexBytes)})),!1;if(G.status==="invalid")return re(i("citationLibrary.fileInvalid")),!1;if(G.entries.some(vn=>vn.citationKey.toLowerCase()===m.citationKey.toLowerCase()))return re(i("citationErrors.alreadyInFile",{key:m.citationKey})),!1;const H=Math.max(0,Math.min(J.length,he.getCursor().offset)),ct=J.slice(0,H),$e=J.slice(H),mt=ct?ct.endsWith(`
15
-
16
- `)?"":ct.endsWith(`
17
- `)?`
18
- `:`
19
-
20
- `:"",Ot=$e?$e.startsWith(`
21
-
22
- `)?"":$e.startsWith(`
23
- `)?`
24
- `:`
25
-
26
- `:"";return De.applyTextEdits(b,[{from:H,to:H,replacement:`${mt}${m.bibtex.trim()}${Ot}`}]),re(i("citationLibrary.imported",{key:m.citationKey})),!0},{files:pt,setFiles:Ro,loadFiles:fu,newFileOpen:pu,setNewFileOpen:Ao,newFilePath:mu,setNewFilePath:No,resourcePreview:gu,setResourcePreview:Oo,resourcePreviewLoading:wu,setResourcePreviewLoading:yu,newFolderOpen:bu,setNewFolderOpen:Fo,newFolderName:xu,setNewFolderName:Mo,fileDialogError:Su,setFileDialogError:$o,selectedFolder:Io,setSelectedFolder:$r,expandedFolders:ku,setExpandedFolders:Po,moveEntry:Cu,setMoveEntry:Uo,moveName:ju,setMoveName:zo,moveDestination:vu,setMoveDestination:Bo,deleteEntry:Ir,setDeleteEntry:qo,fileDragActive:Eu,setFileDragActive:Du,uploadConflict:_u,setUploadConflict:Tu,uploadingFiles:Lu,directoryEntries:Ru,visibleEntries:Au,createFile:Nu,createFolder:Ou,uploadFiles:Wo,upload:Fu,openFile:Pr,movePath:Mu,removePath:$u}=zg({projectId:n,site:t,activeFile:y,dirty:O,save:ts,onError:F,onProject:a,onActiveFile:C,onActiveMainFile:q,onRootDocuments:K}),Vo=()=>St.current||l?.mainFile||"",Iu=()=>{const m=Vo(),b=Ce.current;if(!b||!/\.tex$/i.test(b))return m;const j=pt.filter(G=>G.type==="file"&&/\.tex$/i.test(G.path)).length,k=De.getText(b).toString();return Zl(k)||j===1?(K(G=>{if(G.has(b))return G;const H=new Set(G);return H.add(b),H}),m!==b&&(St.current=b,q(b)),b):m===b&&l?.mainFile&&l.mainFile!==b?(St.current=l.mainFile,q(l.mainFile),l.mainFile):m};f.useEffect(()=>{if(!y||B!==y||I.filePath!==y||!y.toLocaleLowerCase().endsWith(".tex"))return;const m=pt.filter(J=>J.type==="file"&&/\.tex$/i.test(J.path)).length;if(m===0)return;const b=y===l?.mainFile,k=Zl(I.content)||m===1;K(J=>{if(J.has(y)===k)return J;const G=new Set(J);return k?G.add(y):G.delete(y),G}),k&&!b&&St.current!==y?q(y):!k&&St.current===y&&l?.mainFile&&q(l.mainFile)},[y,B,I,pt,l?.mainFile]),f.useEffect(()=>{if(!rt.openFilesInTabs||pt.length===0)return;const m=new Set(pt.filter(b=>b.type==="file"&&Un(b.path)).map(b=>b.path));Ns(b=>{const j=b.filter(k=>m.has(k));return j.length===b.length?b:j})},[pt,rt.openFilesInTabs]);const{comments:Ms,focusComment:Pu,setFocusComment:Ho,commentOpen:Uu,setCommentOpen:Ko,commentText:zu,setCommentText:Bu,addComment:qu,toggleComment:Wu,replyToComment:Vu,editComment:Hu,deleteComment:Ku,editCommentReply:Ju,deleteCommentReply:Gu}=fh({projectId:n,activeFile:y,permission:l?.permission,revision:Qc,selection:ke,save:ts,onError:F,onAdded:()=>pe("comments")}),{pdfUrl:Wt,pdfCompiledAt:ns,pdfLoadingMode:Yu,pdfLoading:Ur,compileLog:zr,compileDiagnostics:Xu,compileOutcome:ss,artifacts:Jo,artifactPreview:Qu,artifactLoading:Zu,editorNotice:ed,localCompiling:Go,cancelling:td,cleaning:Yo,compile:nd,cancelCompile:sd,cleanCompile:Xo,viewArtifact:rd}=$g({projectId:n,project:l,mainFile:_,resolveCompileMainFile:Iu,getCurrentMainFile:Vo,initialLatest:s?.projectId===n?s.latestCompile:null,collaborationSynced:Ge,sharedState:on,onSharedState:Co,save:du,loadOutline:(m,b)=>Fr({signal:m},b),onPreviewTab:oe,onError:F,onCompileStart:()=>{F(""),re("")},onCompileSuccess:()=>{const m=Ce.current;if(m){const b=he.getCursor();Ar(m,b.line,b.column,{silent:!0})}},onPdfChanged:Do});f.useEffect(()=>{if(!l||!_||!Wt&&Ur)return;const m=window.setTimeout(()=>u(!0),Wt?150:0);return()=>window.clearTimeout(m)},[l,Ur,Wt]),f.useEffect(()=>{const m=b=>{(b.ctrlKey||b.metaKey)&&(!b.shiftKey&&b.key.toLocaleLowerCase()==="p"?(b.preventDefault(),$(!0)):b.shiftKey&&b.key.toLocaleLowerCase()==="f"&&(b.preventDefault(),Z(!0)))};return window.addEventListener("keydown",m,!0),()=>window.removeEventListener("keydown",m,!0)},[]);const Qo=m=>{yo(m),Zd(e.id,n,m)},Zo=(m=!1)=>{const b=tn;if(!b)return;Rt(null),At(""),F(""),m&&Qo({...rt,texFmtConfig:""});const j=m?"":void 0;b.action==="selection"?Lo(j):To(j)},id=async()=>{_r(!0);try{await nu()||(F(i("editor.collaboration.permissionDowngradeOtherTabBlocked")),_r(!1))}catch(m){F(ce(m)),_r(!1)}},el=()=>{Rs.current?.isCollapsed()?Rs.current.expand():Rs.current?.collapse()},od=f.useMemo(()=>g.length?g:I.filePath!==y?[]:Sw(I.content).map(m=>({...m,path:y})),[g,I,y]),Br=f.useMemo(()=>ah(zr,ss),[zr,ss]),jn=ne!=="pdf-only",tl=ne!=="editor-only",qr=m=>{A(m),m==="pdf-only"&&oe("pdf")},ld=Ir?ko.filter(m=>m.filePath&&an(Ir.path,m.filePath)):[];if(!l)return o.jsxs("div",{className:"center-card",children:[o.jsx("p",{children:U||i("common.loading")}),U&&o.jsx("button",{className:"primary",onClick:r,children:i("editor.backToProjects")})]});const Vt=l.permission==="read"||!Ge,Wr=Xc.find(m=>m.path===y),Vr=Wr&&!Ts?Wr:null,ad=(m,b)=>{if(Vt)return;const j=Ce.current;if(!j)return;if(De.getText(j).toString().slice(m.from,m.to)!==m.word){F(i("editor.spellCheckSourceChanged"));return}try{De.applyTextEdits(j,[{from:m.from,to:m.to,replacement:b}])}catch(G){F(ce(G))}},Hr=on?.mainFile===_&&(on.status==="queued"||on.status==="running"),$s=Go||Hr||Yo,cd=y?De.getText(y):null,ud=ns?new Date(ns).toLocaleString(as.resolvedLanguage,{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}):"",dd=_.split("/").at(-1)??_,hd=Br.warnings.length+Br.errors.length+Jo.length,fd=Wt?`${Wt}${Wt.includes("?")?"&":"?"}download=1`:"",pd=_||l.mainFile,md=!!(y&&y===pd&&/\.tex$/i.test(y)),nl=m=>{const b=pt.find(j=>j.path===m);b&&Un(b.path)?Pr(b):So(m)},gd=m=>{document.getElementById(`editor-tab-${encodeURIComponent(m)}`)?.focus()},wd=(m,b)=>{if(!["ArrowLeft","ArrowRight","Home","End"].includes(m.key))return;m.preventDefault();const j=m.key==="Home"?0:m.key==="End"?Sn.length-1:(b+(m.key==="ArrowLeft"?-1:1)+Sn.length)%Sn.length,k=Sn[j];k&&(nl(k),window.requestAnimationFrame(()=>gd(k)))},sl=$s?Hr?on?.status==="queued"?i("editor.compileQueued"):i("editor.compilingBy",{name:on?.requestedBy.name??i("common.user")}):i("editor.compiling"):ss==="failed"?Wt&&ns?i("editor.compileFailedRetained",{time:new Date(ns).toLocaleString(as.resolvedLanguage)}):i("editor.compileFailedNoPdf"):ss==="cancelled"?i("compileControls.cancelled"):"",yd=D==="editor.savedAt"&&z?i("editor.savedAt",{time:new Date(z).toLocaleTimeString(as.resolvedLanguage,{hour:"2-digit",minute:"2-digit",second:"2-digit"})}):i(D);return o.jsxs("div",{className:"workspace",children:[o.jsx(Kg,{site:t,project:l,activeFile:y,saveStateLabel:yd,editorPreferences:rt,activeSessions:ko,collaborationStatus:Os,reconnectCollaboration:Zc,protocolUpgradeRequired:Eo,showEditor:jn,filesCollapsed:Pe,toggleFilesPanel:el,workspaceLayout:ne,changeWorkspaceLayout:qr,onBack:r,onShare:()=>Tt(!0),showCitationLibrary:jn&&/\.bib$/i.test(y),citationLibraryOpen:_e,onCitationLibrary:()=>de(!0),onHistory:()=>Ke(!0),onGit:()=>te(!0),canManageGit:l.ownerId===e.id,formatting:Ts,canFormat:Is(y),readOnly:Vt,collaborationSynced:Ge,activeFormatLease:!!Wr,onFormatFile:()=>{To()},onFormatSelection:()=>{Lo()},hasSelection:!!ke.selectedText.trim(),onAddComment:()=>Ko(!0),onToggleComments:()=>pe(le==="comments"?null:"comments"),commentsOpen:le==="comments",unresolvedCommentCount:Ms.filter(m=>!m.resolved).length,hasActiveFile:!!y,onToggleSettings:()=>pe(le==="settings"?null:"settings"),settingsOpen:le==="settings",compileBusy:$s,sharedCompiling:Hr,localCompiling:Go,cancelling:td,compileState:on,onCompile:nd,onCancelCompile:()=>{sd()}}),Eo&&o.jsxs("div",{className:"workspace-update-banner",role:"alert",children:[o.jsx($t,{size:15}),o.jsx("span",{children:i("workspaceUpdates.protocolUpgrade")}),o.jsx("button",{type:"button",onClick:()=>window.location.reload(),children:i("common.reload")})]}),sl&&o.jsxs("div",{className:`compile-status-strip${ss==="failed"?" failed":""}`,role:"status","aria-live":"polite",children:[o.jsx(nt,{className:$s?"spin":"",size:14}),o.jsx("span",{children:sl})]}),(it.error||tn||Dr||Vr)&&o.jsxs("div",{className:"client-tool-recoveries",children:[it.error&&o.jsxs("div",{className:"client-tool-recovery",role:"alert",title:it.error,children:[o.jsx($t,{size:15}),o.jsxs("span",{children:[o.jsx("strong",{children:i("editor.harperRecoveryTitle")}),i("editor.harperFallbackHint")]}),o.jsx("div",{className:"client-tool-recovery-actions",children:o.jsx("button",{type:"button",onClick:it.retry,children:i("common.retry")})}),o.jsx("button",{type:"button",className:"formatter-diagnostics-dismiss",title:i("common.close"),"aria-label":i("common.close"),onClick:it.dismissError,children:o.jsx(Rn,{size:13})})]}),tn&&o.jsxs("div",{className:"client-tool-recovery",role:"alert",title:tn.detail,children:[o.jsx($t,{size:15}),o.jsxs("span",{children:[o.jsx("strong",{children:i(tn.kind==="format"?"editor.texFmtOptionsRecoveryTitle":tn.kind==="load"?"editor.texFmtRecoveryTitle":"editor.texFmtRuntimeRecoveryTitle")}),i("editor.clientToolRecoveryHint")]}),o.jsxs("div",{className:"client-tool-recovery-actions",children:[o.jsx("button",{type:"button",disabled:Ts||Vt,onClick:()=>Zo(),children:i("common.retry")}),tn.kind==="format"&&rt.texFmtConfig.trim()&&o.jsx("button",{type:"button",disabled:Ts||Vt,onClick:()=>Zo(!0),children:i("editor.resetFormatterOptions")}),o.jsx("button",{type:"button",onClick:()=>window.location.reload(),children:i("common.reload")})]}),o.jsx("button",{type:"button",className:"formatter-diagnostics-dismiss",title:i("common.close"),"aria-label":i("common.close"),onClick:()=>Rt(null),children:o.jsx(Rn,{size:13})})]}),Dr&&o.jsxs("div",{className:"client-tool-recovery formatter-diagnostics",role:"status",children:[o.jsx($t,{size:15}),o.jsxs("span",{children:[o.jsx("strong",{children:i("editor.texFmtDiagnosticsTitle")}),i("editor.texFmtDiagnosticsHint")]}),o.jsxs("details",{children:[o.jsx("summary",{children:i("editor.viewFormatterDiagnostics")}),o.jsx("pre",{children:Dr})]}),o.jsx("button",{type:"button",className:"formatter-diagnostics-dismiss",title:i("editor.dismissFormatterDiagnostics"),"aria-label":i("editor.dismissFormatterDiagnostics"),onClick:()=>At(""),children:o.jsx(Rn,{size:13})})]}),Vr&&o.jsxs("div",{className:"client-tool-recovery format-lease-status",role:"status",children:[o.jsx(nt,{className:"spin",size:15}),o.jsx("span",{children:i("editor.formattingBy",{name:Vr.holderName})})]})]}),U&&o.jsx("div",{className:"toast",onClick:()=>F(""),children:U}),Ee&&o.jsx("div",{className:"toast success",onClick:()=>re(""),children:Ee}),o.jsxs(vd,{autoSaveId:"texlite-workspace-layout",direction:"horizontal",className:"work-grid",children:[jn&&o.jsx(Jg,{project:l,filesPanel:Rs,files:pt,visibleEntries:Au,activeFile:y,activeMainFile:_,rootDocuments:Y,selectedFolder:Io,expandedFolders:ku,fileDragActive:Eu,uploadingFiles:Lu,readOnly:Vt,editorFontSize:rt.fontSize,outline:od,sourceCursorStore:he,wordCountBusy:Je,hasSelection:!!ke.selectedText.trim()&&/\.(?:tex|sty|cls)$/i.test(y),uploadInput:Gc,setSelectedFolder:$r,setExpandedFolders:Po,setMoveEntry:Uo,setMoveName:zo,setMoveDestination:Bo,setDeleteEntry:qo,setFileDialogError:$o,setNewFolderName:Mo,setNewFolderOpen:Fo,setNewFilePath:No,setNewFileOpen:Ao,setQuickOpen:$,setProjectSearchOpen:Z,setFileDragActive:Du,setFilesCollapsed:Qe,toggleFilesPanel:el,uploadFiles:Wo,upload:Fu,openFile:Pr,jumpToSource:Rr,syncSourceToPdf:Ar,onWordCount:m=>{cu(m)}}),jn&&o.jsx(Fi,{className:"resize-handle",children:o.jsx(oa,{size:12})}),jn&&o.jsx(Qg,{project:l,activeFile:y,activeMainFile:_,openTabs:Sn,content:W,loadedFile:B,readOnly:Vt,comments:Ms,focusComment:Pu,editorPreferences:rt,completionIndex:p,nativeSpellCheck:it.nativeFallback,spellCheckIssues:it.issues,spellCheckJump:it.jump,sourceJump:iu,collaborativeText:cd,collaborationAwareness:De.awareness,undoManager:y?De.getUndoManager(y):void 0,editorNotice:ed,activateTab:nl,closeTab:So,handleTabKeyDown:wd,updateEditorContent:Nr,setSelection:(m,b,j)=>He({selectedText:m,startOffset:b,endOffset:j}),onCommentClick:m=>{const b=Ms.find(j=>j.id===m);b&&(Ho({...b}),pe("comments"))},onSpellCheckReplace:ad,onCursor:Yc}),tl&&o.jsx(rw,{projectId:n,activeMainFile:_,previewTab:ve,diagnosticTab:Se,pdfUrl:Wt,pdfLoadingMode:Yu,pdfLoading:Ur,pdfCompiledAt:ns,pdfCompiledLabel:ud,pdfTargetLabel:dd,pdfDownloadUrl:fd,pdfTarget:su,pdfViewport:ru,activeFile:y,compileBusy:$s,compileLog:zr,compileDiagnostics:Xu,compileMessages:Br,artifacts:Jo,artifactPreview:Qu,artifactLoading:Zu,cleaning:Yo,readOnly:Vt,collaborationSynced:Ge,workspaceLayout:ne,showSyncResize:jn&&tl,diagnosticCount:hd,selectPreviewTab:oe,changeWorkspaceLayout:qr,onSetNotice:re,onSetPdfViewport:ou,syncVisiblePdfToSource:au,syncCurrentSourceToPdf:()=>{const m=Ce.current;if(!m)return Promise.resolve();const b=he.getCursor();return Ar(m,b.line,b.column)},syncPdfToSource:lu,canSyncWithPdf:md,files:pt,jumpToSource:Rr,onSetCleanMode:Ne,cleanCompile:Xo,viewArtifact:rd}),o.jsx(mw,{sidePanel:le,onClose:()=>pe(null),project:l,projectId:n,site:t,files:pt,currentUserId:e.id,comments:Ms,onFocusComment:m=>Ho({...m}),onToggleComment:Wu,onReplyComment:Vu,onEditComment:Hu,onDeleteComment:Ku,onEditCommentReply:Ju,onDeleteCommentReply:Gu,dictionaryWords:h,onDictionaryChange:d,editorPreferences:rt,onEditorPreferences:Qo,spellCheckCount:it.summary?.total??null,spellCheckUniqueCount:it.summary?.unique??null,spellCheckIndex:it.summary?it.index:-1,onSpellCheckNavigate:it.jumpToIssue,onProject:a})]}),ft&&o.jsx(sa,{title:i("editor.wordCountTitle"),onClose:()=>N(!1),children:o.jsx(yw,{open:!0,mode:M,path:Lt,busy:Je,error:Hc,result:Kc,onOpenChange:N})}),o.jsx(hw,{user:e,project:l,projectId:n,activeFile:y,content:W,maxCitationBibtexBytes:t.maxCitationBibtexBytes,files:pt,directoryEntries:Ru,readOnly:Vt,workspaceLayout:ne,changeWorkspaceLayout:qr,resourcePreview:gu,resourcePreviewLoading:wu,setResourcePreview:Oo,setResourcePreviewLoading:yu,uploadConflict:_u,setUploadConflict:Tu,uploadFiles:Wo,cleanMode:ht,setCleanMode:Ne,cleanCompile:Xo,newFileOpen:pu,setNewFileOpen:Ao,newFilePath:mu,setNewFilePath:No,newFolderOpen:bu,setNewFolderOpen:Fo,newFolderName:xu,setNewFolderName:Mo,selectedFolder:Io,fileDialogError:Su,setFileDialogError:$o,createFile:Nu,createFolder:Ou,moveEntry:Cu,setMoveEntry:Uo,moveName:ju,setMoveName:zo,moveDestination:vu,setMoveDestination:Bo,movePath:Mu,deleteEntry:Ir,setDeleteEntry:qo,deleteActiveSessions:ld,removePath:$u,commentOpen:Uu,setCommentOpen:Ko,selection:ke,commentText:zu,setCommentText:Bu,addComment:qu,shareOpen:zt,setShareOpen:Tt,citationLibraryOpen:_e,setCitationLibraryOpen:de,insertCitationAtCursor:hu,quickOpen:R,setQuickOpen:$,projectSearchOpen:L,setProjectSearchOpen:Z,openFile:Pr,jumpToSource:Rr,historyOpen:ye,setHistoryOpen:Ke,gitOpen:E,setGitOpen:te,save:ts,permissionDowngrade:eu,permissionDowngradeBusy:Jc,dismissPermissionDowngrade:tu,discardPermissionDraft:id})]})}function Sw(t){const e=[],n=/^\s*\\(part|chapter|section|subsection|subsubsection)\*?(?:\[[^\]]*\])?\{([^}]*)\}/,s={part:0,chapter:0,section:1,subsection:2,subsubsection:3};return t.split(`
27
- `).forEach((r,i)=>{const l=r.match(n);l&&e.push({level:s[l[1]],title:l[2],line:i+1})}),e}const Iw=Object.freeze(Object.defineProperty({__proto__:null,ProjectWorkspace:xw},Symbol.toStringTag,{value:"Module"}));export{Ud as A,ia as C,al as H,Iw as P,Gd as R,ul as S,Vp as U,Fw as a,Mw as b,Ow as c,$w as d,gn as e,Rw as f,Ft as g,Tw as h,Kt as i,Xd as j,yi as k,zd as l,zi as m,Lw as n,ih as p,Nw as r,Aw as t};