texlite 0.9.0 → 0.9.2

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 (93) hide show
  1. package/DESIGN.md +7 -0
  2. package/OPERATIONS.md +70 -3
  3. package/README.md +5 -0
  4. package/README.zh-CN.md +5 -0
  5. package/THIRD_PARTY_NOTICES.md +29 -0
  6. package/dist/client/assets/{AdminUsers-3CHb5012.js → AdminUsers-Buf5ZclR.js} +1 -1
  7. package/dist/client/assets/{CitationLibraryDialog-zPpsUhWJ.js → CitationLibraryDialog-DrKbIlD-.js} +1 -1
  8. package/dist/client/assets/Dashboard-DLk2j3oq.js +2 -0
  9. package/dist/client/assets/GitDialog-CTWAU8q6.js +3 -0
  10. package/dist/client/assets/HistoryDialog-Mo4p8HEg.js +7 -0
  11. package/dist/client/assets/LatexEditor-CwvakYva.js +135 -0
  12. package/dist/client/assets/{PdfPreview-BFVNczSk.js → PdfPreview-BUpELZd-.js} +1 -1
  13. package/dist/client/assets/{ProjectIconPickerDialog-Cf0zBf8u.js → ProjectIconPickerDialog-BiWSwDdt.js} +1 -1
  14. package/dist/client/assets/{ProjectNavigationDialogs-TPbe11iR.js → ProjectNavigationDialogs-CpjkXZTz.js} +1 -1
  15. package/dist/client/assets/{ProjectSettings-CDQvIlQ4.js → ProjectSettings-DoxitHbX.js} +1 -1
  16. package/dist/client/assets/ProjectWorkspace-iNqXZlsj.js +29 -0
  17. package/dist/client/assets/SelectionHistoryDialog-9FWlc3Rb.js +3 -0
  18. package/dist/client/assets/{SystemMetricsDialog-CuqHPUnn.js → SystemMetricsDialog-24kifZO6.js} +1 -1
  19. package/dist/client/assets/TagManagementDialog-BHIA0vEA.js +1 -0
  20. package/dist/client/assets/{WordCountDialog-B4PI0vEk.js → WordCountDialog-DFIWvLrP.js} +1 -1
  21. package/dist/client/assets/check-C3GZh6a1.js +1 -0
  22. package/dist/client/assets/chevron-left-l1oupvGO.js +1 -0
  23. package/dist/client/assets/editor-3rgn4IYh.js +14 -0
  24. package/dist/client/assets/{hard-drive-6uYFyezl.js → hard-drive-B-NSDVVA.js} +1 -1
  25. package/dist/client/assets/{index-BRT5O-Hg.js → index-CNTGCh7t.js} +1 -1
  26. package/dist/client/assets/index-CrlfruX_.css +1 -0
  27. package/dist/client/assets/index-DIM_KiG2.js +12 -0
  28. package/dist/client/assets/katex-D9PXdmFF.css +1 -0
  29. package/dist/client/assets/{key-round-DOAxDSfz.js → key-round-BjL9H8-H.js} +1 -1
  30. package/dist/client/assets/{latexFormatterWorker-DYkYtcFy.js → latexFormatterWorker-BRmsns8a.js} +2 -2
  31. package/dist/client/assets/minimize-2-DDCq8c49.js +1 -0
  32. package/dist/client/assets/{minus-9eVJnugf.js → minus-DgKZCT9F.js} +1 -1
  33. package/dist/client/assets/{pdf-BB1XvBIF.js → pdf-DUYcbPMK.js} +1 -1
  34. package/dist/client/assets/{plus-BGXipRoG.js → plus-CezUzSIZ.js} +1 -1
  35. package/dist/client/assets/{refresh-cw-Dvp3O90f.js → refresh-cw-CDFNL-qu.js} +1 -1
  36. package/dist/client/assets/{search-b1ORp1k8.js → search-CrDJjHoj.js} +1 -1
  37. package/dist/client/assets/{sigma-Bk0_MzWi.js → sigma-DOcJr7VG.js} +1 -1
  38. package/dist/client/assets/spellCheck-BgWyesvf.js +1 -0
  39. package/dist/client/assets/{tags-JAkbmWns.js → tags-BedQ75lh.js} +1 -1
  40. package/dist/client/assets/{type-CE2DYkPH.js → type-glZNdzZR.js} +1 -1
  41. package/dist/client/assets/{user-plus-CKalKSsw.js → user-plus-gQ6q5Nom.js} +1 -1
  42. package/dist/client/assets/{x-Bq29njHL.js → x-CSzFikn2.js} +1 -1
  43. package/dist/client/index.html +6 -4
  44. package/dist/server/app.js +130 -83
  45. package/dist/server/cli.js +4 -2
  46. package/dist/server/compileArtifacts.js +3 -2
  47. package/dist/server/config.js +27 -0
  48. package/dist/server/harper.js +205 -8
  49. package/dist/server/history.js +53 -3
  50. package/dist/server/i18n.js +8 -0
  51. package/dist/server/index.js +4 -2
  52. package/dist/server/instanceLock.js +4 -2
  53. package/dist/server/latexCompletion.js +126 -63
  54. package/dist/server/latexDocumentGraph.js +106 -0
  55. package/dist/server/latexSpellMask.js +196 -43
  56. package/dist/server/pm2.js +3 -2
  57. package/dist/server/projectReferences.js +109 -0
  58. package/dist/server/routes/auth.js +5 -2
  59. package/dist/server/routes/comments.js +13 -1
  60. package/dist/server/routes/compile.js +2 -2
  61. package/dist/server/routes/projectFiles.js +12 -3
  62. package/dist/server/routes/projectHistory.js +13 -1
  63. package/dist/server/routes/projectReferences.js +36 -0
  64. package/dist/server/routes/projects.js +41 -4
  65. package/dist/server/routes/system.js +1 -0
  66. package/dist/server/zip.js +2 -16
  67. package/dist/shared/basePath.js +44 -0
  68. package/dist/shared/bibtexReferences.js +135 -0
  69. package/dist/shared/latexCommandSnippets.js +91 -0
  70. package/dist/shared/latexDependencies.js +71 -0
  71. package/dist/shared/latexLiterals.js +215 -0
  72. package/dist/shared/latexReferenceCommands.js +75 -0
  73. package/dist/shared/latexReferences.js +193 -0
  74. package/dist/shared/latexRoot.js +21 -0
  75. package/dist/shared/latexScanner.js +183 -0
  76. package/dist/shared/writingChecks.js +4 -0
  77. package/package.json +11 -4
  78. package/texlite.config.example.json +2 -4
  79. package/dist/client/assets/Dashboard-CWfSLzD3.js +0 -2
  80. package/dist/client/assets/GitDialog-BUU2U_LV.js +0 -3
  81. package/dist/client/assets/HistoryDialog-B6aopsrw.js +0 -7
  82. package/dist/client/assets/LatexEditor-CM445Tk0.js +0 -65
  83. package/dist/client/assets/ProjectWorkspace-C6GrvKN6.js +0 -27
  84. package/dist/client/assets/SelectionHistoryDialog-CyE0_YDs.js +0 -3
  85. package/dist/client/assets/TagManagementDialog-gRLM3lLx.js +0 -1
  86. package/dist/client/assets/check-BXvzrdoz.js +0 -1
  87. package/dist/client/assets/chevron-left-BB5MYb7g.js +0 -1
  88. package/dist/client/assets/editor-CiK7TK0p.js +0 -14
  89. package/dist/client/assets/index-C0t11tlT.js +0 -14
  90. package/dist/client/assets/index-DXWp2bzM.css +0 -1
  91. package/dist/client/assets/katex-CEK31ho9.css +0 -1
  92. package/dist/client/assets/minimize-2-BWtbag2I.js +0 -1
  93. package/dist/client/assets/spellCheck-BJjWgnef.js +0 -1
@@ -0,0 +1,29 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./spellCheck-BgWyesvf.js","./index-DIM_KiG2.js","./react-BVUjbTTn.js","./index-CrlfruX_.css","./check-C3GZh6a1.js","./x-CSzFikn2.js","./search-CrDJjHoj.js","./user-plus-gQ6q5Nom.js","./refresh-cw-CDFNL-qu.js","./LatexEditor-CwvakYva.js","./editor-3rgn4IYh.js","./CitationLibraryDialog-DrKbIlD-.js","./citationLibrary-ZeQPCv5O.js","./plus-CezUzSIZ.js","./chevron-left-l1oupvGO.js","./tags-BedQ75lh.js","./GitDialog-CTWAU8q6.js","./key-round-BjL9H8-H.js","./minus-DgKZCT9F.js","./minimize-2-DDCq8c49.js","./HistoryDialog-Mo4p8HEg.js","./index-CNTGCh7t.js","./hard-drive-B-NSDVVA.js","./SelectionHistoryDialog-9FWlc3Rb.js","./ProjectNavigationDialogs-CpjkXZTz.js","./ProjectSettings-DoxitHbX.js","./type-glZNdzZR.js","./sigma-DOcJr7VG.js","./WordCountDialog-DFIWvLrP.js"])))=>i.map(i=>d[i]);
2
+ import{c as Te,s as fn,g as ae,h as de,a as Sr,A as _i,n as nh,l as sh,r as rh,_ as vt,S as ih,d as nt,i as gs,j as ka,C as bs,M as Yt,e as Sa,k as oh}from"./index-DIM_KiG2.js";import{r as d,u as Ke,j as o,P as Cr,d as Gi,e as lh}from"./react-BVUjbTTn.js";import{C as ah}from"./check-C3GZh6a1.js";import{e as ch,U as Li,B as uh,M as dh,G as hh,X as xs,F as fh,f as kl,g as ph,a as mh,C as Ca,b as gh,T as en,c as va,d as Hn,L as wh,i as Ut,S as Ti,D as rr,A as ir,P as Sl,h as Cl}from"./x-CSzFikn2.js";import{S as yh}from"./search-CrDJjHoj.js";import{U as bh}from"./user-plus-gQ6q5Nom.js";import{R as xh}from"./refresh-cw-CDFNL-qu.js";const kh=Te("AlignLeft",[["path",{d:"M15 12H3",key:"6jk70r"}],["path",{d:"M17 18H3",key:"1amg6g"}],["path",{d:"M21 6H3",key:"1jwq7v"}]]);const Yi=Te("ChevronDown",[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]]);const Sh=Te("CircleCheck",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]);const Xi=Te("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 vl=Te("Columns2",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M12 3v18",key:"108xh3"}]]);const Ri=Te("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 Ch=Te("FileClock",[["path",{d:"M16 22h2a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v3",key:"37hlfg"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["circle",{cx:"8",cy:"16",r:"6",key:"10v15b"}],["path",{d:"M9.5 17.5 8 16.25V14",key:"1o80t2"}]]);const vh=Te("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 ja=Te("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 jl=Te("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 jh=Te("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 El=Te("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 Ea=Te("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 Da=Te("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 Eh=Te("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 Dh=Te("PanelLeft",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]]);const _h=Te("PanelRight",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]]);const Lh=Te("Play",[["polygon",{points:"6 3 20 12 6 21 6 3",key:"1oa8hb"}]]);const Th=Te("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 Rh=Te("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 Dl=Te("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 Ah=Te("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 Nh=Te("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"}]]),Oh="wrap = false",Ai=[{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'}],bt={font:"jetbrains",fontSize:14,lineHeight:1.65,lineWrapping:!0,spellCheck:!0,mathPreviewOnHover:!1,vimMode:!1,formatOnCompile:!1,texFmtConfig:Oh,texFmtConfigInitialized:!0,openFilesInTabs:!1},Fh="texlite-editor-preferences";function _a(t,e){return fn(`${Fh}:${encodeURIComponent(t)}:${encodeURIComponent(e)}`)}function Py(t){return Ai.find(e=>e.id===t)?.stack??Ai[0].stack}function _l(t,e){try{const n=JSON.parse(localStorage.getItem(_a(t,e))??"{}"),s=typeof n.texFmtConfig=="string"&&n.texFmtConfig.length<=16*1024?n.texFmtConfig:null,r=s!==null&&(n.texFmtConfigInitialized===!0||s.trim().length>0)?s:bt.texFmtConfig;return{font:Ai.some(i=>i.id===n.font)?n.font:bt.font,fontSize:[12,13,14,15,16,18,20].includes(Number(n.fontSize))?Number(n.fontSize):bt.fontSize,lineHeight:[1.45,1.65,1.85].includes(Number(n.lineHeight))?Number(n.lineHeight):bt.lineHeight,lineWrapping:typeof n.lineWrapping=="boolean"?n.lineWrapping:bt.lineWrapping,spellCheck:typeof n.spellCheck=="boolean"?n.spellCheck:bt.spellCheck,mathPreviewOnHover:typeof n.mathPreviewOnHover=="boolean"?n.mathPreviewOnHover:bt.mathPreviewOnHover,vimMode:typeof n.vimMode=="boolean"?n.vimMode:bt.vimMode,formatOnCompile:typeof n.formatOnCompile=="boolean"?n.formatOnCompile:bt.formatOnCompile,texFmtConfig:r,texFmtConfigInitialized:!0,openFilesInTabs:typeof n.openFilesInTabs=="boolean"?n.openFilesInTabs:bt.openFilesInTabs}}catch{return bt}}function Mh(t,e,n){localStorage.setItem(_a(t,e),JSON.stringify(n))}function $h(){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 Xt=$h(),Ih=/\.(?:tex|bib|cls|sty)$/i,La=3e4;let xt=null,or=!1,pn=null,Ph=1;const wn=new Map,lr=[];let Mn=null,fs=null;class dt extends Error{constructor(e,n){super(n),this.kind=e,this.name="TexFmtError"}kind}function ai(t){return t instanceof dt}function Pt(t){xt?.terminate(),xt=null,or=!1,pn!==null&&window.clearTimeout(pn),pn=null,Mn=null,lr.length=0,fs=null,Xt.failed(t);for(const e of wn.values())e.timeout!==null&&window.clearTimeout(e.timeout),e.reject(t);wn.clear()}function ws(){if(Mn!==null||lr.length===0)return;let t;try{t=Uh()}catch(s){Pt(s instanceof dt?s:new dt("load","The bundled tex-fmt formatter could not be loaded."));return}if(!or)return;const e=lr.shift();if(e===void 0)return;const n=wn.get(e);if(!n){ws();return}Mn=e,n.timeout=window.setTimeout(()=>{Mn===e&&Pt(new dt("result","The formatter did not respond within 30 seconds."))},La);try{t.postMessage({...n.request,id:e})}catch{Pt(new dt("load","The formatter worker could not receive the source."))}}function Uh(){if(xt)return xt;if(typeof Worker>"u"){const t=new dt("load","This browser does not support formatter workers.");throw Xt.failed(t),t}Xt.loading();try{xt=new Worker(new URL(""+new URL("latexFormatterWorker-BRmsns8a.js",import.meta.url).href,import.meta.url),{type:"module",name:"texlite-latex-formatter"}),pn=window.setTimeout(()=>{or||Pt(new dt("load","The formatter did not finish loading within 30 seconds."))},La)}catch{const t=new dt("load","The bundled tex-fmt formatter could not be loaded.");throw Xt.failed(t),t}return xt.onmessage=t=>{const e=t.data;if(e&&"type"in e){e.type==="ready"&&(or=!0,pn!==null&&window.clearTimeout(pn),pn=null,ws());return}if(!e||typeof e.id!="number"){Pt(new dt("result","The formatter worker returned an invalid response."));return}const n=wn.get(e.id);if(n)if(wn.delete(e.id),n.timeout!==null&&window.clearTimeout(n.timeout),Mn===e.id&&(Mn=null),e.ok)Xt.working(),n.resolve(e.result),ws();else{const s=new dt(e.kind,e.message);e.kind==="format"?(Xt.working(),n.reject(s),ws()):(n.reject(s),Pt(s))}},xt.onerror=()=>{Pt(new dt("load","The bundled tex-fmt formatter could not be loaded."))},xt.onmessageerror=()=>{Pt(new dt("result","The formatter worker returned an unreadable response."))},xt}function Qi(t){const e=Ph++;return new Promise((n,s)=>{wn.set(e,{request:t,resolve:n,reject:s,timeout:null}),lr.push(e),ws()})}function zh(t,e=""){return Qi({action:"format",source:t,config:e})}async function Bh(){xt&&Xt.getSnapshot().status==="working"||(fs||(fs=Qi({action:"probe"}).then(()=>{}).finally(()=>{fs=null})),await fs)}async function Uy(){(xt||wn.size)&&Pt(new dt("load","The formatter runtime was reloaded.")),Xt.loading(),await Bh()}function Js(t){return Ih.test(t)}function qh(t){return t.match(/(?:\r?\n)+$/)?.[0]??""}function Wh(t,e){const n=qh(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 ci(t,e,n=0){return Qi({action:"diff",source:t,formatted:e,baseOffset:n})}function Hh(t,e=null){const n=Ll(t),r=e==="succeeded"||e===null&&Kh(t)?[]:Tl(n.filter(Rl)),i=Ll(Vh(t));return{warnings:Tl(i.filter(a=>!Rl(a)&&Jh(a))),errors:r}}function Ll(t){return t.split(`
5
+ `).map(e=>e.trim()).filter(Boolean)}function Tl(t){return[...new Set(t)]}function Vh(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 Kh(t){return/Latexmk: All targets .* are up-to-date/i.test(t)&&/Output written on .*\.pdf/i.test(t)}function Rl(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 Jh(t){return/\bwarnings?\b|overfull|underfull|badness/i.test(t)}const Al=1,Nl=2,ui=4,di=8,ks=32,zt=64,st=128,Gh=1<<29,vr=31,Ni=63,gn=127,Yh=2147483647,_t=(t,e)=>t>>>e|t<<32-e,Xh=t=>_t(t,2)^_t(t,13)^_t(t,22),Qh=t=>_t(t,6)^_t(t,11)^_t(t,25),Zh=t=>_t(t,7)^_t(t,18)^t>>>3,ef=t=>_t(t,17)^_t(t,19)^t>>>10,tf=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),nf=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);class sf{constructor(){const e=new ArrayBuffer(320);this._H=new Uint32Array(e,0,8),this._H.set(nf),this._W=new Uint32Array(e,64,64)}_updateHash(){const e=this._H,n=this._W;for(let h=16;h<64;h++)n[h]=ef(n[h-2])+n[h-7]+Zh(n[h-15])+n[h-16];let s=e[0],r=e[1],i=e[2],l=e[3],a=e[4],c=e[5],u=e[6],f=e[7];for(let h=0,p,w;h<64;h++)p=f+Qh(a)+(a&c^~a&u)+tf[h]+n[h]>>>0,w=Xh(s)+(s&r^s&i^r&i)>>>0,f=u,u=c,c=a,a=l+p>>>0,l=i,i=r,r=s,s=p+w>>>0;e[0]+=s,e[1]+=r,e[2]+=i,e[3]+=l,e[4]+=a,e[5]+=c,e[6]+=u,e[7]+=f}digest(e){let n=0;for(;n+56<=e.length;){let l=0;for(;l<16&&n+3<e.length;l++)this._W[l]=e[n++]<<24|e[n++]<<16|e[n++]<<8|e[n++];if(n%64!==0){for(this._W.fill(0,l,16);n<e.length;)this._W[l]|=e[n]<<(3-n%4)*8,n++;this._W[l]|=st<<(3-n%4)*8}this._updateHash()}const s=n%64!==0;this._W.fill(0,0,16);let r=0;for(;n<e.length;r++)for(let l=3;l>=0&&n<e.length;l--)this._W[r]|=e[n++]<<l*8;s||(this._W[r-(n%4===0?0:1)]|=st<<(3-n%4)*8),this._W[14]=e.byteLength/Gh,this._W[15]=e.byteLength*8,this._updateHash();const i=new Uint8Array(32);for(let l=0;l<this._H.length;l++)for(let a=0;a<4;a++)i[l*4+a]=this._H[l]>>>(3-a)*8;return i}}const rf=t=>new sf().digest(t);function of(t){return Array.from(rf(new TextEncoder().encode(t)),e=>e.toString(16).padStart(2,"0")).join("")}function lf(t){return t instanceof Error&&t.name==="AbortError"}function af({projectId:t,activeFile:e,content:n,permission:s,revision:r,selection:i,save:l,saveFailureMessage:a,onError:c,onAdded:u,onChanged:f}){const[h,p]=d.useState([]),[w,g]=d.useState(null),[b,k]=d.useState(!1),[D,R]=d.useState(""),[x,T]=d.useState(null),[I,C]=d.useState(!1),[j,A]=d.useState(""),X=d.useRef(null),Q=d.useRef(!1),K=d.useRef(e),V=d.useRef(l),ee=d.useRef(c),_=d.useRef(u),z=d.useRef(f);K.current=e,V.current=l,ee.current=c,_.current=u,z.current=f;const te=async B=>{X.current?.abort();const re=new AbortController;X.current=re;try{const le=await ae(`/api/projects/${t}/comments?path=${encodeURIComponent(B)}`,{signal:re.signal});K.current===B&&p(le.comments)}catch(le){!lf(le)&&K.current===B&&p([])}finally{X.current===re&&(X.current=null)}};d.useEffect(()=>{g(null),k(!1),T(null),A("")},[t,e]),d.useEffect(()=>(e?te(e):p([]),()=>{X.current?.abort(),X.current=null}),[t,e,r]);const ne=()=>{e&&(A(""),T({filePath:e,selection:{...i},sourceHash:of(n)}),k(!0))},J=()=>{Q.current||(k(!1),T(null),A(""))},fe=async()=>{const B=x;if(!(!D.trim()||!B||Q.current)){Q.current=!0,C(!0),A("");try{if(s!=="read"&&!await V.current()){A(a);return}await ae(`/api/projects/${t}/comments`,{method:"POST",body:JSON.stringify({path:B.filePath,content:D,...B.selection,sourceHash:B.sourceHash})}),await te(B.filePath),k(!1),T(null),R(""),_.current(),z.current?.()}catch(re){A(de(re))}finally{Q.current=!1,C(!1)}}},ge=async B=>{try{await ae(`/api/projects/${t}/comments/${B.id}`,{method:"PATCH",body:JSON.stringify({resolved:!B.resolved})}),await te(e),z.current?.()}catch(re){ee.current(de(re))}},ye=async(B,re)=>{try{return await ae(`/api/projects/${t}/comments/${B.id}/replies`,{method:"POST",body:JSON.stringify({content:re})}),await te(e),z.current?.(),!0}catch(le){return ee.current(de(le)),!1}},L=async(B,re)=>{try{return await ae(`/api/projects/${t}/comments/${B.id}`,{method:"PATCH",body:JSON.stringify({content:re})}),await te(e),z.current?.(),!0}catch(le){return ee.current(de(le)),!1}},me=async B=>{try{return await ae(`/api/projects/${t}/comments/${B.id}`,{method:"DELETE"}),await te(e),g(re=>re?.id===B.id?null:re),z.current?.(),!0}catch(re){return ee.current(de(re)),!1}},$=async(B,re,le)=>{try{return await ae(`/api/projects/${t}/comments/${B.id}/replies/${re}`,{method:"PATCH",body:JSON.stringify({content:le})}),await te(e),z.current?.(),!0}catch(we){return ee.current(de(we)),!1}},M=async(B,re)=>{try{return await ae(`/api/projects/${t}/comments/${B.id}/replies/${re}`,{method:"DELETE"}),await te(e),z.current?.(),!0}catch(le){return ee.current(de(le)),!1}};return{comments:h,focusComment:w,setFocusComment:g,commentOpen:b,openComment:ne,closeComment:J,commentText:D,setCommentText:R,commentSelection:x?.selection??i,commentSubmitting:I,commentError:j,addComment:fe,toggleComment:ge,replyToComment:ye,editComment:L,deleteComment:me,editCommentReply:$,deleteCommentReply:M}}function cf(t){return t instanceof Error&&t.name==="AbortError"}function uf(t,e,n){const[s,r]=d.useState([]),i=d.useRef(null),l=d.useRef(n);l.current=n;const a=d.useCallback(async(f=!1)=>{i.current?.abort();const h=new AbortController;i.current=h;try{const p=await ae(`/api/projects/${t}/mentions?unread=1&limit=100`,{signal:h.signal});i.current===h&&r(p.mentions)}catch(p){i.current===h&&!cf(p)&&(r([]),f&&l.current(de(p)))}finally{i.current===h&&(i.current=null)}},[t]);return d.useEffect(()=>(a(),()=>{i.current?.abort(),i.current=null}),[a,e]),{unreadMentions:s,refresh:a,markMentionRead:async f=>{try{return await ae(`/api/projects/${t}/mentions/${encodeURIComponent(f)}/read`,{method:"POST"}),r(h=>h.filter(p=>p.id!==f)),!0}catch(h){return l.current(de(h)),!1}},markAllMentionsRead:async()=>{if(!s.length)return!0;try{return await ae(`/api/projects/${t}/mentions/read-all`,{method:"POST"}),r([]),!0}catch(f){return l.current(de(f)),!1}}}}const lt=()=>new Map,Oi=t=>{const e=lt();return t.forEach((n,s)=>{e.set(s,n)}),e},Rt=(t,e,n)=>{let s=t.get(e);return s===void 0&&t.set(e,s=n()),s},df=(t,e)=>{const n=[];for(const[s,r]of t)n.push(e(r,s));return n},hf=(t,e)=>{for(const[n,s]of t)if(e(s,n))return!0;return!1},tn=()=>new Set,hi=t=>t[t.length-1],ff=(t,e)=>{for(let n=0;n<e.length;n++)t.push(e[n])},Bt=Array.from,Zi=(t,e)=>{for(let n=0;n<t.length;n++)if(!e(t[n],n,t))return!1;return!0},eo=(t,e)=>{for(let n=0;n<t.length;n++)if(e(t[n],n,t))return!0;return!1},pf=(t,e)=>{const n=new Array(t);for(let s=0;s<t;s++)n[s]=e(s,n);return n},Vn=Array.isArray;class to{constructor(){this._observers=lt()}on(e,n){return Rt(this._observers,e,tn).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 Bt((this._observers.get(e)||lt()).values()).forEach(s=>s(...n))}destroy(){this._observers=lt()}}class Ta{constructor(){this._observers=lt()}on(e,n){Rt(this._observers,e,tn).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 Bt((this._observers.get(e)||lt()).values()).forEach(s=>s(...n))}destroy(){this._observers=lt()}}const St=Math.floor,Zs=Math.abs,no=(t,e)=>t<e?t:e,kn=(t,e)=>t>e?t:e,mf=Math.pow,Ra=t=>t!==0?t<0:1/t<0,ar=Number.MAX_SAFE_INTEGER,Ol=Number.MIN_SAFE_INTEGER,gf=Number.isInteger||(t=>typeof t=="number"&&isFinite(t)&&St(t)===t),Aa=String.fromCharCode,wf=t=>t.toLowerCase(),yf=/^\s*/g,bf=t=>t.replace(yf,""),xf=/([A-Z])/g,Fl=(t,e)=>bf(t.replace(xf,n=>`${e}${wf(n)}`)),kf=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},Ss=typeof TextEncoder<"u"?new TextEncoder:null,Sf=t=>Ss.encode(t),Cf=Ss?Sf:kf;let ys=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});ys&&ys.decode(new Uint8Array).length===1&&(ys=null);const vf=(t,e)=>pf(e,()=>t).join("");class As{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const Fe=()=>new As,so=t=>{let e=t.cpos;for(let n=0;n<t.bufs.length;n++)e+=t.bufs[n].length;return e},ke=t=>{const e=new Uint8Array(so(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},jf=(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(kn(n,e)*2),t.cpos=0)},He=(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},Fi=He,H=(t,e)=>{for(;e>gn;)He(t,st|gn&e),e=St(e/128);He(t,gn&e)},ro=(t,e)=>{const n=Ra(e);for(n&&(e=-e),He(t,(e>Ni?st:0)|(n?zt:0)|Ni&e),e=St(e/64);e>0;)He(t,(e>gn?st:0)|gn&e),e=St(e/128)},Mi=new Uint8Array(3e4),Ef=Mi.length/3,Df=(t,e)=>{if(e.length<Ef){const n=Ss.encodeInto(e,Mi).written||0;H(t,n);for(let s=0;s<n;s++)He(t,Mi[s])}else Oe(t,Cf(e))},_f=(t,e)=>{const n=unescape(encodeURIComponent(e)),s=n.length;H(t,s);for(let r=0;r<s;r++)He(t,n.codePointAt(r))},Ye=Ss&&Ss.encodeInto?Df:_f,jr=(t,e)=>{const n=t.cbuf.length,s=t.cpos,r=no(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(kn(n*2,i)),t.cbuf.set(e.subarray(r)),t.cpos=i)},Oe=(t,e)=>{H(t,e.byteLength),jr(t,e)},io=(t,e)=>{jf(t,e);const n=new DataView(t.cbuf.buffer,t.cpos,e);return t.cpos+=e,n},Lf=(t,e)=>io(t,4).setFloat32(0,e,!1),Tf=(t,e)=>io(t,8).setFloat64(0,e,!1),Rf=(t,e)=>io(t,8).setBigInt64(0,e,!1),Ml=new DataView(new ArrayBuffer(4)),Af=t=>(Ml.setFloat32(0,t),Ml.getFloat32(0)===t),Cs=(t,e)=>{switch(typeof e){case"string":He(t,119),Ye(t,e);break;case"number":gf(e)&&Zs(e)<=Yh?(He(t,125),ro(t,e)):Af(e)?(He(t,124),Lf(t,e)):(He(t,123),Tf(t,e));break;case"bigint":He(t,122),Rf(t,e);break;case"object":if(e===null)He(t,126);else if(Vn(e)){He(t,117),H(t,e.length);for(let n=0;n<e.length;n++)Cs(t,e[n])}else if(e instanceof Uint8Array)He(t,116),Oe(t,e);else{He(t,118);const n=Object.keys(e);H(t,n.length);for(let s=0;s<n.length;s++){const r=n[s];Ye(t,r),Cs(t,e[r])}}break;case"boolean":He(t,e?120:121);break;default:He(t,127)}};class $l extends As{constructor(e){super(),this.w=e,this.s=null,this.count=0}write(e){this.s===e?this.count++:(this.count>0&&H(this,this.count-1),this.count=1,this.w(this,e),this.s=e)}}const Il=t=>{t.count>0&&(ro(t.encoder,t.count===1?t.s:-t.s),t.count>1&&H(t.encoder,t.count-2))};class er{constructor(){this.encoder=new As,this.s=0,this.count=0}write(e){this.s===e?this.count++:(Il(this),this.count=1,this.s=e)}toUint8Array(){return Il(this),ke(this.encoder)}}const Pl=t=>{if(t.count>0){const e=t.diff*2+(t.count===1?0:1);ro(t.encoder,e),t.count>1&&H(t.encoder,t.count-2)}};class fi{constructor(){this.encoder=new As,this.s=0,this.count=0,this.diff=0}write(e){this.diff===e-this.s?(this.s=e,this.count++):(Pl(this),this.count=1,this.diff=e-this.s,this.s=e)}toUint8Array(){return Pl(this),ke(this.encoder)}}class Nf{constructor(){this.sarr=[],this.s="",this.lensE=new er}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 As;return this.sarr.push(this.s),this.s="",Ye(e,this.sarr.join("")),jr(e,this.lensE.toUint8Array()),ke(e)}}const Ct=t=>new Error(t),kt=()=>{throw Ct("Method unimplemented")},ht=()=>{throw Ct("Unexpected case")},Na=Ct("Unexpected end of array"),Oa=Ct("Integer out of Range");class Er{constructor(e){this.arr=e,this.pos=0}}const rn=t=>new Er(t),$i=t=>t.pos!==t.arr.length,Of=(t,e)=>{const n=new Uint8Array(t.arr.buffer,t.pos+t.arr.byteOffset,e);return t.pos+=e,n},Qe=t=>Of(t,ie(t)),Kn=t=>t.arr[t.pos++],ie=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&gn)*n,n*=128,r<st)return e;if(e>ar)throw Oa}throw Na},oo=t=>{let e=t.arr[t.pos++],n=e&Ni,s=64;const r=(e&zt)>0?-1:1;if((e&st)===0)return r*n;const i=t.arr.length;for(;t.pos<i;){if(e=t.arr[t.pos++],n=n+(e&gn)*s,s*=128,e<st)return r*n;if(n>ar)throw Oa}throw Na},Ff=t=>{let e=ie(t);if(e===0)return"";{let n=String.fromCodePoint(Kn(t));if(--e<100)for(;e--;)n+=String.fromCodePoint(Kn(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))}},Mf=t=>ys.decode(Qe(t)),_e=ys?Mf:Ff,lo=(t,e)=>{const n=new DataView(t.arr.buffer,t.arr.byteOffset+t.pos,e);return t.pos+=e,n},$f=t=>lo(t,4).getFloat32(0,!1),If=t=>lo(t,8).getFloat64(0,!1),Pf=t=>lo(t,8).getBigInt64(0,!1),Uf=[t=>{},t=>null,oo,$f,If,Pf,t=>!1,t=>!0,_e,t=>{const e=ie(t),n={};for(let s=0;s<e;s++){const r=_e(t);n[r]=vs(t)}return n},t=>{const e=ie(t),n=[];for(let s=0;s<e;s++)n.push(vs(t));return n},Qe],vs=t=>Uf[127-Kn(t)](t);class Ul extends Er{constructor(e,n){super(e),this.reader=n,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),$i(this)?this.count=ie(this)+1:this.count=-1),this.count--,this.s}}class tr extends Er{constructor(e){super(e),this.s=0,this.count=0}read(){if(this.count===0){this.s=oo(this);const e=Ra(this.s);this.count=1,e&&(this.s=-this.s,this.count=ie(this)+2)}return this.count--,this.s}}class pi extends Er{constructor(e){super(e),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){const e=oo(this),n=e&1;this.diff=St(e/2),this.count=1,n&&(this.count=ie(this)+2)}return this.s+=this.diff,this.count--,this.s}}class zf{constructor(e){this.decoder=new tr(e),this.str=_e(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 Bf=crypto.getRandomValues.bind(crypto),Fa=()=>Bf(new Uint32Array(1))[0],qf="10000000-1000-4000-8000"+-1e11,Wf=()=>qf.replace(/[018]/g,t=>(t^Fa()&15>>t/4).toString(16)),nn=Date.now,Jn=t=>new Promise(t);Promise.all.bind(Promise);const zl=t=>t===void 0?null:t;class Hf{constructor(){this.map=new Map}setItem(e,n){this.map.set(e,n)}getItem(e){return this.map.get(e)}}let Ma=new Hf,ao=!0;try{typeof localStorage<"u"&&localStorage&&(Ma=localStorage,ao=!1)}catch{}const $a=Ma,Vf=t=>ao||addEventListener("storage",t),Kf=t=>ao||removeEventListener("storage",t),js=Symbol("Equality"),Ia=(t,e)=>t===e||!!t?.[js]?.(e)||!1,Jf=t=>typeof t=="object",Gf=Object.assign,Yf=Object.keys,Xf=(t,e)=>{for(const n in t)e(t[n],n)},Qf=(t,e)=>{const n=[];for(const s in t)n.push(e(t[s],s));return n},cr=t=>Yf(t).length,Zf=t=>{for(const e in t)return!1;return!0},Ns=(t,e)=>{for(const n in t)if(!e(t[n],n))return!1;return!0},co=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),ep=(t,e)=>t===e||cr(t)===cr(e)&&Ns(t,(n,s)=>(n!==void 0||co(e,s))&&Ia(e[s],n)),tp=Object.freeze,Pa=t=>{for(const e in t){const n=t[e];(typeof n=="object"||typeof n=="function")&&Pa(t[e])}return tp(t)},uo=(t,e,n=0)=>{try{for(;n<t.length;n++)t[n](...e)}finally{n<t.length&&uo(t,e,n+1)}},np=t=>t,$n=(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[js]!=null)return t[js](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)||!$n(t.get(n),e.get(n)))return!1;break}case void 0:case Object:if(cr(t)!==cr(e))return!1;for(const n in t)if(!co(t,n)||!$n(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(!$n(t[n],e[n]))return!1;break;default:return!1}return!0},sp=(t,e)=>e.includes(t);var Ua={};const sn=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]",za=typeof window<"u"&&typeof document<"u"&&!sn;let Dt;const rp=()=>{if(Dt===void 0)if(sn){Dt=lt();const t=process.argv;let e=null;for(let n=0;n<t.length;n++){const s=t[n];s[0]==="-"?(e!==null&&Dt.set(e,""),e=s):e!==null&&(Dt.set(e,s),e=null)}e!==null&&Dt.set(e,"")}else typeof location=="object"?(Dt=lt(),(location.search||"?").slice(1).split("&").forEach(t=>{if(t.length!==0){const[e,n]=t.split("=");Dt.set(`--${Fl(e,"-")}`,n),Dt.set(`-${Fl(e,"-")}`,n)}})):Dt=lt();return Dt},Ii=t=>rp().has(t),ur=t=>zl(sn?Ua[t.toUpperCase().replaceAll("-","_")]:$a.getItem(t)),Ba=t=>Ii("--"+t)||ur(t)!==null,ip=Ba("production"),op=sn&&sp(Ua.FORCE_COLOR,["true","1","2"]),lp=op||!Ii("--no-colors")&&!Ba("no-color")&&(!sn||process.stdout.isTTY)&&(!sn||Ii("--color")||ur("COLORTERM")!==null||(ur("TERM")||"").includes("color")),qa=t=>new Uint8Array(t),ap=(t,e,n)=>new Uint8Array(t,e,n),cp=t=>new Uint8Array(t),up=t=>{let e="";for(let n=0;n<t.byteLength;n++)e+=Aa(t[n]);return btoa(e)},dp=t=>Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("base64"),hp=t=>{const e=atob(t),n=qa(e.length);for(let s=0;s<e.length;s++)n[s]=e.charCodeAt(s);return n},fp=t=>{const e=Buffer.from(t,"base64");return ap(e.buffer,e.byteOffset,e.byteLength)},pp=za?up:dp,mp=za?hp:fp,gp=t=>{const e=qa(t.byteLength);return e.set(t),e};class wp{constructor(e,n){this.left=e,this.right=n}}const It=(t,e)=>new wp(t,e),yp=(t,e)=>t.forEach(n=>e(n.left,n.right)),Bl=t=>t.next()>=.5,mi=(t,e,n)=>St(t.next()*(n+1-e)+e),Wa=(t,e,n)=>St(t.next()*(n+1-e)+e),ho=(t,e,n)=>Wa(t,e,n),bp=t=>Aa(ho(t,97,122)),xp=(t,e=0,n=20)=>{const s=ho(t,e,n);let r="";for(let i=0;i<s;i++)r+=bp(t);return r},gi=(t,e)=>e[ho(t,0,e.length-1)],kp=Symbol("0schema");class Sp{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(vf(" ",(this._rerrs.length-n)*2)+`${s.path!=null?`[${s.path}] `:""}${s.has} doesn't match ${s.expected}. ${s.message}`)}return e.join(`
6
+ `)}}const Pi=(t,e)=>t===e?!0:t==null||e==null||t.constructor!==e.constructor?!1:t[js]?Ia(t,e):Vn(t)?Zi(t,n=>eo(e,s=>Pi(n,s))):Jf(t)?Ns(t,(n,s)=>Pi(n,e[s])):!1;class rt{static _dilutes=!1;extends(e){let[n,s]=[this.shape,e.shape];return this.constructor._dilutes&&([s,n]=[n,s]),Pi(n,s)}equals(e){return this.constructor===e.constructor&&$n(this.shape,e.shape)}[kp](){return!0}[js](e){return this.equals(e)}validate(e){return this.check(e)}check(e,n){kt()}get nullable(){return ts(this,Rr)}get optional(){return new Ka(this)}cast(e){return ql(e,this),e}expect(e){return ql(e,this),e}}class fo extends rt{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 ze=(t,e=null)=>new fo(t,e);ze(fo);class po extends rt{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 Je=t=>new po(t);ze(po);class Dr extends rt{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 _r=(...t)=>new Dr(t),Ha=ze(Dr),Cp=RegExp.escape||(t=>t.replace(/[().|&,$^[\]]/g,e=>"\\"+e)),Va=t=>{if(Gn.check(t))return[Cp(t)];if(Ha.check(t))return t.shape.map(e=>e+"");if(nc.check(t))return["[+-]?\\d+.?\\d*"];if(sc.check(t))return[".*"];if(dr.check(t))return t.shape.map(Va).flat(1);ht()};class vp extends rt{constructor(e){super(),this.shape=e,this._r=new RegExp("^"+e.map(Va).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}}ze(vp);const jp=Symbol("optional");class Ka extends rt{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[jp](){return!0}}const Ep=ze(Ka);class Dp extends rt{check(e,n){return n?.extend(null,"never",typeof e),!1}}ze(Dp);class Lr extends rt{constructor(e,n=!1){super(),this.shape=e,this._isPartial=n}static _dilutes=!0;get partial(){return new Lr(this.shape,!0)}check(e,n){return e==null?(n?.extend(null,"object","null"),!1):Ns(this.shape,(s,r)=>{const i=this._isPartial&&!co(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 _p=t=>new Lr(t),Lp=ze(Lr),Tp=Je(t=>t!=null&&(t.constructor===Object||t.constructor==null));class Ja extends rt{constructor(e,n){super(),this.shape={keys:e,values:n}}check(e,n){return e!=null&&Ns(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 Ga=(t,e)=>new Ja(t,e),Rp=ze(Ja);class Ya extends rt{constructor(e){super(),this.shape=e}check(e,n){return e!=null&&Ns(this.shape,(s,r)=>{const i=s.check(e[r],n);return!i&&n?.extend(r.toString(),"Tuple",typeof s),i})}}const Ap=(...t)=>new Ya(t);ze(Ya);class Xa extends rt{constructor(e){super(),this.shape=e.length===1?e[0]:new mo(e)}check(e,n){const s=Vn(e)&&Zi(e,r=>this.shape.check(r));return!s&&n?.extend(null,"Array",""),s}}const Qa=(...t)=>new Xa(t),Np=ze(Xa),Op=Je(t=>Vn(t));class Za extends rt{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 Fp=(t,e=null)=>new Za(t,e);ze(Za);const Mp=Fp(rt);class $p extends rt{constructor(e){super(),this.len=e.length-1,this.args=Ap(...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 Ip=ze($p),Pp=Je(t=>typeof t=="function");class Up extends rt{constructor(e){super(),this.shape=e}check(e,n){const s=Zi(this.shape,r=>r.check(e,n));return!s&&n?.extend(null,"Intersectinon",typeof e),s}}ze(Up,t=>t.shape.length>0);class mo extends rt{static _dilutes=!0;constructor(e){super(),this.shape=e}check(e,n){const s=eo(this.shape,r=>r.check(e,n));return n?.extend(null,"Union",typeof e),s}}const ts=(...t)=>t.findIndex(e=>dr.check(e))>=0?ts(...t.map(e=>Es(e)).map(e=>dr.check(e)?e.shape:[e]).flat(1)):t.length===1?t[0]:new mo(t),dr=ze(mo),ec=()=>!0,hr=Je(ec),zp=ze(po,t=>t.shape===ec),go=Je(t=>typeof t=="bigint"),Bp=Je(t=>t===go),tc=Je(t=>typeof t=="symbol");Je(t=>t===tc);const In=Je(t=>typeof t=="number"),nc=Je(t=>t===In),Gn=Je(t=>typeof t=="string"),sc=Je(t=>t===Gn),Tr=Je(t=>typeof t=="boolean"),qp=Je(t=>t===Tr),rc=_r(void 0);ze(Dr,t=>t.shape.length===1&&t.shape[0]===void 0);_r(void 0);const Rr=_r(null),Wp=ze(Dr,t=>t.shape.length===1&&t.shape[0]===null);ze(Uint8Array);ze(fo,t=>t.shape===Uint8Array);const Hp=ts(In,Gn,Rr,rc,go,Tr,tc);(()=>{const t=Qa(hr),e=Ga(Gn,hr),n=ts(In,Gn,Rr,Tr,t,e);return t.shape=n,e.shape.values=n,n})();const Es=t=>{if(Mp.check(t))return t;if(Tp.check(t)){const e={};for(const n in t)e[n]=Es(t[n]);return _p(e)}else{if(Op.check(t))return ts(...t.map(Es));if(Hp.check(t))return _r(t);if(Pp.check(t))return ze(t)}ht()},ql=ip?()=>{}:(t,e)=>{const n=new Sp;if(!e.check(t,n))throw Ct(`Expected value to be of type ${e.constructor.name}.
7
+ ${n.toString()}`)};class Vp{constructor(e){this.patterns=[],this.$state=e}if(e,n){return this.patterns.push({if:Es(e),h:n}),this}else(e){return this.if(hr,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 Ct("Unhandled pattern")}}}const Kp=t=>new Vp(t),ic=Kp(hr).if(nc,(t,e)=>mi(e,Ol,ar)).if(sc,(t,e)=>xp(e)).if(qp,(t,e)=>Bl(e)).if(Bp,(t,e)=>BigInt(mi(e,Ol,ar))).if(dr,(t,e)=>An(e,gi(e,t.shape))).if(Lp,(t,e)=>{const n={};for(const s in t.shape){let r=t.shape[s];if(Ep.check(r)){if(Bl(e))continue;r=r.shape}n[s]=ic(r,e)}return n}).if(Np,(t,e)=>{const n=[],s=Wa(e,0,42);for(let r=0;r<s;r++)n.push(An(e,t.shape));return n}).if(Ha,(t,e)=>gi(e,t.shape)).if(Wp,(t,e)=>null).if(Ip,(t,e)=>{const n=An(e,t.res);return()=>n}).if(zp,(t,e)=>An(e,gi(e,[In,Gn,Rr,rc,go,Tr,Qa(In),Ga(ts("a","b","c"),In)]))).if(Rp,(t,e)=>{const n={},s=mi(e,0,3);for(let r=0;r<s;r++){const i=An(e,t.shape.keys),l=An(e,t.shape.values);n[i]=l}return n}).done(),An=(t,e)=>ic(Es(e),t),At=typeof document<"u"?document:{},Jp=t=>At.createElement(t),Gp=()=>At.createDocumentFragment();Je(t=>t.nodeType===rm);const Yp=t=>At.createTextNode(t);typeof DOMParser<"u"&&new DOMParser;const Xp=(t,e)=>(yp(e,(n,s)=>{s===!1?t.removeAttribute(n):s===!0?t.setAttribute(n,""):t.setAttribute(n,s)}),t),Qp=t=>{const e=Gp();for(let n=0;n<t.length;n++)oc(e,t[n]);return e},Zp=(t,e)=>(oc(t,Qp(e)),t),zy=(t,e=[],n=[])=>Zp(Xp(Jp(t),e),n);Je(t=>t.nodeType===tm);const By=Yp;Je(t=>t.nodeType===nm);const em=t=>df(t,(e,n)=>`${n}:${e};`).join(""),oc=(t,e)=>t.appendChild(e),tm=At.ELEMENT_NODE,nm=At.TEXT_NODE;At.CDATA_SECTION_NODE;At.COMMENT_NODE;const sm=At.DOCUMENT_NODE;At.DOCUMENT_TYPE_NODE;const rm=At.DOCUMENT_FRAGMENT_NODE;Je(t=>t.nodeType===sm);const qt=Symbol,lc=qt(),ac=qt(),im=qt(),om=qt(),lm=qt(),cc=qt(),am=qt(),wo=qt(),cm=qt(),um=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},dm={[lc]:It("font-weight","bold"),[ac]:It("font-weight","normal"),[im]:It("color","blue"),[lm]:It("color","green"),[om]:It("color","grey"),[cc]:It("color","red"),[am]:It("color","purple"),[wo]:It("color","orange"),[cm]:It("color","black")},hm=t=>{t.length===1&&t[0]?.constructor===Function&&(t=t[0]());const e=[],n=[],s=lt();let r=[],i=0;for(;i<t.length;i++){const l=t[i],a=dm[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=em(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},uc=lp?hm:um,fm=(...t)=>{console.log(...uc(t)),hc.forEach(e=>e.print(t))},dc=(...t)=>{console.warn(...uc(t)),t.unshift(wo),hc.forEach(e=>e.print(t))},hc=tn(),fc=t=>({[Symbol.iterator](){return this},next:t}),pm=(t,e)=>fc(()=>{let n;do n=t.next();while(!n.done&&!e(n.value));return n}),wi=(t,e)=>fc(()=>{const{done:n,value:s}=t.next();return{done:n,value:n?void 0:e(s)}});class Ar{constructor(e,n){this.clock=e,this.len=n}}class ns{constructor(){this.clients=new Map}}const Yn=(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])_c(t,i,u.clock,u.len,n)}}),mm=(t,e)=>{let n=0,s=t.length-1;for(;n<=s;){const r=St((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},Os=(t,e)=>{const n=t.clients.get(e.client);return n!==void 0&&mm(n,e.clock)!==null},yo=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 Ar(r.clock,kn(r.len,i.clock+i.len-r.clock)):(s<n&&(e[s]=i),s++)}e.length=s})},Ui=t=>{const e=new ns;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++)ff(i,t[l].clients.get(r)||[]);e.clients.set(r,i)}});return yo(e),e},Ds=(t,e,n,s)=>{Rt(t.clients,e,()=>[]).push(new Ar(n,s))},gm=()=>new ns,wm=t=>{const e=gm();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 Ar(a,c))}}r.length>0&&e.clients.set(s,r)}),e},ss=(t,e)=>{H(t.restEncoder,e.clients.size),Bt(e.clients.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{t.resetDsCurVal(),H(t.restEncoder,n);const r=s.length;H(t.restEncoder,r);for(let i=0;i<r;i++){const l=s[i];t.writeDsClock(l.clock),t.writeDsLen(l.len)}})},bo=t=>{const e=new ns,n=ie(t.restDecoder);for(let s=0;s<n;s++){t.resetDsCurVal();const r=ie(t.restDecoder),i=ie(t.restDecoder);if(i>0){const l=Rt(e.clients,r,()=>[]);for(let a=0;a<i;a++)l.push(new Ar(t.readDsClock(),t.readDsLen()))}}return e},Wl=(t,e,n)=>{const s=new ns,r=ie(t.restDecoder);for(let i=0;i<r;i++){t.resetDsCurVal();const l=ie(t.restDecoder),a=ie(t.restDecoder),c=n.clients.get(l)||[],u=Me(n,l);for(let f=0;f<a;f++){const h=t.readDsClock(),p=h+t.readDsLen();if(h<u){u<p&&Ds(s,l,u,p-u);let w=Lt(c,h),g=c[w];for(!g.deleted&&g.id.clock<h&&(c.splice(w+1,0,xr(e,g,h-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,xr(e,g,p-g.id.clock)),g.delete(e))}else Ds(s,l,h,p-h)}}if(s.clients.size>0){const i=new yn;return H(i.restEncoder,0),ss(i,s),i.toUint8Array()}return null},pc=Fa;class Sn extends to{constructor({guid:e=Wf(),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=pc(),this.guid=e,this.collectionid=n,this.share=new Map,this.store=new Ec,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=Jn(u=>{this.on("load",()=>{this.isLoaded=!0,u(this)})});const c=()=>Jn(u=>{const f=h=>{(h===void 0||h===!0)&&(this.off("sync",f),u())};this.on("sync",f)});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&&Se(e.parent.doc,n=>{n.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(Bt(this.subdocs).map(e=>e.guid))}transact(e,n=null){return Se(this,e,n)}get(e,n=Ve){const s=Rt(this.share,e,()=>{const i=new n;return i._integrate(this,null),i}),r=s.constructor;if(n!==Ve&&r!==n)if(r===Ve){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,zn)}getText(e=""){return this.get(e,Zn)}getMap(e=""){return this.get(e,Qn)}getXmlElement(e=""){return this.get(e,es)}getXmlFragment(e=""){return this.get(e,bn)}toJSON(){const e={};return this.share.forEach((n,s)=>{e[s]=n.toJSON()}),e}destroy(){this.isDestroyed=!0,Bt(this.subdocs).forEach(n=>n.destroy());const e=this._item;if(e!==null){this._item=null;const n=e.content;n.doc=new Sn({guid:this.guid,...n.opts,shouldLoad:!1}),n.doc._item=e,Se(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 mc{constructor(e){this.restDecoder=e}resetDsCurVal(){}readDsClock(){return ie(this.restDecoder)}readDsLen(){return ie(this.restDecoder)}}class gc extends mc{readLeftID(){return ue(ie(this.restDecoder),ie(this.restDecoder))}readRightID(){return ue(ie(this.restDecoder),ie(this.restDecoder))}readClient(){return ie(this.restDecoder)}readInfo(){return Kn(this.restDecoder)}readString(){return _e(this.restDecoder)}readParentInfo(){return ie(this.restDecoder)===1}readTypeRef(){return ie(this.restDecoder)}readLen(){return ie(this.restDecoder)}readAny(){return vs(this.restDecoder)}readBuf(){return gp(Qe(this.restDecoder))}readJSON(){return JSON.parse(_e(this.restDecoder))}readKey(){return _e(this.restDecoder)}}class ym{constructor(e){this.dsCurrVal=0,this.restDecoder=e}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=ie(this.restDecoder),this.dsCurrVal}readDsLen(){const e=ie(this.restDecoder)+1;return this.dsCurrVal+=e,e}}class Xn extends ym{constructor(e){super(e),this.keys=[],ie(e),this.keyClockDecoder=new pi(Qe(e)),this.clientDecoder=new tr(Qe(e)),this.leftClockDecoder=new pi(Qe(e)),this.rightClockDecoder=new pi(Qe(e)),this.infoDecoder=new Ul(Qe(e),Kn),this.stringDecoder=new zf(Qe(e)),this.parentInfoDecoder=new Ul(Qe(e),Kn),this.typeRefDecoder=new tr(Qe(e)),this.lenDecoder=new tr(Qe(e))}readLeftID(){return new Pn(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new Pn(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 vs(this.restDecoder)}readBuf(){return Qe(this.restDecoder)}readJSON(){return vs(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 wc{constructor(){this.restEncoder=Fe()}toUint8Array(){return ke(this.restEncoder)}resetDsCurVal(){}writeDsClock(e){H(this.restEncoder,e)}writeDsLen(e){H(this.restEncoder,e)}}class Fs extends wc{writeLeftID(e){H(this.restEncoder,e.client),H(this.restEncoder,e.clock)}writeRightID(e){H(this.restEncoder,e.client),H(this.restEncoder,e.clock)}writeClient(e){H(this.restEncoder,e)}writeInfo(e){Fi(this.restEncoder,e)}writeString(e){Ye(this.restEncoder,e)}writeParentInfo(e){H(this.restEncoder,e?1:0)}writeTypeRef(e){H(this.restEncoder,e)}writeLen(e){H(this.restEncoder,e)}writeAny(e){Cs(this.restEncoder,e)}writeBuf(e){Oe(this.restEncoder,e)}writeJSON(e){Ye(this.restEncoder,JSON.stringify(e))}writeKey(e){Ye(this.restEncoder,e)}}class yc{constructor(){this.restEncoder=Fe(),this.dsCurrVal=0}toUint8Array(){return ke(this.restEncoder)}resetDsCurVal(){this.dsCurrVal=0}writeDsClock(e){const n=e-this.dsCurrVal;this.dsCurrVal=e,H(this.restEncoder,n)}writeDsLen(e){e===0&&ht(),H(this.restEncoder,e-1),this.dsCurrVal+=e}}class yn extends yc{constructor(){super(),this.keyMap=new Map,this.keyClock=0,this.keyClockEncoder=new fi,this.clientEncoder=new er,this.leftClockEncoder=new fi,this.rightClockEncoder=new fi,this.infoEncoder=new $l(Fi),this.stringEncoder=new Nf,this.parentInfoEncoder=new $l(Fi),this.typeRefEncoder=new er,this.lenEncoder=new er}toUint8Array(){const e=Fe();return H(e,0),Oe(e,this.keyClockEncoder.toUint8Array()),Oe(e,this.clientEncoder.toUint8Array()),Oe(e,this.leftClockEncoder.toUint8Array()),Oe(e,this.rightClockEncoder.toUint8Array()),Oe(e,ke(this.infoEncoder)),Oe(e,this.stringEncoder.toUint8Array()),Oe(e,ke(this.parentInfoEncoder)),Oe(e,this.typeRefEncoder.toUint8Array()),Oe(e,this.lenEncoder.toUint8Array()),jr(e,ke(this.restEncoder)),ke(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){Cs(this.restEncoder,e)}writeBuf(e){Oe(this.restEncoder,e)}writeJSON(e){Cs(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 bm=(t,e,n,s)=>{s=kn(s,e[0].id.clock);const r=Lt(e,s);H(t.restEncoder,e.length-r),t.writeClient(n),H(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)},xo=(t,e,n)=>{const s=new Map;n.forEach((r,i)=>{Me(e,i)>r&&s.set(i,r)}),Nr(e).forEach((r,i)=>{n.has(i)||s.set(i,0)}),H(t.restEncoder,s.size),Bt(s.entries()).sort((r,i)=>i[0]-r[0]).forEach(([r,i])=>{bm(t,e.clients.get(r),r,i)})},xm=(t,e)=>{const n=lt(),s=ie(t.restDecoder);for(let r=0;r<s;r++){const i=ie(t.restDecoder),l=new Array(i),a=t.readClient();let c=ie(t.restDecoder);n.set(a,{i:0,refs:l});for(let u=0;u<i;u++){const f=t.readInfo();switch(vr&f){case 0:{const h=t.readLen();l[u]=new gt(ue(a,c),h),c+=h;break}case 10:{const h=ie(t.restDecoder);l[u]=new wt(ue(a,c),h),c+=h;break}default:{const h=(f&(zt|st))===0,p=new je(ue(a,c),null,(f&st)===st?t.readLeftID():null,null,(f&zt)===zt?t.readRightID():null,h?t.readParentInfo()?e.get(t.readString()):t.readLeftID():null,h&&(f&ks)===ks?t.readString():null,Jc(t,f));l[u]=p,c+=p.length}}}}return n},km=(t,e,n)=>{const s=[];let r=Bt(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 Ec,c=new Map,u=(w,g)=>{const b=c.get(w);(b==null||b>g)&&c.set(w,g)};let f=l.refs[l.i++];const h=new Map,p=()=>{for(const w of s){const g=w.id.client,b=n.get(g);b?(b.i--,a.clients.set(g,b.refs.slice(b.i)),n.delete(g),b.i=0,b.refs=[]):a.clients.set(g,[w]),r=r.filter(k=>k!==g)}s.length=0};for(;;){if(f.constructor!==wt){const g=Rt(h,f.id.client,()=>Me(e,f.id.client))-f.id.clock;if(g<0)s.push(f),u(f.id.client,f.id.clock-1),p();else{const b=f.getMissing(t,e);if(b!==null){s.push(f);const k=n.get(b)||{refs:[],i:0};if(k.refs.length===k.i)u(b,Me(e,b)),p();else{f=k.refs[k.i++];continue}}else(g===0||g<f.length)&&(f.integrate(t,g),h.set(f.id.client,f.id.clock+f.length))}}if(s.length>0)f=s.pop();else if(l!==null&&l.i<l.refs.length)f=l.refs[l.i++];else{if(l=i(),l===null)break;f=l.refs[l.i++]}}if(a.clients.size>0){const w=new yn;return xo(w,a,new Map),H(w.restEncoder,0),{missing:c,update:w.toUint8Array()}}return null},Sm=(t,e)=>xo(t,e.doc.store,e.beforeState),Cm=(t,e,n,s=new Xn(t))=>Se(e,r=>{r.local=!1;let i=!1;const l=r.doc,a=l.store,c=xm(s,l),u=km(r,a,c),f=a.pendingStructs;if(f){for(const[p,w]of f.missing)if(w<Me(a,p)){i=!0;break}if(u){for(const[p,w]of u.missing){const g=f.missing.get(p);(g==null||g>w)&&f.missing.set(p,w)}f.update=pr([f.update,u.update])}}else a.pendingStructs=u;const h=Wl(s,r,a);if(a.pendingDs){const p=new Xn(rn(a.pendingDs));ie(p.restDecoder);const w=Wl(p,r,a);h&&w?a.pendingDs=pr([h,w]):a.pendingDs=h||w}else a.pendingDs=h;if(i){const p=a.pendingStructs.update;a.pendingStructs=null,bc(r.doc,p)}},n,!1),bc=(t,e,n,s=Xn)=>{const r=rn(e);Cm(r,t,n,new s(r))},xc=(t,e,n)=>bc(t,e,n,gc),vm=(t,e,n=new Map)=>{xo(t,e.store,n),ss(t,wm(e.store))},jm=(t,e=new Uint8Array([0]),n=new yn)=>{const s=kc(e);vm(n,t,s);const r=[n.toUint8Array()];if(t.store.pendingDs&&r.push(t.store.pendingDs),t.store.pendingStructs&&r.push(Wm(t.store.pendingStructs.update,e)),r.length>1){if(n.constructor===Fs)return Bm(r.map((i,l)=>l===0?i:Vm(i)));if(n.constructor===yn)return pr(r)}return r[0]},ko=(t,e)=>jm(t,e,new Fs),Em=t=>{const e=new Map,n=ie(t.restDecoder);for(let s=0;s<n;s++){const r=ie(t.restDecoder),i=ie(t.restDecoder);e.set(r,i)}return e},kc=t=>Em(new mc(rn(t))),Sc=(t,e)=>(H(t.restEncoder,e.size),Bt(e.entries()).sort((n,s)=>s[0]-n[0]).forEach(([n,s])=>{H(t.restEncoder,n),H(t.restEncoder,s)}),t),Dm=(t,e)=>Sc(t,Nr(e.store)),_m=(t,e=new yc)=>(t instanceof Map?Sc(e,t):Dm(e,t),e.toUint8Array()),Lm=t=>_m(t,new wc);class Tm{constructor(){this.l=[]}}const Hl=()=>new Tm,Vl=(t,e)=>t.l.push(e),Kl=(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.")},Cc=(t,e,n)=>uo(t.l,[e,n]);class Pn{constructor(e,n){this.client=e,this.clock=n}}const Fn=(t,e)=>t===e||t!==null&&e!==null&&t.client===e.client&&t.clock===e.clock,ue=(t,e)=>new Pn(t,e),vc=t=>{for(const[e,n]of t.doc.share.entries())if(n===t)return e;throw ht()},fr=(t,e)=>{for(;e!==null;){if(e.parent===t)return!0;e=e.parent._item}return!1};class jc{constructor(e,n,s,r=0){this.type=e,this.tname=n,this.item=s,this.assoc=r}}const qy=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},Wy=t=>new jc(t.type==null?null:ue(t.type.client,t.type.clock),t.tname??null,t.item==null?null:ue(t.item.client,t.item.clock),t.assoc==null?0:t.assoc);class Rm{constructor(e,n,s=0){this.type=e,this.index=n,this.assoc=s}}const Am=(t,e,n=0)=>new Rm(t,e,n),Gs=(t,e,n)=>{let s=null,r=null;return t._item===null?r=vc(t):s=ue(t._item.id.client,t._item.id.clock),new jc(s,r,e,n)},Hy=(t,e,n=0)=>{let s=t._start;if(n<0){if(e===0)return Gs(t,null,n);e--}for(;s!==null;){if(!s.deleted&&s.countable){if(s.length>e)return Gs(t,ue(s.id.client,s.id.clock+e),n);e-=s.length}if(s.right===null&&n<0)return Gs(t,s.lastId,n);s=s.right}return Gs(t,null,n)},Nm=(t,e)=>{const n=Un(t,e),s=e.clock-n.id.clock;return{item:n,diff:s}},Vy=(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(Me(s,r.client)<=r.clock)return null;const f=n?Wi(s,r):Nm(s,r),h=f.item;if(!(h instanceof je))return null;if(c=h.parent,c._item===null||!c._item.deleted){u=h.deleted||!h.countable?0:f.diff+(a>=0?0:1);let p=h.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(Me(s,i.client)<=i.clock)return null;const{item:f}=n?Wi(s,i):{item:Un(s,i)};if(f instanceof je&&f.content instanceof Nt)c=f.content.type;else return null}else throw ht();a>=0?u=c._length:u=0}return Am(c,u,t.assoc)},Ky=(t,e)=>t===e||t!==null&&e!==null&&t.tname===e.tname&&Fn(t.item,e.item)&&Fn(t.type,e.type)&&t.assoc===e.assoc,Nn=(t,e)=>e===void 0?!t.deleted:e.sv.has(t.id.client)&&(e.sv.get(t.id.client)||0)>t.id.clock&&!Os(e.ds,t.id),zi=(t,e)=>{const n=Rt(t.meta,zi,tn),s=t.doc.store;n.has(e)||(e.sv.forEach((r,i)=>{r<Me(s,i)&&ot(t,ue(i,r))}),Yn(t,e.ds,r=>{}),n.add(e))};class Ec{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const Nr=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},Me=(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},Dc=(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 ht()}n.push(e)},Lt=(t,e)=>{let n=0,s=t.length-1,r=t[s],i=r.id.clock;if(i===e)return s;let l=St(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=St((n+s)/2)}throw ht()},Om=(t,e)=>{const n=t.clients.get(e.client);return n[Lt(n,e.clock)]},Un=Om,Bi=(t,e,n)=>{const s=Lt(e,n),r=e[s];return r.id.clock<n&&r instanceof je?(e.splice(s+1,0,xr(t,r,n-r.id.clock)),s+1):s},ot=(t,e)=>{const n=t.doc.store.clients.get(e.client);return n[Bi(t,n,e.clock)]},Jl=(t,e,n)=>{const s=e.clients.get(n.client),r=Lt(s,n.clock),i=s[r];return n.clock!==i.id.clock+i.length-1&&i.constructor!==gt&&s.splice(r+1,0,xr(t,i,n.clock-i.id.clock+1)),i},Fm=(t,e,n)=>{const s=t.clients.get(e.id.client);s[Lt(s,e.id.clock)]=n},_c=(t,e,n,s,r)=>{if(s===0)return;const i=n+s;let l=Bi(t,e,n),a;do a=e[l++],i<a.id.clock+a.length&&Bi(t,e,i),r(a);while(l<e.length&&e[l].id.clock<i)};class Mm{constructor(e,n,s){this.doc=e,this.deleteSet=new ns,this.beforeState=Nr(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 Gl=(t,e)=>e.deleteSet.clients.size===0&&!hf(e.afterState,(n,s)=>e.beforeState.get(s)!==n)?!1:(yo(e.deleteSet),Sm(t,e),ss(t,e.deleteSet),!0),Yl=(t,e,n)=>{const s=e._item;(s===null||s.id.clock<(t.beforeState.get(s.id.client)||0)&&!s.deleted)&&Rt(t.changed,e,tn).add(n)},nr=(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 je&&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},$m=(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=Lt(i,a.clock),f=i[u];u<i.length&&f.id.clock<c;f=i[++u]){const h=i[u];if(a.clock+a.len<=h.id.clock)break;h instanceof je&&h.deleted&&!h.keep&&n(h)&&h.gc(e,!1)}}}},Im=(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=no(r.length-1,1+Lt(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+nr(r,c)}})},Lc=(t,e)=>{if(e<t.length){const n=t[e],s=n.doc,r=s.store,i=n.deleteSet,l=n._mergeStructs;try{yo(i),n.afterState=Nr(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(f=>f.target._item===null||!f.target._item.deleted),c.forEach(f=>{f.currentTarget=u,f._path=null}),c.sort((f,h)=>f.path.length-h.path.length),a.push(()=>{Cc(u._dEH,c,n)}))}),a.push(()=>s.emit("afterTransaction",[n,s])),a.push(()=>{n._needFormattingCleanup&&og(n)})}),uo(a,[])}finally{s.gc&&$m(i,r,s.gcFilter),Im(i,r),n.afterState.forEach((f,h)=>{const p=n.beforeState.get(h)||0;if(p!==f){const w=r.clients.get(h),g=kn(Lt(w,p),1);for(let b=w.length-1;b>=g;)b-=1+nr(w,b)}});for(let f=l.length-1;f>=0;f--){const{client:h,clock:p}=l[f].id,w=r.clients.get(h),g=Lt(w,p);g+1<w.length&&nr(w,g+1)>1||g>0&&nr(w,g)}if(!n.local&&n.afterState.get(s.clientID)!==n.beforeState.get(s.clientID)&&(fm(wo,lc,"[yjs] ",ac,cc,"Changed the client-id because another client seems to be using it."),s.clientID=pc()),s.emit("afterTransactionCleanup",[n,s]),s._observers.has("update")){const f=new Fs;Gl(f,n)&&s.emit("update",[f.toUint8Array(),n.origin,s,n])}if(s._observers.has("updateV2")){const f=new yn;Gl(f,n)&&s.emit("updateV2",[f.toUint8Array(),n.origin,s,n])}const{subdocsAdded:a,subdocsLoaded:c,subdocsRemoved:u}=n;(a.size>0||u.size>0||c.size>0)&&(a.forEach(f=>{f.clientID=s.clientID,f.collectionid==null&&(f.collectionid=s.collectionid),s.subdocs.add(f)}),u.forEach(f=>s.subdocs.delete(f)),s.emit("subdocs",[{loaded:c,added:a,removed:u},s,n]),u.forEach(f=>f.destroy())),t.length<=e+1?(s._transactionCleanups=[],s.emit("afterAllTransactions",[s,t])):Lc(t,e+1)}}},Se=(t,e,n=null,s=!0)=>{const r=t._transactionCleanups;let i=!1,l=null;t._transaction===null&&(i=!0,t._transaction=new Mm(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&&Lc(r,0)}}return l};class Pm{constructor(e,n){this.insertions=n,this.deletions=e,this.meta=new Map}}const Xl=(t,e,n)=>{Yn(t,n.deletions,s=>{s instanceof je&&e.scope.some(r=>r===t.doc||fr(r,s))&&Lo(s,!1)})},Ql=(t,e,n)=>{let s=null;const r=t.doc,i=t.scope;Se(r,a=>{for(;e.length>0&&t.currStackItem===null;){const c=r.store,u=e.pop(),f=new Set,h=[];let p=!1;Yn(a,u.insertions,w=>{if(w instanceof je){if(w.redone!==null){let{item:g,diff:b}=Wi(c,w.id);b>0&&(g=ot(a,ue(g.id.client,g.id.clock+b))),w=g}!w.deleted&&i.some(g=>g===a.doc||fr(g,w))&&h.push(w)}}),Yn(a,u.deletions,w=>{w instanceof je&&i.some(g=>g===a.doc||fr(g,w))&&!Os(u.insertions,w.id)&&f.add(w)}),f.forEach(w=>{p=Kc(a,w,f,u.insertions,t.ignoreRemoteMapChanges,t)!==null||p});for(let w=h.length-1;w>=0;w--){const g=h[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 Um extends to{constructor(e,{captureTimeout:n=500,captureTransaction:s=c=>!0,deleteFilter:r=()=>!0,trackedOrigins:i=new Set([null]),ignoreRemoteMapChanges:l=!1,doc:a=Vn(e)?e[0].doc:e instanceof Sn?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(k=>c.changedParentTypes.has(k)||k===this.doc)||!this.trackedOrigins.has(c.origin)&&(!c.origin||!this.trackedOrigins.has(c.origin.constructor)))return;const u=this.undoing,f=this.redoing,h=u?this.redoStack:this.undoStack;u?this.stopCapturing():f||this.clear(!1,!0);const p=new ns;c.afterState.forEach((k,D)=>{const R=c.beforeState.get(D)||0,x=k-R;x>0&&Ds(p,D,R,x)});const w=nn();let g=!1;if(this.lastChange>0&&w-this.lastChange<this.captureTimeout&&h.length>0&&!u&&!f){const k=h[h.length-1];k.deletions=Ui([k.deletions,c.deleteSet]),k.insertions=Ui([k.insertions,p])}else h.push(new Pm(c.deleteSet,p)),g=!0;!u&&!f&&(this.lastChange=w),Yn(c,c.deleteSet,k=>{k instanceof je&&this.scope.some(D=>D===c.doc||fr(D,k))&&Lo(k,!0)});const b=[{stackItem:h[h.length-1],origin:c.origin,type:u?"redo":"undo",changedParentTypes:c.changedParentTypes},this];g?this.emit("stack-item-added",b):this.emit("stack-item-updated",b)},this.doc.on("afterTransaction",this.afterTransactionHandler),this.doc.on("destroy",()=>{this.destroy()})}addToScope(e){const n=new Set(this.scope);e=Vn(e)?e:[e],e.forEach(s=>{n.has(s)||(n.add(s),(s instanceof Ve?s.doc!==this.doc:s!==this.doc)&&dc("[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=>Xl(s,this,r)),this.undoStack=[]),n&&(this.redoStack.forEach(r=>Xl(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=Ql(this,this.undoStack,"undo")}finally{this.undoing=!1}return e}redo(){this.redoing=!0;let e;try{e=Ql(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*zm(t){const e=ie(t.restDecoder);for(let n=0;n<e;n++){const s=ie(t.restDecoder),r=t.readClient();let i=ie(t.restDecoder);for(let l=0;l<s;l++){const a=t.readInfo();if(a===10){const c=ie(t.restDecoder);yield new wt(ue(r,i),c),i+=c}else if((vr&a)!==0){const c=(a&(zt|st))===0,u=new je(ue(r,i),null,(a&st)===st?t.readLeftID():null,null,(a&zt)===zt?t.readRightID():null,c?t.readParentInfo()?t.readString():t.readLeftID():null,c&&(a&ks)===ks?t.readString():null,Jc(t,a));yield u,i+=u.length}else{const c=t.readLen();yield new gt(ue(r,i),c),i+=c}}}}class So{constructor(e,n){this.gen=zm(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===wt);return this.curr}}class Co{constructor(e){this.currClient=0,this.startClock=0,this.written=0,this.encoder=e,this.clientStructs=[]}}const Bm=t=>pr(t,gc,Fs),qm=(t,e)=>{if(t.constructor===gt){const{client:n,clock:s}=t.id;return new gt(ue(n,s+e),t.length-e)}else if(t.constructor===wt){const{client:n,clock:s}=t.id;return new wt(ue(n,s+e),t.length-e)}else{const n=t,{client:s,clock:r}=n.id;return new je(ue(s,r+e),null,ue(s,r+e-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(e))}},pr=(t,e=Xn,n=yn)=>{if(t.length===1)return t[0];const s=t.map(f=>new e(rn(f)));let r=s.map(f=>new So(f,!0)),i=null;const l=new n,a=new Co(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===wt?1:-1:g}else return w.curr.id.client-p.curr.id.client}),r.length!==0;){const f=r[0],h=f.curr.id.client;if(i!==null){let p=f.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=f.next(),w=!0;if(p===null||p.id.client!==h||w&&p.id.clock>i.struct.id.clock+i.struct.length)continue;if(h!==i.struct.id.client)Qt(a,i.struct,i.offset),i={struct:p,offset:0},f.next();else if(i.struct.id.clock+i.struct.length<p.id.clock)if(i.struct.constructor===wt)i.struct.length=p.id.clock+p.length-i.struct.id.clock;else{Qt(a,i.struct,i.offset);const g=p.id.clock-i.struct.id.clock-i.struct.length;i={struct:new wt(ue(h,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===wt?i.struct.length-=g:p=qm(p,g)),i.struct.mergeWith(p)||(Qt(a,i.struct,i.offset),i={struct:p,offset:0},f.next())}}else i={struct:f.curr,offset:0},f.next();for(let p=f.curr;p!==null&&p.id.client===h&&p.id.clock===i.struct.id.clock+i.struct.length&&p.constructor!==wt;p=f.next())Qt(a,i.struct,i.offset),i={struct:p,offset:0}}i!==null&&(Qt(a,i.struct,i.offset),i=null),vo(a);const c=s.map(f=>bo(f)),u=Ui(c);return ss(l,u),l.toUint8Array()},Wm=(t,e,n=Xn,s=yn)=>{const r=kc(e),i=new s,l=new Co(i),a=new n(rn(t)),c=new So(a,!1);for(;c.curr;){const f=c.curr,h=f.id.client,p=r.get(h)||0;if(c.curr.constructor===wt){c.next();continue}if(f.id.clock+f.length>p)for(Qt(l,f,kn(p-f.id.clock,0)),c.next();c.curr&&c.curr.id.client===h;)Qt(l,c.curr,0),c.next();else for(;c.curr&&c.curr.id.client===h&&c.curr.id.clock+c.curr.length<=p;)c.next()}vo(l);const u=bo(a);return ss(i,u),i.toUint8Array()},Tc=t=>{t.written>0&&(t.clientStructs.push({written:t.written,restEncoder:ke(t.encoder.restEncoder)}),t.encoder.restEncoder=Fe(),t.written=0)},Qt=(t,e,n)=>{t.written>0&&t.currClient!==e.id.client&&Tc(t),t.written===0&&(t.currClient=e.id.client,t.encoder.writeClient(e.id.client),H(t.encoder.restEncoder,e.id.clock+n)),e.write(t.encoder,n),t.written++},vo=t=>{Tc(t);const e=t.encoder.restEncoder;H(e,t.clientStructs.length);for(let n=0;n<t.clientStructs.length;n++){const s=t.clientStructs[n];H(e,s.written),jr(e,s.restEncoder)}},Hm=(t,e,n,s)=>{const r=new n(rn(t)),i=new So(r,!1),l=new s,a=new Co(l);for(let u=i.curr;u!==null;u=i.next())Qt(a,e(u),0);vo(a);const c=bo(r);return ss(l,c),l.toUint8Array()},Vm=t=>Hm(t,np,Xn,Fs),Zl="You must not compute changes after the event-handler fired.";class Or{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=Km(this.currentTarget,this.target))}deletes(e){return Os(this.transaction.deleteSet,e.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw Ct(Zl);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=hi(c.content.getContent());else return;else c!==null&&this.deletes(c)?(l="update",a=hi(c.content.getContent())):(l="add",a=void 0)}else if(this.deletes(i))l="delete",a=hi(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 Ct(Zl);const n=this.target,s=tn(),r=tn(),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 Km=(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},Ze=()=>{dc("Invalid access: Add Yjs type to a document before reading data.")},Rc=80;let jo=0;class Jm{constructor(e,n){e.marker=!0,this.p=e,this.index=n,this.timestamp=jo++}}const Gm=t=>{t.timestamp=jo++},Ac=(t,e,n)=>{t.p.marker=!1,t.p=e,e.marker=!0,t.index=n,t.timestamp=jo++},Ym=(t,e,n)=>{if(t.length>=Rc){const s=t.reduce((r,i)=>r.timestamp<i.timestamp?r:i);return Ac(s,e,n),s}else{const s=new Jm(e,n);return t.push(s),s}},Fr=(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)=>Zs(e-i.index)<Zs(e-l.index)?i:l);let s=t._start,r=0;for(n!==null&&(s=n.p,r=n.index,Gm(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&&Zs(n.index-r)<s.parent.length/Rc?(Ac(n,s,r),n):Ym(t._searchMarker,s,r)},_s=(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=kn(e,r.index+n))}},Mr=(t,e,n)=>{const s=t,r=e.changedParentTypes;for(;Rt(r,t,()=>[]).push(n),t._item!==null;)t=t._item.parent;Cc(s._eH,n,e)};class Ve{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=Hl(),this._dEH=Hl(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(e,n){this.doc=e,this._item=n}_copy(){throw kt()}clone(){throw kt()}_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){Vl(this._eH,e)}observeDeep(e){Vl(this._dEH,e)}unobserve(e){Kl(this._eH,e)}unobserveDeep(e){Kl(this._dEH,e)}toJSON(){}}const Nc=(t,e,n)=>{t.doc??Ze(),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},Oc=t=>{t.doc??Ze();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},Ls=(t,e)=>{let n=0,s=t._start;for(t.doc??Ze();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}},Fc=(t,e)=>{const n=[];return Ls(t,(s,r)=>{n.push(e(s,r,t))}),n},Xm=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}}}},Mc=(t,e)=>{t.doc??Ze();const n=Fr(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}},mr=(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 f=()=>{u.length>0&&(r=new je(ue(l,Me(a,l)),r,r&&r.lastId,c,c&&c.id,e,null,new xn(u)),r.integrate(t,0),u=[])};s.forEach(h=>{if(h===null)u.push(h);else switch(h.constructor){case Number:case Object:case Boolean:case Array:case String:u.push(h);break;default:switch(f(),h.constructor){case Uint8Array:case ArrayBuffer:r=new je(ue(l,Me(a,l)),r,r&&r.lastId,c,c&&c.id,e,null,new Ms(new Uint8Array(h))),r.integrate(t,0);break;case Sn:r=new je(ue(l,Me(a,l)),r,r&&r.lastId,c,c&&c.id,e,null,new $s(h)),r.integrate(t,0);break;default:if(h instanceof Ve)r=new je(ue(l,Me(a,l)),r,r&&r.lastId,c,c&&c.id,e,null,new Nt(h)),r.integrate(t,0);else throw new Error("Unexpected content type in insert operation")}}}),f()},$c=()=>Ct("Length exceeded!"),Ic=(t,e,n,s)=>{if(n>e._length)throw $c();if(n===0)return e._searchMarker&&_s(e._searchMarker,n,s.length),mr(t,e,null,s);const r=n,i=Fr(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&&ot(t,ue(l.id.client,l.id.clock+n));break}n-=l.length}return e._searchMarker&&_s(e._searchMarker,r,s.length),mr(t,e,l,s)},Qm=(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 mr(t,e,r,n)},Pc=(t,e,n,s)=>{if(s===0)return;const r=n,i=s,l=Fr(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&&ot(t,ue(a.id.client,a.id.clock+n)),n-=a.length);for(;s>0&&a!==null;)a.deleted||(s<a.length&&ot(t,ue(a.id.client,a.id.clock+s)),a.delete(t),s-=a.length),a=a.right;if(s>0)throw $c();e._searchMarker&&_s(e._searchMarker,r,-i+s)},gr=(t,e,n)=>{const s=e._map.get(n);s!==void 0&&s.delete(t)},Eo=(t,e,n,s)=>{const r=e._map.get(n)||null,i=t.doc,l=i.clientID;let a;if(s==null)a=new xn([s]);else switch(s.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:a=new xn([s]);break;case Uint8Array:a=new Ms(s);break;case Sn:a=new $s(s);break;default:if(s instanceof Ve)a=new Nt(s);else throw new Error("Unexpected content type")}new je(ue(l,Me(i.store,l)),r,r&&r.lastId,null,null,e,n,a).integrate(t,0)},Do=(t,e)=>{t.doc??Ze();const n=t._map.get(e);return n!==void 0&&!n.deleted?n.content.getContent()[n.length-1]:void 0},Uc=t=>{const e={};return t.doc??Ze(),t._map.forEach((n,s)=>{n.deleted||(e[s]=n.content.getContent()[n.length-1])}),e},zc=(t,e)=>{t.doc??Ze();const n=t._map.get(e);return n!==void 0&&!n.deleted},Zm=(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&&Nn(i,e)&&(n[r]=i.content.getContent()[i.length-1])}),n},Ys=t=>(t.doc??Ze(),pm(t._map.entries(),e=>!e[1].deleted));class eg extends Or{}class zn extends Ve{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(e){const n=new zn;return n.push(e),n}_integrate(e,n){super._integrate(e,n),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new zn}clone(){const e=new zn;return e.insert(0,this.toArray().map(n=>n instanceof Ve?n.clone():n)),e}get length(){return this.doc??Ze(),this._length}_callObserver(e,n){super._callObserver(e,n),Mr(this,e,new eg(this,e))}insert(e,n){this.doc!==null?Se(this.doc,s=>{Ic(s,this,e,n)}):this._prelimContent.splice(e,0,...n)}push(e){this.doc!==null?Se(this.doc,n=>{Qm(n,this,e)}):this._prelimContent.push(...e)}unshift(e){this.insert(0,e)}delete(e,n=1){this.doc!==null?Se(this.doc,s=>{Pc(s,this,e,n)}):this._prelimContent.splice(e,n)}get(e){return Mc(this,e)}toArray(){return Oc(this)}slice(e=0,n=this.length){return Nc(this,e,n)}toJSON(){return this.map(e=>e instanceof Ve?e.toJSON():e)}map(e){return Fc(this,e)}forEach(e){Ls(this,e)}[Symbol.iterator](){return Xm(this)}_write(e){e.writeTypeRef(jg)}}const tg=t=>new zn;class ng extends Or{constructor(e,n,s){super(e,n),this.keysChanged=s}}class Qn extends Ve{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 Qn}clone(){const e=new Qn;return this.forEach((n,s)=>{e.set(s,n instanceof Ve?n.clone():n)}),e}_callObserver(e,n){Mr(this,e,new ng(this,e,n))}toJSON(){this.doc??Ze();const e={};return this._map.forEach((n,s)=>{if(!n.deleted){const r=n.content.getContent()[n.length-1];e[s]=r instanceof Ve?r.toJSON():r}}),e}get size(){return[...Ys(this)].length}keys(){return wi(Ys(this),e=>e[0])}values(){return wi(Ys(this),e=>e[1].content.getContent()[e[1].length-1])}entries(){return wi(Ys(this),e=>[e[0],e[1].content.getContent()[e[1].length-1]])}forEach(e){this.doc??Ze(),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?Se(this.doc,n=>{gr(n,this,e)}):this._prelimContent.delete(e)}set(e,n){return this.doc!==null?Se(this.doc,s=>{Eo(s,this,e,n)}):this._prelimContent.set(e,n),n}get(e){return Do(this,e)}has(e){return zc(this,e)}clear(){this.doc!==null?Se(this.doc,e=>{this.forEach(function(n,s,r){gr(e,r,s)})}):this._prelimContent.clear()}_write(e){e.writeTypeRef(Eg)}}const sg=t=>new Qn,Zt=(t,e)=>t===e||typeof t=="object"&&typeof e=="object"&&t&&e&&ep(t,e);class qi{constructor(e,n,s,r){this.left=e,this.right=n,this.index=s,this.currentAttributes=r}forward(){this.right===null&&ht(),this.right.content.constructor===We?this.right.deleted||rs(this.currentAttributes,this.right.content):this.right.deleted||(this.index+=this.right.length),this.left=this.right,this.right=this.right.right}}const ea=(t,e,n)=>{for(;e.right!==null&&n>0;)e.right.content.constructor===We?e.right.deleted||rs(e.currentAttributes,e.right.content):e.right.deleted||(n<e.right.length&&ot(t,ue(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},Xs=(t,e,n,s)=>{const r=new Map,i=s?Fr(e,n):null;if(i){const l=new qi(i.p.left,i.p,i.index,r);return ea(t,l,n-i.index)}else{const l=new qi(null,e._start,0,r);return ea(t,l,n)}},Bc=(t,e,n,s)=>{for(;n.right!==null&&(n.right.deleted===!0||n.right.content.constructor===We&&Zt(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,f=new je(ue(i,Me(r.store,i)),c,c&&c.lastId,u,u&&u.id,e,null,new We(a,l));f.integrate(t,0),n.right=f,n.forward()})},rs=(t,e)=>{const{key:n,value:s}=e;s===null?t.delete(n):t.set(n,s)},qc=(t,e)=>{for(;t.right!==null;){if(!(t.right.deleted||t.right.content.constructor===We&&Zt(e[t.right.content.key]??null,t.right.content.value)))break;t.forward()}},Wc=(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(!Zt(u,c)){l.set(a,u);const{left:f,right:h}=n;n.right=new je(ue(i,Me(r.store,i)),f,f&&f.lastId,h,h&&h.id,e,null,new We(a,c)),n.right.integrate(t,0),n.forward()}}return l},yi=(t,e,n,s,r)=>{n.currentAttributes.forEach((p,w)=>{r[w]===void 0&&(r[w]=null)});const i=t.doc,l=i.clientID;qc(n,r);const a=Wc(t,e,n,r),c=s.constructor===String?new Tt(s):s instanceof Ve?new Nt(s):new Cn(s);let{left:u,right:f,index:h}=n;e._searchMarker&&_s(e._searchMarker,n.index,c.getLength()),f=new je(ue(l,Me(i.store,l)),u,u&&u.lastId,f,f&&f.id,e,null,c),f.integrate(t,0),n.right=f,n.index=h,n.forward(),Bc(t,e,n,a)},ta=(t,e,n,s,r)=>{const i=t.doc,l=i.clientID;qc(n,r);const a=Wc(t,e,n,r);e:for(;n.right!==null&&(s>0||a.size>0&&(n.right.deleted||n.right.content.constructor===We));){if(!n.right.deleted)switch(n.right.content.constructor){case We:{const{key:c,value:u}=n.right.content,f=r[c];if(f!==void 0){if(Zt(f,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&&ot(t,ue(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 je(ue(l,Me(i.store,l)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,e,null,new Tt(c)),n.right.integrate(t,0),n.forward()}Bc(t,e,n,a)},Hc=(t,e,n,s,r)=>{let i=e;const l=lt();for(;i&&(!i.countable||i.deleted);){if(!i.deleted&&i.content.constructor===We){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===We){const{key:f,value:h}=u,p=s.get(f)??null;(l.get(f)!==u||p===h)&&(e.delete(t),a++,!c&&(r.get(f)??null)===h&&p!==h&&(p===null?r.delete(f):r.set(f,p))),!c&&!e.deleted&&rs(r,u)}}e=e.right}return a},rg=(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===We){const s=e.content.key;n.has(s)?e.delete(t):n.add(s)}e=e.left}},ig=t=>{let e=0;return Se(t.doc,n=>{let s=t._start,r=t._start,i=lt();const l=Oi(i);for(;r;)r.deleted===!1&&(r.content.constructor===We?rs(l,r.content):(e+=Hc(n,s,r,i,l),i=Oi(l),s=r)),r=r.right}),e},og=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&&_c(t,n.store.clients.get(s),i,r,l=>{!l.deleted&&l.content.constructor===We&&l.constructor!==gt&&e.add(l.parent)})}Se(n,s=>{Yn(t,t.deleteSet,r=>{if(r instanceof gt||!r.parent._hasFormatting||e.has(r.parent))return;const i=r.parent;r.content.constructor===We?e.add(i):rg(s,r)});for(const r of e)ig(r)})},na=(t,e,n)=>{const s=n,r=Oi(e.currentAttributes),i=e.right;for(;n>0&&e.right!==null;){if(e.right.deleted===!1)switch(e.right.content.constructor){case Nt:case Cn:case Tt:n<e.right.length&&ot(t,ue(e.right.id.client,e.right.id.clock+n)),n-=e.right.length,e.right.delete(t);break}e.forward()}i&&Hc(t,i,e.right,r,e.currentAttributes);const l=(e.left||e.right).parent;return l._searchMarker&&_s(l._searchMarker,e.index,-s+n),e};class lg extends Or{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=[];Se(e,s=>{const r=new Map,i=new Map;let l=this.target._start,a=null;const c={};let u="",f=0,h=0;const p=()=>{if(a!==null){let w=null;switch(a){case"delete":h>0&&(w={delete:h}),h=0;break;case"insert":(typeof u=="object"||u.length>0)&&(w={insert:u},r.size>0&&(w.attributes={},r.forEach((g,b)=>{g!==null&&(w.attributes[b]=g)}))),u="";break;case"retain":f>0&&(w={retain:f},Zf(c)||(w.attributes=Gf({},c))),f=0;break}w&&n.push(w),a=null}};for(;l!==null;){switch(l.content.constructor){case Nt:case Cn:this.adds(l)?this.deletes(l)||(p(),a="insert",u=l.content.getContent()[0],p()):this.deletes(l)?(a!=="delete"&&(p(),a="delete"),h+=1):l.deleted||(a!=="retain"&&(p(),a="retain"),f+=1);break;case Tt:this.adds(l)?this.deletes(l)||(a!=="insert"&&(p(),a="insert"),u+=l.content.str):this.deletes(l)?(a!=="delete"&&(p(),a="delete"),h+=l.length):l.deleted||(a!=="retain"&&(p(),a="retain"),f+=l.length);break;case We:{const{key:w,value:g}=l.content;if(this.adds(l)){if(!this.deletes(l)){const b=r.get(w)??null;Zt(b,g)?g!==null&&l.delete(s):(a==="retain"&&p(),Zt(g,i.get(w)??null)?delete c[w]:c[w]=g)}}else if(this.deletes(l)){i.set(w,g);const b=r.get(w)??null;Zt(b,g)||(a==="retain"&&p(),c[w]=b)}else if(!l.deleted){i.set(w,g);const b=c[w];b!==void 0&&(Zt(b,g)?b!==null&&l.delete(s):(a==="retain"&&p(),g===null?delete c[w]:c[w]=g))}l.deleted||(a==="insert"&&p(),rs(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 Zn extends Ve{constructor(e){super(),this._pending=e!==void 0?[()=>this.insert(0,e)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??Ze(),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 Zn}clone(){const e=new Zn;return e.applyDelta(this.toDelta()),e}_callObserver(e,n){super._callObserver(e,n);const s=new lg(this,e,n);Mr(this,e,s),!e.local&&this._hasFormatting&&(e._needFormattingCleanup=!0)}toString(){this.doc??Ze();let e="",n=this._start;for(;n!==null;)!n.deleted&&n.countable&&n.content.constructor===Tt&&(e+=n.content.str),n=n.right;return e}toJSON(){return this.toString()}applyDelta(e,{sanitize:n=!0}={}){this.doc!==null?Se(this.doc,s=>{const r=new qi(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)&&yi(s,this,r,a,l.attributes||{})}else l.retain!==void 0?ta(s,this,r,l.retain,l.attributes||{}):l.delete!==void 0&&na(s,r,l.delete)}}):this._pending.push(()=>this.applyDelta(e))}toDelta(e,n,s){this.doc??Ze();const r=[],i=new Map,l=this.doc;let a="",c=this._start;function u(){if(a.length>0){const h={};let p=!1;i.forEach((g,b)=>{p=!0,h[b]=g});const w={insert:a};p&&(w.attributes=h),r.push(w),a=""}}const f=()=>{for(;c!==null;){if(Nn(c,e)||n!==void 0&&Nn(c,n))switch(c.content.constructor){case Tt:{const h=i.get("ychange");e!==void 0&&!Nn(c,e)?(h===void 0||h.user!==c.id.client||h.type!=="removed")&&(u(),i.set("ychange",s?s("removed",c.id):{type:"removed"})):n!==void 0&&!Nn(c,n)?(h===void 0||h.user!==c.id.client||h.type!=="added")&&(u(),i.set("ychange",s?s("added",c.id):{type:"added"})):h!==void 0&&(u(),i.delete("ychange")),a+=c.content.str;break}case Nt:case Cn:{u();const h={insert:c.content.getContent()[0]};if(i.size>0){const p={};h.attributes=p,i.forEach((w,g)=>{p[g]=w})}r.push(h);break}case We:Nn(c,e)&&(u(),rs(i,c.content));break}c=c.right}u()};return e||n?Se(l,h=>{e&&zi(h,e),n&&zi(h,n),f()},"cleanup"):f(),r}insert(e,n,s){if(n.length<=0)return;const r=this.doc;r!==null?Se(r,i=>{const l=Xs(i,this,e,!s);s||(s={},l.currentAttributes.forEach((a,c)=>{s[c]=a})),yi(i,this,l,n,s)}):this._pending.push(()=>this.insert(e,n,s))}insertEmbed(e,n,s){const r=this.doc;r!==null?Se(r,i=>{const l=Xs(i,this,e,!s);yi(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?Se(s,r=>{na(r,Xs(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?Se(r,i=>{const l=Xs(i,this,e,!1);l.right!==null&&ta(i,this,l,n,s)}):this._pending.push(()=>this.format(e,n,s))}removeAttribute(e){this.doc!==null?Se(this.doc,n=>{gr(n,this,e)}):this._pending.push(()=>this.removeAttribute(e))}setAttribute(e,n){this.doc!==null?Se(this.doc,s=>{Eo(s,this,e,n)}):this._pending.push(()=>this.setAttribute(e,n))}getAttribute(e){return Do(this,e)}getAttributes(){return Uc(this)}_write(e){e.writeTypeRef(Dg)}}const ag=t=>new Zn;class bi{constructor(e,n=()=>!0){this._filter=n,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc??Ze()}[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===es||n.constructor===bn)&&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 bn extends Ve{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 bn}clone(){const e=new bn;return e.insert(0,this.toArray().map(n=>n instanceof Ve?n.clone():n)),e}get length(){return this.doc??Ze(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(e){return new bi(this,e)}querySelector(e){e=e.toUpperCase();const s=new bi(this,r=>r.nodeName&&r.nodeName.toUpperCase()===e).next();return s.done?null:s.value}querySelectorAll(e){return e=e.toUpperCase(),Bt(new bi(this,n=>n.nodeName&&n.nodeName.toUpperCase()===e))}_callObserver(e,n){Mr(this,e,new dg(this,n,e))}toString(){return Fc(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),Ls(this,i=>{r.insertBefore(i.toDOM(e,n,s),null)}),r}insert(e,n){this.doc!==null?Se(this.doc,s=>{Ic(s,this,e,n)}):this._prelimContent.splice(e,0,...n)}insertAfter(e,n){if(this.doc!==null)Se(this.doc,s=>{const r=e&&e instanceof Ve?e._item:e;mr(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 Ct("Reference item not found");s.splice(r,0,...n)}}delete(e,n=1){this.doc!==null?Se(this.doc,s=>{Pc(s,this,e,n)}):this._prelimContent.splice(e,n)}toArray(){return Oc(this)}push(e){this.insert(this.length,e)}unshift(e){this.insert(0,e)}get(e){return Mc(this,e)}slice(e=0,n=this.length){return Nc(this,e,n)}forEach(e){Ls(this,e)}_write(e){e.writeTypeRef(Lg)}}const cg=t=>new bn;class es extends bn{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 es(this.nodeName)}clone(){const e=new es(this.nodeName),n=this.getAttributes();return Xf(n,(s,r)=>{e.setAttribute(r,s)}),e.insert(0,this.toArray().map(s=>s instanceof Ve?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?Se(this.doc,n=>{gr(n,this,e)}):this._prelimAttrs.delete(e)}setAttribute(e,n){this.doc!==null?Se(this.doc,s=>{Eo(s,this,e,n)}):this._prelimAttrs.set(e,n)}getAttribute(e){return Do(this,e)}hasAttribute(e){return zc(this,e)}getAttributes(e){return e?Zm(this,e):Uc(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 Ls(this,l=>{r.appendChild(l.toDOM(e,n,s))}),s!==void 0&&s._createAssociation(r,this),r}_write(e){e.writeTypeRef(_g),e.writeKey(this.nodeName)}}const ug=t=>new es(t.readKey());class dg extends Or{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 wr extends Qn{constructor(e){super(),this.hookName=e}_copy(){return new wr(this.hookName)}clone(){const e=new wr(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(Tg),e.writeKey(this.hookName)}}const hg=t=>new wr(t.readKey());class yr extends Zn{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 yr}clone(){const e=new yr;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(Rg)}}const fg=t=>new yr;class _o{constructor(e,n){this.id=e,this.length=n}get deleted(){throw kt()}mergeWith(e){return!1}write(e,n,s){throw kt()}integrate(e,n){throw kt()}}const pg=0;class gt extends _o{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),Dc(e.doc.store,this)}write(e,n){e.writeInfo(pg),e.writeLen(this.length-n)}getMissing(e,n){return null}}class Ms{constructor(e){this.content=e}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new Ms(this.content)}splice(e){throw kt()}mergeWith(e){return!1}integrate(e,n){}delete(e){}gc(e){}write(e,n){e.writeBuf(this.content)}getRef(){return 3}}const mg=t=>new Ms(t.readBuf());class Ts{constructor(e){this.len=e}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new Ts(this.len)}splice(e){const n=new Ts(this.len-e);return this.len=e,n}mergeWith(e){return this.len+=e.len,!0}integrate(e,n){Ds(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 gg=t=>new Ts(t.readLen()),Vc=(t,e)=>new Sn({guid:t,...e,shouldLoad:e.shouldLoad||e.autoLoad||!1});class $s{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 $s(Vc(this.doc.guid,this.opts))}splice(e){throw kt()}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 wg=t=>new $s(Vc(t.readString(),t.readAny()));class Cn{constructor(e){this.embed=e}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new Cn(this.embed)}splice(e){throw kt()}mergeWith(e){return!1}integrate(e,n){}delete(e){}gc(e){}write(e,n){e.writeJSON(this.embed)}getRef(){return 5}}const yg=t=>new Cn(t.readJSON());class We{constructor(e,n){this.key=e,this.value=n}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new We(this.key,this.value)}splice(e){throw kt()}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 bg=t=>new We(t.readKey(),t.readJSON());class br{constructor(e){this.arr=e}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new br(this.arr)}splice(e){const n=new br(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 xg=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 br(n)},kg=ur("node_env")==="development";class xn{constructor(e){this.arr=e,kg&&Pa(e)}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new xn(this.arr)}splice(e){const n=new xn(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 Sg=t=>{const e=t.readLen(),n=[];for(let s=0;s<e;s++)n.push(t.readAny());return new xn(n)};class Tt{constructor(e){this.str=e}getLength(){return this.str.length}getContent(){return this.str.split("")}isCountable(){return!0}copy(){return new Tt(this.str)}splice(e){const n=new Tt(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 Cg=t=>new Tt(t.readString()),vg=[tg,sg,ag,ug,cg,hg,fg],jg=0,Eg=1,Dg=2,_g=3,Lg=4,Tg=5,Rg=6;class Nt{constructor(e){this.type=e}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new Nt(this.type._copy())}splice(e){throw kt()}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 Ag=t=>new Nt(vg[t.readTypeRef()](t)),Wi=(t,e)=>{let n=e,s=0,r;do s>0&&(n=ue(n.client,n.clock+s)),r=Un(t,n),s=n.clock-r.id.clock,n=r.redone;while(n!==null&&r instanceof je);return{item:r,diff:s}},Lo=(t,e)=>{for(;t!==null&&t.keep!==e;)t.keep=e,t=t.parent._item},xr=(t,e,n)=>{const{client:s,clock:r}=e.id,i=new je(ue(s,r+n),e,ue(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=ue(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},sa=(t,e)=>eo(t,n=>Os(n.deletions,e)),Kc=(t,e,n,s,r,i)=>{const l=t.doc,a=l.store,c=l.clientID,u=e.redone;if(u!==null)return ot(t,u);let f=e.parent._item,h=null,p;if(f!==null&&f.deleted===!0){if(f.redone===null&&(!n.has(f)||Kc(t,f,n,s,r,i)===null))return null;for(;f.redone!==null;)f=ot(t,f.redone)}const w=f===null?e.parent:f.content.type;if(e.parentSub===null){for(h=e.left,p=e;h!==null;){let D=h;for(;D!==null&&D.parent._item!==f;)D=D.redone===null?null:ot(t,D.redone);if(D!==null&&D.parent._item===f){h=D;break}h=h.left}for(;p!==null;){let D=p;for(;D!==null&&D.parent._item!==f;)D=D.redone===null?null:ot(t,D.redone);if(D!==null&&D.parent._item===f){p=D;break}p=p.right}}else{if(p=null,e.right&&!r){for(h=e;h!==null&&h.right!==null&&(h.right.redone||Os(s,h.right.id)||sa(i.undoStack,h.right.id)||sa(i.redoStack,h.right.id));)for(h=h.right;h.redone;)h=ot(t,h.redone);if(h&&h.right!==null)return null}else h=w._map.get(e.parentSub)||null;h!==null&&h.parent._item!==f&&(h=w._map.get(e.parentSub)||null)}const g=Me(a,c),b=ue(c,g),k=new je(b,h,h&&h.lastId,p,p&&p.id,w,e.parentSub,e.content.copy());return e.redone=b,Lo(k,!0),k.integrate(t,0),k};class je extends _o{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()?Nl:0}set marker(e){(this.info&di)>0!==e&&(this.info^=di)}get marker(){return(this.info&di)>0}get keep(){return(this.info&Al)>0}set keep(e){this.keep!==e&&(this.info^=Al)}get countable(){return(this.info&Nl)>0}get deleted(){return(this.info&ui)>0}set deleted(e){this.deleted!==e&&(this.info^=ui)}markDeleted(){this.info|=ui}getMissing(e,n){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=Me(n,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=Me(n,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===Pn&&this.id.client!==this.parent.client&&this.parent.clock>=Me(n,this.parent.client))return this.parent.client;if(this.origin&&(this.left=Jl(e,n,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=ot(e,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===gt||this.right&&this.right.constructor===gt)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===je?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===je&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===Pn){const s=Un(n,this.parent);s.constructor===gt?this.parent=null:this.parent=s.content.type}return null}integrate(e,n){if(n>0&&(this.id.clock+=n,this.left=Jl(e,e.doc.store,ue(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),Fn(this.origin,r.origin)){if(r.id.client<this.id.client)s=r,i.clear();else if(Fn(this.rightOrigin,r.rightOrigin))break}else if(r.origin!==null&&l.has(Un(e.doc.store,r.origin)))i.has(Un(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),Dc(e.doc.store,this),this.content.integrate(e,this),Yl(e,this.parent,this.parentSub),(this.parent._item!==null&&this.parent._item.deleted||this.parentSub!==null&&this.right!==null)&&this.delete(e)}else new gt(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:ue(this.id.client,this.id.clock+this.length-1)}mergeWith(e){if(this.constructor===e.constructor&&Fn(e.origin,this.lastId)&&this.right===e&&Fn(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(),Ds(e.deleteSet,this.id.client,this.id.clock,this.length),Yl(e,n,this.parentSub),this.content.delete(e)}}gc(e,n){if(!this.deleted)throw ht();this.content.gc(e),n?Fm(e,this,new gt(this.id,this.length)):this.content=new Ts(this.length)}write(e,n){const s=n>0?ue(this.id.client,this.id.clock+n-1):this.origin,r=this.rightOrigin,i=this.parentSub,l=this.content.getRef()&vr|(s===null?0:st)|(r===null?0:zt)|(i===null?0:ks);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=vc(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===Pn?(e.writeParentInfo(!1),e.writeLeftID(a)):ht();i!==null&&e.writeString(i)}this.content.write(e,n)}}const Jc=(t,e)=>Ng[e&vr](t),Ng=[()=>{ht()},gg,xg,mg,Cg,yg,bg,Ag,Sg,wg,()=>{ht()}],Og=10;class wt extends _o{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor!==e.constructor?!1:(this.length+=e.length,!0)}integrate(e,n){ht()}write(e,n){e.writeInfo(Og),H(e.restEncoder,this.length-n)}getMissing(e,n){return null}}const Gc=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:{},Yc="__ $YJS$ __";Gc[Yc]===!0&&console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438");Gc[Yc]=!0;function Fg(t){for(let e=0;e<t.length;e+=1)t[e]=Math.floor(Math.random()*256);return t}function Mg(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 Hi(t=globalThis.crypto){if(typeof t?.randomUUID=="function")return t.randomUUID();const e=new Uint8Array(16),n=typeof t?.getRandomValues=="function"?t.getRandomValues(e):Fg(e);return Mg(n)}const Xc=new Map;class $g{constructor(e){this.room=e,this.onmessage=null,this._onChange=n=>n.key===e&&this.onmessage!==null&&this.onmessage({data:mp(n.newValue||"")}),Vf(this._onChange)}postMessage(e){$a.setItem(this.room,pp(cp(e)))}close(){Kf(this._onChange)}}const Ig=typeof BroadcastChannel>"u"?$g:BroadcastChannel,To=t=>Rt(Xc,t,()=>{const e=tn(),n=new Ig(t);return n.onmessage=s=>e.forEach(r=>r(s.data,"broadcastchannel")),{bc:n,subs:e}}),Pg=(t,e)=>(To(t).subs.add(e),e),Ug=(t,e)=>{const n=To(t),s=n.subs.delete(e);return s&&n.subs.size===0&&(n.bc.close(),Xc.delete(t)),s},On=(t,e,n=null)=>{const s=To(t);s.bc.postMessage(e),s.subs.forEach(r=>r(e,n))},Qc=0,Ro=1,Zc=2,kr=(t,e)=>{H(t,Qc);const n=Lm(e);Oe(t,n)},eu=(t,e,n)=>{H(t,Ro),Oe(t,ko(e,n))},zg=(t,e,n)=>eu(e,n,Qe(t)),tu=(t,e,n,s)=>{try{xc(e,Qe(t),n)}catch(r){s?.(r),console.error("Caught error while handling a Yjs update",r)}},Bg=(t,e)=>{H(t,Zc),Oe(t,e)},qg=tu,Wg=(t,e,n,s,r)=>{const i=ie(t);switch(i){case Qc:zg(t,e,n);break;case Ro:tu(t,n,s,r);break;case Zc:qg(t,n,s,r);break;default:throw new Error("Unknown message type")}return i},Hg=0,Vg=(t,e,n)=>{ie(t)===Hg&&n(e,_e(t))},xi=3e4;class Kg extends Ta{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{const n=nn();this.getLocalState()!==null&&xi/2<=n-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());const s=[];this.meta.forEach((r,i)=>{i!==this.clientID&&xi<=n-r.lastUpdated&&this.states.has(i)&&s.push(i)}),s.length>0&&Ao(this,s,"timeout")},St(xi/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:nn()});const l=[],a=[],c=[],u=[];e===null?u.push(n):i==null?e!=null&&l.push(n):(a.push(n),$n(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 Ao=(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:nn()})}s.push(i)}}s.length>0&&(t.emit("change",[{added:[],updated:[],removed:s},n]),t.emit("update",[{added:[],updated:[],removed:s},n]))},Bn=(t,e,n=t.states)=>{const s=e.length,r=Fe();H(r,s);for(let i=0;i<s;i++){const l=e[i],a=n.get(l)||null,c=t.meta.get(l).clock;H(r,l),H(r,c),Ye(r,JSON.stringify(a))}return ke(r)},Jg=(t,e,n)=>{const s=rn(e),r=nn(),i=[],l=[],a=[],c=[],u=ie(s);for(let f=0;f<u;f++){const h=ie(s);let p=ie(s);const w=JSON.parse(_e(s)),g=t.meta.get(h),b=t.states.get(h),k=g===void 0?0:g.clock;(k<p||k===p&&w===null&&t.states.has(h))&&(w===null?h===t.clientID&&t.getLocalState()!=null?p++:t.states.delete(h):t.states.set(h,w),t.meta.set(h,{clock:p,lastUpdated:r}),g===void 0&&w!==null?i.push(h):g!==void 0&&w===null?c.push(h):w!==null&&($n(w,b)||a.push(h),l.push(h)))}(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])},Gg=t=>Qf(t,(e,n)=>`${encodeURIComponent(n)}=${encodeURIComponent(e)}`).join("&"),mn=0,nu=3,qn=1,Yg=2,Is=[];Is[mn]=(t,e,n,s,r)=>{H(t,mn);const i=Wg(e,t,n.doc,n);s&&i===Ro&&!n.synced&&(n.synced=!0)};Is[nu]=(t,e,n,s,r)=>{H(t,qn),Oe(t,Bn(n.awareness,Array.from(n.awareness.getStates().keys())))};Is[qn]=(t,e,n,s,r)=>{Jg(n.awareness,Qe(e),n)};Is[Yg]=(t,e,n,s,r)=>{Vg(e,n.doc,(i,l)=>Xg(n,l))};const ra=3e4,Xg=(t,e)=>console.warn(`Permission denied to access ${t.url}.
10
+ ${e}`),su=(t,e,n)=>{const s=rn(e),r=Fe(),i=ie(s),l=t.messageHandlers[i];return l?l(r,s,t,n,i):console.error("Unable to compute message"),r},Vi=(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,Ao(t.awareness,Array.from(t.awareness.getStates().keys()).filter(s=>s!==t.doc.clientID),t),t.emit("status",[{status:"disconnected"}])):t.wsUnsuccessfulReconnects++,setTimeout(ru,no(mf(2,t.wsUnsuccessfulReconnects)*100,t.maxBackoffTime),t))},ru=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=nn();const s=su(t,new Uint8Array(n.data),!0);so(s)>1&&e.send(ke(s))},e.onerror=n=>{t.emit("connection-error",[n,t])},e.onclose=n=>{Vi(t,e,n)},e.onopen=()=>{t.wsLastMessageReceived=nn(),t.wsconnecting=!1,t.wsconnected=!0,t.wsUnsuccessfulReconnects=0,t.emit("status",[{status:"connected"}]);const n=Fe();if(H(n,mn),kr(n,t.doc),e.send(ke(n)),t.awareness.getLocalState()!==null){const s=Fe();H(s,qn),Oe(s,Bn(t.awareness,[t.doc.clientID])),e.send(ke(s))}},t.emit("status",[{status:"connecting"}])}},ki=(t,e)=>{const n=t.ws;t.wsconnected&&n&&n.readyState===n.OPEN&&n.send(e),t.bcconnected&&On(t.bcChannel,e,t)};class Qg extends to{constructor(e,n,s,{connect:r=!0,awareness:i=new Kg(s),params:l={},protocols:a=[],WebSocketPolyfill:c=WebSocket,resyncInterval:u=-1,maxBackoffTime:f=2500,disableBc:h=!1}={}){for(super();e[e.length-1]==="/";)e=e.slice(0,e.length-1);this.serverUrl=e,this.bcChannel=e+"/"+n,this.maxBackoffTime=f,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=h,this.wsUnsuccessfulReconnects=0,this.messageHandlers=Is.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=Fe();H(p,mn),kr(p,s),this.ws.send(ke(p))}},u)),this._bcSubscriber=(p,w)=>{if(w!==this){const g=su(this,new Uint8Array(p),!1);so(g)>1&&On(this.bcChannel,ke(g),this)}},this._updateHandler=(p,w)=>{if(w!==this){const g=Fe();H(g,mn),Bg(g,p),ki(this,ke(g))}},this.doc.on("update",this._updateHandler),this._awarenessUpdateHandler=({added:p,updated:w,removed:g},b)=>{const k=p.concat(w).concat(g),D=Fe();H(D,qn),Oe(D,Bn(i,k)),ki(this,ke(D))},this._exitHandler=()=>{Ao(this.awareness,[s.clientID],"app closed")},sn&&typeof process<"u"&&process.on("exit",this._exitHandler),i.on("update",this._awarenessUpdateHandler),this._checkInterval=setInterval(()=>{this.wsconnected&&ra<nn()-this.wsLastMessageReceived&&Vi(this,this.ws,null)},ra/10),r&&this.connect()}get url(){const e=Gg(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(),sn&&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||(Pg(this.bcChannel,this._bcSubscriber),this.bcconnected=!0);const e=Fe();H(e,mn),kr(e,this.doc),On(this.bcChannel,ke(e),this);const n=Fe();H(n,mn),eu(n,this.doc),On(this.bcChannel,ke(n),this);const s=Fe();H(s,nu),On(this.bcChannel,ke(s),this);const r=Fe();H(r,qn),Oe(r,Bn(this.awareness,[this.doc.clientID])),On(this.bcChannel,ke(r),this)}disconnectBc(){const e=Fe();H(e,qn),Oe(e,Bn(this.awareness,[this.doc.clientID],new Map)),ki(this,ke(e)),this.bcconnected&&(Ug(this.bcChannel,this._bcSubscriber),this.bcconnected=!1)}disconnect(){this.shouldConnect=!1,this.disconnectBc(),this.ws!==null&&Vi(this,this.ws,null)}connect(){this.shouldConnect=!0,!this.wsconnected&&this.ws===null&&(ru(this),this.connectBc())}}const vn=t=>Jn((e,n)=>{t.onerror=s=>n(new Error(s.target.error)),t.onsuccess=s=>e(s.target.result)}),Zg=(t,e)=>Jn((n,s)=>{const r=indexedDB.open(t);r.onupgradeneeded=i=>e(i.target.result),r.onerror=i=>s(Ct(i.target.error)),r.onsuccess=i=>{const l=i.target.result;l.onversionchange=()=>{l.close()},n(l)}}),ew=t=>vn(indexedDB.deleteDatabase(t)),tw=(t,e)=>e.forEach(n=>t.createObjectStore.apply(t,n)),ps=(t,e,n="readwrite")=>{const s=t.transaction(e,n);return e.map(r=>cw(s,r))},iu=(t,e)=>vn(t.count(e)),nw=(t,e)=>vn(t.get(e)),ou=(t,e)=>vn(t.delete(e)),sw=(t,e,n)=>vn(t.put(e,n)),Ki=(t,e)=>vn(t.add(e)),rw=(t,e,n)=>vn(t.getAll(e,n)),iw=(t,e,n)=>{let s=null;return aw(t,e,r=>(s=r,!1),n).then(()=>s)},ow=(t,e=null)=>iw(t,e,"prev"),lw=(t,e)=>Jn((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()}}),aw=(t,e,n,s="next")=>lw(t.openKeyCursor(e,s),r=>n(r.key)),cw=(t,e)=>t.objectStore(e),uw=(t,e)=>IDBKeyRange.upperBound(t,e),dw=(t,e)=>IDBKeyRange.lowerBound(t,e),Si="custom",lu="updates",au=500,cu=(t,e=()=>{},n=()=>{})=>{const[s]=ps(t.db,[lu]);return rw(s,dw(t._dbref,!1)).then(r=>{t._destroyed||(e(s),Se(t.doc,()=>{r.forEach(i=>xc(t.doc,i))},t,!1),n(s))}).then(()=>ow(s).then(r=>{t._dbref=r+1})).then(()=>iu(s).then(r=>{t._dbsize=r})).then(()=>s)},hw=(t,e=!0)=>cu(t).then(n=>{(e||t._dbsize>=au)&&Ki(n,ko(t.doc)).then(()=>ou(n,uw(t._dbref,!0))).then(()=>iu(n).then(s=>{t._dbsize=s}))});class fw extends Ta{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=Zg(e,s=>tw(s,[["updates",{autoIncrement:!0}],["custom"]])),this.whenSynced=Jn(s=>this.on("synced",()=>s(this))),this._db.then(s=>{this.db=s,cu(this,l=>Ki(l,ko(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]=ps(this.db,[lu]);Ki(i,s),++this._dbsize>=au&&(this._storeTimeoutId!==null&&clearTimeout(this._storeTimeoutId),this._storeTimeoutId=setTimeout(()=>{hw(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(()=>{ew(this.name)})}get(e){return this._db.then(n=>{const[s]=ps(n,[Si],"readonly");return nw(s,e)})}set(e,n){return this._db.then(s=>{const[r]=ps(s,[Si]);return sw(r,n,e)})}del(e){return this._db.then(n=>{const[s]=ps(n,[Si]);return ou(s,e)})}}const ia=[["#1677c8","#1677c833"],["#d65745","#d6574533"],["#16866a","#16866a33"],["#9a58b5","#9a58b533"],["#d27b18","#d27b1833"],["#3f7d20","#3f7d2033"],["#be3e7b","#be3e7b33"],["#4964c6","#4964c633"],["#8a6a14","#8a6a1433"],["#087f8c","#087f8c33"]],oa=4,la=5,pw=6,mw=7,gw=8,Ci=9,vi=3,ww=6e4,yw=720*60*60*1e3,bw=15e3,xw=5*6e4;function kw(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 aa(t){if(!t||typeof t!="object"||Array.isArray(t))return{};const e={};for(const[n,s]of Object.entries(t)){const r=kw(s);r&&r.mainFile===n&&(e[n]=r)}return e}function Sw(t,e,n){return t<=n&&e<=n}function ca(t,e,n){const s=r=>r>0&&n-r<=xw;return{recoverable:t.some(r=>r.tabId===e||!s(r.activeAt)),otherActive:t.some(r=>r.tabId!==e&&s(r.activeAt))}}class Cw{constructor(e,n){this.projectId=e,this.user=n;const s=window.location.protocol==="https:"?"wss:":"ws:";this.draftTabId=Dw(fn(`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 fw(fn(`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 Qg(`${s}//${window.location.host}${Sr("/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[oa]=(l,a)=>{const c=_e(a),u=this.flushRequests.get(c);if(!u)return;const f=ie(a)===1,h=ie(a),p=_e(a),w=ie(a),g=[];for(let b=0;b<w;b++)g.push(_e(a));if(window.clearTimeout(u.timer),this.flushRequests.delete(c),f)this.clearOwnWritableDraftMarker(u.draftGeneration),u.resolve({revision:h,persistedAt:p,ok:!0,failedPaths:[]});else{const b=Object.assign(new Error(g.length?`保存失败:${g.join(", ")}`:"源码保存到服务器磁盘失败"),{failedPaths:g});u.reject(b)}},this.provider.messageHandlers[la]=(l,a)=>{const c=_e(a),u=this.epochStorageKey(),f=ua(u),h=/^([0-9]+):/.exec(c)?.[1]??null,p=f?/^([0-9]+):/.exec(f)?.[1]??null:null,w=!this.epoch&&h===String(vi)&&p!==null&&p!==h;if((this.epoch&&this.epoch!==c||f&&f!==c)&&!w){this.provider.disconnect(),this.rejectFlushes(new Error("Collaboration state changed"));const R=c.endsWith(":reload")||h!==null&&h!==String(vi),x=()=>{ji(u,c.replace(/:reload$/,"")),window.location.reload()};if(R)for(const T of this.protocolUpgradeListeners)T();else this.persistence.clearData().then(()=>{this.clearWritableDraftMarkers(),x()});return}this.epoch=c,ji(u,c);const g=this.provider.ws;if(!g||g.readyState!==WebSocket.OPEN)return;const b=Fe();H(b,la),Ye(b,c),H(b,vi),g.send(ke(b));const k=Fe();H(k,0),kr(k,this.doc),g.send(ke(k));const D=Fe();H(D,1),Oe(D,Bn(this.awareness,[this.doc.clientID])),g.send(ke(D))},this.provider.messageHandlers[mw]=(l,a)=>{const c=_e(a),u=_e(a);if(c!==this.user.id)return;if(u==="revoked"){this.rejectFlushes(new Error("Project access revoked")),this.provider.disconnect();for(const h of this.permissionListeners)h("revoked",this.permission);return}if(u!=="read"&&u!=="edit"&&u!=="owner")return;const f=this.permission;if(this.setPermission(u),f!==u){u==="read"&&this.rejectFlushes(new Error("Project permission changed to read-only"));for(const h of this.permissionListeners)h(u,f)}},this.provider.messageHandlers[pw]=(l,a)=>{_e(a)},this.provider.messageHandlers[gw]=(l,a)=>{let c={};try{c=aa(JSON.parse(_e(a)))}catch{}this.authoritativeCompileStates=c,this.notifyCompileStateListeners()},this.provider.messageHandlers[Ci]=(l,a)=>{const c=_e(a),u=_e(a),f=_e(a),h=_e(a),p=_e(a),w=_e(a);if(c==="state"){const b=$i(a)?_e(a):"",k=$i(a)?_e(a):"",D=Number(p);if(!b||!Number.isFinite(D)||D<=Date.now())this.removeFormatLeaseState(f),this.notifyFormatLeaseListeners(null);else{const R={path:f,holderUserId:b,holderName:k,expiresAt:D};this.formatLeaseStatesByPath.set(f,R);const x=this.formatLeaseExpiryTimers.get(f);x!==void 0&&window.clearTimeout(x);const T=window.setTimeout(()=>{const I=this.formatLeaseStatesByPath.get(f);!I||I.expiresAt>Date.now()||(this.removeFormatLeaseState(f),this.notifyFormatLeaseListeners(null))},Math.max(0,D-Date.now())+25);this.formatLeaseExpiryTimers.set(f,T),this.notifyFormatLeaseListeners(R)}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:f,token:h,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 Sn;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 Um(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??aa(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 ca(e.map(({tabId:n,marker:s})=>({tabId:n,activeAt:s.activeAt})),this.draftTabId,Date.now()).recoverable}get hasOtherWritableDraft(){const e=this.readWritableDraftMarkers();return ca(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=Hi(),s=this.draftGeneration,r=Fe();return H(r,oa),Ye(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(ke(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=Hi(),l=Fe();return H(l,Ci),Ye(l,e),Ye(l,i),Ye(l,n),Ye(l,s),new Promise((a,c)=>{const u=window.setTimeout(()=>{if(this.formatLeaseRequests.delete(i),e==="acquire"){const f=this.provider.ws;if(f?.readyState===WebSocket.OPEN){const h=Fe();H(h,Ci),Ye(h,"cancel"),Ye(h,i),Ye(h,n),Ye(h,""),f.send(ke(h))}}c(new Error("Format lease request timed out"))},e==="acquire"?ww:5e3);this.formatLeaseRequests.set(i,{resolve:a,reject:c,timer:u}),r.send(ke(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]=ia[Math.abs(this.doc.clientID)%ia.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 fn(`texlite:collaboration-epoch:${this.user.id}:${this.projectId}`)}writableDraftStoragePrefix(){return`${fn(`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())hs(e);this.draftMarkerPresent=!1,this.stopDraftHeartbeat(),hs(this.writableDraftStoragePrefix().slice(0,-1))}clearOwnWritableDraftMarker(e){const n=this.readOwnWritableDraftMarker();!n||!Sw(n.generation,this.draftGeneration,e)||(hs(this.ownWritableDraftStorageKey()),this.draftMarkerPresent=!1,this.stopDraftHeartbeat())}readOwnWritableDraftMarker(){return this.readWritableDraftMarker(this.ownWritableDraftStorageKey())}readWritableDraftMarkers(){const e=this.writableDraftStoragePrefix(),n=[];for(const s of vw()){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=ua(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>yw)return hs(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 hs(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};ji(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)},bw))}stopDraftHeartbeat(){this.draftHeartbeatTimer!==null&&(window.clearInterval(this.draftHeartbeatTimer),this.draftHeartbeatTimer=null)}}function ua(t){try{return window.localStorage.getItem(t)}catch{return null}}function ji(t,e){try{window.localStorage.setItem(t,e)}catch{}}function hs(t){try{window.localStorage.removeItem(t)}catch{}}function vw(){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 jw(t){try{return window.sessionStorage.getItem(t)}catch{return null}}function Ew(t,e){try{window.sessionStorage.setItem(t,e)}catch{}}function Dw(t){const e=jw(t);if(e)return e;const n=Hi();return Ew(t,n),n}function _w(t,e){return Array.from(t.trim()||e.trim()||"?")[0]?.toLocaleUpperCase()??"?"}function Lw(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 Tw(t,e,n,s,r,i){const[l]=d.useState(()=>new Cw(t,e)),[a,c]=d.useState("connecting"),[u,f]=d.useState(!1),[h,p]=d.useState([]),[w,g]=d.useState(null),[b,k]=d.useState(null),[D,R]=d.useState(""),[x,T]=d.useState(!1),[I,C]=d.useState(""),[j,A]=d.useState([]),[X,Q]=d.useState(!1),[K,V]=d.useState(s),[ee,_]=d.useState(null),[z,te]=d.useState(!1),ne=d.useRef(n),J=d.useRef(i),fe=d.useRef(r);ne.current=n,J.current=i,fe.current=r,d.useEffect(()=>{const $=l.compileStates();g($[n]??null)},[n,l]),d.useEffect(()=>{const $=()=>p(l.sessions()),M=()=>{f(!1),p([]),g(null),k(null),R(""),T(!1),C(""),A([]),J.current()},B=({status:he})=>{c(he),he!=="connected"&&M()},re=he=>{f(he),he||M()},le=()=>{c("disconnected"),M()},we=()=>{T(l.meta.get("historyWarning")===!0);const he=l.meta.get("filesEvent");Lw(he)&&k(he);const be=l.meta.get("commentsRevision");typeof be=="string"&&R(be);const Be=l.meta.get("dictionaryRevision");typeof Be=="string"&&C(Be);const De=l.compileStates();g(De[ne.current]??null)},$e=()=>{const he=l.compileStates();g(he[ne.current]??null)};l.awareness.on("change",$),l.provider.on("status",B),l.provider.on("sync",re),l.provider.on("connection-close",le),l.provider.on("connection-error",le),l.meta.observe(we);const q=l.onCompileStates($e),G=l.onProtocolUpgrade(()=>{te(!0),c("disconnected"),M()}),Re=()=>A(l.formatLeaseStates()),P=l.onFormatLeaseState(Re),Ie=()=>{if(!fe.current||l.currentPermission!=="read")return;const he=l.hasWritableDraft,be=l.hasOtherWritableDraft;!he&&!be||_({previous:"edit",localDraftReady:he,otherTabDraft:be})},Ae=l.onDraftReady(()=>{Q(!0),Ie()}),Ee=l.onPermissionChanged((he,be)=>{if(he==="revoked"){c("disconnected"),f(!1),J.current();return}V(he),he==="read"&&be!=="read"?_({previous:be,localDraftReady:l.hasWritableDraft,otherTabDraft:l.hasOtherWritableDraft}):he!=="read"&&_(null)});return $(),we(),c(l.connected?"connected":"connecting"),f(l.synced),()=>{l.awareness.off("change",$),l.provider.off("status",B),l.provider.off("sync",re),l.provider.off("connection-close",le),l.provider.off("connection-error",le),l.meta.unobserve(we),q(),G(),P(),Ae(),Ee(),l.destroy()}},[l]),d.useEffect(()=>{r&&l.connect()},[l,r]),d.useEffect(()=>{l.setPermission(s),V(s),r&&s==="read"&&(l.hasWritableDraft||l.hasOtherWritableDraft)?_({previous:"edit",localDraftReady:l.hasWritableDraft,otherTabDraft:l.hasOtherWritableDraft}):s!=="read"&&_(null)},[l,s,r]);const ge=ee!==null;return d.useEffect(()=>{if(!ge)return;const $=()=>{if(l.currentPermission!=="read")return;const B=l.hasWritableDraft,re=l.hasOtherWritableDraft;_(le=>!le||le.localDraftReady===B&&le.otherTabDraft===re?le:{...le,localDraftReady:B,otherTabDraft:re})};$();const M=window.setInterval($,2e3);return()=>window.clearInterval(M)},[l,ge]),{collaboration:l,status:a,synced:u,activeSessions:h,compileState:w,setCompileState:g,formatLeaseStates:j,filesEvent:b,commentsRevision:D,historyWarning:x,dictionaryRevision:I,localDraftReady:X,permission:K,protocolUpgradeRequired:z,reconnect:()=>{z||(c("connecting"),f(!1),p([]),g(null),A([]),l.reconnect())},permissionDowngrade:ee,dismissPermissionDowngrade:()=>_(null),discardLocalDraft:async()=>await l.discardLocalDraft()?(_(null),window.location.reload(),!0):(_(M=>M&&{...M,otherTabDraft:!0}),!1)}}function da(t){return t?.status==="succeeded"?"succeeded":t?.log.includes("Compilation was cancelled.")?"cancelled":t?.status==="failed"?"failed":null}function dn(t){return t instanceof Error&&t.name==="AbortError"}function Rw(t){return t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement}function Aw({projectId:t,project:e,mainFile:n,resolveCompileMainFile:s,getCurrentMainFile:r,initialLatest:i,collaborationSynced:l,sharedState:a,onSharedState:c,save:u,loadOutline:f,onPreviewTab:h,onError:p,onCompileStart:w,onCompileSuccess:g,onPdfChanged:b}){const{t:k}=Ke(),[D,R]=d.useState(""),[x,T]=d.useState(!0),[I,C]=d.useState(null),[j,A]=d.useState("full"),[X,Q]=d.useState(""),[K,V]=d.useState(null),[ee,_]=d.useState(null),[z,te]=d.useState([]),[ne,J]=d.useState(null),[fe,ge]=d.useState(!1),[ye,L]=d.useState(!1),[me,$]=d.useState(()=>new Set),[M,B]=d.useState(()=>new Set),[re,le]=d.useState(""),we=d.useRef(n),$e=d.useRef(""),q=d.useRef(null),G=d.useRef(null),Re=d.useRef(null),P=d.useRef(i),Ie=d.useRef(!1),Ae=d.useRef(null),Ee=d.useRef(null),he=d.useRef(new Set),be=d.useRef(new Map),Be=d.useRef(null),De=d.useRef(()=>{}),E=d.useRef({onSharedState:c,save:u,loadOutline:f,onPreviewTab:h,onError:p,onCompileStart:w,onCompileSuccess:g,onPdfChanged:b,resolveCompileMainFile:s,getCurrentMainFile:r});we.current=n,E.current={onSharedState:c,save:u,loadOutline:f,onPreviewTab:h,onError:p,onCompileStart:w,onCompileSuccess:g,onPdfChanged:b,resolveCompileMainFile:s,getCurrentMainFile:r};const ce=()=>E.current.getCurrentMainFile?.()||we.current,Ce=N=>{Be.current!==N&&(Be.current=N,E.current.onCompileSuccess())},et=async(N,Z)=>{Z||(Ae.current?.abort(),Ae.current=new AbortController,Z=Ae.current.signal);try{const O=N?`?mainFile=${encodeURIComponent(N)}`:"",oe=await ae(`/api/projects/${t}/compile/artifacts${O}`,{signal:Z});we.current===N&&(te(oe.artifacts),J(null))}catch(O){!dn(O)&&we.current===N&&(te([]),J(null))}finally{Ae.current?.signal===Z&&(Ae.current=null)}};d.useEffect(()=>{if(q.current?.abort(),!n){T(!1),R(""),C(null),A("full"),Q(""),V(null),_(null),te([]),J(null),Re.current=null,E.current.onPdfChanged();return}Re.current?.mainFile!==n&&(Re.current=null);const N=new AbortController;q.current=N,T(!0),Q(""),V(null),_(null),D&&n&&$e.current===n||(R(""),C(null),A("full")),te([]),J(null),E.current.onPdfChanged();let O=null;const oe=`?mainFile=${encodeURIComponent(n)}`,pt=Ie.current?null:P.current;pt&&(Ie.current=!0);const mt=()=>ae(`/api/projects/${t}/compile/latest${oe}`,{signal:N.signal}),Xe=pt?pt.then(pe=>pe.mainFile!==n?mt():pe,()=>mt()):mt();let at=!1;const jt=()=>{if(at||N.signal.aborted||!n)return;at=!0;const pe=new AbortController;he.current.add(pe),et(n,pe.signal).finally(()=>{he.current.delete(pe)}),E.current.loadOutline(N.signal,n).catch(()=>{})};return Xe.then(pe=>{if(N.signal.aborted||n&&pe.mainFile!==we.current)return;const F=Re.current;F&&F.mainFile===n&&pe.latestRun?.id!==F.runId||(Q(pe.latestRun?.log??""),V(pe.latestRun?.diagnostics??null),_(da(pe.latestRun)),n&&pe.latestRun?.requestedBy&&(pe.latestRun.status==="queued"||pe.latestRun.status==="running")&&E.current.onSharedState({mainFile:n,runId:pe.latestRun.id,status:pe.latestRun.status,requestedBy:pe.latestRun.requestedBy,updatedAt:new Date().toISOString()}),pe.pdfUrl&&($e.current=pe.mainFile,R(pe.pdfUrl),C(pe.pdfCompiledAt),A(pe.pdfLoadingMode??"full"),E.current.onPreviewTab("pdf")))}).catch(pe=>{!dn(pe)&&we.current===n&&E.current.onError(de(pe))}).finally(()=>{q.current===N&&(q.current=null),N.signal.aborted||(T(!1),O=window.setTimeout(jt,0))}),()=>{O!==null&&window.clearTimeout(O),N.abort(),Ee.current?.abort();for(const pe of he.current)pe.abort();he.current.clear()}},[t,n]),d.useEffect(()=>{if(!(!a||a.mainFile!==n||a.status!=="cleaned"||!a.cleanMode)){q.current?.abort(),G.current?.abort(),Ae.current?.abort(),Ee.current?.abort();for(const N of he.current)N.abort();he.current.clear(),a.cleanMode==="artifacts"?(Re.current=null,Q(""),V(null),_(null),R(""),C(null),A("full"),te([]),J(null),E.current.onPdfChanged(),E.current.onPreviewTab("pdf"),le(k("editor.cleanArtifactsComplete"))):le(k("editor.cleanCacheComplete"))}},[a?.runId,a?.status,a?.cleanMode,a?.mainFile,n,k]),d.useEffect(()=>{!n||a?.mainFile===n&&(a.status==="queued"||a.status==="running")||B(N=>{if(!N.has(n))return N;const Z=new Set(N);return Z.delete(n),Z})},[n,a?.mainFile,a?.status]),d.useEffect(()=>{if(!a||a.mainFile!==n||a.status!=="succeeded"&&a.status!=="failed")return;let N=!1;G.current?.abort(),Ee.current?.abort();const Z=new AbortController;return G.current=Z,T(!0),ae(`/api/projects/${t}/compile/latest?mainFile=${encodeURIComponent(n)}`,{signal:Z.signal}).then(O=>{N||O.mainFile!==we.current||O.latestRun?.id!==a.runId||(Q(O.latestRun.log),V(O.latestRun.diagnostics),_(da(O.latestRun)),a.status==="succeeded"&&a.stale&&le(k("editor.compileSnapshotStale")),a.status==="succeeded"&&O.pdfUrl?(Re.current={mainFile:n,runId:a.runId},E.current.onPdfChanged(),R(O.pdfUrl),C(O.pdfCompiledAt),A(O.pdfLoadingMode??"full"),E.current.onPreviewTab("pdf"),Ce(a.runId),et(n)):a.status==="failed"&&E.current.onPreviewTab(O.latestRun.diagnostics.errors.length?"errors":"log"))}).catch(O=>{!dn(O)&&!N&&E.current.onError(de(O))}).finally(()=>{G.current===Z&&(G.current=null),N||T(!1)}),()=>{N=!0,Z.abort(),G.current===Z&&(G.current=null)}},[a?.runId,a?.status,a?.mainFile,a?.stale,n,t,k]);const Ne=async()=>{if(!e||e.permission==="read"||!l)return;const N=E.current.resolveCompileMainFile?.()||ce();if(!N||be.current.has(N)||a?.mainFile===N&&(a.status==="queued"||a.status==="running"))return;$(O=>new Set([...O,N])),E.current.onCompileStart(),le(""),Ee.current?.abort(),Ee.current=null,Q(""),V(null),_(null),E.current.onPreviewTab(D?"pdf":"log");const Z=new AbortController;be.current.set(N,Z);try{if(!await E.current.save())return;const O=await ae(`/api/projects/${t}/compile`,{method:"POST",signal:Z.signal,body:JSON.stringify({mainFile:N})});if(O.mainFile!==N||ce()!==N)return;Q(O.log),V(O.diagnostics),_(O.cancelled?"cancelled":O.ok?"succeeded":"failed"),O.cancelled&&le(k("compileControls.cancelled")),O.skipped&&le(k("editor.upToDate")),O.ok&&O.stale&&le(k("editor.compileSnapshotStale")),O.pdfUrl?(O.ok&&(Re.current={mainFile:N,runId:O.runId}),E.current.onPdfChanged(),R(O.pdfUrl),C(O.pdfCompiledAt),A(O.pdfLoadingMode??"full"),E.current.onPreviewTab("pdf"),O.ok&&(O.skipped?E.current.onCompileSuccess():Ce(O.runId))):E.current.onPreviewTab(O.diagnostics.errors.length?"errors":"log")}catch(O){!dn(O)&&ce()===N&&E.current.onError(de(O))}finally{be.current.get(N)===Z&&(be.current.delete(N),$(O=>{const oe=new Set(O);return oe.delete(N),oe}),B(O=>{if(!O.has(N))return O;const oe=new Set(O);return oe.delete(N),oe}))}},xe=async()=>{if(!e||e.permission==="read"||!l)return;const N=ce();if(N){B(Z=>new Set([...Z,N]));try{(await ae(`/api/projects/${t}/compile/cancel`,{method:"POST",body:JSON.stringify({mainFile:N})})).cancelled||B(O=>{const oe=new Set(O);return oe.delete(N),oe})}catch(Z){B(O=>{const oe=new Set(O);return oe.delete(N),oe}),!dn(Z)&&ce()===N&&E.current.onError(de(Z))}}},ft=async N=>{if(!e||e.permission==="read"||!l||ye)return;const Z=ce();if(!(!Z||be.current.has(Z)||a?.mainFile===Z&&(a.status==="queued"||a.status==="running"))){L(!0),q.current?.abort(),G.current?.abort(),Ae.current?.abort(),Ee.current?.abort();try{if((await ae(`/api/projects/${t}/compile/clean`,{method:"POST",body:JSON.stringify({mainFile:Z,mode:N})})).mainFile!==Z||ce()!==Z)return;E.current.onSharedState(null),N==="artifacts"&&(Re.current=null,Q(""),V(null),_(null),R(""),C(null),A("full"),te([]),J(null),E.current.onPdfChanged()),le(k(N==="cache"?"editor.cleanCacheComplete":"editor.cleanArtifactsComplete"))}catch(O){!dn(O)&&ce()===Z&&E.current.onError(de(O))}finally{L(!1)}}};De.current=()=>{Ne()},d.useEffect(()=>{if(!re)return;const N=window.setTimeout(()=>le(""),3e3);return()=>window.clearTimeout(N)},[re]),d.useEffect(()=>{const N=Z=>{if(!(!(Z.ctrlKey||Z.metaKey)||Z.key.toLocaleLowerCase()!=="s")){if(Rw(Z.target)){Z.preventDefault();return}Z.preventDefault(),Z.stopPropagation(),Z.repeat||De.current()}};return window.addEventListener("keydown",N,!0),()=>window.removeEventListener("keydown",N,!0)},[]),d.useEffect(()=>()=>{q.current?.abort(),G.current?.abort(),Ae.current?.abort(),Ee.current?.abort();for(const N of he.current)N.abort();he.current.clear();for(const N of be.current.values())N.abort();be.current.clear()},[]);const qe=async N=>{if(!N.viewable)return;Ee.current?.abort();const Z=new AbortController;Ee.current=Z,ge(!0);try{const O=await ae(`/api/projects/${t}/compile/artifacts?mainFile=${encodeURIComponent(n)}&path=${encodeURIComponent(N.path)}`,{signal:Z.signal});!Z.signal.aborted&&Ee.current===Z&&we.current===n&&J(O)}catch(O){dn(O)||E.current.onError(de(O))}finally{Ee.current===Z&&(Ee.current=null,ge(!1))}};return{pdfUrl:D,pdfCompiledAt:I,pdfLoadingMode:j,pdfLoading:x,compileLog:X,compileDiagnostics:K,compileOutcome:ee,artifacts:z,artifactPreview:ne,artifactLoading:fe,editorNotice:re,localCompiling:me.has(n),cancelling:M.has(n),cleaning:ye,compile:Ne,cancelCompile:xe,cleanCompile:ft,viewArtifact:qe}}const Ji=10*1024*1024,Nw=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 ha(t){return t instanceof Error&&t.name==="AbortError"}function ms(t){const e=t.split("/").filter(Boolean);return e.pop(),e.map((n,s)=>e.slice(0,s+1).join("/"))}function hn(t,e){return!!(t&&e)&&(e===t||e.startsWith(`${t}/`))}function Ow(t){const e=`.${t.split(".").at(-1)?.toLocaleLowerCase()??""}`;return!Nw.has(e)}function Wn(t){return/(?:\.(?:tex|bib|sty|cls|txt|md)|latexmkrc)$/i.test(t)}function fa(t){const e=t.split(".").at(-1)?.toLocaleLowerCase()??"";return e==="pdf"?"pdf":["png","jpg","jpeg","gif","webp","svg","bmp","ico","avif"].includes(e)?"image":Ow(t)?"text":"unsupported"}function Fw(t,e){return Sr(`/api/projects/${t}/file/raw?path=${encodeURIComponent(e)}`)}function Mw({projectId:t,site:e,activeFile:n,dirty:s,save:r,onError:i,onProject:l,onActiveFile:a,onActiveMainFile:c,onRootDocuments:u}){const{t:f}=Ke(),[h,p]=d.useState([]),[w,g]=d.useState(!1),[b,k]=d.useState(""),[D,R]=d.useState(null),[x,T]=d.useState(!1),[I,C]=d.useState(!1),[j,A]=d.useState(""),[X,Q]=d.useState(""),[K,V]=d.useState(""),[ee,_]=d.useState(new Set),[z,te]=d.useState(null),[ne,J]=d.useState(""),[fe,ge]=d.useState(""),[ye,L]=d.useState(null),[me,$]=d.useState(!1),[M,B]=d.useState(null),[re,le]=d.useState(!1),we=d.useRef(null),$e=d.useRef(null),q=async(E={})=>{we.current?.abort(),we.current=null;const ce=E.signal?null:new AbortController;ce&&(we.current=ce);try{const Ce=await ae(`/api/projects/${t}/files`,{signal:E.signal??ce?.signal});return(!E.isCurrent||E.isCurrent())&&p(Ce.files),Ce.files}catch(Ce){if(!ha(Ce))throw Ce;return}finally{ce&&we.current===ce&&(we.current=null)}},G=async()=>{if(!(!b.trim()||b.trim().endsWith("/"))){Q("");try{await ae(`/api/projects/${t}/file`,{method:"POST",body:JSON.stringify({path:b,content:""})}),await q(),a(b),_(E=>new Set([...E,...ms(b)])),g(!1),k("")}catch(E){Q(de(E))}}},Re=async()=>{if(!j.trim())return;Q("");const E=K?`${K}/${j.trim()}`:j.trim();try{const ce=await ae(`/api/projects/${t}/folders`,{method:"POST",body:JSON.stringify({path:E})});await q(),_(Ce=>new Set([...Ce,...ms(ce.path),ce.path])),V(ce.path),C(!1),A("")}catch(ce){Q(de(ce))}},P=async(E,ce=new Set,Ce=K)=>{if(!E.length)return;const et=e.maxUploadSizeMB;if(E.find(oe=>oe.size>et*1024*1024))return i(f("errors.fileTooLarge",{size:et}));const xe=Ce,ft=E.map(oe=>xe?`${xe}/${oe.name}`:oe.name),qe=new Map;for(const oe of ft)qe.set(oe,(qe.get(oe)??0)+1);const N=[...qe.entries()].filter(([,oe])=>oe>1).map(([oe])=>oe);if(N.length)return i(f("errors.duplicateUploadNames",{files:N.join(", ")}));const Z=new Set(h.map(oe=>oe.path)),O=[...new Set(ft.filter(oe=>Z.has(oe)&&!ce.has(oe)))];if(O.length){B({files:E,directory:xe,collisions:O});return}B(null),le(!0);try{const oe=new URLSearchParams;xe&&oe.set("directory",xe);let pt="";for(const[mt,Xe]of E.entries()){const at=ft[mt];oe.delete("overwrite"),ce.has(at)&&oe.set("overwrite","1");const jt=oe.toString()?`?${oe.toString()}`:"",pe=new FormData;pe.append("file",Xe);try{const F=await ae(`/api/projects/${t}/upload${jt}`,{method:"POST",body:pe});typeof F.path=="string"&&Wn(F.path)&&(pt=F.path)}catch(F){if(F instanceof _i&&F.status===409&&!ce.has(at)&&F.code==="FILE_EXISTS"){mt>0&&await q(),B({files:E.slice(mt),directory:xe,collisions:[at]});return}throw F}}await q(),pt&&a(pt)}catch(oe){i(de(oe))}finally{le(!1)}},Ie=async E=>{await P(Array.from(E.target.files??[])),E.target.value=""},Ae=async E=>{$e.current?.abort(),$e.current=null,T(!1);const ce=Fw(t,E.path);if((E.size??0)>Ji){R({path:E.path,kind:"large",size:E.size??0,url:ce});return}const Ce=fa(E.path);if(Ce!=="text"){R({path:E.path,kind:Ce,size:E.size??0,url:ce});return}R({path:E.path,kind:Ce,size:E.size??0,url:ce,content:""}),T(!0);const et=new AbortController;$e.current=et;try{let Ne;try{Ne=await fetch(ce,{signal:et.signal})}catch(qe){throw nh(qe)}const xe=Ne.headers.get("content-type")??"";if(!Ne.ok){let qe=null;try{qe=xe.includes("application/json")?await Ne.json():await Ne.text()}catch{}throw new _i(sh(qe,Ne.status),Ne.status,rh(qe))}const ft=await Ne.text();R(qe=>qe?.path===E.path?{...qe,content:ft}:qe)}catch(Ne){ha(Ne)||(R(null),i(de(Ne)))}finally{$e.current===et&&($e.current=null,T(!1))}},Ee=E=>{const ce=fa(E.path),Ce=e.maxCollaborativeFileSizeMB*1024*1024;(E.size??0)>Ji||Wn(E.path)&&(E.size??0)>Ce||ce!=="text"||!Wn(E.path)?Ae(E):a(E.path)},he=async()=>{if(!z)return;const E=ne.trim();if(E){Q("");try{if(!await r())return;const ce=await ae(`/api/projects/${t}/path`,{method:"PATCH",body:JSON.stringify({source:z.path,destinationDirectory:fe,destinationName:E})}),Ce=xe=>xe===z.path?ce.path:xe.startsWith(`${z.path}/`)?`${ce.path}${xe.slice(z.path.length)}`:xe;a(xe=>Ce(xe)),c(xe=>Ce(xe)),u(xe=>new Set([...xe].map(Ce))),V(xe=>xe&&Ce(xe));const[et,Ne]=await Promise.all([ae(`/api/projects/${t}/files`),ae(`/api/projects/${t}`)]);p(et.files),l(Ne.project),_(xe=>new Set([...xe,...ms(ce.path),fe].filter(Boolean))),te(null),J(""),ge("")}catch(ce){Q(de(ce))}}},be=async()=>{if(ye){Q("");try{if(s&&!await r())return;await ae(`/api/projects/${t}/file?path=${encodeURIComponent(ye.path)}`,{method:"DELETE"}),L(null)}catch(E){Q(de(E))}}};d.useEffect(()=>()=>{we.current?.abort(),$e.current?.abort()},[]),d.useEffect(()=>{$e.current?.abort(),$e.current=null,T(!1)},[n]);const Be=h.filter(E=>E.type==="directory"),De=h.filter(E=>ms(E.path).every(ce=>ee.has(ce)));return{files:h,setFiles:p,loadFiles:q,newFileOpen:w,setNewFileOpen:g,newFilePath:b,setNewFilePath:k,resourcePreview:D,setResourcePreview:R,resourcePreviewLoading:x,setResourcePreviewLoading:T,newFolderOpen:I,setNewFolderOpen:C,newFolderName:j,setNewFolderName:A,fileDialogError:X,setFileDialogError:Q,selectedFolder:K,setSelectedFolder:V,expandedFolders:ee,setExpandedFolders:_,moveEntry:z,setMoveEntry:te,moveName:ne,setMoveName:J,moveDestination:fe,setMoveDestination:ge,deleteEntry:ye,setDeleteEntry:L,fileDragActive:me,setFileDragActive:$,uploadConflict:M,setUploadConflict:B,uploadingFiles:re,directoryEntries:Be,visibleEntries:De,createFile:G,createFolder:Re,uploadFiles:P,upload:Ie,openFile:Ee,movePath:he,removePath:be}}function $w({active:t,projectId:e,activeFile:n,content:s,dictionaryWords:r}){const[i,l]=d.useState([]),[a,c]=d.useState(""),[u,f]=d.useState(""),[h,p]=d.useState(0),[w,g]=d.useState(null),[b,k]=d.useState(null),[D,R]=d.useState(!1),[x,T]=d.useState(0),I=d.useRef(0),C=d.useRef(!1),j=d.useRef(!1),A=d.useRef(s),X=d.useRef(n),Q=d.useRef(0);A.current=s,X.current=n,j.current=D,d.useEffect(()=>{l([]),c(""),f(""),g(null),k(null),R(!1)},[n,r]),d.useEffect(()=>{k(null),R(!1)},[e]),d.useEffect(()=>{p(_=>i.length?Math.min(_,i.length-1):0)},[i]),d.useEffect(()=>{const _=++I.current;if(!t||!n){l([]),c(""),f(""),g(null);return}if(b){l([]),c(""),f("");return}const z=s,te=n;let ne=!1;const J=window.setTimeout(()=>{k(null),(async()=>{try{const{lintLatex:fe,isHarperLintSupersededError:ge}=await vt(async()=>{const{lintLatex:L,isHarperLintSupersededError:me}=await import("./spellCheck-BgWyesvf.js");return{lintLatex:L,isHarperLintSupersededError:me}},__vite__mapDeps([0,1,2,3,4,5,6,7,8]),import.meta.url);if(ne||_!==I.current||A.current!==z||X.current!==te)return;let ye;try{ye=await fe(e,te,z,r)}catch(L){if(ge(L))return;throw L}if(ne||_!==I.current||A.current!==z||X.current!==te)return;C.current=!1,R(!1),l(ye),c(z),f(te),p(0),g(null)}catch(fe){if(ne||_!==I.current||A.current!==z||X.current!==te)return;l([]),c(""),f(""),k(fe instanceof Error?fe.message:String(fe));const ge=C.current;C.current=!1,R(ge?j.current:!1)}})()},700);return()=>{ne=!0,window.clearTimeout(J)}},[t,e,n,s,r,x,b]),d.useEffect(()=>{if(!b||!t)return;let _=!1;const z=()=>{_||(_=!0,C.current=!0,k(null),T(ne=>ne+1))},te=window.setTimeout(z,15e3);return window.addEventListener("online",z,{once:!0}),()=>{window.clearTimeout(te),window.removeEventListener("online",z)}},[b,t]);const K=t&&u===n&&a===s,V=d.useMemo(()=>K?{total:i.length,unique:new Set(i.map(_=>`${_.kind}:${_.word.toLocaleLowerCase("en-US")}`)).size}:null,[K,i]);return{issues:K?i:[],jump:K?w:null,index:h,summary:V,jumpToIssue:_=>{if(!i.length)return;const z=Math.max(0,Math.min(_,i.length-1)),te=i[z];p(z),g({from:te.from,to:te.to,nonce:++Q.current})},error:t&&!D?b:null,nativeFallback:t&&!!b,retry:()=>{C.current=!1,k(null),R(!1),T(_=>_+1)},dismissError:()=>{C.current=!1,R(!0)}}}function pa(t){return t instanceof Error&&t.name==="AbortError"}function Iw({projectId:t,mainFile:e,activeFile:n,onActiveFile:s,onError:r,onShowPdf:i}){const[l,a]=d.useState(null),[c,u]=d.useState(null),[f,h]=d.useState(null),p=d.useRef(null),w=d.useRef(0),g=d.useRef(n),b=d.useRef(s),k=d.useRef(r),D=d.useRef(i),R=j=>j===e&&/\.tex$/i.test(j);g.current=n,b.current=s,k.current=r,D.current=i,d.useEffect(()=>(p.current?.abort(),p.current=null,a(null),u(null),h(null),()=>p.current?.abort()),[t,e]);const x=(j,A,X)=>{h({path:j,line:A,column:X,nonce:++w.current}),g.current!==j&&b.current(j)},T=async(j,A,X,Q={})=>{if(!R(j))return;p.current?.abort();const K=new AbortController;p.current=K;try{const V=await ae(`/api/projects/${t}/sync/pdf?mainFile=${encodeURIComponent(e)}&path=${encodeURIComponent(j)}&line=${A}&column=${X}`,{signal:K.signal});if(p.current!==K||!V)return;a({...V,nonce:++w.current}),D.current()}catch(V){!pa(V)&&!Q.silent&&k.current(de(V))}finally{p.current===K&&(p.current=null)}},I=async(j,A,X)=>{if(!R(g.current))return;const Q=g.current;p.current?.abort();const K=new AbortController;p.current=K;try{const V=await ae(`/api/projects/${t}/sync/source?mainFile=${encodeURIComponent(e)}&page=${j}&x=${A}&y=${X}`,{signal:K.signal});if(p.current!==K||g.current!==Q||!R(g.current))return;x(V.path,V.line,V.column)}catch(V){pa(V)||k.current(de(V))}finally{p.current===K&&(p.current=null)}};return{pdfTarget:l,pdfViewport:c,sourceJump:f,setPdfViewport:u,clearPdfViewport:()=>u(null),jumpToSource:x,syncSourceToPdf:T,syncPdfToSource:I,syncVisiblePdfToSource:()=>{c&&I(c.page,c.x,c.y)}}}function uu(t,e){return fn(`texlite.workspaceLayout:${encodeURIComponent(t)}:${encodeURIComponent(e)}`)}function ma(t,e){try{const n=window.localStorage.getItem(uu(t,e));if(n==="editor-pdf"||n==="editor-only"||n==="pdf-only")return n}catch{}return"editor-pdf"}function Pw(t,e){const[n,s]=d.useState(()=>ma(t,e));return d.useEffect(()=>{s(ma(t,e))},[t,e]),{workspaceLayout:n,setWorkspaceLayout:i=>{s(i);try{window.localStorage.setItem(uu(t,e),i)}catch{}}}}function Uw(t){return!/\.bib$/i.test(t.trim())}const zw=["verbatim","verbatim*","Verbatim","BVerbatim","LVerbatim","SaveVerbatim","VerbatimOut","bverbatim","bverbatim*","lverbatim","lverbatim*","saveverbatim","saveverbatim*","verbatimout","verbatimwrite","lstlisting","lstlisting*","minted","minted*","tcblisting","tcblisting*","pygmented","alltt","filecontents","filecontents*","luacode","luacodestar","comment"],Bw=new Set(zw);function qw(t){return Bw.has(t)}function Ww(t,e,n){if(t[e]!=="[")return e;let s=1;for(let r=e+1;r<n;r+=1){if(t[r]==="\\"){r+=1;continue}if(t[r]==="["&&(s+=1),t[r]==="]"&&(s-=1,s===0))return r+1}return null}function ga(t,e,n){if(t[e]!=="{")return null;let s=1;for(let r=e+1;r<n;r+=1){if(t[r]==="\\"){r+=1;continue}if(t[r]==="{"&&(s+=1),t[r]==="}"&&(s-=1,s===0))return r+1}return null}function du(t,e,n=t.length){const s=t.indexOf(`
11
+ `,e);s>=0&&(n=Math.min(n,s));const r=/^\\(verb\*?|Verb\*?|lstinline\*?|mintinline\*?)(?![A-Za-z@])/.exec(t.slice(e,n));if(!r)return null;const i=r[1].replace(/\*$/,"");let l=e+r[0].length;if(i!=="verb"){const u=Ww(t,l,n);if(u===null)return null;l=u}if(i==="mintinline"){const u=ga(t,l,n);if(u===null)return null;l=u}const a=t[l];if(!a||/\s/.test(a))return null;if(a==="{"&&i!=="verb"){const u=ga(t,l,n);return{end:u??n,closed:u!==null}}const c=t.indexOf(a,l+1);return c<0||c>=n?{end:n,closed:!1}:{end:c+1,closed:!0}}function Hw(t,e,n=t.length){return du(t,e,n)?.end??null}function hu(t,e,n){const s=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=new RegExp(String.raw`\\end\s*\{\s*${s}\s*\}`,"g");r.lastIndex=e;const i=r.exec(t);return i?{from:i.index,to:i.index+i[0].length}:null}function Rs(t,e){let n=0;for(let s=e-1;s>=0&&t[s]==="\\";s-=1)n+=1;return n%2===1}function Vw(t,e){let n=e+1;if(/[A-Za-z@]/.test(t[n]??"")){for(;/[A-Za-z@]/.test(t[n]??"");)n+=1;return t[n]==="*"&&(n+=1),n}return Math.min(t.length,n+1)}function fu(t,e){const n=/^\\begin\s*\{\s*([A-Za-z0-9@:_*.\-]+)\s*\}/.exec(t.slice(e));return!n||!qw(n[1])?null:{name:n[1],to:e+n[0].length}}function Jy(t,e){const n=Math.max(0,Math.min(t.length,e));for(let s=0;s<n;){if(t[s]==="%"&&!Rs(t,s)){const l=t.indexOf(`
12
+ `,s),a=l<0?t.length:l;if(n<=a)return"comment";s=a+1;continue}if(t[s]!=="\\"||Rs(t,s)){s+=1;continue}const r=du(t,s);if(r!==null){if(n<r.end||!r.closed&&n<=r.end)return"literal";s=r.end;continue}const i=fu(t,s);if(i){const l=hu(t,i.to,i.name),a=l?.to??t.length;if(n<a||!l&&n<=a)return"literal";s=a;continue}s=Vw(t,s)}return null}function wa(t,e,n){return t.slice(e,n).replace(/[^\r\n]/g," ")}function Kw(t){const e=t.split("");for(let n=0;n<t.length;n+=1){if(t[n]!=="%"||Rs(t,n))continue;const s=t.indexOf(`
13
+ `,n),r=s<0?t.length:s;for(let i=n;i<r;i+=1)e[i]=" ";n=r}return e.join("")}function Jw(t){let e="",n=0;for(;n<t.length;){if(t[n]==="%"&&!Rs(t,n)){const i=t.indexOf(`
14
+ `,n),l=i<0?t.length:i;e+=t.slice(n,l),n=l;continue}if(t[n]!=="\\"||Rs(t,n)){e+=t[n],n+=1;continue}const s=Hw(t,n);if(s!==null){e+=wa(t,n,s),n=s;continue}const r=fu(t,n);if(r){const l=hu(t,r.to,r.name)?.to??t.length;e+=wa(t,n,l),n=l;continue}e+=t[n],n+=1}return e}function Gw(t,e){let n=0;for(let s=e-1;s>=0&&t[s]==="\\";s-=1)n+=1;return n%2===1}function ya(t){const e=Kw(Jw(t)),n=/\\documentclass(?![A-Za-z@])\s*(?:\[[^\]]*\]\s*)?\{/g;for(const s of e.matchAll(n))if(s.index!==void 0&&!Gw(e,s.index))return!0;return!1}function Yw({sessions:t,status:e}){const{t:n}=Ke(),[s,r]=d.useState(!1),i=Math.max(0,t.length-5),l=s&&i>0,a=l?t:t.slice(0,5);return d.useEffect(()=>{t.length<=5&&r(!1)},[t.length]),t.length<=1?null:o.jsxs("div",{className:`collaboration-presence collaboration-${e}`,children:[o.jsx("span",{className:"collaboration-status-dot","data-tooltip":n(`editor.collaboration.${e}`),"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"),f=c.permission==="read"?n("common.readOnly"):n("common.readWrite"),h=n("editor.collaboration.sessionTooltip",{name:c.name,username:c.username,file:c.filePath||n("editor.collaboration.joining"),activity:u,permission:f});return o.jsxs("span",{className:`collaboration-avatar${c.editing?" editing":""}${c.local?" local":""}`,style:{"--session-color":c.color},"aria-label":h,tabIndex:0,children:[_w(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," · ",f]})]})]},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 Xw({value:t,onChange:e}){const{t:n}=Ke(),[s,r]=d.useState(!1),i=d.useRef(null),l=[{value:"editor-pdf",icon:vl},{value:"editor-only",icon:Dh},{value:"pdf-only",icon:_h}];return d.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(vl,{size:15}),o.jsxs("span",{children:[o.jsx("small",{children:n("editor.layout.label")}),n(`editor.layout.${t}.name`)]}),o.jsx(Yi,{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(ah,{size:16})]},a.value)})]})]})}function Qw({site:t,project:e,activeFile:n,saveStateLabel:s,editorPreferences:r,activeSessions:i,collaborationStatus:l,reconnectCollaboration:a,protocolUpgradeRequired:c,showEditor:u,filesCollapsed:f,toggleFilesPanel:h,workspaceLayout:p,changeWorkspaceLayout:w,onBack:g,onShare:b,showCitationLibrary:k,citationLibraryOpen:D,onCitationLibrary:R,onSelectionHistory:x,onHistory:T,onGit:I,canManageGit:C,formatting:j,readOnly:A,collaborationSynced:X,hasSelection:Q,onAddComment:K,onToggleComments:V,commentsOpen:ee,unresolvedCommentCount:_,hasActiveFile:z,onToggleSettings:te,settingsOpen:ne,compileBusy:J,sharedCompiling:fe,localCompiling:ge,cancelling:ye,compileState:L,onCompile:me,onCancelCompile:$}){const{t:M}=Ke();return o.jsxs("header",{className:"editor-topbar",children:[o.jsx("button",{className:"back",title:M("editor.backToProjects"),"aria-label":M("editor.backToProjects"),onClick:g,children:o.jsx(ch,{size:18})}),o.jsx("a",{className:"brand-link compact-brand-link",href:Sr("/"),"aria-label":t.siteName,onClick:B=>{B.preventDefault(),g()},children:o.jsx(ih,{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:M("editor.vimOnHint"),children:[o.jsx(jh,{size:14}),M("editor.vimOn")]}),o.jsx(Yw,{sessions:i,status:l}),l==="disconnected"&&!c&&o.jsxs("div",{className:"collaboration-recovery",role:"status",children:[o.jsx("span",{children:M("editor.collaboration.disconnected")}),o.jsx("button",{type:"button",onClick:a,children:M("editor.collaboration.reconnect")})]}),o.jsxs("div",{className:"editor-actions",children:[u&&o.jsxs("button",{className:f?"":"active",onClick:h,children:[f?o.jsx(Eh,{size:15}):o.jsx(Da,{size:15}),M("common.files")]}),o.jsx(Xw,{value:p,onChange:w}),o.jsxs("button",{onClick:b,children:[o.jsx(Li,{size:15}),M("projectSettings.share")]}),k&&o.jsxs("button",{className:D?"active":"",onClick:R,children:[o.jsx(uh,{size:15}),M("citationLibrary.title")]}),o.jsxs("div",{className:"history-action",role:"group","aria-label":M("history.title"),children:[o.jsxs("div",{className:"history-action-label",children:[o.jsx(Ch,{size:14}),o.jsx("span",{children:M("history.title")})]}),o.jsxs("div",{className:"history-action-options",children:[o.jsx("button",{type:"button",className:"history-action-selection",title:M(Q?"selectionHistory.title":"selectionHistory.selectSourceHint"),onMouseDown:B=>B.preventDefault(),onClick:x,disabled:!Q||!z,children:M("selectionHistory.buttonLabel")}),o.jsx("button",{type:"button",className:"history-action-snapshots",title:M("history.projectSnapshots"),onClick:T,children:M("history.projectSnapshotsButton")})]})]}),o.jsxs("div",{className:"comments-action",role:"group","aria-label":M("common.comments"),children:[o.jsxs("div",{className:"comments-action-label",children:[o.jsx(dh,{size:14}),o.jsx("span",{children:M("common.comments")})]}),o.jsxs("div",{className:"comments-action-options",children:[o.jsx("button",{type:"button",className:"comments-action-add",title:M("editor.addComment"),"aria-label":M("editor.addComment"),onMouseDown:B=>B.preventDefault(),onClick:K,disabled:!z,children:M("editor.commentsAdd")}),o.jsxs("button",{type:"button",className:`comments-action-all${ee?" active":""}`,title:M("editor.commentsAll"),onClick:V,children:[M("editor.commentsAll")," ",_||""]})]})]}),o.jsxs("button",{className:"git-action",title:M(C?"git.title":"git.ownerOnly"),disabled:!C,onClick:I,children:[o.jsx(hh,{size:15}),"Git"]}),o.jsxs("button",{className:ne?"active":"",onClick:te,children:[o.jsx(Nh,{size:15}),M("common.settings")]}),fe||ge?o.jsxs("button",{className:"compile cancel-compile",title:M("compileControls.cancel"),onClick:$,disabled:ye||j||A||!X,children:[ye?o.jsx(nt,{className:"spin",size:15}):o.jsx(xs,{size:15}),M(ye?"compileControls.cancelling":"compileControls.cancel")]}):o.jsxs("button",{className:"compile",title:M("editor.compileShortcut"),onClick:me,disabled:J||j||A||!X,children:[J?o.jsx(nt,{className:"spin",size:15}):o.jsx(Lh,{size:15}),M("editor.compile",{engine:e.engine})]})]})]})}function Zw(t){return`${t.path}\0${t.line}`}function ey(t){const e=[],n=[];for(const s of t){for(;n.length&&n.at(-1).level>=s.level;)n.pop();const r=n.at(-1);r&&(e[r.index].hasChildren=!0),e.push({item:s,key:Zw(s),ancestorKeys:n.map(({index:i})=>e[i].key),hasChildren:!1}),n.push({level:s.level,index:e.length-1})}return e}function ty(t,e){return t.filter(n=>!n.ancestorKeys.some(s=>e.has(s)))}function ny({project:t,filesPanel:e,files:n,visibleEntries:s,activeFile:r,activeMainFile:i,rootDocuments:l,selectedFolder:a,expandedFolders:c,fileDragActive:u,uploadingFiles:f,readOnly:h,formatting:p,canFormat:w,activeFormatLease:g,collaborationSynced:b,editorFontSize:k,outline:D,sourceCursorStore:R,wordCountBusy:x,hasSelection:T,hasFormatSelection:I,uploadInput:C,setSelectedFolder:j,setExpandedFolders:A,setMoveEntry:X,setMoveName:Q,setMoveDestination:K,setDeleteEntry:V,setFileDialogError:ee,setNewFolderName:_,setNewFolderOpen:z,setNewFilePath:te,setNewFileOpen:ne,setQuickOpen:J,setProjectSearchOpen:fe,setFileDragActive:ge,setFilesCollapsed:ye,toggleFilesPanel:L,uploadFiles:me,upload:$,openFile:M,onFormatFile:B,onFormatSelection:re,jumpToSource:le,syncSourceToPdf:we,onWordCount:$e}){const{t:q}=Ke(),[G,Re]=d.useState(!1);return o.jsx(Cr,{id:"files",order:1,ref:e,defaultSize:16,minSize:12,maxSize:30,collapsible:!0,collapsedSize:0,onCollapse:()=>ye(!0),onExpand:()=>ye(!1),children:o.jsxs("aside",{className:"left-panel",children:[o.jsxs("section",{className:`files-panel${u?" drop-active":""}`,onDragEnter:P=>{P.dataTransfer.types.includes("Files")&&(P.preventDefault(),!h&&!f&&ge(!0))},onDragOver:P=>{P.dataTransfer.types.includes("Files")&&(P.preventDefault(),P.dataTransfer.dropEffect=h||f?"none":"copy")},onDragLeave:P=>{P.currentTarget.contains(P.relatedTarget)||ge(!1)},onDrop:P=>{P.preventDefault(),ge(!1),!h&&!f&&me(Array.from(P.dataTransfer.files))},children:[o.jsxs("div",{className:"panel-title",children:[o.jsx("button",{className:"file-size-toggle",type:"button","aria-pressed":G,title:q(G?"editor.hideFileSizes":"editor.showFileSizes"),onClick:()=>Re(P=>!P),children:q("common.files")}),o.jsxs("span",{className:"file-tools",children:[o.jsx("button",{"aria-label":q("navigation.quickOpen"),title:`${q("navigation.quickOpen")} (Ctrl/Cmd+P)`,onClick:()=>J(!0),children:o.jsx(fh,{size:15})}),o.jsx("button",{"aria-label":q("navigation.projectSearch"),title:`${q("navigation.projectSearch")} (Ctrl/Cmd+Shift+F)`,onClick:()=>fe(!0),children:o.jsx(yh,{size:15})}),!h&&o.jsxs(o.Fragment,{children:[o.jsx("button",{disabled:f,"aria-label":q("editor.uploadAttachment"),title:q("editor.uploadTo",{folder:a||q("editor.projectRoot")}),onClick:()=>C.current?.click(),children:o.jsx(kl,{size:15})}),o.jsx("button",{"aria-label":q("editor.newFolder"),title:q("editor.newFolder"),onClick:()=>{_(""),z(!0)},children:o.jsx(ph,{size:15})}),o.jsx("button",{"aria-label":q("editor.newFile"),title:q("editor.newFile"),onClick:()=>{te(a?`${a}/`:""),ne(!0)},children:o.jsx(vh,{size:15})}),o.jsx("input",{ref:C,type:"file",multiple:!0,hidden:!0,onChange:P=>{$(P)}})]}),o.jsx("button",{"aria-label":q("editor.collapseFiles"),title:q("editor.collapseFiles"),onClick:L,children:o.jsx(Da,{size:15})})]})]}),u&&o.jsxs("div",{className:"file-drop-overlay",children:[o.jsx(kl,{size:24}),o.jsx("strong",{children:q("editor.dropFiles")}),o.jsx("span",{children:q("editor.uploadTo",{folder:a||q("editor.projectRoot")})})]}),o.jsxs("div",{className:"file-list",style:{fontSize:`${k}px`},children:[o.jsx("div",{className:`file-entry folder-entry root-entry${a===""?" selected":""}`,children:o.jsxs("button",{className:"file-entry-main",onClick:()=>j(""),children:[o.jsx(mh,{size:15}),o.jsx("span",{children:q("editor.projectRoot")})]})}),s.map(P=>{const Ie=P.path.split("/").length-1,Ae=P.path.split("/").at(-1),Ee=c.has(P.path),he=l.has(P.path),be=i===P.path,Be=P.path!==t.mainFile&&!t.mainFile.startsWith(`${P.path}/`);return P.type==="directory"?o.jsxs("div",{className:`file-entry folder-entry${a===P.path?" selected":""}`,style:{paddingLeft:`${Ie*13+5}px`},children:[o.jsxs("button",{className:"file-entry-main",onClick:()=>{j(P.path),A(De=>{const E=new Set(De);return E.has(P.path)?E.delete(P.path):E.add(P.path),E})},children:[Ee?o.jsx(Yi,{size:13}):o.jsx(Ca,{size:13}),o.jsx(gh,{size:14}),o.jsx("span",{children:Ae})]}),!h&&o.jsxs(o.Fragment,{children:[o.jsx("button",{className:"file-entry-action",title:q("editor.move"),"aria-label":q("editor.move"),onClick:()=>{X(P),Q(Ae??""),K("")},children:o.jsx(El,{size:13})}),Be&&o.jsx("button",{className:"file-entry-action danger-text",title:q("editor.deletePath"),"aria-label":q("editor.deletePath"),onClick:()=>{V(P),ee("")},children:o.jsx(en,{size:13})})]})]},P.path):o.jsxs("div",{className:`file-entry${r===P.path?" active":""}${he?" root-document":""}${be?" compile-target":""}`,style:{paddingLeft:`${Ie*13+18}px`},children:[o.jsxs("button",{className:"file-entry-main",onClick:()=>M(P),children:[he?o.jsx(va,{size:13}):o.jsx(Hn,{size:13}),o.jsx("span",{children:Ae}),be&&o.jsx("small",{children:q("editor.currentMainShort")})]}),G&&typeof P.size=="number"&&o.jsx("span",{className:"file-entry-size",children:ry(P.size)}),!h&&o.jsxs(o.Fragment,{children:[o.jsx("button",{className:"file-entry-action",title:q("editor.move"),"aria-label":q("editor.move"),onClick:()=>{X(P),Q(Ae??""),K("")},children:o.jsx(El,{size:13})}),Be&&o.jsx("button",{className:"file-entry-action danger-text",title:q("editor.deletePath"),"aria-label":q("editor.deletePath"),onClick:()=>{V(P),ee("")},children:o.jsx(en,{size:13})})]})]},P.path)})]}),!h&&w&&o.jsxs("div",{className:"file-format-footer",role:"group","aria-label":q("editor.format"),"aria-busy":p,children:[o.jsxs("div",{className:"file-format-label",children:[o.jsx(kh,{size:13}),q("editor.format")]}),o.jsxs("div",{className:"file-format-actions",children:[o.jsx("button",{className:I?"":"active",type:"button",title:q("editor.formatFileHint"),onMouseDown:P=>P.preventDefault(),onClick:B,disabled:p||g||!b,children:q("editor.formatFile")}),o.jsx("button",{className:I?"active":"",type:"button",title:q(I?"editor.formatSelection":"editor.formatSelectionHint"),onMouseDown:P=>P.preventDefault(),onClick:re,disabled:p||g||!b||!I,children:q("editor.formatSelected")})]})]})]}),o.jsx(sy,{outline:D,activeFile:r,activeMainFile:i,sourceCursorStore:R,wordCountBusy:x,hasSelection:T,jumpToSource:le,syncSourceToPdf:we,onWordCount:$e})]})})}function sy({outline:t,activeFile:e,activeMainFile:n,sourceCursorStore:s,wordCountBusy:r,hasSelection:i,jumpToSource:l,syncSourceToPdf:a,onWordCount:c}){const{t:u}=Ke(),f=d.useSyncExternalStore(s.subscribe,s.getOutlineLine,s.getOutlineLine),h=d.useMemo(()=>ey(t),[t]),p=d.useMemo(()=>h.filter(x=>x.hasChildren).map(x=>x.key),[h]),[w,g]=d.useState(()=>new Set);d.useEffect(()=>{const x=new Set(p);g(T=>{const I=new Set([...T].filter(C=>x.has(C)));return I.size===T.size?T:I})},[p]);const b=p.length>0&&p.every(x=>w.has(x)),k=d.useMemo(()=>ty(h,w),[h,w]),D=()=>g(x=>b?new Set([...x].filter(T=>!p.includes(T))):new Set([...x,...p])),R=x=>g(T=>{const I=new Set(T);return I.has(x)?I.delete(x):I.add(x),I});return o.jsxs("section",{className:"outline-panel",children:[o.jsxs("div",{className:"panel-title",children:[o.jsxs("button",{className:"outline-heading",type:"button","aria-expanded":!b,title:u(b?"editor.expandOutline":"editor.collapseOutline"),onClick:D,disabled:p.length===0,children:[o.jsx(wh,{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(jl,{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(jl,{size:12}),u("editor.wordCountSelection")]})]})]}),o.jsxs("div",{className:"outline",children:[k.map(x=>{const{item:T}=x,I=w.has(x.key),C=e===T.path&&f===T.line;return o.jsxs("div",{className:`outline-row${C?" current":""}`,children:[o.jsx("span",{className:"outline-guides","aria-hidden":!0,style:{width:`${T.level*12}px`}}),x.hasChildren?o.jsx("button",{className:"outline-toggle",type:"button","aria-label":u(I?"editor.expandOutlineItem":"editor.collapseOutlineItem",{title:T.title}),"aria-expanded":!I,onClick:()=>R(x.key),children:I?o.jsx(Ca,{size:13}):o.jsx(Yi,{size:13})}):o.jsx("span",{className:"outline-toggle-spacer","aria-hidden":!0}),o.jsxs("button",{className:"outline-item",type:"button",onClick:()=>{l(T.path,T.line,1),a(T.path,T.line,1)},children:[o.jsx("small",{children:T.path===e?T.line:T.path.split("/").at(-1)}),o.jsx("span",{className:"outline-title",children:T.title})]})]},x.key)}),t.length===0&&o.jsx("p",{className:"muted padded",children:u("editor.noOutline")})]})]})}function ry(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 iy=d.lazy(()=>vt(()=>import("./LatexEditor-CwvakYva.js"),__vite__mapDeps([9,2,10,1,3,4,5,6,7,8]),import.meta.url).then(t=>({default:t.LatexEditor})));function oy({project:t,activeFile:e,activeMainFile:n,openTabs:s,content:r,loadedFile:i,readOnly:l,comments:a,focusComment:c,editorPreferences:u,completionIndex:f,nativeSpellCheck:h,spellCheckIssues:p,spellCheckJump:w,sourceJump:g,collaborativeText:b,collaborationAwareness:k,undoManager:D,editorNotice:R,activateTab:x,closeTab:T,handleTabKeyDown:I,updateEditorContent:C,setSelection:j,onCommentClick:A,onSpellCheckReplace:X,onReferenceNavigate:Q,onCursor:K}){const{t:V}=Ke();return o.jsx(Cr,{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((ee,_)=>{const z=ee===e,te=ee===(n||t.mainFile),ne=ee.split("/").at(-1)||ee;return o.jsxs("div",{className:`editor-tab-item${z?" active":""}`,role:"presentation",children:[o.jsxs("button",{id:`editor-tab-${encodeURIComponent(ee)}`,type:"button",role:"tab","aria-selected":z,"aria-controls":"editor-source-content",tabIndex:z?0:-1,className:`editor-tab${z?" active":""}${te?" main-tab":""}`,onClick:()=>x(ee),onKeyDown:J=>I(J,_),title:ee,children:[o.jsx("span",{className:"editor-tab-icon",children:te?o.jsx(va,{size:13}):o.jsx(Hn,{size:13})}),o.jsx("span",{className:"editor-tab-title",children:ne}),te&&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")} ${ne}`,onClick:()=>T(ee),children:o.jsx(xs,{size:12})})]},ee)})})}),o.jsxs("div",{id:"editor-source-content",className:"editor-content-container",children:[o.jsx(d.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(iy,{value:r,filePath:e,readOnly:l,comments:a,focusComment:c,preferences:u,nativeSpellCheck:h,completionIndex:f,spellCheckIssues:p,spellCheckJump:w,jumpTo:i===e&&g?.path===e?g:null,searchRequest:0,collaboration:b?{text:b,awareness:k,undoManager:l?void 0:D}:void 0,onChange:C,onSelection:j,onCommentClick:A,onSpellCheckReplace:X,onReferenceNavigate:Q,onCursor:K},e)}),R&&o.jsx("div",{className:"editor-centered-notice",role:"status","aria-live":"polite",children:R})]})]})})}function ba({diagnostics:t,files:e,empty:n,tone:s,onJump:r}){const{t:i}=Ke(),l=s==="error"?Xi:Ut;return t.length?o.jsx("div",{className:`compile-diagnostic-list compile-${s}`,children:t.map((a,c)=>{const u=cy(a.file,e),f=!!(u&&a.line);return o.jsxs("button",{type:"button",disabled:!f,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 Ei({lines:t,empty:e,tone:n="log"}){const s=n==="error"?Xi:n==="warning"?Ut:Ti;return t.length?o.jsx("pre",{className:`compile-output compile-${n}`,children:t.join(`
15
+ `)}):o.jsxs("div",{className:`compile-empty compile-${n}`,children:[o.jsx(s,{size:26}),o.jsx("span",{children:e})]})}function ly({projectId:t,mainFile:e,artifacts:n,preview:s,loading:r,onView:i}){const{t:l}=Ke(),a=c=>Sr(`/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(Hn,{size:14}),o.jsxs("span",{children:[o.jsx("strong",{children:c.path}),o.jsx("small",{children:uy(c.size)})]})]}),o.jsx("a",{href:a(c.path),title:l("editor.downloadArtifact"),"aria-label":l("editor.downloadArtifact"),children:o.jsx(rr,{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(rr,{size:13}),l("projects.download")]})]}),o.jsx("pre",{children:s.content})]}):o.jsxs("div",{className:"compile-empty",children:[o.jsx(Hn,{size:24}),o.jsx("span",{children:l("editor.selectArtifact")})]})})]}):o.jsxs("div",{className:"compile-empty",children:[o.jsx(Ea,{size:26}),o.jsx("span",{children:l("editor.noArtifacts")})]})}function ay({mainFile:t,disabled:e,cleaning:n,onCleanCache:s,onCleanArtifacts:r}){const{t:i}=Ke();return o.jsxs("div",{className:"compile-clean-panel",children:[o.jsxs("div",{className:"compile-clean-intro",children:[o.jsx(Ut,{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(Ri,{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(Ri,{size:14}),i("editor.cleanCache")]})]})]}),o.jsxs("article",{className:"danger",children:[o.jsx("div",{className:"compile-clean-action-icon",children:o.jsx(en,{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(en,{size:14}),i("editor.cleanArtifacts")]})]})]})]})]})}function cy(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 uy(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/1024/1024).toFixed(1)} MB`}const dy=d.lazy(()=>ka().then(t=>({default:t.PdfPreview})));function hy({projectId:t,activeMainFile:e,previewTab:n,diagnosticTab:s,pdfUrl:r,pdfLoadingMode:i,pdfLoading:l,pdfCompiledAt:a,pdfCompiledLabel:c,pdfTargetLabel:u,pdfDownloadUrl:f,pdfTarget:h,pdfViewport:p,activeFile:w,compileBusy:g,compileLog:b,compileDiagnostics:k,compileMessages:D,artifacts:R,artifactPreview:x,artifactLoading:T,cleaning:I,readOnly:C,collaborationSynced:j,workspaceLayout:A,showSyncResize:X,diagnosticCount:Q,selectPreviewTab:K,changeWorkspaceLayout:V,onSetNotice:ee,onSetPdfViewport:_,syncVisiblePdfToSource:z,syncCurrentSourceToPdf:te,syncPdfToSource:ne,canSyncWithPdf:J,files:fe,jumpToSource:ge,onSetCleanMode:ye,cleanCompile:L,viewArtifact:me}){const{t:$}=Ke();return o.jsxs(o.Fragment,{children:[X&&o.jsxs(Gi,{className:"resize-handle sync-resize-handle",children:[o.jsx(ja,{className:"resize-grip",size:12}),o.jsxs("span",{className:"sync-direction-buttons",onPointerDown:M=>M.stopPropagation(),children:[o.jsx("button",{disabled:!p||!J,title:$(J?"editor.showInSource":"editor.syncTexOnlyForMain"),"aria-label":$("editor.showInSource"),onClick:()=>{if(!J){ee($("editor.syncTexOnlyForMain"));return}z()},children:o.jsx("span",{"aria-hidden":!0,children:"←"})}),o.jsx("button",{disabled:!w||!r||!J,title:$(J?"editor.showInPdf":"editor.syncTexOnlyForMain"),"aria-label":$("editor.showInPdf"),onClick:()=>{if(!J){ee($("editor.syncTexOnlyForMain"));return}te()},children:o.jsx("span",{"aria-hidden":!0,children:"→"})})]})]}),o.jsx(Cr,{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":$("editor.outputTabs"),children:[o.jsxs("button",{role:"tab","aria-selected":n==="pdf",className:`pdf-tab${n==="pdf"?" active":""}`,onClick:()=>K("pdf"),title:a?$("editor.pdfCompiledAtFor",{file:e,time:new Date(a).toLocaleString(gs.resolvedLanguage)}):$("editor.currentMainDocument",{path:e}),children:[o.jsx(Hn,{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:()=>K("diagnostics"),children:[o.jsx(Ti,{size:14}),$("editor.outputTabs"),o.jsx("span",{children:Q})]})]}),f&&o.jsxs("a",{className:"pdf-download-top",href:f,download:!0,title:$("editor.downloadPdf"),"aria-label":$("editor.downloadPdf"),children:[o.jsx(rr,{size:15}),o.jsx("span",{children:$("editor.downloadPdf")})]})]}),n==="diagnostics"&&o.jsxs("div",{className:"preview-subtabs",role:"tablist","aria-label":$("editor.outputTabs"),children:[o.jsxs("button",{role:"tab","aria-selected":s==="log",className:s==="log"?"active":"",onClick:()=>K("log"),children:[o.jsx(Ti,{size:13}),$("editor.log")]}),o.jsxs("button",{role:"tab","aria-selected":s==="warnings",className:s==="warnings"?"active":"",onClick:()=>K("warnings"),children:[o.jsx(Ut,{size:13}),$("editor.warnings"),o.jsx("span",{children:D.warnings.length})]}),o.jsxs("button",{role:"tab","aria-selected":s==="errors",className:s==="errors"?"active":"",onClick:()=>K("errors"),children:[o.jsx(Xi,{size:13}),$("editor.errors"),o.jsx("span",{children:D.errors.length})]}),o.jsxs("button",{role:"tab","aria-selected":s==="artifacts",className:s==="artifacts"?"active":"",onClick:()=>K("artifacts"),children:[o.jsx(Ea,{size:13}),$("editor.artifacts"),o.jsx("span",{children:R.length})]}),o.jsxs("button",{role:"tab","aria-selected":s==="clean",className:s==="clean"?"active":"",onClick:()=>K("clean"),children:[o.jsx(Ri,{size:13}),$("editor.clean")]})]}),o.jsxs("div",{className:`preview-content preview-${n} ${n==="diagnostics"?`preview-${s}`:""}`,children:[n==="pdf"&&(r?o.jsx(d.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:$("editor.loadingPdf")})]}),children:o.jsx(dy,{url:r,loadingMode:i,target:h,compiling:g,onViewportLocation:(M,B,re)=>_({page:M,x:B,y:re}),onDoubleClickLocation:(M,B,re)=>{if(_({page:M,x:B,y:re}),!J){ee($("editor.syncTexOnlyForMain"));return}ne(M,B,re)}})}):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:$("editor.loadingPdf")})]}):o.jsxs("div",{className:"preview-empty",children:[o.jsx(Hn,{size:28}),o.jsx("strong",{children:$("editor.preview")}),o.jsx("span",{children:$("editor.previewHint")})]})),n==="diagnostics"&&s==="log"&&o.jsx(Ei,{lines:b?b.split(`
16
+ `):[],empty:$(g?"editor.compiling":"editor.noLog")}),n==="diagnostics"&&s==="warnings"&&(k?o.jsx(ba,{tone:"warning",diagnostics:k.warnings,files:fe,empty:$("editor.noWarnings"),onJump:(M,B,re)=>{A==="pdf-only"&&V("editor-pdf"),ge(M,B,re)}}):o.jsx(Ei,{tone:"warning",lines:D.warnings,empty:$("editor.noWarnings")})),n==="diagnostics"&&s==="errors"&&(k?o.jsx(ba,{tone:"error",diagnostics:k.errors,files:fe,empty:$("editor.noErrors"),onJump:(M,B,re)=>{A==="pdf-only"&&V("editor-pdf"),ge(M,B,re)}}):o.jsx(Ei,{tone:"error",lines:D.errors,empty:$("editor.noErrors")})),n==="diagnostics"&&s==="artifacts"&&o.jsx(ly,{projectId:t,mainFile:e,artifacts:R,preview:x,loading:T,onView:M=>{me(M)}}),n==="diagnostics"&&s==="clean"&&o.jsx(ay,{mainFile:e,disabled:C||!j||g,cleaning:I,onCleanCache:()=>ye("cache"),onCleanArtifacts:()=>ye("artifacts")})]})]})})]})}function fy(t,e){const n=t.slice(0,e),s=/(^|[^\p{L}\p{N}_.-])@([\p{L}\p{N}_.-]*)$/u.exec(n);return s?{start:e-s[2].length-1,end:e,query:s[2]}:null}function sr({projectId:t,value:e,onChange:n,onKeyDown:s,onFocus:r,...i}){const{t:l}=Ke(),a=d.useRef(null),[c,u]=d.useState(null),[f,h]=d.useState(!1),[p,w]=d.useState(null),[g,b]=d.useState(0),k=d.useMemo(()=>{if(!p||!c)return[];const C=p.query.toLocaleLowerCase();return(C?c.filter(A=>A.username.toLocaleLowerCase().includes(C)||A.displayName.toLocaleLowerCase().includes(C)):c).slice(0,8)},[c,p]),D=!!(p&&k.length),R=async()=>{if(!(c||f)){h(!0);try{const C=await ae(`/api/projects/${t}/mention-candidates`);u(C.users)}catch{u([])}finally{h(!1)}}},x=(C,j)=>{const A=fy(C,j);w(A),b(0),A&&R()},T=C=>{if(!p)return;const j=`@${C.username} `,A=`${e.slice(0,p.start)}${j}${e.slice(p.end)}`,X=p.start+j.length;n(A),w(null),b(0),window.requestAnimationFrame(()=>{a.current?.focus(),a.current?.setSelectionRange(X,X)})},I=C=>{if(!C.nativeEvent.isComposing&&D){if(C.key==="ArrowDown"){C.preventDefault(),b(j=>(j+1)%k.length);return}if(C.key==="ArrowUp"){C.preventDefault(),b(j=>(j-1+k.length)%k.length);return}if(C.key==="Enter"&&!C.ctrlKey&&!C.metaKey&&!C.shiftKey){C.preventDefault(),T(k[g]??k[0]);return}if(C.key==="Escape"){w(null);return}}s?.(C)};return o.jsxs("span",{className:"mention-textarea",children:[o.jsx("textarea",{...i,ref:a,value:e,onFocus:C=>{r?.(C),x(e,C.currentTarget.selectionStart??e.length)},onClick:C=>x(e,C.currentTarget.selectionStart??e.length),onChange:C=>{const j=C.currentTarget.value;n(j),x(j,C.currentTarget.selectionStart??j.length)},onKeyDown:I}),D&&o.jsx("span",{className:"mention-menu",role:"listbox","aria-label":l("editor.mentionUsers"),children:k.map((C,j)=>o.jsxs("button",{type:"button",role:"option","aria-selected":j===g,className:j===g?"active":"",onMouseDown:A=>A.preventDefault(),onClick:()=>T(C),children:[o.jsx(ir,{"aria-hidden":!0,size:13}),o.jsxs("span",{children:[o.jsx("strong",{children:C.displayName}),o.jsxs("small",{children:["(",C.username,")"]})]})]},C.id))})]})}function Di(t,e){!(t.ctrlKey||t.metaKey)||t.key!=="Enter"||t.nativeEvent.isComposing||(t.preventDefault(),t.stopPropagation(),e())}function py({projectId:t,comment:e,currentUserId:n,unreadCommentMentionId:s,unreadReplyMentionIds:r,highlightedComment:i,highlightedReplyId:l,onMarkMentionRead:a,onFocus:c,onToggle:u,onReply:f,onEdit:h,onDelete:p,onEditReply:w,onDeleteReply:g}){const{t:b}=Ke(),[k,D]=d.useState(!1),[R,x]=d.useState(""),[T,I]=d.useState(!1),[C,j]=d.useState(e.content),[A,X]=d.useState(!1),[Q,K]=d.useState(null),[V,ee]=d.useState(""),[_,z]=d.useState(null),te=async L=>{L?.preventDefault(),R.trim()&&await f(R)&&(x(""),D(!1))},ne=async L=>{L?.preventDefault(),C.trim()&&await h(C)&&I(!1)},J=async L=>{L?.preventDefault(),!(!Q||!V.trim())&&await w(Q,V)&&K(null)},fe=e.authorUsername,ge=L=>new Date(L).toLocaleString(gs.resolvedLanguage),ye=async(L,me)=>{me.stopPropagation(),await a(L)};return o.jsxs(o.Fragment,{children:[o.jsxs("article",{"data-comment-id":e.id,className:`comment-thread${e.resolved?" resolved":""}${e.orphaned?" orphaned":""}${i?" mention-target":""}`,onClick:()=>{window.getSelection()?.toString()||c()},children:[o.jsxs("header",{className:"comment-header",children:[o.jsxs("span",{className:"comment-author",children:[o.jsx("strong",{children:e.authorDisplayName??fe??b("editor.deletedUser")}),fe&&o.jsxs("small",{children:["@",fe]})]}),o.jsxs("span",{className:"comment-times",children:[o.jsx("time",{dateTime:e.createdAt,title:new Date(e.createdAt).toISOString(),children:ge(e.createdAt)}),e.editedAt&&o.jsx("small",{children:b("editor.editedAt",{time:ge(e.editedAt)})})]})]}),o.jsx("div",{className:"comment-location",children:e.orphaned?b("editor.orphaned"):b("editor.line",{line:e.startLine})}),e.selectedText&&o.jsx("blockquote",{className:"comment-selected-text",children:e.selectedText}),T?o.jsxs("form",{className:"comment-reply-form comment-edit-form",onSubmit:L=>{ne(L)},onClick:L=>L.stopPropagation(),children:[o.jsx(sr,{projectId:t,autoFocus:!0,rows:4,value:C,onChange:j,onKeyDown:L=>Di(L,ne)}),o.jsxs("div",{children:[o.jsx("button",{type:"button",onClick:()=>I(!1),children:b("common.cancel")}),o.jsxs("button",{className:"primary",type:"submit",disabled:!C.trim(),children:[o.jsx(Dl,{size:13}),b("editor.saveChanges")]})]})]}):o.jsx("p",{className:"comment-content",children:e.content}),s&&o.jsxs("div",{className:"comment-mention",children:[o.jsxs("span",{children:[o.jsx(ir,{"aria-hidden":!0,size:12}),b("editor.mentionedYou")]}),o.jsx("button",{type:"button",onClick:L=>{ye(s,L)},children:b("editor.markMentionRead")})]}),e.replies.length>0&&o.jsx("div",{className:"comment-replies",children:e.replies.map(L=>{const me=r?.get(L.id);return o.jsxs("div",{"data-comment-reply-id":L.id,className:`comment-reply${l===L.id?" mention-target":""}`,children:[o.jsxs("header",{children:[o.jsxs("span",{className:"comment-author",children:[o.jsx("strong",{children:L.authorDisplayName??L.authorUsername??b("editor.deletedUser")}),L.authorUsername&&o.jsxs("small",{children:["@",L.authorUsername]})]}),o.jsxs("span",{className:"comment-times",children:[o.jsx("time",{dateTime:L.createdAt,title:new Date(L.createdAt).toISOString(),children:ge(L.createdAt)}),L.editedAt&&o.jsx("small",{children:b("editor.editedAt",{time:ge(L.editedAt)})})]})]}),Q===L.id?o.jsxs("form",{className:"comment-reply-form comment-edit-form",onSubmit:$=>{J($)},onClick:$=>$.stopPropagation(),children:[o.jsx(sr,{projectId:t,autoFocus:!0,rows:3,value:V,onChange:ee,onKeyDown:$=>Di($,J)}),o.jsxs("div",{children:[o.jsx("button",{type:"button",onClick:()=>K(null),children:b("common.cancel")}),o.jsxs("button",{className:"primary",type:"submit",disabled:!V.trim(),children:[o.jsx(Dl,{size:13}),b("editor.saveChanges")]})]})]}):o.jsx("p",{className:"comment-content",children:L.content}),me&&o.jsxs("div",{className:"comment-mention",children:[o.jsxs("span",{children:[o.jsx(ir,{"aria-hidden":!0,size:12}),b("editor.mentionedYou")]}),o.jsx("button",{type:"button",onClick:$=>{ye(me,$)},children:b("editor.markMentionRead")})]}),L.authorId===n&&Q!==L.id&&o.jsxs("div",{className:"comment-owner-actions",children:[o.jsx("button",{title:b("editor.editReply"),"aria-label":b("editor.editReply"),onClick:$=>{$.stopPropagation(),K(L.id),ee(L.content)},children:o.jsx(Sl,{size:12})}),o.jsx("button",{className:"danger-text",title:b("editor.deleteReply"),"aria-label":b("editor.deleteReply"),onClick:$=>{$.stopPropagation(),z(L.id)},children:o.jsx(en,{size:12})})]})]},L.id)})}),o.jsxs("div",{className:"comment-actions",children:[o.jsxs("button",{className:"resolve",onClick:L=>{L.stopPropagation(),u()},children:[e.resolved?o.jsx(Rh,{size:13}):o.jsx(Sh,{size:13}),e.resolved?b("editor.reopen"):b("editor.resolve")]}),o.jsxs("button",{className:"reply-action",onClick:L=>{L.stopPropagation(),D(me=>!me)},children:[o.jsx(Th,{size:13}),b("editor.reply")]}),e.authorId===n&&!T&&o.jsxs("span",{className:"comment-owner-actions",children:[o.jsx("button",{title:b("editor.editComment"),"aria-label":b("editor.editComment"),onClick:L=>{L.stopPropagation(),j(e.content),I(!0)},children:o.jsx(Sl,{size:13})}),o.jsx("button",{className:"danger-text",title:b("editor.deleteComment"),"aria-label":b("editor.deleteComment"),onClick:L=>{L.stopPropagation(),X(!0)},children:o.jsx(en,{size:13})})]})]}),k&&o.jsxs("form",{className:"comment-reply-form",onSubmit:L=>{te(L)},onClick:L=>L.stopPropagation(),children:[o.jsx(sr,{projectId:t,autoFocus:!0,rows:3,value:R,placeholder:b("editor.replyPlaceholder"),onChange:x,onKeyDown:L=>Di(L,te)}),o.jsxs("div",{children:[o.jsx("button",{type:"button",onClick:()=>{D(!1),x("")},children:b("common.cancel")}),o.jsxs("button",{className:"primary",type:"submit",disabled:!R.trim(),children:[o.jsx(Ah,{size:13}),b("editor.sendReply")]})]})]})]}),o.jsx(bs,{open:A,title:b("editor.deleteCommentTitle"),description:b("editor.deleteCommentDescription",{count:e.replies.length}),confirmLabel:b("common.delete"),danger:!0,onCancel:()=>X(!1),onConfirm:()=>{p().then(L=>{L&&X(!1)})}}),o.jsx(bs,{open:!!_,title:b("editor.deleteReplyTitle"),description:b("editor.deleteReplyDescription"),confirmLabel:b("common.delete"),danger:!0,onCancel:()=>z(null),onConfirm:()=>{_&&g(_).then(L=>{L&&z(null)})}})]})}function my({open:t,onOpenChange:e,project:n,projectId:s}){const{t:r}=Ke(),[i,l]=d.useState([]),[a,c]=d.useState([]),[u,f]=d.useState(""),[h,p]=d.useState("read"),[w,g]=d.useState(null),[b,k]=d.useState(""),D=n.permission==="owner",R=async()=>{try{const[j,A]=await Promise.all([ae(`/api/projects/${s}/members`),ae("/api/users")]);l(j.members),c(A.users.filter(X=>X.id!==n.ownerId))}catch(j){k(de(j))}};d.useEffect(()=>{t&&R()},[t,s]);const x=async()=>{if(u)try{await ae(`/api/projects/${s}/members/${u}`,{method:"PUT",body:JSON.stringify({permission:h})}),f(""),p("read"),await R()}catch(j){k(de(j))}},T=async(j,A)=>{try{await ae(`/api/projects/${s}/members/${j.id}`,{method:"PUT",body:JSON.stringify({permission:A})}),await R()}catch(X){k(de(X))}},I=async()=>{if(w)try{await ae(`/api/projects/${s}/members/${w.id}`,{method:"DELETE"}),g(null),await R()}catch(j){k(de(j))}},C=a.filter(j=>!i.some(A=>A.id===j.id));return o.jsxs(o.Fragment,{children:[o.jsx(Yt,{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:[b&&o.jsx("p",{className:"error",children:b}),o.jsxs("div",{className:"share-owner",children:[o.jsx(Li,{size:17}),o.jsxs("span",{children:[o.jsx("small",{children:r("projects.owner")}),o.jsx("strong",{children:n.ownerDisplayName??n.ownerUsername})]})]}),D&&o.jsxs("div",{className:"share-add",children:[o.jsxs("label",{className:"form-field",children:[r("common.user"),o.jsxs("select",{value:u,onChange:j=>f(j.target.value),children:[o.jsx("option",{value:"",children:r("projectSettings.chooseUser")}),C.map(j=>o.jsx("option",{value:j.id,children:j.displayName??j.username},j.id))]})]}),o.jsxs("label",{className:"form-field",children:[r("common.permission"),o.jsxs("select",{value:h,onChange:j=>p(j.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:()=>{x()},children:[o.jsx(bh,{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(j=>o.jsxs("div",{className:"shared-member",children:[o.jsxs("span",{className:"member-identity",children:[o.jsx("span",{className:"member-avatar",children:(j.displayName??j.username).slice(0,1).toLocaleUpperCase()}),o.jsxs("span",{children:[o.jsx("strong",{children:j.displayName??j.username}),o.jsxs("small",{children:["@",j.username]})]})]}),o.jsxs("span",{className:"member-controls",children:[o.jsxs("select",{"aria-label":r("common.permission"),disabled:!D,value:j.permission,onChange:A=>{T(j,A.target.value)},children:[o.jsx("option",{value:"read",children:r("common.readOnly")}),o.jsx("option",{value:"edit",children:r("common.readWrite")})]}),D&&o.jsx("button",{className:"icon-only danger-text",title:r("common.remove"),"aria-label":r("common.remove"),onClick:()=>g(j),children:o.jsx(en,{size:15})})]})]},j.id)),i.length===0&&o.jsxs("div",{className:"share-empty",children:[o.jsx(Li,{size:24}),o.jsx("span",{children:r("projectSettings.noMembers")})]})]})]})}),o.jsx(bs,{open:!!w,title:r("projectSettings.removeTitle"),description:r("projectSettings.removeDescription",{username:w?.username??""}),confirmLabel:r("common.remove"),danger:!0,onCancel:()=>g(null),onConfirm:()=>{I()}})]})}const gy=d.lazy(()=>vt(()=>import("./CitationLibraryDialog-DrKbIlD-.js"),__vite__mapDeps([11,2,1,3,12,5,13,4,6,14,15]),import.meta.url).then(t=>({default:t.CitationLibraryDialog}))),wy=d.lazy(()=>vt(()=>import("./GitDialog-CTWAU8q6.js"),__vite__mapDeps([16,2,1,3,5,17,18,13,19,4,6,7,8]),import.meta.url).then(t=>({default:t.GitDialog}))),yy=d.lazy(()=>vt(()=>import("./HistoryDialog-Mo4p8HEg.js"),__vite__mapDeps([20,2,1,3,21,22,5,18,13,19,4,6,7,8]),import.meta.url).then(t=>({default:t.HistoryDialog}))),by=d.lazy(()=>vt(()=>import("./SelectionHistoryDialog-9FWlc3Rb.js"),__vite__mapDeps([23,2,1,3,21,4,5,6,7,8]),import.meta.url).then(t=>({default:t.SelectionHistoryDialog}))),xy=d.lazy(()=>vt(()=>import("./ProjectNavigationDialogs-CpjkXZTz.js"),__vite__mapDeps([24,2,1,3,6,5,4]),import.meta.url).then(t=>({default:t.ProjectSearchDialog}))),ky=d.lazy(()=>vt(()=>import("./ProjectNavigationDialogs-CpjkXZTz.js"),__vite__mapDeps([24,2,1,3,6,5,4]),import.meta.url).then(t=>({default:t.QuickOpenDialog})));function Sy({user:t,project:e,projectId:n,activeFile:s,content:r,maxCitationBibtexBytes:i,files:l,directoryEntries:a,readOnly:c,workspaceLayout:u,changeWorkspaceLayout:f,resourcePreview:h,resourcePreviewLoading:p,setResourcePreview:w,setResourcePreviewLoading:g,uploadConflict:b,setUploadConflict:k,uploadFiles:D,cleanMode:R,setCleanMode:x,cleanCompile:T,newFileOpen:I,setNewFileOpen:C,newFilePath:j,setNewFilePath:A,newFolderOpen:X,setNewFolderOpen:Q,newFolderName:K,setNewFolderName:V,selectedFolder:ee,fileDialogError:_,setFileDialogError:z,createFile:te,createFolder:ne,moveEntry:J,setMoveEntry:fe,moveName:ge,setMoveName:ye,moveDestination:L,setMoveDestination:me,movePath:$,deleteEntry:M,setDeleteEntry:B,deleteActiveSessions:re,removePath:le,commentOpen:we,closeComment:$e,commentSelection:q,selection:G,commentText:Re,setCommentText:P,commentSubmitting:Ie,commentError:Ae,addComment:Ee,shareOpen:he,setShareOpen:be,citationLibraryOpen:Be,setCitationLibraryOpen:De,insertCitationAtCursor:E,quickOpen:ce,setQuickOpen:Ce,projectSearchOpen:et,setProjectSearchOpen:Ne,openFile:xe,jumpToSource:ft,selectionHistoryOpen:qe,setSelectionHistoryOpen:N,historyOpen:Z,setHistoryOpen:O,gitOpen:oe,setGitOpen:pt,save:mt,permissionDowngrade:Xe,permissionDowngradeBusy:at,dismissPermissionDowngrade:jt,discardPermissionDraft:pe}){const{t:F}=Ke();return o.jsxs(o.Fragment,{children:[Xe&&o.jsx(Yt,{open:!0,title:F("editor.collaboration.permissionDowngradeTitle"),description:Xe.localDraftReady&&Xe.otherTabDraft?F("editor.collaboration.permissionDowngradeMultipleDrafts"):Xe.otherTabDraft?F("editor.collaboration.permissionDowngradeOtherTab"):Xe.localDraftReady?F("editor.collaboration.permissionDowngradeDescription",{previous:F("common.readWrite")}):F("editor.collaboration.permissionDowngradeNoDraft"),onOpenChange:W=>{!W&&!at&&jt()},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",disabled:at,onClick:jt,children:Xe.localDraftReady?F("editor.collaboration.permissionDowngradeKeep"):F("common.close")}),!Xe.otherTabDraft&&o.jsxs("button",{type:"button",className:"danger",disabled:at,onClick:()=>{pe()},children:[at?o.jsx(nt,{className:"spin",size:14}):Xe.localDraftReady?o.jsx(en,{size:14}):o.jsx(xh,{size:14}),Xe.localDraftReady?F("editor.collaboration.permissionDowngradeDiscard"):F("editor.collaboration.permissionDowngradeReload")]})]}),children:o.jsx("div",{})}),o.jsxs(Yt,{open:!!h,extraWide:h?.kind==="image"||h?.kind==="pdf"||h?.kind==="text",title:h?.path??"",description:h?.kind==="large"?F("editor.resourceTooLarge",{size:Cy(h.size),limit:`${Ji/1024/1024} MB`}):F(`editor.resourcePreview.${h?.kind??"text"}`),onOpenChange:W=>{W||(w(null),g(!1))},footer:h&&o.jsxs("a",{className:"primary resource-download",href:`${h.url}&download=1`,download:!0,children:[o.jsx(rr,{size:14}),F("editor.downloadResource")]}),children:[h?.kind==="large"&&o.jsxs("div",{className:"resource-preview-message",children:[o.jsx(Cl,{size:34}),o.jsx("strong",{children:F("editor.resourceTooLargeTitle")}),o.jsx("span",{children:F("editor.resourceTooLargeDescription")})]}),h?.kind==="unsupported"&&o.jsxs("div",{className:"resource-preview-message",children:[o.jsx(Cl,{size:34}),o.jsx("strong",{children:F("editor.resourceUnsupportedTitle")}),o.jsx("span",{children:F("editor.resourceUnsupportedDescription")})]}),h?.kind==="image"&&o.jsx("div",{className:"resource-image-wrap",children:o.jsx("img",{className:"resource-image",src:h.url,alt:h.path})}),h?.kind==="pdf"&&o.jsx("iframe",{className:"resource-pdf",src:h.url,title:h.path}),h?.kind==="text"&&(p?o.jsxs("div",{className:"resource-preview-message",children:[o.jsx(nt,{className:"spin",size:24}),o.jsx("span",{children:F("common.loading")})]}):o.jsx("pre",{className:"resource-text",children:h.content}))]}),o.jsx(bs,{open:!!b,title:F("editor.uploadOverwriteTitle"),description:F("editor.uploadOverwriteDescription",{files:b?.collisions.join(", ")??""}),confirmLabel:F("editor.uploadOverwrite"),danger:!0,onCancel:()=>k(null),onConfirm:()=>{const W=b;k(null),W&&D(W.files,new Set(W.collisions),W.directory)}}),o.jsx(bs,{open:!!R,title:F(R==="cache"?"editor.cleanCacheConfirmTitle":"editor.cleanArtifactsConfirmTitle"),description:F(R==="cache"?"editor.cleanCacheConfirmDescription":"editor.cleanArtifactsConfirmDescription"),confirmLabel:F("editor.cleanConfirm"),danger:R==="artifacts",onCancel:()=>x(null),onConfirm:()=>{const W=R;x(null),W&&T(W)}}),o.jsx(Yt,{open:I,title:F("editor.newFile"),description:F("editor.newFileDescription"),onOpenChange:W=>{C(W),W||z("")},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>C(!1),children:F("common.cancel")}),o.jsx("button",{className:"primary",onClick:()=>{te()},children:F("common.create")})]}),children:o.jsxs(o.Fragment,{children:[_&&o.jsx("p",{className:"error dialog-error",children:_}),o.jsxs("label",{className:"form-field",children:[F("editor.filePath"),o.jsx("input",{autoFocus:!0,value:j,onChange:W=>A(W.target.value),onKeyDown:W=>{W.key==="Enter"&&!W.nativeEvent.isComposing&&(W.preventDefault(),te())}})]})]})}),o.jsx(Yt,{open:X,title:F("editor.newFolder"),description:F("editor.folderDestination",{folder:ee||F("editor.projectRoot")}),onOpenChange:W=>{Q(W),W||z("")},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>Q(!1),children:F("common.cancel")}),o.jsx("button",{className:"primary",onClick:()=>{ne()},children:F("common.create")})]}),children:o.jsxs(o.Fragment,{children:[_&&o.jsx("p",{className:"error dialog-error",children:_}),o.jsxs("label",{className:"form-field",children:[F("editor.folderName"),o.jsx("input",{autoFocus:!0,value:K,onChange:W=>V(W.target.value),onKeyDown:W=>{W.key==="Enter"&&ne()}})]})]})}),o.jsx(Yt,{open:!!J,title:F("editor.moveTitle",{name:J?.path.split("/").at(-1)??""}),description:F("editor.moveDescription"),onOpenChange:W=>{W||(fe(null),ye(""),z(""))},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>fe(null),children:F("common.cancel")}),o.jsx("button",{className:"primary",disabled:!ge.trim(),onClick:()=>{$()},children:F("editor.moveApply")})]}),children:o.jsxs(o.Fragment,{children:[_&&o.jsx("p",{className:"error dialog-error",children:_}),o.jsxs("label",{className:"form-field",children:[F("editor.pathName"),o.jsx("input",{autoFocus:!0,value:ge,onChange:W=>ye(W.target.value),onKeyDown:W=>{W.key==="Enter"&&$()}})]}),o.jsxs("label",{className:"form-field",children:[F("editor.destinationFolder"),o.jsxs("select",{value:L,onChange:W=>me(W.target.value),children:[o.jsx("option",{value:"",children:F("editor.projectRoot")}),a.filter(W=>J?.type!=="directory"||W.path!==J.path&&!W.path.startsWith(`${J.path}/`)).map(W=>o.jsx("option",{value:W.path,children:W.path},W.path))]})]})]})}),o.jsx(Yt,{open:!!M,title:F("editor.deletePathTitle",{name:M?.path.split("/").at(-1)??""}),description:re.length?F("editor.deletePathActiveDescription",{path:M?.path??"",users:[...new Set(re.map(W=>W.name))].join(", ")}):F("editor.deletePathDescription",{path:M?.path??""}),onOpenChange:W=>{W||(B(null),z(""))},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{onClick:()=>B(null),children:F("common.cancel")}),o.jsx("button",{className:"danger",onClick:()=>{le()},children:F("common.delete")})]}),children:o.jsxs(o.Fragment,{children:[_&&o.jsx("p",{className:"error dialog-error",children:_}),re.length>0&&o.jsxs("p",{className:"warning",children:[o.jsx(Ut,{size:15}),F("editor.deletePathWillClose")]})]})}),o.jsxs(Yt,{open:we,title:F("editor.addComment"),description:q.selectedText?F("editor.commentDescription",{count:q.endOffset-q.startOffset}):F("editor.pointComment"),onOpenChange:W=>{W||$e()},footer:o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",disabled:Ie,onClick:$e,children:F("common.cancel")}),o.jsxs("button",{type:"button",className:"primary",disabled:Ie||!Re.trim(),onClick:()=>{Ee()},children:[Ie&&o.jsx(nt,{className:"spin",size:14}),F("editor.addComment")]})]}),children:[Ae&&o.jsx("p",{className:"error dialog-error",children:Ae}),o.jsxs("label",{className:"form-field",children:[F("editor.commentContent"),o.jsx(sr,{projectId:n,autoFocus:!0,rows:5,disabled:Ie,value:Re,onChange:P,onKeyDown:W=>{(W.ctrlKey||W.metaKey)&&W.key==="Enter"&&!W.nativeEvent.isComposing&&(W.preventDefault(),W.stopPropagation(),Ee())}})]}),q.selectedText&&o.jsx("blockquote",{className:"selection-preview",children:q.selectedText})]}),o.jsx(my,{open:he,onOpenChange:be,project:e,projectId:n}),Be&&o.jsx(Sa,{title:F("citationLibrary.title"),onClose:()=>De(!1),children:o.jsx(gy,{open:!0,onOpenChange:De,currentFile:s,currentSource:r,readOnly:c,currentUserId:t.id,maxBibtexBytes:i,onInsert:E})}),ce&&o.jsx(d.Suspense,{fallback:null,children:o.jsx(ky,{open:!0,files:l,onOpenChange:Ce,onOpenFile:W=>{const Ot=l.find(is=>is.path===W);Ot&&xe(Ot)}})}),et&&o.jsx(d.Suspense,{fallback:null,children:o.jsx(xy,{open:!0,project:e,onOpenChange:Ne,onJump:(W,Ot,is)=>{u==="pdf-only"&&f("editor-pdf"),ft(W,Ot,is)}})}),qe&&o.jsx(d.Suspense,{fallback:null,children:o.jsx(by,{open:!0,onOpenChange:N,project:e,filePath:s,selection:G,currentSource:r})}),Z&&o.jsx(d.Suspense,{fallback:null,children:o.jsx(yy,{open:!0,onOpenChange:O,project:e,onBeforeMutation:e.permission==="read"?async()=>!0:mt})}),e.ownerId===t.id&&oe&&o.jsx(d.Suspense,{fallback:null,children:o.jsx(wy,{open:!0,onOpenChange:pt,project:e,onBeforeMutation:mt})})]})}function Cy(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/1024/1024).toFixed(1)} MB`}const vy=d.lazy(()=>vt(()=>import("./ProjectSettings-DoxitHbX.js"),__vite__mapDeps([25,2,1,3,5,26,27,14,8,4,6,7]),import.meta.url).then(t=>({default:t.ProjectSettings})));function jy({sidePanel:t,onClose:e,project:n,projectId:s,site:r,files:i,currentUserId:l,comments:a,unreadMentions:c,onMarkMentionRead:u,onMarkAllMentionsRead:f,targetCommentId:h,targetReplyId:p,onFocusComment:w,onToggleComment:g,onReplyComment:b,onEditComment:k,onDeleteComment:D,onEditCommentReply:R,onDeleteCommentReply:x,dictionaryWords:T,onDictionaryChange:I,editorPreferences:C,onEditorPreferences:j,spellCheckCount:A,spellCheckUniqueCount:X,spellCheckIndex:Q,onSpellCheckNavigate:K,onProject:V}){const{t:ee}=Ke();return t?o.jsxs(o.Fragment,{children:[o.jsx(Gi,{className:"resize-handle"}),o.jsx(Cr,{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:ee("editor.sourceComments")}),o.jsxs("span",{className:"drawer-title-actions",children:[c.length>0&&o.jsxs("button",{className:"drawer-mention-read-all",type:"button",onClick:()=>{f()},title:ee("editor.markAllMentionsRead"),children:[o.jsx(ir,{"aria-hidden":!0,size:13}),o.jsx("span",{children:ee("editor.markAllMentionsRead")})]}),o.jsx("button",{"aria-label":ee("common.close"),onClick:e,children:o.jsx(xs,{size:17})})]})]}),o.jsxs("div",{className:"comments",children:[a.map(_=>{const z=c.find(ne=>ne.commentId===_.id&&!ne.replyId)?.id,te=new Map(c.filter(ne=>ne.commentId===_.id&&ne.replyId).map(ne=>[ne.replyId,ne.id]));return o.jsx(py,{projectId:s,comment:_,currentUserId:l,unreadCommentMentionId:z,unreadReplyMentionIds:te,highlightedComment:h===_.id&&!p,highlightedReplyId:h===_.id?p:null,onMarkMentionRead:u,onFocus:()=>w(_),onToggle:()=>{g(_)},onReply:ne=>b(_,ne),onEdit:ne=>k(_,ne),onDelete:()=>D(_),onEditReply:(ne,J)=>R(_,ne,J),onDeleteReply:ne=>x(_,ne)},_.id)}),a.length===0&&o.jsx("p",{className:"muted padded",children:ee("editor.noComments")})]})]}),t==="settings"&&o.jsx(oh,{onClose:e,children:o.jsx(vy,{onClose:e,project:n,projectId:s,site:r,files:i,dictionaryWords:T,onDictionaryChange:I,editorPreferences:C,onEditorPreferences:j,spellCheckCount:A,spellCheckUniqueCount:X,spellCheckIndex:Q,onSpellCheckNavigate:K,onProject:V})})]})})]}):null}function Ey(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 Dy(){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=Ey(l))};return{getCursor:()=>t,getOutlineLine:()=>e,subscribe:c=>(r.add(c),()=>r.delete(c)),update:(c,u,f)=>{t.line===c&&t.column===u&&t.offset===f||(t={line:c,column:u,offset:f},(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 _y=d.lazy(()=>vt(()=>import("./WordCountDialog-DFIWvLrP.js"),__vite__mapDeps([28,2,1,3,26,5,4,6,7,8]),import.meta.url).then(t=>({default:t.WordCountDialog})));let Qs=null;function xa(){return Qs||(Qs=vt(()=>import("./citationLibrary-ZeQPCv5O.js"),[],import.meta.url).catch(t=>{throw Qs=null,t})),Qs}function Gt(t){return t instanceof Error&&t.name==="AbortError"}const Ly=300;function Ty({site:t,user:e,projectId:n,preload:s,mentionId:r=null,onMentionTargeted:i,onMentionsRead:l,onBack:a}){const{t:c}=Ke(),[u,f]=d.useState(null),[h,p]=d.useState(!1),[w,g]=d.useState([]),[b,k]=d.useState(null),[D,R]=d.useState([]),[x,T]=d.useState(""),[I,C]=d.useState(""),[j,A]=d.useState(new Set),[X,Q]=d.useState(""),[K,V]=d.useState({filePath:"",content:""}),[ee,_]=d.useState(""),[z,te]=d.useState(!1),[ne,J]=d.useState("editor.saved"),[fe,ge]=d.useState(null),ye=d.useRef(fe);ye.current=fe;const L=d.useRef(null);L.current||(L.current=Dy());const me=L.current,[$,M]=d.useState("pdf"),[B,re]=d.useState("log"),le=m=>{if(m==="pdf"){M("pdf");return}if(m==="diagnostics"){M("diagnostics");return}re(m),M("diagnostics")},{workspaceLayout:we,setWorkspaceLayout:$e}=Pw(e.id,n),[q,G]=d.useState(""),[Re,P]=d.useState(""),[Ie,Ae]=d.useState({selectedText:"",startOffset:0,endOffset:0}),Ee=d.useRef({selectedText:"",startOffset:0,endOffset:0}),he=m=>{const y=Ee.current;y.selectedText===m.selectedText&&y.startOffset===m.startOffset&&y.endOffset===m.endOffset||(Ee.current=m,Ae(m))},[be,Be]=d.useState(null),[De,E]=d.useState(null),[ce,Ce]=d.useState(!1),[et,Ne]=d.useState(!1),[xe,ft]=d.useState(!1),[qe,N]=d.useState(!1),[Z,O]=d.useState(!1),[oe,pt]=d.useState(!1),[mt,Xe]=d.useState(null),[at,jt]=d.useState(!1),[pe,F]=d.useState(!1),[W,Ot]=d.useState(!1),[is,pu]=d.useState("full"),[mu,gu]=d.useState(""),[$r,Ir]=d.useState(!1),[wu,Pr]=d.useState(""),[yu,Ur]=d.useState(null),[os,jn]=d.useState(!1),[on,Ft]=d.useState(null),[bu,zr]=d.useState(!1),[ct,No]=d.useState(()=>_l(e.id,n)),[En,Ps]=d.useState([]),Wt=d.useRef([]);Wt.current=En;const xu=d.useRef(null),Us=d.useRef(null),zs=d.useRef(0),Br=d.useRef(0),ve=d.useRef(""),tt=d.useRef(""),Oo=d.useRef(we),Fo=d.useRef(0),ln=d.useRef(null),Mo=d.useRef(null),an=d.useRef(null),cn=d.useRef(null),Dn=d.useRef(null),_n=d.useRef(null),Ln=d.useRef(null),Ht=d.useRef(null),qr=d.useRef(null),Mt=d.useRef(!1),Vt=d.useRef(null),$o=d.useRef(a),Wr=d.useRef(i),Hr=d.useRef(l);$o.current=a,Wr.current=i,Hr.current=l,ve.current=x,tt.current=I,Oo.current=we,d.useEffect(()=>{if(!Re)return;const m=window.setTimeout(()=>P(""),3e3);return()=>window.clearTimeout(m)},[Re]);const ku=d.useCallback((m,y,v=0)=>{me.update(m,y,v)},[me]);d.useEffect(()=>()=>me.dispose(),[me]),d.useEffect(()=>()=>{Ht.current?.abort(),Ht.current=null},[]);const Bs=m=>{const y=Wt.current,v=m(y);v!==y&&(Wt.current=v,Ps(v))};d.useEffect(()=>{Wt.current=[],Ps([]),Ft(null),O(!1),_n.current?.abort(),_n.current=null,Ln.current?.abort(),Ln.current=null,Ht.current?.abort(),Ht.current=null,qr.current=null,E(null),Ot(!1),Ir(!1),Pr(""),Ur(null)},[n]);const Io=m=>{const y=Wt.current,v=y.indexOf(m);if(v<0)return;const S=y.filter(U=>U!==m);if(Wt.current=S,Ps(S),ve.current!==m)return;const Y=S.length>0?S[Math.min(v,S.length-1)]:u?.mainFile??"";T(Y)},{collaboration:Le,status:qs,synced:Ge,activeSessions:Po,formatLeaseStates:Su,compileState:un,setCompileState:Uo,filesEvent:Pe,commentsRevision:zo,historyWarning:Cu,dictionaryRevision:Bo,localDraftReady:qo,permission:Vr,reconnect:vu,protocolUpgradeRequired:Wo,permissionDowngrade:ju,dismissPermissionDowngrade:Eu,discardLocalDraft:Du}=Tw(n,e,I,u?.permission??"read",h,()=>J("editor.offlineDraft")),{unreadMentions:Ho,refresh:_u,markMentionRead:Lu,markAllMentionsRead:Tu}=uf(n,zo,G),{pdfTarget:Ru,pdfViewport:Au,sourceJump:Nu,setPdfViewport:Ou,clearPdfViewport:Vo,jumpToSource:ls,syncSourceToPdf:Kr,syncPdfToSource:Fu,syncVisiblePdfToSource:Mu}=Iw({projectId:n,mainFile:I,activeFile:x,onActiveFile:T,onError:G,onShowPdf:()=>le("pdf")}),ut=$w({active:!!(u&&x&&Ge&&ct.spellCheck&&Uw(x)),projectId:n,activeFile:x,content:X,dictionaryWords:w});d.useEffect(()=>{No(_l(e.id,n))},[e.id,n]);const Jr=m=>{Q(m)};d.useEffect(()=>{if(!x||ee!==x){V(S=>S.filePath||S.content?{filePath:"",content:""}:S);return}const m=x,y=X,v=window.setTimeout(()=>{V(S=>S.filePath===m&&S.content===y?S:{filePath:m,content:y})},Ly);return()=>window.clearTimeout(v)},[x,ee,X]),d.useEffect(()=>{if(ve.current=x,me.reset(),he({selectedText:"",startOffset:0,endOffset:0}),!ct.openFilesInTabs){Wt.current.length>0&&(Wt.current=[],Ps([]));return}x&&Bs(m=>m.includes(x)?m:[...m,x])},[x,ct.openFilesInTabs,n,me]),d.useEffect(()=>{if(!z)return;const m=y=>{y.preventDefault(),y.returnValue=""};return window.addEventListener("beforeunload",m),()=>window.removeEventListener("beforeunload",m)},[z]),d.useEffect(()=>{if(qs!=="disconnected")return;const m=new AbortController;return ae(`/api/projects/${n}`,{signal:m.signal}).then(({project:y})=>{m.signal.aborted||(f(y),G(""))}).catch(y=>{if(!Gt(y)){if(y instanceof _i&&[401,403,404].includes(y.status)){G(de(y)),$o.current();return}G(c("errors.collaborationUnavailable"))}}),()=>m.abort()},[qs,n,c]);const Ws=async(m={},y=tt.current)=>{ln.current?.abort(),ln.current=null;const v=m.signal?null:new AbortController;v&&(ln.current=v);try{const S=y?`?mainFile=${encodeURIComponent(y)}`:"",Y=await ae(`/api/projects/${n}/completions${S}`,{signal:m.signal??v?.signal});(!m.isCurrent||m.isCurrent())&&k(Y.index)}catch(S){if(Gt(S))return;(!m.isCurrent||m.isCurrent())&&k(null)}finally{v&&ln.current===v&&(ln.current=null)}},Gr=async(m={},y=tt.current)=>{an.current?.abort(),an.current=null;const v=m.signal?null:new AbortController;v&&(an.current=v);try{const S=y?`?mainFile=${encodeURIComponent(y)}`:"",Y=await ae(`/api/projects/${n}/outline${S}`,{signal:m.signal??v?.signal});(!m.isCurrent||m.isCurrent())&&R(Y.outline)}catch(S){!Gt(S)&&(!m.isCurrent||m.isCurrent())&&R([])}finally{v&&an.current===v&&(an.current=null)}},Ko=async(m={})=>{cn.current?.abort(),cn.current=null;const y=m.signal?null:new AbortController;y&&(cn.current=y);try{const v=await ae(`/api/projects/${n}/dictionary`,{signal:m.signal??y?.signal});(!m.isCurrent||m.isCurrent())&&g(v.words)}catch(v){if(Gt(v))return;(!m.isCurrent||m.isCurrent())&&g([])}finally{y&&cn.current===y&&(cn.current=null)}};d.useEffect(()=>{let m=!1;const y=++Fo.current,v=new AbortController,S=()=>!m&&Fo.current===y;let Y=!1,U="";f(null),Yo([]),R([]),T(""),C(""),A(new Set),Q(""),_(""),Uo(null),Vo(),k(null),g([]),ka();const se=(s?.projectId===n?s.project:ae(`/api/projects/${n}`,{signal:v.signal})).then(Ue=>{S()&&(Y=!0,U=Ue.project.mainFile,f(Ue.project),T(Ue.project.mainFile),tt.current=Ue.project.mainFile,C(Ue.project.mainFile),A(new Set),rl(new Set(ms(Ue.project.mainFile))))}).catch(Ue=>{S()&&G(de(Ue))}),Et=ae(`/api/projects/${n}/files`,{signal:v.signal}).then(Ue=>{S()&&Yo(Ue.files)}).catch(Ue=>{S()&&G(de(Ue))});let it=null;return Promise.allSettled([se,Et]).then(()=>{!S()||!Y||(it=window.setTimeout(()=>{S()&&Promise.all([Ws({signal:v.signal,isCurrent:S},tt.current||U),Ko({signal:v.signal,isCurrent:S})])},0))}),()=>{m=!0,it!==null&&window.clearTimeout(it),v.abort(),ln.current?.abort(),ln.current=null,an.current?.abort(),an.current=null,cn.current?.abort(),cn.current=null,Dn.current?.abort(),Dn.current=null}},[n,s]),d.useEffect(()=>{if(!(!u||!I)){if(Mo.current!==n){Mo.current=n;return}Ws({},I)}},[I,u?.id,n]),d.useEffect(()=>{if(!r||!u)return;Ln.current?.abort();const m=new AbortController;return Ln.current=m,ae(`/api/projects/${n}/mentions/${encodeURIComponent(r)}`,{signal:m.signal}).then(({mention:y})=>{m.signal.aborted||(E(y),Be("comments"),T(y.filePath),Wr.current?.(y.id))}).catch(y=>{Gt(y)||m.signal.aborted||(G(de(y)),Wr.current?.(r))}).finally(()=>{Ln.current===m&&(Ln.current=null)}),()=>m.abort()},[r,u?.id,n]),d.useEffect(()=>{Bo&&Ko()},[Bo,n]),d.useEffect(()=>{!u||qs!=="connected"||Vr===u.permission||f(m=>m&&{...m,permission:Vr})},[Vr,u?.permission]),d.useEffect(()=>{if(!Pe)return;const m=Pe.kind==="delete"&&!!Pe.path&&hn(Pe.path,ve.current),y=Pe.kind==="delete"&&!!Pe.path&&hn(Pe.path,tt.current);if(Pe.kind==="move"&&Pe.source&&Pe.destination){const S=Pe.source,Y=Pe.destination,U=se=>se===S?Y:se.startsWith(`${S}/`)?`${Y}${se.slice(S.length)}`:se;T(se=>U(se)),C(se=>U(se)),A(se=>new Set([...se].map(U))),Xr(se=>se&&U(se)),Bs(se=>se.map(U))}m&&(T(""),_(""),Jr(""),P(c("editor.fileDeletedByCollaborator",{path:Pe.path}))),Pe.kind==="delete"&&Pe.path&&(A(S=>new Set([...S].filter(Y=>!hn(Pe.path,Y)))),Xr(S=>hn(Pe.path,S)?"":S),Zo(S=>S&&hn(Pe.path,S.path)?null:S),Bs(S=>S.filter(Y=>!hn(Pe.path,Y)))),Dn.current?.abort();const v=new AbortController;Dn.current=v,Promise.all([zu({signal:v.signal}),ae(`/api/projects/${n}`,{signal:v.signal})]).then(([S,Y])=>{if(f(Y.project),y&&C(Y.project.mainFile),m&&S){const U=S.find(se=>se.type==="file"&&se.path===Y.project.mainFile)??S.find(se=>se.type==="file"&&Wn(se.path));T(U?.path??"")}Ws({signal:v.signal}),Gr({signal:v.signal},y?Y.project.mainFile:tt.current)}).catch(S=>{Gt(S)}).finally(()=>{Dn.current===v&&(Dn.current=null)})},[Pe?.revision]),d.useEffect(()=>{if(Le.setActiveFile(x),!x)return;_(""),J("editor.loading");const m=Le.getText(x),y=(v,S)=>{Jr(m.toString()),_(x),S?.local&&u?.permission!=="read"?(zs.current+=1,te(!0),J("editor.pending")):zs.current<=Br.current&&J(ye.current?"editor.savedAt":"editor.saved")};return m.observe(y),(Ge||qo)&&y(),()=>{m.unobserve(y)}},[x,Le,Ge,qo,u?.permission]);const Hs=async()=>{if(!Ge)throw new Error("Collaboration is not synchronized");const m=zs.current,y=await Le.flush();return Br.current=Math.max(Br.current,m),ge(y.persistedAt),/\.tex$/i.test(ve.current)&&Gr(),zs.current===m?(te(!1),J("editor.savedAt")):J("editor.pending"),y};d.useEffect(()=>{if(!z||!x)return;if(!Ge){J("editor.offlineDraft");return}J("editor.pending");const m=window.setTimeout(()=>{J("editor.saving"),Hs().catch(()=>{J(Le.connected?"editor.saveFailed":"editor.offlineDraft")})},750);return()=>window.clearTimeout(m)},[X,z,x,Ge]);const as=async()=>{if(!u||u.permission==="read"||!Ge||!x)return!1;J("editor.saving");try{return await Hs(),Ws(),!0}catch(m){return J("editor.saveFailed"),G(de(m)||c("errors.collaborationUnavailable")),!1}},$u=async m=>{if(!u||$r)return;const y=m==="full"?tt.current||u.mainFile:ve.current,v=m==="selection"?Ee.current.selectedText:"";if(!y)return;if(m==="selection"&&(!v.trim()||!/\.(?:tex|sty|cls)$/i.test(y))){P(c("editor.wordCountSelectionEmpty"));return}_n.current?.abort();const S=new AbortController;_n.current=S,pu(m),gu(y),Ur(null),Pr(""),Ot(!0),Ir(!0);try{if(m==="full"&&z&&u.permission!=="read"&&!await as())throw new Error(c("editor.wordCountSaveRequired"));const Y=m==="selection"?{mode:m,path:y,source:v}:{mode:m,mainFile:y},U=await ae(`/api/projects/${n}/word-count`,{method:"POST",body:JSON.stringify(Y),signal:S.signal});if(S.signal.aborted)return;Ur(U)}catch(Y){if(Gt(Y))return;S.signal.aborted||Pr(de(Y))}finally{_n.current===S&&(_n.current=null,Ir(!1))}},Yr=async(m,y,v=ct.texFmtConfig)=>{if(/\.bib$/i.test(m)){const Y=await xa();try{return{formatted:Y.formatBibtex(y,t.maxCitationBibtexBytes)}}catch(U){throw U instanceof Y.BibtexFormatError?U.kind==="too-large"?new Error(c("citationLibrary.fileTooLarge",{size:Y.citationBibtexLimitLabel(t.maxCitationBibtexBytes)})):new Error(c("citationLibrary.fileInvalid")):U}}return{formatted:(await zh(y,v)).output}},Jo=async m=>{if(!u||u.permission==="read"||!Ge||Mt.current||!Js(ve.current))return;const y=ve.current,v=Le.getText(y);Mt.current=!0,jn(!0);let S=()=>{};const Y=new Promise(se=>{S=se});Vt.current=Y;let U=null;try{U=await Le.acquireFormatLease(y);const se=v.toString(),{formatted:Et}=await Yr(y,se,m);if(ve.current!==y||v.toString()!==se){G(c("editor.formatSourceChanged"));return}await U.confirm();const it=await ci(se,Et);if(ve.current!==y||v.toString()!==se){G(c("editor.formatSourceChanged"));return}if(await U.confirm(),ve.current!==y||v.toString()!==se){G(c("editor.formatSourceChanged"));return}it.length&&Le.applyTextEdits(y,it),it.length&&await Hs(),Ft(null),G(""),P(c("editor.formatFileComplete"))}catch(se){ai(se)?(Ft({action:"file",kind:se.kind,detail:se.message}),G("")):G(c("editor.formatFileFailed",{message:de(se)}))}finally{U&&await U.release(),Mt.current=!1,jn(!1),S(),Vt.current===Y&&(Vt.current=null)}},Iu=async()=>{if(!ct.formatOnCompile||!u||u.permission==="read"||!Ge||!Js(ve.current)||Mt.current)return;const m=ve.current,y=Le.getText(m);Mt.current=!0,jn(!0);let v=null;try{v=await Le.acquireFormatLease(m);const S=y.toString(),{formatted:Y}=await Yr(m,S);await v.confirm();const U=await ci(S,Y);if(ve.current!==m||y.toString()!==S)throw new Error(c("editor.formatSourceChanged"));if(await v.confirm(),ve.current!==m||y.toString()!==S)throw new Error(c("editor.formatSourceChanged"));U.length&&Le.applyTextEdits(m,U),U.length&&await Le.flush(),Ft(null)}catch(S){ai(S)?(Ft({action:"file",kind:S.kind,detail:S.message}),G("")):G(c("editor.formatFailedContinue",{message:de(S)}))}finally{v&&await v.release(),Mt.current=!1,jn(!1)}},Pu=async()=>(Vt.current&&await Vt.current,await Iu(),as()),Go=async m=>{if(!u||u.permission==="read"||!Ge||Mt.current||!Js(ve.current))return;const y=Ee.current;if(!y.selectedText.trim()){P(c("editor.formatSelectionRequired"));return}const v=ve.current,{startOffset:S,endOffset:Y,selectedText:U}=y,se=Le.getText(v);if(se.toString().slice(S,Y)!==U){G(c("editor.formatSelectionChanged"));return}Mt.current=!0,jn(!0);let Et=()=>{};const it=new Promise($t=>{Et=$t});Vt.current=it;let Ue=null;try{if(Ue=await Le.acquireFormatLease(v),se.toString().slice(S,Y)!==U){G(c("editor.formatSelectionChanged"));return}const ds=await Yr(v,U,m),th=Wh(U,ds.formatted);await Ue.confirm();const li=await ci(U,th,S);if(ve.current!==v||se.toString().slice(S,Y)!==U){G(c("editor.formatSelectionChanged"));return}if(await Ue.confirm(),ve.current!==v||se.toString().slice(S,Y)!==U){G(c("editor.formatSelectionChanged"));return}li.length&&Le.applyTextEdits(v,li),li.length&&await Hs(),Ft(null),G(""),P(c("editor.formatSelectionComplete"))}catch($t){ai($t)?(Ft({action:"selection",kind:$t.kind,detail:$t.message}),G("")):G(c("editor.formatFailed",{message:de($t)}))}finally{Ue&&await Ue.release(),Mt.current=!1,jn(!1),Et(),Vt.current===it&&(Vt.current=null)}},Uu=async m=>{const y=ve.current;if(!/\.bib$/i.test(y)||u?.permission==="read"||!Ge)return P(c("citationLibrary.importRequiresWrite")),!1;const v=Le.getText(y);let S;try{S=await xa()}catch(ds){return G(de(ds)),!1}if(ve.current!==y||!Ge)return!1;const Y=v.toString(),U=S.parseBibEntriesResult(Y,t.maxCitationBibtexBytes);if(U.status==="too-large")return P(c("citationLibrary.fileTooLarge",{size:S.citationBibtexLimitLabel(t.maxCitationBibtexBytes)})),!1;if(U.status==="invalid")return P(c("citationLibrary.fileInvalid")),!1;if(U.entries.some(ds=>ds.citationKey.toLowerCase()===m.citationKey.toLowerCase()))return P(c("citationErrors.alreadyInFile",{key:m.citationKey})),!1;const se=Math.max(0,Math.min(Y.length,me.getCursor().offset)),Et=Y.slice(0,se),it=Y.slice(se),Ue=Et?Et.endsWith(`
17
+
18
+ `)?"":Et.endsWith(`
19
+ `)?`
20
+ `:`
21
+
22
+ `:"",$t=it?it.startsWith(`
23
+
24
+ `)?"":it.startsWith(`
25
+ `)?`
26
+ `:`
27
+
28
+ `:"";return Le.applyTextEdits(y,[{from:se,to:se,replacement:`${Ue}${m.bibtex.trim()}${$t}`}]),P(c("citationLibrary.imported",{key:m.citationKey})),!0},{files:yt,setFiles:Yo,loadFiles:zu,newFileOpen:Bu,setNewFileOpen:Xo,newFilePath:qu,setNewFilePath:Qo,resourcePreview:Wu,setResourcePreview:Zo,resourcePreviewLoading:Hu,setResourcePreviewLoading:Vu,newFolderOpen:Ku,setNewFolderOpen:el,newFolderName:Ju,setNewFolderName:tl,fileDialogError:Gu,setFileDialogError:nl,selectedFolder:sl,setSelectedFolder:Xr,expandedFolders:Yu,setExpandedFolders:rl,moveEntry:Xu,setMoveEntry:il,moveName:Qu,setMoveName:ol,moveDestination:Zu,setMoveDestination:ll,deleteEntry:Qr,setDeleteEntry:al,fileDragActive:ed,setFileDragActive:td,uploadConflict:nd,setUploadConflict:sd,uploadingFiles:rd,directoryEntries:id,visibleEntries:od,createFile:ld,createFolder:ad,uploadFiles:cl,upload:cd,openFile:Zr,movePath:ud,removePath:dd}=Mw({projectId:n,site:t,activeFile:x,dirty:z,save:as,onError:G,onProject:f,onActiveFile:T,onActiveMainFile:C,onRootDocuments:A}),ul=()=>tt.current||u?.mainFile||"",hd=()=>{const m=ul(),y=ve.current;if(!y||!/\.tex$/i.test(y))return m;const v=yt.filter(U=>U.type==="file"&&/\.tex$/i.test(U.path)).length,S=Le.getText(y).toString();return ya(S)||v===1?(A(U=>{if(U.has(y))return U;const se=new Set(U);return se.add(y),se}),m!==y&&(tt.current=y,C(y)),y):m===y&&u?.mainFile&&u.mainFile!==y?(tt.current=u.mainFile,C(u.mainFile),u.mainFile):m};d.useEffect(()=>{if(!x||ee!==x||K.filePath!==x||!x.toLocaleLowerCase().endsWith(".tex"))return;const m=yt.filter(Y=>Y.type==="file"&&/\.tex$/i.test(Y.path)).length;if(m===0)return;const y=x===u?.mainFile,S=ya(K.content)||m===1;A(Y=>{if(Y.has(x)===S)return Y;const U=new Set(Y);return S?U.add(x):U.delete(x),U}),S&&!y&&tt.current!==x?C(x):!S&&tt.current===x&&u?.mainFile&&C(u.mainFile)},[x,ee,K,yt,u?.mainFile]),d.useEffect(()=>{if(!ct.openFilesInTabs||yt.length===0)return;const m=new Set(yt.filter(y=>y.type==="file"&&Wn(y.path)).map(y=>y.path));Bs(y=>{const v=y.filter(S=>m.has(S));return v.length===y.length?y:v})},[yt,ct.openFilesInTabs]);const{comments:Tn,focusComment:fd,setFocusComment:ei,commentOpen:pd,openComment:md,closeComment:gd,commentText:wd,setCommentText:yd,commentSelection:bd,commentSubmitting:xd,commentError:kd,addComment:Sd,toggleComment:Cd,replyToComment:vd,editComment:jd,deleteComment:Ed,editCommentReply:Dd,deleteCommentReply:_d}=af({projectId:n,activeFile:x,content:X,permission:u?.permission,revision:zo,selection:Ie,save:as,saveFailureMessage:c("errors.collaborationUnavailable"),onError:G,onAdded:()=>Be("comments"),onChanged:()=>{_u()}}),Ld=async m=>{const y=await Lu(m);return y&&Hr.current?.(1),y},Td=async()=>{const m=Ho.length,y=await Tu();return y&&m&&Hr.current?.(m,!0),y};d.useEffect(()=>{if(!De||x!==De.filePath||be!=="comments")return;const m=Tn.find(U=>U.id===De.commentId);if(!m||De.replyId&&!m.replies.some(U=>U.id===De.replyId))return;const y=De.replyId?`[data-comment-reply-id="${De.replyId}"]`:`[data-comment-id="${De.commentId}"]`,v=document.querySelector(y);if(!v||qr.current===De.id)return;qr.current=De.id,ei({...m});const S=window.requestAnimationFrame(()=>v.scrollIntoView({block:"center",behavior:"smooth"})),Y=window.setTimeout(()=>E(U=>U?.id===De.id?null:U),3e3);return()=>{window.cancelAnimationFrame(S),window.clearTimeout(Y)}},[x,Tn,be,De]);const{pdfUrl:Kt,pdfCompiledAt:cs,pdfLoadingMode:Rd,pdfLoading:ti,compileLog:ni,compileDiagnostics:Ad,compileOutcome:us,artifacts:dl,artifactPreview:Nd,artifactLoading:Od,editorNotice:Fd,localCompiling:hl,cancelling:Md,cleaning:fl,compile:$d,cancelCompile:Id,cleanCompile:pl,viewArtifact:Pd}=Aw({projectId:n,project:u,mainFile:I,resolveCompileMainFile:hd,getCurrentMainFile:ul,initialLatest:s?.projectId===n?s.latestCompile:null,collaborationSynced:Ge,sharedState:un,onSharedState:Uo,save:Pu,loadOutline:(m,y)=>Gr({signal:m},y),onPreviewTab:le,onError:G,onCompileStart:()=>{G(""),P("")},onCompileSuccess:()=>{const m=ve.current;if(m){const y=me.getCursor();Kr(m,y.line,y.column,{silent:!0})}},onPdfChanged:Vo});d.useEffect(()=>{if(!u||!I||!Kt&&ti)return;const m=window.setTimeout(()=>p(!0),Kt?150:0);return()=>window.clearTimeout(m)},[u,ti,Kt]),d.useEffect(()=>{const m=y=>{(y.ctrlKey||y.metaKey)&&(!y.shiftKey&&y.key.toLocaleLowerCase()==="p"?(y.preventDefault(),jt(!0)):y.shiftKey&&y.key.toLocaleLowerCase()==="f"&&(y.preventDefault(),F(!0)))};return window.addEventListener("keydown",m,!0),()=>window.removeEventListener("keydown",m,!0)},[]);const ml=m=>{No(m),Mh(e.id,n,m)},gl=(m=!1)=>{const y=on;if(!y)return;Ft(null),G(""),m&&ml({...ct,texFmtConfig:""});const v=m?"":void 0;y.action==="selection"?Go(v):Jo(v)},Ud=async()=>{zr(!0);try{await Du()||(G(c("editor.collaboration.permissionDowngradeOtherTabBlocked")),zr(!1))}catch(m){G(de(m)),zr(!1)}},wl=()=>{Us.current?.isCollapsed()?Us.current.expand():Us.current?.collapse()},zd=d.useMemo(()=>D.length?D:K.filePath!==x?[]:Ry(K.content).map(m=>({...m,path:x})),[D,K,x]),si=d.useMemo(()=>Hh(ni,us),[ni,us]),Rn=we!=="pdf-only",yl=we!=="editor-only",Vs=m=>{$e(m),m==="pdf-only"&&le("pdf")},Bd=d.useCallback(m=>{Ht.current?.abort();const y=new AbortController;Ht.current=y;const v=ve.current,S=tt.current,Y=new URLSearchParams({kind:m.kind,key:m.key,...v?{path:v}:{},...S?{mainFile:S}:{}});ae(`/api/projects/${n}/references/resolve?${Y}`,{signal:y.signal}).then(({target:U})=>{if(!(y.signal.aborted||ve.current!==v||tt.current!==S)){if(!U){G(c(m.kind==="citation"?"editor.citationTargetNotFound":"editor.labelTargetNotFound",{key:m.key}));return}Oo.current==="pdf-only"&&Vs("editor-pdf"),ls(U.path,U.line,U.column)}}).catch(U=>{!y.signal.aborted&&!Gt(U)&&G(de(U))}).finally(()=>{Ht.current===y&&(Ht.current=null)})},[ls,n,c]),qd=Qr?Po.filter(m=>m.filePath&&hn(Qr.path,m.filePath)):[];if(!u)return o.jsxs("div",{className:"center-card",children:[o.jsx("p",{children:q||c("common.loading")}),q&&o.jsx("button",{className:"primary",onClick:a,children:c("editor.backToProjects")})]});const Jt=u.permission==="read"||!Ge,ri=Su.find(m=>m.path===x),ii=ri&&!os?ri:null,Wd=(m,y)=>{if(Jt)return;const v=ve.current;if(!v)return;if(Le.getText(v).toString().slice(m.from,m.to)!==m.word){G(c("editor.spellCheckSourceChanged"));return}try{Le.applyTextEdits(v,[{from:m.from,to:m.to,replacement:y}])}catch(U){G(de(U))}},oi=un?.mainFile===I&&(un.status==="queued"||un.status==="running"),Ks=hl||oi||fl,Hd=x?Le.getText(x):null,Vd=cs?new Date(cs).toLocaleString(gs.resolvedLanguage,{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}):"",Kd=I.split("/").at(-1)??I,Jd=si.warnings.length+si.errors.length+dl.length,Gd=Kt?`${Kt}${Kt.includes("?")?"&":"?"}download=1`:"",Yd=I||u.mainFile,Xd=!!(x&&x===Yd&&/\.tex$/i.test(x)),bl=m=>{const y=yt.find(v=>v.path===m);y&&Wn(y.path)?Zr(y):Io(m)},Qd=m=>{document.getElementById(`editor-tab-${encodeURIComponent(m)}`)?.focus()},Zd=(m,y)=>{if(!["ArrowLeft","ArrowRight","Home","End"].includes(m.key))return;m.preventDefault();const v=m.key==="Home"?0:m.key==="End"?En.length-1:(y+(m.key==="ArrowLeft"?-1:1)+En.length)%En.length,S=En[v];S&&(bl(S),window.requestAnimationFrame(()=>Qd(S)))},xl=Ks?oi?un?.status==="queued"?c("editor.compileQueued"):c("editor.compilingBy",{name:un?.requestedBy.name??c("common.user")}):c("editor.compiling"):us==="failed"?Kt&&cs?c("editor.compileFailedRetained",{time:new Date(cs).toLocaleString(gs.resolvedLanguage)}):c("editor.compileFailedNoPdf"):us==="cancelled"?c("compileControls.cancelled"):"",eh=ne==="editor.savedAt"&&fe?c("editor.savedAt",{time:new Date(fe).toLocaleTimeString(gs.resolvedLanguage,{hour:"2-digit",minute:"2-digit",second:"2-digit"})}):c(ne);return o.jsxs("div",{className:"workspace",children:[o.jsx(Qw,{site:t,project:u,activeFile:x,saveStateLabel:eh,editorPreferences:ct,activeSessions:Po,collaborationStatus:qs,reconnectCollaboration:vu,protocolUpgradeRequired:Wo,showEditor:Rn,filesCollapsed:ce,toggleFilesPanel:wl,workspaceLayout:we,changeWorkspaceLayout:Vs,onBack:a,onShare:()=>Ne(!0),showCitationLibrary:Rn&&/\.bib$/i.test(x),citationLibraryOpen:oe,onCitationLibrary:()=>pt(!0),onSelectionHistory:()=>O(!0),onHistory:()=>N(!0),onGit:()=>ft(!0),canManageGit:u.ownerId===e.id,formatting:os,readOnly:Jt,collaborationSynced:Ge,hasSelection:!!Ie.selectedText.trim(),onAddComment:md,onToggleComments:()=>Be(be==="comments"?null:"comments"),commentsOpen:be==="comments",unresolvedCommentCount:Tn.filter(m=>!m.resolved).length,hasActiveFile:!!x,onToggleSettings:()=>Be(be==="settings"?null:"settings"),settingsOpen:be==="settings",compileBusy:Ks,sharedCompiling:oi,localCompiling:hl,cancelling:Md,compileState:un,onCompile:$d,onCancelCompile:()=>{Id()}}),Wo&&o.jsxs("div",{className:"workspace-update-banner",role:"alert",children:[o.jsx(Ut,{size:15}),o.jsx("span",{children:c("workspaceUpdates.protocolUpgrade")}),o.jsx("button",{type:"button",onClick:()=>window.location.reload(),children:c("common.reload")})]}),xl&&o.jsxs("div",{className:`compile-status-strip${us==="failed"?" failed":""}`,role:"status","aria-live":"polite",children:[o.jsx(nt,{className:Ks?"spin":"",size:14}),o.jsx("span",{children:xl})]}),(ut.error||on||ii)&&o.jsxs("div",{className:"client-tool-recoveries",children:[ut.error&&o.jsxs("div",{className:"client-tool-recovery",role:"alert",title:ut.error,children:[o.jsx(Ut,{size:15}),o.jsxs("span",{children:[o.jsx("strong",{children:c("editor.harperRecoveryTitle")}),c("editor.harperFallbackHint")]}),o.jsx("div",{className:"client-tool-recovery-actions",children:o.jsx("button",{type:"button",onClick:ut.retry,children:c("common.retry")})}),o.jsx("button",{type:"button",className:"formatter-diagnostics-dismiss",title:c("common.close"),"aria-label":c("common.close"),onClick:ut.dismissError,children:o.jsx(xs,{size:13})})]}),on&&o.jsxs("div",{className:"client-tool-recovery",role:"alert",title:on.detail,children:[o.jsx(Ut,{size:15}),o.jsxs("span",{children:[o.jsx("strong",{children:c(on.kind==="format"?"editor.texFmtOptionsRecoveryTitle":on.kind==="load"?"editor.texFmtRecoveryTitle":"editor.texFmtRuntimeRecoveryTitle")}),c("editor.clientToolRecoveryHint")]}),o.jsxs("div",{className:"client-tool-recovery-actions",children:[o.jsx("button",{type:"button",disabled:os||Jt,onClick:()=>gl(),children:c("common.retry")}),on.kind==="format"&&ct.texFmtConfig.trim()&&o.jsx("button",{type:"button",disabled:os||Jt,onClick:()=>gl(!0),children:c("editor.resetFormatterOptions")}),o.jsx("button",{type:"button",onClick:()=>window.location.reload(),children:c("common.reload")})]}),o.jsx("button",{type:"button",className:"formatter-diagnostics-dismiss",title:c("common.close"),"aria-label":c("common.close"),onClick:()=>Ft(null),children:o.jsx(xs,{size:13})})]}),ii&&o.jsxs("div",{className:"client-tool-recovery format-lease-status",role:"status",children:[o.jsx(nt,{className:"spin",size:15}),o.jsx("span",{children:c("editor.formattingBy",{name:ii.holderName})})]})]}),Cu&&o.jsxs("div",{className:"client-tool-recovery",role:"status",children:[o.jsx(Ut,{size:15}),o.jsx("span",{children:c("history.saveWarning")})]}),q&&o.jsx("div",{className:"toast",onClick:()=>G(""),children:q}),Re&&o.jsx("div",{className:"toast success",onClick:()=>P(""),children:Re}),o.jsxs(lh,{autoSaveId:fn("texlite-workspace-layout"),direction:"horizontal",className:"work-grid",children:[Rn&&o.jsx(ny,{project:u,filesPanel:Us,files:yt,visibleEntries:od,activeFile:x,activeMainFile:I,rootDocuments:j,selectedFolder:sl,expandedFolders:Yu,fileDragActive:ed,uploadingFiles:rd,readOnly:Jt,formatting:os,canFormat:Js(x),activeFormatLease:!!ri,collaborationSynced:Ge,editorFontSize:ct.fontSize,outline:zd,sourceCursorStore:me,wordCountBusy:$r,hasSelection:!!Ie.selectedText.trim()&&/\.(?:tex|sty|cls)$/i.test(x),hasFormatSelection:!!Ie.selectedText.trim(),uploadInput:xu,setSelectedFolder:Xr,setExpandedFolders:rl,setMoveEntry:il,setMoveName:ol,setMoveDestination:ll,setDeleteEntry:al,setFileDialogError:nl,setNewFolderName:tl,setNewFolderOpen:el,setNewFilePath:Qo,setNewFileOpen:Xo,setQuickOpen:jt,setProjectSearchOpen:F,setFileDragActive:td,setFilesCollapsed:Ce,toggleFilesPanel:wl,uploadFiles:cl,upload:cd,openFile:Zr,onFormatFile:()=>{Jo()},onFormatSelection:()=>{Go()},jumpToSource:ls,syncSourceToPdf:Kr,onWordCount:m=>{$u(m)}}),Rn&&o.jsx(Gi,{className:"resize-handle",children:o.jsx(ja,{size:12})}),Rn&&o.jsx(oy,{project:u,activeFile:x,activeMainFile:I,openTabs:En,content:X,loadedFile:ee,readOnly:Jt,comments:Tn,focusComment:fd,editorPreferences:ct,completionIndex:b,nativeSpellCheck:ut.nativeFallback,spellCheckIssues:ut.issues,spellCheckJump:ut.jump,sourceJump:Nu,collaborativeText:Hd,collaborationAwareness:Le.awareness,undoManager:x?Le.getUndoManager(x):void 0,editorNotice:Fd,activateTab:bl,closeTab:Io,handleTabKeyDown:Zd,updateEditorContent:Jr,setSelection:(m,y,v)=>he({selectedText:m,startOffset:y,endOffset:v}),onCommentClick:m=>{const y=Tn.find(v=>v.id===m);y&&(ei({...y}),Be("comments"))},onSpellCheckReplace:Wd,onReferenceNavigate:Bd,onCursor:ku}),yl&&o.jsx(hy,{projectId:n,activeMainFile:I,previewTab:$,diagnosticTab:B,pdfUrl:Kt,pdfLoadingMode:Rd,pdfLoading:ti,pdfCompiledAt:cs,pdfCompiledLabel:Vd,pdfTargetLabel:Kd,pdfDownloadUrl:Gd,pdfTarget:Ru,pdfViewport:Au,activeFile:x,compileBusy:Ks,compileLog:ni,compileDiagnostics:Ad,compileMessages:si,artifacts:dl,artifactPreview:Nd,artifactLoading:Od,cleaning:fl,readOnly:Jt,collaborationSynced:Ge,workspaceLayout:we,showSyncResize:Rn&&yl,diagnosticCount:Jd,selectPreviewTab:le,changeWorkspaceLayout:Vs,onSetNotice:P,onSetPdfViewport:Ou,syncVisiblePdfToSource:Mu,syncCurrentSourceToPdf:()=>{const m=ve.current;if(!m)return Promise.resolve();const y=me.getCursor();return Kr(m,y.line,y.column)},syncPdfToSource:Fu,canSyncWithPdf:Xd,files:yt,jumpToSource:ls,onSetCleanMode:Xe,cleanCompile:pl,viewArtifact:Pd}),o.jsx(jy,{sidePanel:be,onClose:()=>Be(null),project:u,projectId:n,site:t,files:yt,currentUserId:e.id,comments:Tn,unreadMentions:Ho,onMarkMentionRead:Ld,onMarkAllMentionsRead:Td,targetCommentId:De?.commentId,targetReplyId:De?.replyId,onFocusComment:m=>ei({...m}),onToggleComment:Cd,onReplyComment:vd,onEditComment:jd,onDeleteComment:Ed,onEditCommentReply:Dd,onDeleteCommentReply:_d,dictionaryWords:w,onDictionaryChange:g,editorPreferences:ct,onEditorPreferences:ml,spellCheckCount:ut.summary?.total??null,spellCheckUniqueCount:ut.summary?.unique??null,spellCheckIndex:ut.summary?ut.index:-1,onSpellCheckNavigate:ut.jumpToIssue,onProject:f})]}),W&&o.jsx(Sa,{title:c("editor.wordCountTitle"),onClose:()=>Ot(!1),children:o.jsx(_y,{open:!0,mode:is,path:mu,busy:$r,error:wu,result:yu,onOpenChange:Ot})}),o.jsx(Sy,{user:e,project:u,projectId:n,activeFile:x,content:X,maxCitationBibtexBytes:t.maxCitationBibtexBytes,files:yt,directoryEntries:id,readOnly:Jt,workspaceLayout:we,changeWorkspaceLayout:Vs,resourcePreview:Wu,resourcePreviewLoading:Hu,setResourcePreview:Zo,setResourcePreviewLoading:Vu,uploadConflict:nd,setUploadConflict:sd,uploadFiles:cl,cleanMode:mt,setCleanMode:Xe,cleanCompile:pl,newFileOpen:Bu,setNewFileOpen:Xo,newFilePath:qu,setNewFilePath:Qo,newFolderOpen:Ku,setNewFolderOpen:el,newFolderName:Ju,setNewFolderName:tl,selectedFolder:sl,fileDialogError:Gu,setFileDialogError:nl,createFile:ld,createFolder:ad,moveEntry:Xu,setMoveEntry:il,moveName:Qu,setMoveName:ol,moveDestination:Zu,setMoveDestination:ll,movePath:ud,deleteEntry:Qr,setDeleteEntry:al,deleteActiveSessions:qd,removePath:dd,commentOpen:pd,closeComment:gd,commentSelection:bd,selection:Ie,commentText:wd,setCommentText:yd,commentSubmitting:xd,commentError:kd,addComment:Sd,shareOpen:et,setShareOpen:Ne,citationLibraryOpen:oe,setCitationLibraryOpen:pt,insertCitationAtCursor:Uu,quickOpen:at,setQuickOpen:jt,projectSearchOpen:pe,setProjectSearchOpen:F,openFile:Zr,jumpToSource:ls,selectionHistoryOpen:Z,setSelectionHistoryOpen:O,historyOpen:qe,setHistoryOpen:N,gitOpen:xe,setGitOpen:ft,save:as,permissionDowngrade:ju,permissionDowngradeBusy:bu,dismissPermissionDowngrade:Eu,discardPermissionDraft:Ud})]})}function Ry(t){const e=[],n=/^\s*\\(part|chapter|section|subsection|subsubsection)\*?(?:\[[^\]]*\])?\{([^}]*)\}/,s={part:0,chapter:0,section:1,subsection:2,subsubsection:3};return t.split(`
29
+ `).forEach((r,i)=>{const l=r.match(n);l&&e.push({level:s[l[1]],title:l[2],line:i+1})}),e}const Gy=Object.freeze(Object.defineProperty({__proto__:null,ProjectWorkspace:Ty},Symbol.toStringTag,{value:"Module"}));export{kh as A,Uy as B,Yi as C,Ch as F,jl as H,Gy as P,Rh as R,Dl as S,Um as U,Wy as a,Hy as b,Hi as c,Vy as d,Ky as e,kn as f,zy as g,It as h,Hw as i,qw as j,Jy as k,hu as l,no as m,zw as n,Kw as o,Jw as p,Py as q,qy as r,Uw as s,By as t,Sh as u,of as v,Xt as w,Bh as x,Nh as y,Ai as z};