texlite 0.22.0 → 0.23.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/DESIGN.md +5 -0
- package/OPERATIONS.md +21 -1
- package/README.md +1 -0
- package/README.zh-CN.md +1 -0
- package/addon.md +76 -0
- package/dist/client/assets/{AdminUsers-DepqkT6m.js → AdminUsers-xuVuiwoh.js} +1 -1
- package/dist/client/assets/AdminUsers-xuVuiwoh.js.br +0 -0
- package/dist/client/assets/AdminUsers-xuVuiwoh.js.gz +0 -0
- package/dist/client/assets/{AgentIcon-DeoZDwgh.css → AgentIcon-DJGGRJnV.css} +1 -1
- package/dist/client/assets/AgentIcon-DJGGRJnV.css.br +0 -0
- package/dist/client/assets/AgentIcon-DJGGRJnV.css.gz +0 -0
- package/dist/client/assets/{AgentManagement-DlV6tHez.js → AgentManagement-D-0hrv6f.js} +1 -1
- package/dist/client/assets/AgentManagement-D-0hrv6f.js.br +0 -0
- package/dist/client/assets/AgentManagement-D-0hrv6f.js.gz +0 -0
- package/dist/client/assets/AgentTerminal-DZo-22RN.js +2 -0
- package/dist/client/assets/AgentTerminal-DZo-22RN.js.br +0 -0
- package/dist/client/assets/AgentTerminal-DZo-22RN.js.gz +0 -0
- package/dist/client/assets/AgentTerminalSurface-CcC17_CY.js +16 -0
- package/dist/client/assets/AgentTerminalSurface-CcC17_CY.js.br +0 -0
- package/dist/client/assets/AgentTerminalSurface-CcC17_CY.js.gz +0 -0
- package/dist/client/assets/{AvatarSettingsDialog-C8WQhZBK.js → AvatarSettingsDialog-ChKrdDqp.js} +1 -1
- package/dist/client/assets/AvatarSettingsDialog-ChKrdDqp.js.br +0 -0
- package/dist/client/assets/AvatarSettingsDialog-ChKrdDqp.js.gz +0 -0
- package/dist/client/assets/{CitationBibtexEditor-SpudGDwi.js → CitationBibtexEditor-BZIU4Lif.js} +1 -1
- package/dist/client/assets/{CitationLibraryDialog-DgOIkLwK.js → CitationLibraryDialog-DqO9e0GV.js} +3 -3
- package/dist/client/assets/CitationLibraryDialog-DqO9e0GV.js.br +0 -0
- package/dist/client/assets/CitationLibraryDialog-DqO9e0GV.js.gz +0 -0
- package/dist/client/assets/{Dashboard-CD1w42mA.js → Dashboard-BYgqCgBM.js} +3 -3
- package/dist/client/assets/Dashboard-BYgqCgBM.js.br +0 -0
- package/dist/client/assets/Dashboard-BYgqCgBM.js.gz +0 -0
- package/dist/client/assets/{GitDialog-DGzZ3GRj.js → GitDialog-CA68baSd.js} +1 -1
- package/dist/client/assets/GitDialog-CA68baSd.js.br +0 -0
- package/dist/client/assets/GitDialog-CA68baSd.js.gz +0 -0
- package/dist/client/assets/{GitHubAccountDialog-CGZl3mcY.js → GitHubAccountDialog-CnxfR0JD.js} +1 -1
- package/dist/client/assets/GitHubAccountDialog-CnxfR0JD.js.br +0 -0
- package/dist/client/assets/GitHubAccountDialog-CnxfR0JD.js.gz +0 -0
- package/dist/client/assets/{HistoryDialog-DTZxCgyT.js → HistoryDialog-c2EEaFsl.js} +1 -1
- package/dist/client/assets/HistoryDialog-c2EEaFsl.js.br +0 -0
- package/dist/client/assets/HistoryDialog-c2EEaFsl.js.gz +0 -0
- package/dist/client/assets/{InfoPopover-Ba7GvcuW.js → InfoPopover-BJYnFn1P.js} +1 -1
- package/dist/client/assets/{LatexEditor-Boc-45KL.js → LatexEditor-vNOVTIl7.js} +1 -1
- package/dist/client/assets/LatexEditor-vNOVTIl7.js.br +0 -0
- package/dist/client/assets/LatexEditor-vNOVTIl7.js.gz +0 -0
- package/dist/client/assets/{MarkdownPreview-BH2iwvle.js → MarkdownPreview-BJPqGTcw.js} +1 -1
- package/dist/client/assets/MarkdownPreview-BJPqGTcw.js.br +0 -0
- package/dist/client/assets/MarkdownPreview-BJPqGTcw.js.gz +0 -0
- package/dist/client/assets/{ProjectIconPickerDialog-Bfkaxcnh.js → ProjectIconPickerDialog-ChiEUQ0g.js} +1 -1
- package/dist/client/assets/ProjectIconPickerDialog-ChiEUQ0g.js.br +0 -0
- package/dist/client/assets/ProjectIconPickerDialog-ChiEUQ0g.js.gz +0 -0
- package/dist/client/assets/{ProjectSearchDialog-DPIzxVYj.js → ProjectSearchDialog-DxgjbnmY.js} +1 -1
- package/dist/client/assets/ProjectSearchDialog-DxgjbnmY.js.br +0 -0
- package/dist/client/assets/ProjectSearchDialog-DxgjbnmY.js.gz +0 -0
- package/dist/client/assets/{ProjectSettings-ChXx_cmP.js → ProjectSettings-BwQTbXhh.js} +1 -1
- package/dist/client/assets/ProjectSettings-BwQTbXhh.js.br +0 -0
- package/dist/client/assets/ProjectSettings-BwQTbXhh.js.gz +0 -0
- package/dist/client/assets/ProjectWorkspace-C2QAb-Fc.js +25 -0
- package/dist/client/assets/ProjectWorkspace-C2QAb-Fc.js.br +0 -0
- package/dist/client/assets/ProjectWorkspace-C2QAb-Fc.js.gz +0 -0
- package/dist/client/assets/{QuickOpenDialog-CHjPlBu2.js → QuickOpenDialog-B7NTqOpu.js} +1 -1
- package/dist/client/assets/QuickOpenDialog-B7NTqOpu.js.br +0 -0
- package/dist/client/assets/QuickOpenDialog-B7NTqOpu.js.gz +0 -0
- package/dist/client/assets/{ReadOnlySource-DKcmDg0e.js → ReadOnlySource-DIalHHvP.js} +1 -1
- package/dist/client/assets/{SelectionHistoryDialog-Dnj22E8N.js → SelectionHistoryDialog-BhOyneNx.js} +1 -1
- package/dist/client/assets/SelectionHistoryDialog-BhOyneNx.js.br +0 -0
- package/dist/client/assets/SelectionHistoryDialog-BhOyneNx.js.gz +0 -0
- package/dist/client/assets/{SharedProjectPage-l8GSYTm-.js → SharedProjectPage-s-khOyvB.js} +2 -2
- package/dist/client/assets/SharedProjectPage-s-khOyvB.js.br +0 -0
- package/dist/client/assets/SharedProjectPage-s-khOyvB.js.gz +0 -0
- package/dist/client/assets/{SystemMetricsDialog-DkmBA4o4.js → SystemMetricsDialog-Bycm88U1.js} +1 -1
- package/dist/client/assets/SystemMetricsDialog-Bycm88U1.js.br +0 -0
- package/dist/client/assets/SystemMetricsDialog-Bycm88U1.js.gz +0 -0
- package/dist/client/assets/{TagManagementDialog-BM1MRuwh.js → TagManagementDialog-DwUAA8uC.js} +1 -1
- package/dist/client/assets/TagManagementDialog-DwUAA8uC.js.br +0 -0
- package/dist/client/assets/TagManagementDialog-DwUAA8uC.js.gz +0 -0
- package/dist/client/assets/{ThemeSwitcher-dcvtWVCO.js → ThemeSwitcher-RSqZi7kx.js} +1 -1
- package/dist/client/assets/TikzGalleryDialog-Bqzl2256.css +1 -0
- package/dist/client/assets/TikzGalleryDialog-Bqzl2256.css.br +0 -0
- package/dist/client/assets/TikzGalleryDialog-Bqzl2256.css.gz +0 -0
- package/dist/client/assets/TikzGalleryDialog-CLAmKmS6.js +1 -0
- package/dist/client/assets/TikzGalleryDialog-CLAmKmS6.js.br +0 -0
- package/dist/client/assets/TikzGalleryDialog-CLAmKmS6.js.gz +0 -0
- package/dist/client/assets/WordCountDialog-ByxE-RUs.js +1 -0
- package/dist/client/assets/WordCountDialog-ByxE-RUs.js.br +0 -0
- package/dist/client/assets/WordCountDialog-ByxE-RUs.js.gz +0 -0
- package/dist/client/assets/{chktex-BrzPYHey.js → chktex-22lKGvKa.js} +1 -1
- package/dist/client/assets/{i18n-Dtn6w-qA.js → i18n-Wn96VbWM.js} +4 -4
- package/dist/client/assets/i18n-Wn96VbWM.js.br +0 -0
- package/dist/client/assets/i18n-Wn96VbWM.js.gz +0 -0
- package/dist/client/assets/{index-CPR6YZEf.js → index-CemLYDYL.js} +2 -2
- package/dist/client/assets/index-CemLYDYL.js.br +0 -0
- package/dist/client/assets/index-CemLYDYL.js.gz +0 -0
- package/dist/client/assets/index-DSF5eT29.css +1 -0
- package/dist/client/assets/index-DSF5eT29.css.br +0 -0
- package/dist/client/assets/index-DSF5eT29.css.gz +0 -0
- package/dist/client/assets/{relativeTime-mmWGtWRR.js → relativeTime-C-GTw3lA.js} +1 -1
- package/dist/client/assets/relativeTime-C-GTw3lA.js.br +0 -0
- package/dist/client/assets/relativeTime-C-GTw3lA.js.gz +0 -0
- package/dist/client/assets/sourceCursorStore-Dpoi7PAL.js +1 -0
- package/dist/client/assets/sourceCursorStore-Dpoi7PAL.js.br +0 -0
- package/dist/client/assets/sourceCursorStore-Dpoi7PAL.js.gz +0 -0
- package/dist/client/assets/{spellCheck-BTyLQAFH.js → spellCheck-kxvnxrvw.js} +1 -1
- package/dist/client/assets/spellCheck-kxvnxrvw.js.br +0 -0
- package/dist/client/assets/spellCheck-kxvnxrvw.js.gz +0 -0
- package/dist/client/assets/{useDeletionTransitions-Ba_yhkrl.js → useDeletionTransitions-Xlq7HabP.js} +1 -1
- package/dist/client/assets/useDeletionTransitions-Xlq7HabP.js.br +0 -0
- package/dist/client/assets/useDeletionTransitions-Xlq7HabP.js.gz +0 -0
- package/dist/client/index.html +3 -3
- package/dist/server/agents/workspaces.js +14 -1
- package/dist/server/app.js +2 -0
- package/dist/server/cli.js +12 -1
- package/dist/server/config.js +10 -0
- package/dist/server/i18n.js +6 -0
- package/dist/server/locales/zh-Hant.js +3 -0
- package/dist/server/routes/compile.js +56 -4
- package/dist/server/routes/system.js +1 -0
- package/dist/server/routes/tikzGallery.js +38 -0
- package/dist/server/tikzEditorAddon.js +115 -0
- package/dist/server/tikzEditorRelease.js +9 -0
- package/dist/server/tikzGallery.js +63 -0
- package/dist/shared/tikzStandalone.js +15 -0
- package/package.json +2 -1
- package/templates/agents/AGENTS.md +12 -0
- package/texlite.config.example.json +4 -0
- package/dist/client/assets/AdminUsers-DepqkT6m.js.br +0 -0
- package/dist/client/assets/AdminUsers-DepqkT6m.js.gz +0 -0
- package/dist/client/assets/AgentIcon-DeoZDwgh.css.br +0 -0
- package/dist/client/assets/AgentIcon-DeoZDwgh.css.gz +0 -0
- package/dist/client/assets/AgentManagement-DlV6tHez.js.br +0 -0
- package/dist/client/assets/AgentManagement-DlV6tHez.js.gz +0 -0
- package/dist/client/assets/AgentTerminal-CvOz5X_j.js +0 -2
- package/dist/client/assets/AgentTerminal-CvOz5X_j.js.br +0 -0
- package/dist/client/assets/AgentTerminal-CvOz5X_j.js.gz +0 -0
- package/dist/client/assets/AgentTerminalSurface-COqg_GdK.js +0 -16
- package/dist/client/assets/AgentTerminalSurface-COqg_GdK.js.br +0 -0
- package/dist/client/assets/AgentTerminalSurface-COqg_GdK.js.gz +0 -0
- package/dist/client/assets/AvatarSettingsDialog-C8WQhZBK.js.br +0 -0
- package/dist/client/assets/AvatarSettingsDialog-C8WQhZBK.js.gz +0 -0
- package/dist/client/assets/CitationLibraryDialog-DgOIkLwK.js.br +0 -0
- package/dist/client/assets/CitationLibraryDialog-DgOIkLwK.js.gz +0 -0
- package/dist/client/assets/Dashboard-CD1w42mA.js.br +0 -0
- package/dist/client/assets/Dashboard-CD1w42mA.js.gz +0 -0
- package/dist/client/assets/GitDialog-DGzZ3GRj.js.br +0 -0
- package/dist/client/assets/GitDialog-DGzZ3GRj.js.gz +0 -0
- package/dist/client/assets/GitHubAccountDialog-CGZl3mcY.js.br +0 -0
- package/dist/client/assets/GitHubAccountDialog-CGZl3mcY.js.gz +0 -0
- package/dist/client/assets/HistoryDialog-DTZxCgyT.js.br +0 -0
- package/dist/client/assets/HistoryDialog-DTZxCgyT.js.gz +0 -0
- package/dist/client/assets/LatexEditor-Boc-45KL.js.br +0 -0
- package/dist/client/assets/LatexEditor-Boc-45KL.js.gz +0 -0
- package/dist/client/assets/MarkdownPreview-BH2iwvle.js.br +0 -0
- package/dist/client/assets/MarkdownPreview-BH2iwvle.js.gz +0 -0
- package/dist/client/assets/ProjectIconPickerDialog-Bfkaxcnh.js.br +0 -0
- package/dist/client/assets/ProjectIconPickerDialog-Bfkaxcnh.js.gz +0 -0
- package/dist/client/assets/ProjectSearchDialog-DPIzxVYj.js.br +0 -0
- package/dist/client/assets/ProjectSearchDialog-DPIzxVYj.js.gz +0 -0
- package/dist/client/assets/ProjectSettings-ChXx_cmP.js.br +0 -0
- package/dist/client/assets/ProjectSettings-ChXx_cmP.js.gz +0 -0
- package/dist/client/assets/ProjectWorkspace-B-w2ix8N.js +0 -25
- package/dist/client/assets/ProjectWorkspace-B-w2ix8N.js.br +0 -0
- package/dist/client/assets/ProjectWorkspace-B-w2ix8N.js.gz +0 -0
- package/dist/client/assets/QuickOpenDialog-CHjPlBu2.js.br +0 -0
- package/dist/client/assets/QuickOpenDialog-CHjPlBu2.js.gz +0 -0
- package/dist/client/assets/SelectionHistoryDialog-Dnj22E8N.js.br +0 -0
- package/dist/client/assets/SelectionHistoryDialog-Dnj22E8N.js.gz +0 -0
- package/dist/client/assets/SharedProjectPage-l8GSYTm-.js.br +0 -0
- package/dist/client/assets/SharedProjectPage-l8GSYTm-.js.gz +0 -0
- package/dist/client/assets/SystemMetricsDialog-DkmBA4o4.js.br +0 -0
- package/dist/client/assets/SystemMetricsDialog-DkmBA4o4.js.gz +0 -0
- package/dist/client/assets/TagManagementDialog-BM1MRuwh.js.br +0 -0
- package/dist/client/assets/TagManagementDialog-BM1MRuwh.js.gz +0 -0
- package/dist/client/assets/WordCountDialog-DI0Jv-fg.js +0 -1
- package/dist/client/assets/WordCountDialog-DI0Jv-fg.js.br +0 -0
- package/dist/client/assets/WordCountDialog-DI0Jv-fg.js.gz +0 -0
- package/dist/client/assets/i18n-Dtn6w-qA.js.br +0 -0
- package/dist/client/assets/i18n-Dtn6w-qA.js.gz +0 -0
- package/dist/client/assets/index-BbU2fbRw.css +0 -1
- package/dist/client/assets/index-BbU2fbRw.css.br +0 -0
- package/dist/client/assets/index-BbU2fbRw.css.gz +0 -0
- package/dist/client/assets/index-CPR6YZEf.js.br +0 -0
- package/dist/client/assets/index-CPR6YZEf.js.gz +0 -0
- package/dist/client/assets/relativeTime-mmWGtWRR.js.br +0 -0
- package/dist/client/assets/relativeTime-mmWGtWRR.js.gz +0 -0
- package/dist/client/assets/sourceCursorStore-BVDvDKeP.js +0 -1
- package/dist/client/assets/sourceCursorStore-BVDvDKeP.js.br +0 -0
- package/dist/client/assets/sourceCursorStore-BVDvDKeP.js.gz +0 -0
- package/dist/client/assets/spellCheck-BTyLQAFH.js.br +0 -0
- package/dist/client/assets/spellCheck-BTyLQAFH.js.gz +0 -0
- package/dist/client/assets/useDeletionTransitions-Ba_yhkrl.js.br +0 -0
- package/dist/client/assets/useDeletionTransitions-Ba_yhkrl.js.gz +0 -0
- /package/dist/client/assets/{AgentIcon-CA-PfOka.js → AgentIcon-qmglBc3M.js} +0 -0
- /package/dist/client/assets/{AgentIcon-CA-PfOka.js.br → AgentIcon-qmglBc3M.js.br} +0 -0
- /package/dist/client/assets/{AgentIcon-CA-PfOka.js.gz → AgentIcon-qmglBc3M.js.gz} +0 -0
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./spellCheck-kxvnxrvw.js","./index-CemLYDYL.js","./rolldown-runtime-XKyaHtl9.js","./react-DUEFWlB7.js","./useTranslation-DwkoADSz.js","./i18nInstance-CIMFwH0l.js","./i18n-Wn96VbWM.js","./basePath-B5-c90eh.js","./vite-runtime-CRzLMJPS.js","./createLucideIcon-CDYIzuiB.js","./loader-circle-DKGyi5EK.js","./dist-DdUqlCPw.js","./es2015-D2UDOM09.js","./index-DSF5eT29.css","./chktex-22lKGvKa.js","./LatexEditor-vNOVTIl7.js","./useDeletionTransitions-Xlq7HabP.js","./dist-B_WjsTVV.js","./editor-CkUEg2La.js","./editorThemeExtension-BWtZV1Af.js","./generatedParser-CZa2vsK6.js","./latexScanner-D9bMX44Y.js","./citationAuthors-BWHXhKvT.js","./bibtexNames-CPGbBJxd.js","./bibtexReferences-xpSF8IXH.js","./textLanguages-CwWstpJ5.js","./MarkdownPreview-BJPqGTcw.js","./MarkdownContent-BeKi2gI5.js","./katex.min-VLoWtPY0.js","./katex-CvRo0776.css","./katex-Ca9qmXPj.js","./CitationLibraryDialog-DqO9e0GV.js","./relativeTime-C-GTw3lA.js","./check-Dw16EqG-.js","./chevron-up-BHaMUEEA.js","./TagMarquee-BLmCTTCt.js","./InfoPopover-BJYnFn1P.js","./library-big-B8e_Fiql.js","./plus-Cei21TlT.js","./SaveButton-wiTpGLho.js","./circle-check-CunlnBPw.js","./search-DjOWqLig.js","./dist-C9O-A_C4.js","./citationLibrary-DxGdbZEQ.js","./SuccessNotice-ubBtzzi_.js","./TagColorSelect-e-Tq5V3H.js","./GitDialog-CA68baSd.js","./GitHubIcon-CExJn0AV.js","./git-compare-arrows-158rS_vn.js","./minimize-2-CkBmeGXp.js","./minus-DrpwqY8Y.js","./HistoryDialog-c2EEaFsl.js","./clock-3-DztJubz_.js","./sourceCursorStore-Dpoi7PAL.js","./hard-drive-CXlummIE.js","./dist-Dxkdrap6.js","./SelectionHistoryDialog-BhOyneNx.js","./bot-ClmnQ29j.js","./TikzGalleryDialog-CLAmKmS6.js","./TikzGalleryDialog-Bqzl2256.css","./QuickOpenDialog-B7NTqOpu.js","./ProjectSearchDialog-DxgjbnmY.js","./ProjectSettings-BwQTbXhh.js","./palette-8_-Y5XON.js","./refresh-cw-IqExWG6S.js","./terminal-DD9WJ56e.js","./type-CKe1tHHo.js","./AgentTerminal-DZo-22RN.js","./AgentIcon-qmglBc3M.js","./AgentIcon-DJGGRJnV.css","./WordCountDialog-ByxE-RUs.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{n as e,r as t}from"./rolldown-runtime-XKyaHtl9.js";import{i as n,r,t as i}from"./react-DUEFWlB7.js";import{_ as a,b as o,g as s,h as c,i as l,m as u,n as d,p as f,t as p,u as m,v as h,x as g,y as _}from"./relativeTime-C-GTw3lA.js";import{t as v}from"./useTranslation-DwkoADSz.js";import{t as y}from"./i18n-Wn96VbWM.js";import{r as b,t as x}from"./basePath-B5-c90eh.js";import{t as S}from"./vite-runtime-CRzLMJPS.js";import{t as C}from"./createLucideIcon-CDYIzuiB.js";import{t as w}from"./arrow-down-C_4f1E-E.js";import{B as T,D as E,E as D,H as O,P as k,R as A,S as j,T as M,U as ee,_ as N,b as P,c as te,d as F,h as ne,j as I,k as re,m as ie,o as ae,p as L,s as R,u as oe,v as se,w as ce,x as z,y as le,z as B}from"./useDeletionTransitions-Xlq7HabP.js";import{t as V}from"./check-Dw16EqG-.js";import{o as H}from"./dist-B_WjsTVV.js";import{t as ue}from"./chevron-up-BHaMUEEA.js";import{t as de}from"./circle-check-CunlnBPw.js";import{C as fe,D as pe,E as me,O as he,S as ge,_ as _e,b as ve,c as ye,d as be,f as xe,g as Se,h as Ce,l as we,m as Te,n as Ee,o as De,p as Oe,r as ke,s as Ae,t as je,u as Me,v as Ne,w as Pe,x as Fe,y as Ie}from"./sourceCursorStore-Dpoi7PAL.js";import{t as Le}from"./InfoPopover-BJYnFn1P.js";import{t as Re}from"./loader-circle-DKGyi5EK.js";import{t as ze}from"./plus-Cei21TlT.js";import{t as Be}from"./refresh-cw-IqExWG6S.js";import{t as Ve}from"./SaveButton-wiTpGLho.js";import{t as He}from"./user-plus-NNBQOWDP.js";import{C as Ue,D as U,E as We,O as Ge,S as Ke,a as qe,c as Je,f as Ye,g as Xe,h as Ze,k as Qe,l as $e,m as W,o as et,s as tt,u as nt,w as G,y as K}from"./index-CemLYDYL.js";import{a as rt,i as it,l as at,n as ot,o as st,r as ct,s as lt,t as ut}from"./dist-C9O-A_C4.js";import{a as dt,c as ft,h as pt,m as mt,n as ht,p as gt,s as _t,t as vt}from"./latexScanner-D9bMX44Y.js";import{r as yt}from"./dist-Dxkdrap6.js";var bt={name:`arrow-right`,size:24,node:[[`path`,{d:`M5 12h14`,key:`1ays0h`}],[`path`,{d:`m12 5 7 7-7 7`,key:`xquz4c`}]]};bt.node;var xt=C(bt),St={name:`arrow-up`,size:24,node:[[`path`,{d:`m5 12 7-7 7 7`,key:`hav0vg`}],[`path`,{d:`M12 19V5`,key:`x0mq9r`}]]};St.node;var Ct=C(St),wt={name:`circle-question-mark`,size:24,node:[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3`,key:`1u773s`}],[`path`,{d:`M12 17h.01`,key:`p32p05`}]],aliases:[`help-circle`,`circle-help`]};wt.node;var Tt=C(wt),Et={name:`circle-x`,size:24,node:[[`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`}]],aliases:[`x-circle`]};Et.node;var Dt=C(Et),Ot={name:`eraser`,size:24,node:[[`path`,{d:`M21 21H8a2 2 0 0 1-1.42-.587l-3.994-3.999a2 2 0 0 1 0-2.828l10-10a2 2 0 0 1 2.829 0l5.999 6a2 2 0 0 1 0 2.828L12.834 21`,key:`g5wo59`}],[`path`,{d:`m5.082 11.09 8.828 8.828`,key:`1wx5vj`}]]};Ot.node;var kt=C(Ot),At={name:`file-output`,size:24,node:[[`path`,{d:`M4.226 20.925A2 2 0 0 0 6 22h12a2 2 0 0 0 2-2V8a2.4 2.4 0 0 0-.706-1.706l-3.588-3.588A2.4 2.4 0 0 0 14 2H6a2 2 0 0 0-2 2v3.127`,key:`wfxp4w`}],[`path`,{d:`M14 2v5a1 1 0 0 0 1 1h5`,key:`wfsgrz`}],[`path`,{d:`m5 11-3 3`,key:`1dgrs4`}],[`path`,{d:`m5 17-3-3h10`,key:`1mvvaf`}]]};At.node;var jt=C(At),Mt={name:`keyboard`,size:24,node:[[`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`}]]};Mt.node;var Nt=C(Mt),Pt={name:`link`,size:24,node:[[`path`,{d:`M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71`,key:`1cjeqo`}],[`path`,{d:`M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71`,key:`19qd67`}]]};Pt.node;var Ft=C(Pt),It={name:`logs`,size:24,node:[[`path`,{d:`M3 5h1`,key:`1mv5vm`}],[`path`,{d:`M3 12h1`,key:`lp3yf2`}],[`path`,{d:`M3 19h1`,key:`w6f3n9`}],[`path`,{d:`M8 5h1`,key:`1nxr5w`}],[`path`,{d:`M8 12h1`,key:`1con00`}],[`path`,{d:`M8 19h1`,key:`k7p10e`}],[`path`,{d:`M13 5h8`,key:`a7qcls`}],[`path`,{d:`M13 12h8`,key:`h98zly`}],[`path`,{d:`M13 19h8`,key:`c3s6r1`}]]};It.node;var Lt=C(It),Rt={name:`messages-square`,size:24,node:[[`path`,{d:`M16 10a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 14.286V4a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z`,key:`1n2ejm`}],[`path`,{d:`M20 9a2 2 0 0 1 2 2v10.286a.71.71 0 0 1-1.212.502l-2.202-2.202A2 2 0 0 0 17.172 19H10a2 2 0 0 1-2-2v-1`,key:`1qfcsi`}]]};Rt.node;var zt=C(Rt),Bt={name:`package-open`,size:24,node:[[`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`}]]};Bt.node;var Vt=C(Bt),Ht={name:`rotate-ccw`,size:24,node:[[`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`}]]};Ht.node;var Ut=C(Ht),Wt={name:`send`,size:24,node:[[`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`}]]};Wt.node;var Gt=C(Wt),q=t(n(),1),J=i(),Kt=()=>new Map,qt=e=>{let t=Kt();return e.forEach((e,n)=>{t.set(n,e)}),t},Jt=(e,t,n)=>{let r=e.get(t);return r===void 0&&e.set(t,r=n()),r},Yt=(e,t)=>{let n=[];for(let[r,i]of e)n.push(t(i,r));return n},Xt=(e,t)=>{for(let[n,r]of e)if(t(r,n))return!0;return!1},Zt=()=>new Set,Qt=e=>e[e.length-1],$t=(e,t)=>{for(let n=0;n<t.length;n++)e.push(t[n])},en=Array.from,tn=(e,t)=>{for(let n=0;n<e.length;n++)if(!t(e[n],n,e))return!1;return!0},nn=(e,t)=>{for(let n=0;n<e.length;n++)if(t(e[n],n,e))return!0;return!1},rn=(e,t)=>{let n=Array(e);for(let r=0;r<e;r++)n[r]=t(r,n);return n},an=Array.isArray,on=class{constructor(){this._observers=Kt()}on(e,t){return Jt(this._observers,e,Zt).add(t),t}once(e,t){let n=(...r)=>{this.off(e,n),t(...r)};this.on(e,n)}off(e,t){let n=this._observers.get(e);n!==void 0&&(n.delete(t),n.size===0&&this._observers.delete(e))}emit(e,t){return en((this._observers.get(e)||Kt()).values()).forEach(e=>e(...t))}destroy(){this._observers=Kt()}},sn=class{constructor(){this._observers=Kt()}on(e,t){Jt(this._observers,e,Zt).add(t)}once(e,t){let n=(...r)=>{this.off(e,n),t(...r)};this.on(e,n)}off(e,t){let n=this._observers.get(e);n!==void 0&&(n.delete(t),n.size===0&&this._observers.delete(e))}emit(e,t){return en((this._observers.get(e)||Kt()).values()).forEach(e=>e(...t))}destroy(){this._observers=Kt()}},cn=Math.floor,ln=Math.abs,un=(e,t)=>e<t?e:t,dn=(e,t)=>e>t?e:t;Number.isNaN;var fn=Math.pow,pn=e=>e===0?1/e<0:e<0,mn=1<<29,hn=2**53-1,gn=-(2**53-1),_n=Number.isInteger||(e=>typeof e==`number`&&isFinite(e)&&cn(e)===e);Number.isNaN,Number.parseInt;var vn=String.fromCharCode;String.fromCodePoint,vn(65535);var yn=e=>e.toLowerCase(),bn=/^\s*/g,xn=e=>e.replace(bn,``),Sn=/([A-Z])/g,Cn=(e,t)=>xn(e.replace(Sn,e=>`${t}${yn(e)}`)),wn=e=>{let t=unescape(encodeURIComponent(e)),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.codePointAt(e);return r},Tn=typeof TextEncoder<`u`?new TextEncoder:null,En=Tn?e=>Tn.encode(e):wn,Dn=typeof TextDecoder>`u`?null:new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0});Dn&&Dn.decode(new Uint8Array).length===1&&(Dn=null);var On=(e,t)=>rn(t,()=>e).join(``),kn=class{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}},An=()=>new kn,jn=e=>{let t=e.cpos;for(let n=0;n<e.bufs.length;n++)t+=e.bufs[n].length;return t},Y=e=>{let t=new Uint8Array(jn(e)),n=0;for(let r=0;r<e.bufs.length;r++){let i=e.bufs[r];t.set(i,n),n+=i.length}return t.set(new Uint8Array(e.cbuf.buffer,0,e.cpos),n),t},Mn=(e,t)=>{let n=e.cbuf.length;n-e.cpos<t&&(e.bufs.push(new Uint8Array(e.cbuf.buffer,0,e.cpos)),e.cbuf=new Uint8Array(dn(n,t)*2),e.cpos=0)},X=(e,t)=>{let n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},Nn=X,Z=(e,t)=>{for(;t>127;)X(e,128|127&t),t=cn(t/128);X(e,127&t)},Pn=(e,t)=>{let n=pn(t);for(n&&(t=-t),X(e,(t>63?128:0)|(n?64:0)|63&t),t=cn(t/64);t>0;)X(e,(t>127?128:0)|127&t),t=cn(t/128)},Fn=new Uint8Array(3e4),In=Fn.length/3,Ln=Tn&&Tn.encodeInto?(e,t)=>{if(t.length<In){let n=Tn.encodeInto(t,Fn).written||0;Z(e,n);for(let t=0;t<n;t++)X(e,Fn[t])}else zn(e,En(t))}:(e,t)=>{let n=unescape(encodeURIComponent(t)),r=n.length;Z(e,r);for(let t=0;t<r;t++)X(e,n.codePointAt(t))},Rn=(e,t)=>{let n=e.cbuf.length,r=e.cpos,i=un(n-r,t.length),a=t.length-i;e.cbuf.set(t.subarray(0,i),r),e.cpos+=i,a>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(dn(n*2,a)),e.cbuf.set(t.subarray(i)),e.cpos=a)},zn=(e,t)=>{Z(e,t.byteLength),Rn(e,t)},Bn=(e,t)=>{Mn(e,t);let n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},Vn=(e,t)=>Bn(e,4).setFloat32(0,t,!1),Hn=(e,t)=>Bn(e,8).setFloat64(0,t,!1),Un=(e,t)=>Bn(e,8).setBigInt64(0,t,!1),Wn=new DataView(new ArrayBuffer(4)),Gn=e=>(Wn.setFloat32(0,e),Wn.getFloat32(0)===e),Kn=(e,t)=>{switch(typeof t){case`string`:X(e,119),Ln(e,t);break;case`number`:_n(t)&&ln(t)<=2147483647?(X(e,125),Pn(e,t)):Gn(t)?(X(e,124),Vn(e,t)):(X(e,123),Hn(e,t));break;case`bigint`:X(e,122),Un(e,t);break;case`object`:if(t===null)X(e,126);else if(an(t)){X(e,117),Z(e,t.length);for(let n=0;n<t.length;n++)Kn(e,t[n])}else if(t instanceof Uint8Array)X(e,116),zn(e,t);else{X(e,118);let n=Object.keys(t);Z(e,n.length);for(let r=0;r<n.length;r++){let i=n[r];Ln(e,i),Kn(e,t[i])}}break;case`boolean`:X(e,t?120:121);break;default:X(e,127)}},qn=class extends kn{constructor(e){super(),this.w=e,this.s=null,this.count=0}write(e){this.s===e?this.count++:(this.count>0&&Z(this,this.count-1),this.count=1,this.w(this,e),this.s=e)}},Jn=e=>{e.count>0&&(Pn(e.encoder,e.count===1?e.s:-e.s),e.count>1&&Z(e.encoder,e.count-2))},Yn=class{constructor(){this.encoder=new kn,this.s=0,this.count=0}write(e){this.s===e?this.count++:(Jn(this),this.count=1,this.s=e)}toUint8Array(){return Jn(this),Y(this.encoder)}},Xn=e=>{if(e.count>0){let t=e.diff*2+(e.count===1?0:1);Pn(e.encoder,t),e.count>1&&Z(e.encoder,e.count-2)}},Zn=class{constructor(){this.encoder=new kn,this.s=0,this.count=0,this.diff=0}write(e){this.diff===e-this.s?(this.s=e,this.count++):(Xn(this),this.count=1,this.diff=e-this.s,this.s=e)}toUint8Array(){return Xn(this),Y(this.encoder)}},Qn=class{constructor(){this.sarr=[],this.s=``,this.lensE=new Yn}write(e){this.s+=e,this.s.length>19&&(this.sarr.push(this.s),this.s=``),this.lensE.write(e.length)}toUint8Array(){let e=new kn;return this.sarr.push(this.s),this.s=``,Ln(e,this.sarr.join(``)),Rn(e,this.lensE.toUint8Array()),Y(e)}},$n=e=>Error(e),er=()=>{throw $n(`Method unimplemented`)},tr=()=>{throw $n(`Unexpected case`)},nr=$n(`Unexpected end of array`),rr=$n(`Integer out of Range`),ir=class{constructor(e){this.arr=e,this.pos=0}},ar=e=>new ir(e),or=e=>e.pos!==e.arr.length,sr=(e,t)=>{let n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},cr=e=>sr(e,Q(e)),lr=e=>e.arr[e.pos++],Q=e=>{let t=0,n=1,r=e.arr.length;for(;e.pos<r;){let r=e.arr[e.pos++];if(t+=(r&127)*n,n*=128,r<128)return t;if(t>hn)throw rr}throw nr},ur=e=>{let t=e.arr[e.pos++],n=t&63,r=64,i=(t&64)>0?-1:1;if(!(t&128))return i*n;let a=e.arr.length;for(;e.pos<a;){if(t=e.arr[e.pos++],n+=(t&127)*r,r*=128,t<128)return i*n;if(n>hn)throw rr}throw nr},dr=Dn?e=>Dn.decode(cr(e)):e=>{let t=Q(e);if(t===0)return``;{let n=String.fromCodePoint(lr(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(lr(e));else for(;t>0;){let r=t<1e4?t:1e4,i=e.arr.subarray(e.pos,e.pos+r);e.pos+=r,n+=String.fromCodePoint.apply(null,i),t-=r}return decodeURIComponent(escape(n))}},fr=(e,t)=>{let n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},pr=[e=>void 0,e=>null,ur,e=>fr(e,4).getFloat32(0,!1),e=>fr(e,8).getFloat64(0,!1),e=>fr(e,8).getBigInt64(0,!1),e=>!1,e=>!0,dr,e=>{let t=Q(e),n={};for(let r=0;r<t;r++){let t=dr(e);n[t]=mr(e)}return n},e=>{let t=Q(e),n=[];for(let r=0;r<t;r++)n.push(mr(e));return n},cr],mr=e=>pr[127-lr(e)](e),hr=class extends ir{constructor(e,t){super(e),this.reader=t,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),this.count=or(this)?Q(this)+1:-1),this.count--,this.s}},gr=class extends ir{constructor(e){super(e),this.s=0,this.count=0}read(){if(this.count===0){this.s=ur(this);let e=pn(this.s);this.count=1,e&&(this.s=-this.s,this.count=Q(this)+2)}return this.count--,this.s}},_r=class extends ir{constructor(e){super(e),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){let e=ur(this),t=e&1;this.diff=cn(e/2),this.count=1,t&&(this.count=Q(this)+2)}return this.s+=this.diff,this.count--,this.s}},vr=class{constructor(e){this.decoder=new gr(e),this.str=dr(this.decoder),this.spos=0}read(){let e=this.spos+this.decoder.read(),t=this.str.slice(this.spos,e);return this.spos=e,t}};crypto.subtle;var yr=crypto.getRandomValues.bind(crypto),br=()=>yr(new Uint32Array(1))[0],xr=`10000000-1000-4000-8000-100000000000`,Sr=()=>xr.replace(/[018]/g,e=>(e^br()&15>>e/4).toString(16)),Cr=Date.now,wr=e=>new Promise(e);Promise.all.bind(Promise);var Tr=e=>e===void 0?null:e,Er=new class{constructor(){this.map=new Map}setItem(e,t){this.map.set(e,t)}getItem(e){return this.map.get(e)}},Dr=!0;try{typeof localStorage<`u`&&localStorage&&(Er=localStorage,Dr=!1)}catch{}var Or=Er,kr=e=>Dr||addEventListener(`storage`,e),Ar=e=>Dr||removeEventListener(`storage`,e),jr=Symbol(`Equality`),Mr=(e,t)=>e===t||!!e?.[jr]?.(t)||!1,Nr=e=>typeof e==`object`,Pr=Object.assign,Fr=Object.keys,Ir=(e,t)=>{for(let n in e)t(e[n],n)},Lr=(e,t)=>{let n=[];for(let r in e)n.push(t(e[r],r));return n},Rr=e=>Fr(e).length,zr=e=>{for(let t in e)return!1;return!0},Br=(e,t)=>{for(let n in e)if(!t(e[n],n))return!1;return!0},Vr=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Hr=(e,t)=>e===t||Rr(e)===Rr(t)&&Br(e,(e,n)=>(e!==void 0||Vr(t,n))&&Mr(t[n],e)),Ur=Object.freeze,Wr=e=>{for(let t in e){let n=e[t];(typeof n==`object`||typeof n==`function`)&&Wr(e[t])}return Ur(e)},Gr=(e,t,n=0)=>{try{for(;n<e.length;n++)e[n](...t)}finally{n<e.length&&Gr(e,t,n+1)}},Kr=e=>e,qr=(e,t)=>{if(e===t)return!0;if(e==null||t==null||e.constructor!==t.constructor&&(e.constructor||Object)!==(t.constructor||Object))return!1;if(e[jr]!=null)return e[jr](t);switch(e.constructor){case ArrayBuffer:e=new Uint8Array(e),t=new Uint8Array(t);case Uint8Array:if(e.byteLength!==t.byteLength)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;break;case Set:if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;break;case Map:if(e.size!==t.size)return!1;for(let n of e.keys())if(!t.has(n)||!qr(e.get(n),t.get(n)))return!1;break;case void 0:case Object:if(Rr(e)!==Rr(t))return!1;for(let n in e)if(!Vr(e,n)||!qr(e[n],t[n]))return!1;break;case Array:if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!qr(e[n],t[n]))return!1;break;default:return!1}return!0},Jr=(e,t)=>t.includes(e),Yr=typeof process<`u`&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<`u`?process:0)===`[object process]`,Xr=typeof window<`u`&&typeof document<`u`&&!Yr;typeof navigator<`u`&&/Mac/.test(navigator.platform);var Zr,Qr=[],$r=()=>{if(Zr===void 0){if(Yr){Zr=Kt();let e=process.argv,t=null;for(let n=0;n<e.length;n++){let r=e[n];r[0]===`-`?(t!==null&&Zr.set(t,``),t=r):t===null?Qr.push(r):(Zr.set(t,r),t=null)}t!==null&&Zr.set(t,``)}else typeof location==`object`?(Zr=Kt(),(location.search||`?`).slice(1).split(`&`).forEach(e=>{if(e.length!==0){let[t,n]=e.split(`=`);Zr.set(`--${Cn(t,`-`)}`,n),Zr.set(`-${Cn(t,`-`)}`,n)}})):Zr=Kt()}return Zr},ei=e=>$r().has(e),ti=e=>Tr(Yr?{}[e.toUpperCase().replaceAll(`-`,`_`)]:Or.getItem(e)),ni=e=>ei(`--`+e)||ti(e)!==null,ri=ni(`production`),ii=Yr&&Jr({}.FORCE_COLOR,[`true`,`1`,`2`])||!ei(`--no-colors`)&&!ni(`no-color`)&&(!Yr||process.stdout.isTTY)&&(!Yr||ei(`--color`)||ti(`COLORTERM`)!==null||(ti(`TERM`)||``).includes(`color`)),ai=e=>new Uint8Array(e),oi=(e,t,n)=>new Uint8Array(e,t,n),si=e=>new Uint8Array(e),ci=e=>{let t=``;for(let n=0;n<e.byteLength;n++)t+=vn(e[n]);return btoa(t)},li=e=>Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString(`base64`),ui=e=>{let t=atob(e),n=ai(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n},di=e=>{let t=Buffer.from(e,`base64`);return oi(t.buffer,t.byteOffset,t.byteLength)},fi=Xr?ci:li,pi=Xr?ui:di,mi=e=>{let t=ai(e.byteLength);return t.set(e),t},hi=class{constructor(e,t){this.left=e,this.right=t}},gi=(e,t)=>new hi(e,t),_i=(e,t)=>e.forEach(e=>t(e.left,e.right)),vi=e=>e.next()>=.5,yi=(e,t,n)=>cn(e.next()*(n+1-t)+t),bi=(e,t,n)=>cn(e.next()*(n+1-t)+t),xi=(e,t,n)=>bi(e,t,n),Si=e=>vn(xi(e,97,122)),Ci=(e,t=0,n=20)=>{let r=xi(e,t,n),i=``;for(let t=0;t<r;t++)i+=Si(e);return i},wi=(e,t)=>t[xi(e,0,t.length-1)],Ti=Symbol(`0schema`),Ei=class{constructor(){this._rerrs=[]}extend(e,t,n,r=null){this._rerrs.push({path:e,expected:t,has:n,message:r})}toString(){let e=[];for(let t=this._rerrs.length-1;t>0;t--){let n=this._rerrs[t];e.push(On(` `,(this._rerrs.length-t)*2)+`${n.path==null?``:`[${n.path}] `}${n.has} doesn't match ${n.expected}. ${n.message}`)}return e.join(`
|
|
3
|
+
`)}},Di=(e,t)=>e===t?!0:e==null||t==null||e.constructor!==t.constructor?!1:e[jr]?Mr(e,t):an(e)?tn(e,e=>nn(t,t=>Di(e,t))):Nr(e)?Br(e,(e,n)=>Di(e,t[n])):!1,Oi=class{static _dilutes=!1;extends(e){let[t,n]=[this.shape,e.shape];return this.constructor._dilutes&&([n,t]=[t,n]),Di(t,n)}equals(e){return this.constructor===e.constructor&&qr(this.shape,e.shape)}[Ti](){return!0}[jr](e){return this.equals(e)}validate(e){return this.check(e)}check(e,t){er()}get nullable(){return sa(this,Sa)}get optional(){return new zi(this)}cast(e){return Ea(e,this),e}expect(e){return Ea(e,this),e}},ki=class extends Oi{constructor(e,t){super(),this.shape=e,this._c=t}check(e,t=void 0){let n=e?.constructor===this.shape&&(this._c==null||this._c(e));return!n&&t?.extend(null,this.shape.name,e?.constructor.name,e?.constructor===this.shape?`Check failed`:`Constructor match failed`),n}},Ai=(e,t=null)=>new ki(e,t);Ai(ki);var ji=class extends Oi{constructor(e){super(),this.shape=e}check(e,t){let n=this.shape(e);return!n&&t?.extend(null,`custom prop`,e?.constructor.name,`failed to check custom prop`),n}},Mi=e=>new ji(e);Ai(ji);var Ni=class extends Oi{constructor(e){super(),this.shape=e}check(e,t){let n=this.shape.some(t=>t===e);return!n&&t?.extend(null,this.shape.join(` | `),e.toString()),n}},Pi=(...e)=>new Ni(e),Fi=Ai(Ni),Ii=RegExp.escape||(e=>e.replace(/[().|&,$^[\]]/g,e=>`\\`+e)),Li=e=>{if(_a.check(e))return[Ii(e)];if(Fi.check(e))return e.shape.map(e=>e+``);if(ga.check(e))return[`[+-]?\\d+.?\\d*`];if(va.check(e))return[`.*`];if(ca.check(e))return e.shape.map(Li).flat(1);tr()};Ai(class extends Oi{constructor(e){super(),this.shape=e,this._r=RegExp(`^`+e.map(Li).map(e=>`(${e.join(`|`)})`).join(``)+`$`)}check(e,t){let n=this._r.exec(e)!=null;return!n&&t?.extend(null,this._r.toString(),e.toString(),`String doesn't match string template.`),n}});var Ri=Symbol(`optional`),zi=class extends Oi{constructor(e){super(),this.shape=e}check(e,t){let n=e===void 0||this.shape.check(e);return!n&&t?.extend(null,`undefined (optional)`,`()`),n}get[Ri](){return!0}},Bi=Ai(zi),Vi=class extends Oi{check(e,t){return t?.extend(null,`never`,typeof e),!1}};new Vi,Ai(Vi);var Hi=class e extends Oi{constructor(e,t=!1){super(),this.shape=e,this._isPartial=t}static _dilutes=!0;get partial(){return new e(this.shape,!0)}check(e,t){return e==null?(t?.extend(null,`object`,`null`),!1):Br(this.shape,(n,r)=>{let i=this._isPartial&&!Vr(e,r)||n.check(e[r],t);return!i&&t?.extend(r.toString(),n.toString(),typeof e[r],`Object property does not match`),i})}},Ui=e=>new Hi(e),Wi=Ai(Hi),Gi=Mi(e=>e!=null&&(e.constructor===Object||e.constructor==null)),Ki=class extends Oi{constructor(e,t){super(),this.shape={keys:e,values:t}}check(e,t){return e!=null&&Br(e,(n,r)=>{let i=this.shape.keys.check(r,t);return!i&&t?.extend(r+``,`Record`,typeof e,i?`Key doesn't match schema`:`Value doesn't match value`),i&&this.shape.values.check(n,t)})}},qi=(e,t)=>new Ki(e,t),Ji=Ai(Ki),Yi=class extends Oi{constructor(e){super(),this.shape=e}check(e,t){return e!=null&&Br(this.shape,(n,r)=>{let i=n.check(e[r],t);return!i&&t?.extend(r.toString(),`Tuple`,typeof n),i})}},Xi=(...e)=>new Yi(e);Ai(Yi);var Zi=class extends Oi{constructor(e){super(),this.shape=e.length===1?e[0]:new oa(e)}check(e,t){let n=an(e)&&tn(e,e=>this.shape.check(e));return!n&&t?.extend(null,`Array`,``),n}},Qi=(...e)=>new Zi(e),$i=Ai(Zi),ea=Mi(e=>an(e)),ta=class extends Oi{constructor(e,t){super(),this.shape=e,this._c=t}check(e,t){let n=e instanceof this.shape&&(this._c==null||this._c(e));return!n&&t?.extend(null,this.shape.name,e?.constructor.name),n}},na=(e,t=null)=>new ta(e,t);Ai(ta);var ra=na(Oi),ia=Ai(class extends Oi{constructor(e){super(),this.len=e.length-1,this.args=Xi(...e.slice(-1)),this.res=e[this.len]}check(e,t){let n=e.constructor===Function&&e.length<=this.len;return!n&&t?.extend(null,`function`,typeof e),n}}),aa=Mi(e=>typeof e==`function`);Ai(class extends Oi{constructor(e){super(),this.shape=e}check(e,t){let n=tn(this.shape,n=>n.check(e,t));return!n&&t?.extend(null,`Intersectinon`,typeof e),n}},e=>e.shape.length>0);var oa=class extends Oi{static _dilutes=!0;constructor(e){super(),this.shape=e}check(e,t){let n=nn(this.shape,n=>n.check(e,t));return t?.extend(null,`Union`,typeof e),n}},sa=(...e)=>e.findIndex(e=>ca.check(e))>=0?sa(...e.map(e=>Ta(e)).map(e=>ca.check(e)?e.shape:[e]).flat(1)):e.length===1?e[0]:new oa(e),ca=Ai(oa),la=()=>!0,ua=Mi(la),da=Ai(ji,e=>e.shape===la),fa=Mi(e=>typeof e==`bigint`),pa=Mi(e=>e===fa),ma=Mi(e=>typeof e==`symbol`);Mi(e=>e===ma);var ha=Mi(e=>typeof e==`number`),ga=Mi(e=>e===ha),_a=Mi(e=>typeof e==`string`),va=Mi(e=>e===_a),ya=Mi(e=>typeof e==`boolean`),ba=Mi(e=>e===ya),xa=Pi(void 0);Ai(Ni,e=>e.shape.length===1&&e.shape[0]===void 0),Pi(void 0);var Sa=Pi(null),Ca=Ai(Ni,e=>e.shape.length===1&&e.shape[0]===null);Ai(Uint8Array),Ai(ki,e=>e.shape===Uint8Array);var wa=sa(ha,_a,Sa,xa,fa,ya,ma);(()=>{let e=Qi(ua),t=qi(_a,ua),n=sa(ha,_a,Sa,ya,e,t);return e.shape=n,t.shape.values=n,n})();var Ta=e=>{if(ra.check(e))return e;if(Gi.check(e)){let t={};for(let n in e)t[n]=Ta(e[n]);return Ui(t)}if(ea.check(e))return sa(...e.map(Ta));if(wa.check(e))return Pi(e);if(aa.check(e))return Ai(e);tr()},Ea=ri?()=>{}:(e,t)=>{let n=new Ei;if(!t.check(e,n))throw $n(`Expected value to be of type ${t.constructor.name}.\n${n.toString()}`)},Da=class{constructor(e){this.patterns=[],this.$state=e}if(e,t){return this.patterns.push({if:Ta(e),h:t}),this}else(e){return this.if(ua,e)}done(){return(e,t)=>{for(let n=0;n<this.patterns.length;n++){let r=this.patterns[n];if(r.if.check(e))return r.h(e,t)}throw $n(`Unhandled pattern`)}}},Oa=(e=>new Da(e))(ua).if(ga,(e,t)=>yi(t,gn,hn)).if(va,(e,t)=>Ci(t)).if(ba,(e,t)=>vi(t)).if(pa,(e,t)=>BigInt(yi(t,gn,hn))).if(ca,(e,t)=>ka(t,wi(t,e.shape))).if(Wi,(e,t)=>{let n={};for(let r in e.shape){let i=e.shape[r];if(Bi.check(i)){if(vi(t))continue;i=i.shape}n[r]=Oa(i,t)}return n}).if($i,(e,t)=>{let n=[],r=bi(t,0,42);for(let i=0;i<r;i++)n.push(ka(t,e.shape));return n}).if(Fi,(e,t)=>wi(t,e.shape)).if(Ca,(e,t)=>null).if(ia,(e,t)=>{let n=ka(t,e.res);return()=>n}).if(da,(e,t)=>ka(t,wi(t,[ha,_a,Sa,xa,fa,ya,Qi(ha),qi(sa(`a`,`b`,`c`),ha)]))).if(Ji,(e,t)=>{let n={},r=yi(t,0,3);for(let i=0;i<r;i++){let r=ka(t,e.shape.keys);n[r]=ka(t,e.shape.values)}return n}).done(),ka=(e,t)=>Oa(Ta(t),e),Aa=typeof document<`u`?document:{},ja=e=>Aa.createElement(e),Ma=()=>Aa.createDocumentFragment();Mi(e=>e.nodeType===Wa);var Na=e=>Aa.createTextNode(e);typeof DOMParser<`u`&&new DOMParser;var Pa=(e,t)=>(_i(t,(t,n)=>{n===!1?e.removeAttribute(t):n===!0?e.setAttribute(t,``):e.setAttribute(t,n)}),e),Fa=e=>{let t=Ma();for(let n=0;n<e.length;n++)Ba(t,e[n]);return t},Ia=(e,t)=>(Ba(e,Fa(t)),e),La=(e,t=[],n=[])=>Ia(Pa(ja(e),t),n);Mi(e=>e.nodeType===Va);var Ra=Na;Mi(e=>e.nodeType===Ha);var za=e=>Yt(e,(e,t)=>`${t}:${e};`).join(``),Ba=(e,t)=>e.appendChild(t),Va=Aa.ELEMENT_NODE,Ha=Aa.TEXT_NODE;Aa.CDATA_SECTION_NODE,Aa.COMMENT_NODE;var Ua=Aa.DOCUMENT_NODE;Aa.DOCUMENT_TYPE_NODE;var Wa=Aa.DOCUMENT_FRAGMENT_NODE;Mi(e=>e.nodeType===Ua);var Ga=Symbol,Ka=Ga(),qa=Ga(),Ja=Ga(),Ya=Ga(),Xa=Ga(),Za=Ga(),Qa=Ga(),$a=Ga(),eo=Ga(),to=e=>{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());let t=[],n=[],r=0;for(;r<e.length;r++){let n=e[r];if(n===void 0)break;if(n.constructor===String||n.constructor===Number)t.push(n);else if(n.constructor===Object)break}for(r>0&&n.push(t.join(``));r<e.length;r++){let t=e[r];t instanceof Symbol||n.push(t)}return n};Cr();var no={[Ka]:gi(`font-weight`,`bold`),[qa]:gi(`font-weight`,`normal`),[Ja]:gi(`color`,`blue`),[Xa]:gi(`color`,`green`),[Ya]:gi(`color`,`grey`),[Za]:gi(`color`,`red`),[Qa]:gi(`color`,`purple`),[$a]:gi(`color`,`orange`),[eo]:gi(`color`,`black`)},ro=ii?e=>{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());let t=[],n=[],r=Kt(),i=[],a=0;for(;a<e.length;a++){let i=e[a],o=no[i];if(o!==void 0)r.set(o.left,o.right);else{if(i===void 0)break;if(i.constructor===String||i.constructor===Number){let e=za(r);a>0||e.length>0?(t.push(`%c`+i),n.push(e)):t.push(i)}else break}}for(a>0&&(i=n,i.unshift(t.join(``)));a<e.length;a++){let t=e[a];t instanceof Symbol||i.push(t)}return i}:to,io=(...e)=>{console.log(...ro(e)),oo.forEach(t=>t.print(e))},ao=(...e)=>{console.warn(...ro(e)),e.unshift($a),oo.forEach(t=>t.print(e))},oo=Zt(),so=e=>({[Symbol.iterator](){return this},next:e}),co=(e,t)=>so(()=>{let n;do n=e.next();while(!n.done&&!t(n.value));return n}),lo=(e,t)=>so(()=>{let{done:n,value:r}=e.next();return{done:n,value:n?void 0:t(r)}}),uo=class{constructor(e,t){this.clock=e,this.len=t}},fo=class{constructor(){this.clients=new Map}},po=(e,t,n)=>t.clients.forEach((t,r)=>{let i=e.doc.store.clients.get(r);if(i!=null){let r=i[i.length-1],a=r.id.clock+r.length;for(let r=0,o=t[r];r<t.length&&o.clock<a;o=t[++r])ks(e,i,o.clock,o.len,n)}}),mo=(e,t)=>{let n=0,r=e.length-1;for(;n<=r;){let i=cn((n+r)/2),a=e[i],o=a.clock;if(o<=t){if(t<o+a.len)return i;n=i+1}else r=i-1}return null},ho=(e,t)=>{let n=e.clients.get(t.client);return n!==void 0&&mo(n,t.clock)!==null},go=e=>{e.clients.forEach(e=>{e.sort((e,t)=>e.clock-t.clock);let t,n;for(t=1,n=1;t<e.length;t++){let r=e[n-1],i=e[t];r.clock+r.len>=i.clock?e[n-1]=new uo(r.clock,dn(r.len,i.clock+i.len-r.clock)):(n<t&&(e[n]=i),n++)}e.length=n})},_o=e=>{let t=new fo;for(let n=0;n<e.length;n++)e[n].clients.forEach((r,i)=>{if(!t.clients.has(i)){let a=r.slice();for(let t=n+1;t<e.length;t++)$t(a,e[t].clients.get(i)||[]);t.clients.set(i,a)}});return go(t),t},vo=(e,t,n,r)=>{Jt(e.clients,t,()=>[]).push(new uo(n,r))},yo=()=>new fo,bo=e=>{let t=yo();return e.clients.forEach((e,n)=>{let r=[];for(let t=0;t<e.length;t++){let n=e[t];if(n.deleted){let i=n.id.clock,a=n.length;if(t+1<e.length)for(let n=e[t+1];t+1<e.length&&n.deleted;n=e[++t+1])a+=n.length;r.push(new uo(i,a))}}r.length>0&&t.clients.set(n,r)}),t},xo=(e,t)=>{Z(e.restEncoder,t.clients.size),en(t.clients.entries()).sort((e,t)=>t[0]-e[0]).forEach(([t,n])=>{e.resetDsCurVal(),Z(e.restEncoder,t);let r=n.length;Z(e.restEncoder,r);for(let t=0;t<r;t++){let r=n[t];e.writeDsClock(r.clock),e.writeDsLen(r.len)}})},So=e=>{let t=new fo,n=Q(e.restDecoder);for(let r=0;r<n;r++){e.resetDsCurVal();let n=Q(e.restDecoder),r=Q(e.restDecoder);if(r>0){let i=Jt(t.clients,n,()=>[]);for(let t=0;t<r;t++)i.push(new uo(e.readDsClock(),e.readDsLen()))}}return t},Co=(e,t,n)=>{let r=new fo,i=Q(e.restDecoder);for(let a=0;a<i;a++){e.resetDsCurVal();let i=Q(e.restDecoder),a=Q(e.restDecoder),o=n.clients.get(i)||[],s=xs(n,i);for(let n=0;n<a;n++){let n=e.readDsClock(),a=n+e.readDsLen();if(n<s){s<a&&vo(r,i,s,a-s);let e=Cs(o,n),c=o[e];for(!c.deleted&&c.id.clock<n&&(o.splice(e+1,0,Gl(t,c,n-c.id.clock)),e++);e<o.length&&(c=o[e++],c.id.clock<a);)c.deleted||(a<c.id.clock+c.length&&o.splice(e,0,Gl(t,c,a-c.id.clock)),c.delete(t))}else vo(r,i,n,a-n)}}if(r.clients.size>0){let e=new No;return Z(e.restEncoder,0),xo(e,r),e.toUint8Array()}return null},wo=br,To=class e extends on{constructor({guid:e=Sr(),collectionid:t=null,gc:n=!0,gcFilter:r=()=>!0,meta:i=null,autoLoad:a=!1,shouldLoad:o=!0}={}){super(),this.gc=n,this.gcFilter=r,this.clientID=wo(),this.guid=e,this.collectionid=t,this.share=new Map,this.store=new ys,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=o,this.autoLoad=a,this.meta=i,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=wr(e=>{this.on(`load`,()=>{this.isLoaded=!0,e(this)})});let s=()=>wr(e=>{let t=n=>{(n===void 0||n===!0)&&(this.off(`sync`,t),e())};this.on(`sync`,t)});this.on(`sync`,e=>{e===!1&&this.isSynced&&(this.whenSynced=s()),this.isSynced=e===void 0||e===!0,this.isSynced&&!this.isLoaded&&this.emit(`load`,[this])}),this.whenSynced=s()}load(){let e=this._item;e!==null&&!this.shouldLoad&&Ls(e.parent.doc,e=>{e.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(en(this.subdocs).map(e=>e.guid))}transact(e,t=null){return Ls(this,e,t)}get(e,t=pc){let n=Jt(this.share,e,()=>{let e=new t;return e._integrate(this,null),e}),r=n.constructor;if(t!==pc&&r!==t){if(r===pc){let r=new t;r._map=n._map,n._map.forEach(e=>{for(;e!==null;e=e.left)e.parent=r}),r._start=n._start;for(let e=r._start;e!==null;e=e.right)e.parent=r;return r._length=n._length,this.share.set(e,r),r._integrate(this,null),r}throw Error(`Type with the name ${e} has already been defined with a different constructor`)}return n}getArray(e=``){return this.get(e,Nc)}getText(e=``){return this.get(e,el)}getMap(e=``){return this.get(e,Ic)}getXmlElement(e=``){return this.get(e,al)}getXmlFragment(e=``){return this.get(e,rl)}toJSON(){let e={};return this.share.forEach((t,n)=>{e[n]=t.toJSON()}),e}destroy(){this.isDestroyed=!0,en(this.subdocs).forEach(e=>e.destroy());let t=this._item;if(t!==null){this._item=null;let n=t.content;n.doc=new e({guid:this.guid,...n.opts,shouldLoad:!1}),n.doc._item=t,Ls(t.parent.doc,e=>{let r=n.doc;t.deleted||e.subdocsAdded.add(r),e.subdocsRemoved.add(this)},null,!0)}this.emit(`destroyed`,[!0]),this.emit(`destroy`,[this]),super.destroy()}},Eo=class{constructor(e){this.restDecoder=e}resetDsCurVal(){}readDsClock(){return Q(this.restDecoder)}readDsLen(){return Q(this.restDecoder)}},Do=class extends Eo{readLeftID(){return $(Q(this.restDecoder),Q(this.restDecoder))}readRightID(){return $(Q(this.restDecoder),Q(this.restDecoder))}readClient(){return Q(this.restDecoder)}readInfo(){return lr(this.restDecoder)}readString(){return dr(this.restDecoder)}readParentInfo(){return Q(this.restDecoder)===1}readTypeRef(){return Q(this.restDecoder)}readLen(){return Q(this.restDecoder)}readAny(){return mr(this.restDecoder)}readBuf(){return mi(cr(this.restDecoder))}readJSON(){return JSON.parse(dr(this.restDecoder))}readKey(){return dr(this.restDecoder)}},Oo=class{constructor(e){this.dsCurrVal=0,this.restDecoder=e}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=Q(this.restDecoder),this.dsCurrVal}readDsLen(){let e=Q(this.restDecoder)+1;return this.dsCurrVal+=e,e}},ko=class extends Oo{constructor(e){super(e),this.keys=[],Q(e),this.keyClockDecoder=new _r(cr(e)),this.clientDecoder=new gr(cr(e)),this.leftClockDecoder=new _r(cr(e)),this.rightClockDecoder=new _r(cr(e)),this.infoDecoder=new hr(cr(e),lr),this.stringDecoder=new vr(cr(e)),this.parentInfoDecoder=new hr(cr(e),lr),this.typeRefDecoder=new gr(cr(e)),this.lenDecoder=new gr(cr(e))}readLeftID(){return new ns(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new ns(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 mr(this.restDecoder)}readBuf(){return cr(this.restDecoder)}readJSON(){return mr(this.restDecoder)}readKey(){let e=this.keyClockDecoder.read();if(e<this.keys.length)return this.keys[e];{let e=this.stringDecoder.read();return this.keys.push(e),e}}},Ao=class{constructor(){this.restEncoder=An()}toUint8Array(){return Y(this.restEncoder)}resetDsCurVal(){}writeDsClock(e){Z(this.restEncoder,e)}writeDsLen(e){Z(this.restEncoder,e)}},jo=class extends Ao{writeLeftID(e){Z(this.restEncoder,e.client),Z(this.restEncoder,e.clock)}writeRightID(e){Z(this.restEncoder,e.client),Z(this.restEncoder,e.clock)}writeClient(e){Z(this.restEncoder,e)}writeInfo(e){Nn(this.restEncoder,e)}writeString(e){Ln(this.restEncoder,e)}writeParentInfo(e){Z(this.restEncoder,+!!e)}writeTypeRef(e){Z(this.restEncoder,e)}writeLen(e){Z(this.restEncoder,e)}writeAny(e){Kn(this.restEncoder,e)}writeBuf(e){zn(this.restEncoder,e)}writeJSON(e){Ln(this.restEncoder,JSON.stringify(e))}writeKey(e){Ln(this.restEncoder,e)}},Mo=class{constructor(){this.restEncoder=An(),this.dsCurrVal=0}toUint8Array(){return Y(this.restEncoder)}resetDsCurVal(){this.dsCurrVal=0}writeDsClock(e){let t=e-this.dsCurrVal;this.dsCurrVal=e,Z(this.restEncoder,t)}writeDsLen(e){e===0&&tr(),Z(this.restEncoder,e-1),this.dsCurrVal+=e}},No=class extends Mo{constructor(){super(),this.keyMap=new Map,this.keyClock=0,this.keyClockEncoder=new Zn,this.clientEncoder=new Yn,this.leftClockEncoder=new Zn,this.rightClockEncoder=new Zn,this.infoEncoder=new qn(Nn),this.stringEncoder=new Qn,this.parentInfoEncoder=new qn(Nn),this.typeRefEncoder=new Yn,this.lenEncoder=new Yn}toUint8Array(){let e=An();return Z(e,0),zn(e,this.keyClockEncoder.toUint8Array()),zn(e,this.clientEncoder.toUint8Array()),zn(e,this.leftClockEncoder.toUint8Array()),zn(e,this.rightClockEncoder.toUint8Array()),zn(e,Y(this.infoEncoder)),zn(e,this.stringEncoder.toUint8Array()),zn(e,Y(this.parentInfoEncoder)),zn(e,this.typeRefEncoder.toUint8Array()),zn(e,this.lenEncoder.toUint8Array()),Rn(e,Y(this.restEncoder)),Y(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)}writeTypeRef(e){this.typeRefEncoder.write(e)}writeLen(e){this.lenEncoder.write(e)}writeAny(e){Kn(this.restEncoder,e)}writeBuf(e){zn(this.restEncoder,e)}writeJSON(e){Kn(this.restEncoder,e)}writeKey(e){let t=this.keyMap.get(e);t===void 0?(this.keyClockEncoder.write(this.keyClock++),this.stringEncoder.write(e)):this.keyClockEncoder.write(t)}},Po=(e,t,n,r)=>{r=dn(r,t[0].id.clock);let i=Cs(t,r);Z(e.restEncoder,t.length-i),e.writeClient(n),Z(e.restEncoder,r);let a=t[i];a.write(e,r-a.id.clock);for(let n=i+1;n<t.length;n++)t[n].write(e,0)},Fo=(e,t,n)=>{let r=new Map;n.forEach((e,n)=>{xs(t,n)>e&&r.set(n,e)}),bs(t).forEach((e,t)=>{n.has(t)||r.set(t,0)}),Z(e.restEncoder,r.size),en(r.entries()).sort((e,t)=>t[0]-e[0]).forEach(([n,r])=>{Po(e,t.clients.get(n),n,r)})},Io=(e,t)=>{let n=Kt(),r=Q(e.restDecoder);for(let i=0;i<r;i++){let r=Q(e.restDecoder),i=Array(r),a=e.readClient(),o=Q(e.restDecoder);n.set(a,{i:0,refs:i});for(let n=0;n<r;n++){let r=e.readInfo();switch(31&r){case 0:{let t=e.readLen();i[n]=new ml($(a,o),t),o+=t;break}case 10:{let t=Q(e.restDecoder);i[n]=new Ql($(a,o),t),o+=t;break}default:{let s=!(r&192),c=new Jl($(a,o),null,(r&128)==128?e.readLeftID():null,null,(r&64)==64?e.readRightID():null,s?e.readParentInfo()?t.get(e.readString()):e.readLeftID():null,s&&(r&32)==32?e.readString():null,Yl(e,r));i[n]=c,o+=c.length}}}}return n},Lo=(e,t,n)=>{let r=[],i=en(n.keys()).sort((e,t)=>e-t);if(i.length===0)return null;let a=()=>{if(i.length===0)return null;let e=n.get(i[i.length-1]);for(;e.refs.length===e.i;)if(i.pop(),i.length>0)e=n.get(i[i.length-1]);else return null;return e},o=a();if(o===null)return null;let s=new ys,c=new Map,l=(e,t)=>{let n=c.get(e);(n==null||n>t)&&c.set(e,t)},u=o.refs[o.i++],d=new Map,f=()=>{for(let e of r){let t=e.id.client,r=n.get(t);r?(r.i--,s.clients.set(t,r.refs.slice(r.i)),n.delete(t),r.i=0,r.refs=[]):s.clients.set(t,[e]),i=i.filter(e=>e!==t)}r.length=0};for(;;){if(u.constructor!==Ql){let i=Jt(d,u.id.client,()=>xs(t,u.id.client))-u.id.clock;if(i<0)r.push(u),l(u.id.client,u.id.clock-1),f();else{let a=u.getMissing(e,t);if(a!==null){r.push(u);let e=n.get(a)||{refs:[],i:0};if(e.refs.length===e.i)l(a,xs(t,a)),f();else{u=e.refs[e.i++];continue}}else(i===0||i<u.length)&&(u.integrate(e,i),d.set(u.id.client,u.id.clock+u.length))}}if(r.length>0)u=r.pop();else if(o!==null&&o.i<o.refs.length)u=o.refs[o.i++];else{if(o=a(),o===null)break;u=o.refs[o.i++]}}if(s.clients.size>0){let e=new No;return Fo(e,s,new Map),Z(e.restEncoder,0),{missing:c,update:e.toUint8Array()}}return null},Ro=(e,t)=>Fo(e,t.doc.store,t.beforeState),zo=(e,t,n,r=new ko(e))=>Ls(t,e=>{e.local=!1;let t=!1,n=e.doc,i=n.store,a=Lo(e,i,Io(r,n)),o=i.pendingStructs;if(o){for(let[e,n]of o.missing)if(n<xs(i,e)){t=!0;break}if(a){for(let[e,t]of a.missing){let n=o.missing.get(e);(n==null||n>t)&&o.missing.set(e,t)}o.update=qs([o.update,a.update])}}else i.pendingStructs=a;let s=Co(r,e,i);if(i.pendingDs){let t=new ko(ar(i.pendingDs));Q(t.restDecoder);let n=Co(t,e,i);i.pendingDs=s&&n?qs([s,n]):s||n}else i.pendingDs=s;if(t){let t=i.pendingStructs.update;i.pendingStructs=null,Bo(e.doc,t)}},n,!1),Bo=(e,t,n,r=ko)=>{let i=ar(t);zo(i,e,n,new r(i))},Vo=(e,t,n)=>Bo(e,t,n,Do),Ho=(e,t,n=new Map)=>{Fo(e,t.store,n),xo(e,bo(t.store))},Uo=(e,t=new Uint8Array([0]),n=new No)=>{Ho(n,e,Ko(t));let r=[n.toUint8Array()];if(e.store.pendingDs&&r.push(e.store.pendingDs),e.store.pendingStructs&&r.push(Js(e.store.pendingStructs.update,t)),r.length>1){if(n.constructor===jo)return Gs(r.map((e,t)=>t===0?e:$s(e)));if(n.constructor===No)return qs(r)}return r[0]},Wo=(e,t)=>Uo(e,t,new jo),Go=e=>{let t=new Map,n=Q(e.restDecoder);for(let r=0;r<n;r++){let n=Q(e.restDecoder),r=Q(e.restDecoder);t.set(n,r)}return t},Ko=e=>Go(new Eo(ar(e))),qo=(e,t)=>(Z(e.restEncoder,t.size),en(t.entries()).sort((e,t)=>t[0]-e[0]).forEach(([t,n])=>{Z(e.restEncoder,t),Z(e.restEncoder,n)}),e),Jo=(e,t)=>qo(e,bs(t.store)),Yo=(e,t=new Mo)=>(e instanceof Map?qo(t,e):Jo(t,e),t.toUint8Array()),Xo=e=>Yo(e,new Ao),Zo=class{constructor(){this.l=[]}},Qo=()=>new Zo,$o=(e,t)=>e.l.push(t),es=(e,t)=>{let n=e.l,r=n.length;e.l=n.filter(e=>t!==e),r===e.l.length&&console.error(`[yjs] Tried to remove event handler that doesn't exist.`)},ts=(e,t,n)=>Gr(e.l,[t,n]),ns=class{constructor(e,t){this.client=e,this.clock=t}},rs=(e,t)=>e===t||e!==null&&t!==null&&e.client===t.client&&e.clock===t.clock,$=(e,t)=>new ns(e,t),is=e=>{for(let[t,n]of e.doc.share.entries())if(n===e)return t;throw tr()},as=(e,t)=>{for(;t!==null;){if(t.parent===e)return!0;t=t.parent._item}return!1},os=class{constructor(e,t,n,r=0){this.type=e,this.tname=t,this.item=n,this.assoc=r}},ss=e=>{let t={};return e.type&&(t.type=e.type),e.tname&&(t.tname=e.tname),e.item&&(t.item=e.item),e.assoc!=null&&(t.assoc=e.assoc),t},cs=e=>new os(e.type==null?null:$(e.type.client,e.type.clock),e.tname??null,e.item==null?null:$(e.item.client,e.item.clock),e.assoc==null?0:e.assoc),ls=class{constructor(e,t,n=0){this.type=e,this.index=t,this.assoc=n}},us=(e,t,n=0)=>new ls(e,t,n),ds=(e,t,n)=>{let r=null,i=null;return e._item===null?i=is(e):r=$(e._item.id.client,e._item.id.clock),new os(r,i,t,n)},fs=(e,t,n=0)=>{let r=e._start;if(n<0){if(t===0)return ds(e,null,n);t--}for(;r!==null;){if(!r.deleted&&r.countable){if(r.length>t)return ds(e,$(r.id.client,r.id.clock+t),n);t-=r.length}if(r.right===null&&n<0)return ds(e,r.lastId,n);r=r.right}return ds(e,null,n)},ps=(e,t)=>{let n=ws(e,t);return{item:n,diff:t.clock-n.id.clock}},ms=(e,t,n=!0)=>{let r=t.store,i=e.item,a=e.type,o=e.tname,s=e.assoc,c=null,l=0;if(i!==null){if(xs(r,i.client)<=i.clock)return null;let e=n?Ul(r,i):ps(r,i),t=e.item;if(!(t instanceof Jl))return null;if(c=t.parent,c._item===null||!c._item.deleted){l=t.deleted||!t.countable?0:e.diff+(s>=0?0:1);let n=t.left;for(;n!==null;)!n.deleted&&n.countable&&(l+=n.length),n=n.left}}else{if(o!==null)c=t.get(o);else if(a!==null){if(xs(r,a.client)<=a.clock)return null;let{item:e}=n?Ul(r,a):{item:ws(r,a)};if(e instanceof Jl&&e.content instanceof Vl)c=e.content.type;else return null}else throw tr();l=s>=0?c._length:0}return us(c,l,e.assoc)},hs=(e,t)=>e===t||e!==null&&t!==null&&e.tname===t.tname&&rs(e.item,t.item)&&rs(e.type,t.type)&&e.assoc===t.assoc,gs=class{constructor(e,t){this.ds=e,this.sv=t}};((e,t)=>new gs(e,t))(yo(),new Map);var _s=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!ho(t.ds,e.id),vs=(e,t)=>{let n=Jt(e.meta,vs,Zt),r=e.doc.store;n.has(t)||(t.sv.forEach((t,n)=>{t<xs(r,n)&&Es(e,$(n,t))}),po(e,t.ds,e=>{}),n.add(t))},ys=class{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}},bs=e=>{let t=new Map;return e.clients.forEach((e,n)=>{let r=e[e.length-1];t.set(n,r.id.clock+r.length)}),t},xs=(e,t)=>{let n=e.clients.get(t);if(n===void 0)return 0;let r=n[n.length-1];return r.id.clock+r.length},Ss=(e,t)=>{let n=e.clients.get(t.id.client);if(n===void 0)n=[],e.clients.set(t.id.client,n);else{let e=n[n.length-1];if(e.id.clock+e.length!==t.id.clock)throw tr()}n.push(t)},Cs=(e,t)=>{let n=0,r=e.length-1,i=e[r],a=i.id.clock;if(a===t)return r;let o=cn(t/(a+i.length-1)*r);for(;n<=r;){if(i=e[o],a=i.id.clock,a<=t){if(t<a+i.length)return o;n=o+1}else r=o-1;o=cn((n+r)/2)}throw tr()},ws=(e,t)=>{let n=e.clients.get(t.client);return n[Cs(n,t.clock)]},Ts=(e,t,n)=>{let r=Cs(t,n),i=t[r];return i.id.clock<n&&i instanceof Jl?(t.splice(r+1,0,Gl(e,i,n-i.id.clock)),r+1):r},Es=(e,t)=>{let n=e.doc.store.clients.get(t.client);return n[Ts(e,n,t.clock)]},Ds=(e,t,n)=>{let r=t.clients.get(n.client),i=Cs(r,n.clock),a=r[i];return n.clock!==a.id.clock+a.length-1&&a.constructor!==ml&&r.splice(i+1,0,Gl(e,a,n.clock-a.id.clock+1)),a},Os=(e,t,n)=>{let r=e.clients.get(t.id.client);r[Cs(r,t.id.clock)]=n},ks=(e,t,n,r,i)=>{if(r===0)return;let a=n+r,o=Ts(e,t,n),s;do s=t[o++],a<s.id.clock+s.length&&Ts(e,t,a),i(s);while(o<t.length&&t[o].id.clock<a)},As=class{constructor(e,t,n){this.doc=e,this.deleteSet=new fo,this.beforeState=bs(e.store),this.afterState=new Map,this.changed=new Map,this.changedParentTypes=new Map,this._mergeStructs=[],this.origin=t,this.meta=new Map,this.local=n,this.subdocsAdded=new Set,this.subdocsRemoved=new Set,this.subdocsLoaded=new Set,this._needFormattingCleanup=!1}},js=(e,t)=>t.deleteSet.clients.size===0&&!Xt(t.afterState,(e,n)=>t.beforeState.get(n)!==e)?!1:(go(t.deleteSet),Ro(e,t),xo(e,t.deleteSet),!0),Ms=(e,t,n)=>{let r=t._item;(r===null||r.id.clock<(e.beforeState.get(r.id.client)||0)&&!r.deleted)&&Jt(e.changed,t,Zt).add(n)},Ns=(e,t)=>{let n=e[t],r=e[t-1],i=t;for(;i>0&&r.deleted===n.deleted&&r.constructor===n.constructor&&r.mergeWith(n);n=r,r=e[--i-1])n instanceof Jl&&n.parentSub!==null&&n.parent._map.get(n.parentSub)===n&&n.parent._map.set(n.parentSub,r);let a=t-i;return a&&e.splice(t+1-a,a),a},Ps=(e,t,n)=>{for(let[r,i]of e.clients.entries()){let e=t.clients.get(r);for(let r=i.length-1;r>=0;r--){let a=i[r],o=a.clock+a.len;for(let r=Cs(e,a.clock),i=e[r];r<e.length&&i.id.clock<o;i=e[++r]){let i=e[r];if(a.clock+a.len<=i.id.clock)break;i instanceof Jl&&i.deleted&&!i.keep&&n(i)&&i.gc(t,!1)}}}},Fs=(e,t)=>{e.clients.forEach((e,n)=>{let r=t.clients.get(n);for(let t=e.length-1;t>=0;t--){let n=e[t],i=un(r.length-1,1+Cs(r,n.clock+n.len-1));for(let e=i,t=r[e];e>0&&t.id.clock>=n.clock;t=r[e])e-=1+Ns(r,e)}})},Is=(e,t)=>{if(t<e.length){let n=e[t],r=n.doc,i=r.store,a=n.deleteSet,o=n._mergeStructs;try{go(a),n.afterState=bs(n.doc.store),r.emit(`beforeObserverCalls`,[n,r]);let e=[];n.changed.forEach((t,r)=>e.push(()=>{(r._item===null||!r._item.deleted)&&r._callObserver(n,t)})),e.push(()=>{n.changedParentTypes.forEach((t,r)=>{r._dEH.l.length>0&&(r._item===null||!r._item.deleted)&&(t=t.filter(e=>e.target._item===null||!e.target._item.deleted),t.forEach(e=>{e.currentTarget=r,e._path=null}),t.sort((e,t)=>e.path.length-t.path.length),e.push(()=>{ts(r._dEH,t,n)}))}),e.push(()=>r.emit(`afterTransaction`,[n,r])),e.push(()=>{n._needFormattingCleanup&&Zc(n)})}),Gr(e,[])}finally{r.gc&&Ps(a,i,r.gcFilter),Fs(a,i),n.afterState.forEach((e,t)=>{let r=n.beforeState.get(t)||0;if(r!==e){let e=i.clients.get(t),n=dn(Cs(e,r),1);for(let t=e.length-1;t>=n;)t-=1+Ns(e,t)}});for(let e=o.length-1;e>=0;e--){let{client:t,clock:n}=o[e].id,r=i.clients.get(t),a=Cs(r,n);a+1<r.length&&Ns(r,a+1)>1||a>0&&Ns(r,a)}if(!n.local&&n.afterState.get(r.clientID)!==n.beforeState.get(r.clientID)&&(io($a,Ka,`[yjs] `,qa,Za,`Changed the client-id because another client seems to be using it.`),r.clientID=wo()),r.emit(`afterTransactionCleanup`,[n,r]),r._observers.has(`update`)){let e=new jo;js(e,n)&&r.emit(`update`,[e.toUint8Array(),n.origin,r,n])}if(r._observers.has(`updateV2`)){let e=new No;js(e,n)&&r.emit(`updateV2`,[e.toUint8Array(),n.origin,r,n])}let{subdocsAdded:s,subdocsLoaded:c,subdocsRemoved:l}=n;(s.size>0||l.size>0||c.size>0)&&(s.forEach(e=>{e.clientID=r.clientID,e.collectionid??=r.collectionid,r.subdocs.add(e)}),l.forEach(e=>r.subdocs.delete(e)),r.emit(`subdocs`,[{loaded:c,added:s,removed:l},r,n]),l.forEach(e=>e.destroy())),e.length<=t+1?(r._transactionCleanups=[],r.emit(`afterAllTransactions`,[r,e])):Is(e,t+1)}}},Ls=(e,t,n=null,r=!0)=>{let i=e._transactionCleanups,a=!1,o=null;e._transaction===null&&(a=!0,e._transaction=new As(e,n,r),i.push(e._transaction),i.length===1&&e.emit(`beforeAllTransactions`,[e]),e.emit(`beforeTransaction`,[e._transaction,e]));try{o=t(e._transaction)}finally{if(a){let t=e._transaction===i[0];e._transaction=null,t&&Is(i,0)}}return o},Rs=class{constructor(e,t){this.insertions=t,this.deletions=e,this.meta=new Map}},zs=(e,t,n)=>{po(e,n.deletions,n=>{n instanceof Jl&&t.scope.some(t=>t===e.doc||as(t,n))&&Wl(n,!1)})},Bs=(e,t,n)=>{let r=null,i=e.doc,a=e.scope;Ls(i,n=>{for(;t.length>0&&e.currStackItem===null;){let r=i.store,o=t.pop(),s=new Set,c=[],l=!1;po(n,o.insertions,e=>{if(e instanceof Jl){if(e.redone!==null){let{item:t,diff:i}=Ul(r,e.id);i>0&&(t=Es(n,$(t.id.client,t.id.clock+i))),e=t}!e.deleted&&a.some(t=>t===n.doc||as(t,e))&&c.push(e)}}),po(n,o.deletions,e=>{e instanceof Jl&&a.some(t=>t===n.doc||as(t,e))&&!ho(o.insertions,e.id)&&s.add(e)}),s.forEach(t=>{l=ql(n,t,s,o.insertions,e.ignoreRemoteMapChanges,e)!==null||l});for(let t=c.length-1;t>=0;t--){let r=c[t];e.deleteFilter(r)&&(r.delete(n),l=!0)}e.currStackItem=l?o:null}n.changed.forEach((e,t)=>{e.has(null)&&t._searchMarker&&(t._searchMarker.length=0)}),r=n},e);let o=e.currStackItem;if(o!=null){let t=r.changedParentTypes;e.emit(`stack-item-popped`,[{stackItem:o,type:n,changedParentTypes:t,origin:e},e]),e.currStackItem=null}return o},Vs=class extends on{constructor(e,{captureTimeout:t=500,captureTransaction:n=e=>!0,deleteFilter:r=()=>!0,trackedOrigins:i=new Set([null]),ignoreRemoteMapChanges:a=!1,doc:o=an(e)?e[0].doc:e instanceof To?e:e.doc}={}){super(),this.scope=[],this.doc=o,this.addToScope(e),this.deleteFilter=r,i.add(this),this.trackedOrigins=i,this.captureTransaction=n,this.undoStack=[],this.redoStack=[],this.undoing=!1,this.redoing=!1,this.currStackItem=null,this.lastChange=0,this.ignoreRemoteMapChanges=a,this.captureTimeout=t,this.afterTransactionHandler=e=>{if(!this.captureTransaction(e)||!this.scope.some(t=>e.changedParentTypes.has(t)||t===this.doc)||!this.trackedOrigins.has(e.origin)&&(!e.origin||!this.trackedOrigins.has(e.origin.constructor)))return;let t=this.undoing,n=this.redoing,r=t?this.redoStack:this.undoStack;t?this.stopCapturing():n||this.clear(!1,!0);let i=new fo;e.afterState.forEach((t,n)=>{let r=e.beforeState.get(n)||0,a=t-r;a>0&&vo(i,n,r,a)});let a=Cr(),o=!1;if(this.lastChange>0&&a-this.lastChange<this.captureTimeout&&r.length>0&&!t&&!n){let t=r[r.length-1];t.deletions=_o([t.deletions,e.deleteSet]),t.insertions=_o([t.insertions,i])}else r.push(new Rs(e.deleteSet,i)),o=!0;!t&&!n&&(this.lastChange=a),po(e,e.deleteSet,t=>{t instanceof Jl&&this.scope.some(n=>n===e.doc||as(n,t))&&Wl(t,!0)});let s=[{stackItem:r[r.length-1],origin:e.origin,type:t?`redo`:`undo`,changedParentTypes:e.changedParentTypes},this];o?this.emit(`stack-item-added`,s):this.emit(`stack-item-updated`,s)},this.doc.on(`afterTransaction`,this.afterTransactionHandler),this.doc.on(`destroy`,()=>{this.destroy()})}addToScope(e){let t=new Set(this.scope);e=an(e)?e:[e],e.forEach(e=>{t.has(e)||(t.add(e),(e instanceof pc?e.doc!==this.doc:e!==this.doc)&&ao(`[yjs#509] Not same Y.Doc`),this.scope.push(e))})}addTrackedOrigin(e){this.trackedOrigins.add(e)}removeTrackedOrigin(e){this.trackedOrigins.delete(e)}clear(e=!0,t=!0){(e&&this.canUndo()||t&&this.canRedo())&&this.doc.transact(n=>{e&&(this.undoStack.forEach(e=>zs(n,this,e)),this.undoStack=[]),t&&(this.redoStack.forEach(e=>zs(n,this,e)),this.redoStack=[]),this.emit(`stack-cleared`,[{undoStackCleared:e,redoStackCleared:t}])})}stopCapturing(){this.lastChange=0}undo(){this.undoing=!0;let e;try{e=Bs(this,this.undoStack,`undo`)}finally{this.undoing=!1}return e}redo(){this.redoing=!0;let e;try{e=Bs(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*Hs(e){let t=Q(e.restDecoder);for(let n=0;n<t;n++){let t=Q(e.restDecoder),n=e.readClient(),r=Q(e.restDecoder);for(let i=0;i<t;i++){let t=e.readInfo();if(t===10){let t=Q(e.restDecoder);yield new Ql($(n,r),t),r+=t}else if(31&t){let i=!(t&192),a=new Jl($(n,r),null,(t&128)==128?e.readLeftID():null,null,(t&64)==64?e.readRightID():null,i?e.readParentInfo()?e.readString():e.readLeftID():null,i&&(t&32)==32?e.readString():null,Yl(e,t));yield a,r+=a.length}else{let t=e.readLen();yield new ml($(n,r),t),r+=t}}}}var Us=class{constructor(e,t){this.gen=Hs(e),this.curr=null,this.done=!1,this.filterSkips=t,this.next()}next(){do this.curr=this.gen.next().value||null;while(this.filterSkips&&this.curr!==null&&this.curr.constructor===Ql);return this.curr}},Ws=class{constructor(e){this.currClient=0,this.startClock=0,this.written=0,this.encoder=e,this.clientStructs=[]}},Gs=e=>qs(e,Do,jo),Ks=(e,t)=>{if(e.constructor===ml){let{client:n,clock:r}=e.id;return new ml($(n,r+t),e.length-t)}if(e.constructor===Ql){let{client:n,clock:r}=e.id;return new Ql($(n,r+t),e.length-t)}{let n=e,{client:r,clock:i}=n.id;return new Jl($(r,i+t),null,$(r,i+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},qs=(e,t=ko,n=No)=>{if(e.length===1)return e[0];let r=e.map(e=>new t(ar(e))),i=r.map(e=>new Us(e,!0)),a=null,o=new n,s=new Ws(o);for(;i=i.filter(e=>e.curr!==null),i.sort((e,t)=>{if(e.curr.id.client===t.curr.id.client){let n=e.curr.id.clock-t.curr.id.clock;return n===0?e.curr.constructor===t.curr.constructor?0:e.curr.constructor===Ql?1:-1:n}return t.curr.id.client-e.curr.id.client}),i.length!==0;){let e=i[0],t=e.curr.id.client;if(a!==null){let n=e.curr,r=!1;for(;n!==null&&n.id.clock+n.length<=a.struct.id.clock+a.struct.length&&n.id.client>=a.struct.id.client;)n=e.next(),r=!0;if(n===null||n.id.client!==t||r&&n.id.clock>a.struct.id.clock+a.struct.length)continue;if(t!==a.struct.id.client)Xs(s,a.struct,a.offset),a={struct:n,offset:0},e.next();else if(a.struct.id.clock+a.struct.length<n.id.clock){if(a.struct.constructor===Ql)a.struct.length=n.id.clock+n.length-a.struct.id.clock;else{Xs(s,a.struct,a.offset);let e=n.id.clock-a.struct.id.clock-a.struct.length;a={struct:new Ql($(t,a.struct.id.clock+a.struct.length),e),offset:0}}}else{let t=a.struct.id.clock+a.struct.length-n.id.clock;t>0&&(a.struct.constructor===Ql?a.struct.length-=t:n=Ks(n,t)),a.struct.mergeWith(n)||(Xs(s,a.struct,a.offset),a={struct:n,offset:0},e.next())}}else a={struct:e.curr,offset:0},e.next();for(let n=e.curr;n!==null&&n.id.client===t&&n.id.clock===a.struct.id.clock+a.struct.length&&n.constructor!==Ql;n=e.next())Xs(s,a.struct,a.offset),a={struct:n,offset:0}}return a!==null&&(Xs(s,a.struct,a.offset),a=null),Zs(s),xo(o,_o(r.map(e=>So(e)))),o.toUint8Array()},Js=(e,t,n=ko,r=No)=>{let i=Ko(t),a=new r,o=new Ws(a),s=new n(ar(e)),c=new Us(s,!1);for(;c.curr;){let e=c.curr,t=e.id.client,n=i.get(t)||0;if(c.curr.constructor===Ql)c.next();else if(e.id.clock+e.length>n)for(Xs(o,e,dn(n-e.id.clock,0)),c.next();c.curr&&c.curr.id.client===t;)Xs(o,c.curr,0),c.next();else for(;c.curr&&c.curr.id.client===t&&c.curr.id.clock+c.curr.length<=n;)c.next()}return Zs(o),xo(a,So(s)),a.toUint8Array()},Ys=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:Y(e.encoder.restEncoder)}),e.encoder.restEncoder=An(),e.written=0)},Xs=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&Ys(e),e.written===0&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),Z(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},Zs=e=>{Ys(e);let t=e.encoder.restEncoder;Z(t,e.clientStructs.length);for(let n=0;n<e.clientStructs.length;n++){let r=e.clientStructs[n];Z(t,r.written),Rn(t,r.restEncoder)}},Qs=(e,t,n,r)=>{let i=new n(ar(e)),a=new Us(i,!1),o=new r,s=new Ws(o);for(let e=a.curr;e!==null;e=a.next())Xs(s,t(e),0);return Zs(s),xo(o,So(i)),o.toUint8Array()},$s=e=>Qs(e,Kr,ko,jo),ec=`You must not compute changes after the event-handler fired.`,tc=class{constructor(e,t){this.target=e,this.currentTarget=e,this.transaction=t,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||=nc(this.currentTarget,this.target)}deletes(e){return ho(this.transaction.deleteSet,e.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw $n(ec);let e=new Map,t=this.target;this.transaction.changed.get(t).forEach(n=>{if(n!==null){let r=t._map.get(n),i,a;if(this.adds(r)){let e=r.left;for(;e!==null&&this.adds(e);)e=e.left;if(this.deletes(r)){if(e!==null&&this.deletes(e))i=`delete`,a=Qt(e.content.getContent());else return}else e!==null&&this.deletes(e)?(i=`update`,a=Qt(e.content.getContent())):(i=`add`,a=void 0)}else if(this.deletes(r))i=`delete`,a=Qt(r.content.getContent());else return;e.set(n,{action:i,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 $n(ec);let t=this.target,n=Zt(),r=Zt(),i=[];if(e={added:n,deleted:r,delta:i,keys:this.keys},this.transaction.changed.get(t).has(null)){let e=null,a=()=>{e&&i.push(e)};for(let i=t._start;i!==null;i=i.right)i.deleted?this.deletes(i)&&!this.adds(i)&&((e===null||e.delete===void 0)&&(a(),e={delete:0}),e.delete+=i.length,r.add(i)):this.adds(i)?((e===null||e.insert===void 0)&&(a(),e={insert:[]}),e.insert=e.insert.concat(i.content.getContent()),n.add(i)):((e===null||e.retain===void 0)&&(a(),e={retain:0}),e.retain+=i.length);e!==null&&e.retain===void 0&&a()}this._changes=e}return e}},nc=(e,t)=>{let n=[];for(;t._item!==null&&t!==e;){if(t._item.parentSub!==null)n.unshift(t._item.parentSub);else{let e=0,r=t._item.parent._start;for(;r!==t._item&&r!==null;)!r.deleted&&r.countable&&(e+=r.length),r=r.right;n.unshift(e)}t=t._item.parent}return n},rc=()=>{ao(`Invalid access: Add Yjs type to a document before reading data.`)},ic=80,ac=0,oc=class{constructor(e,t){e.marker=!0,this.p=e,this.index=t,this.timestamp=ac++}},sc=e=>{e.timestamp=ac++},cc=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=ac++},lc=(e,t,n)=>{if(e.length>=ic){let r=e.reduce((e,t)=>e.timestamp<t.timestamp?e:t);return cc(r,t,n),r}{let r=new oc(t,n);return e.push(r),r}},uc=(e,t)=>{if(e._start===null||t===0||e._searchMarker===null)return null;let n=e._searchMarker.length===0?null:e._searchMarker.reduce((e,n)=>ln(t-e.index)<ln(t-n.index)?e:n),r=e._start,i=0;for(n!==null&&(r=n.p,i=n.index,sc(n));r.right!==null&&i<t;){if(!r.deleted&&r.countable){if(t<i+r.length)break;i+=r.length}r=r.right}for(;r.left!==null&&i>t;)r=r.left,!r.deleted&&r.countable&&(i-=r.length);for(;r.left!==null&&r.left.id.client===r.id.client&&r.left.id.clock+r.left.length===r.id.clock;)r=r.left,!r.deleted&&r.countable&&(i-=r.length);return n!==null&&ln(n.index-i)<r.parent.length/ic?(cc(n,r,i),n):lc(e._searchMarker,r,i)},dc=(e,t,n)=>{for(let r=e.length-1;r>=0;r--){let i=e[r];if(n>0){let t=i.p;for(t.marker=!1;t&&(t.deleted||!t.countable);)t=t.left,t&&!t.deleted&&t.countable&&(i.index-=t.length);if(t===null||t.marker===!0){e.splice(r,1);continue}i.p=t,t.marker=!0}(t<i.index||n>0&&t===i.index)&&(i.index=dn(t,i.index+n))}},fc=(e,t,n)=>{let r=e,i=t.changedParentTypes;for(;Jt(i,e,()=>[]).push(n),e._item!==null;)e=e._item.parent;ts(r._eH,n,t)},pc=class{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=Qo(),this._dEH=Qo(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(e,t){this.doc=e,this._item=t}_copy(){throw er()}clone(){throw er()}_write(e){}get _first(){let e=this._start;for(;e!==null&&e.deleted;)e=e.right;return e}_callObserver(e,t){!e.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(e){$o(this._eH,e)}observeDeep(e){$o(this._dEH,e)}unobserve(e){es(this._eH,e)}unobserveDeep(e){es(this._dEH,e)}toJSON(){}},mc=(e,t,n)=>{e.doc??rc(),t<0&&(t=e._length+t),n<0&&(n=e._length+n);let r=n-t,i=[],a=e._start;for(;a!==null&&r>0;){if(a.countable&&!a.deleted){let e=a.content.getContent();if(e.length<=t)t-=e.length;else{for(let n=t;n<e.length&&r>0;n++)i.push(e[n]),r--;t=0}}a=a.right}return i},hc=e=>{e.doc??rc();let t=[],n=e._start;for(;n!==null;){if(n.countable&&!n.deleted){let e=n.content.getContent();for(let n=0;n<e.length;n++)t.push(e[n])}n=n.right}return t},gc=(e,t)=>{let n=0,r=e._start;for(e.doc??rc();r!==null;){if(r.countable&&!r.deleted){let i=r.content.getContent();for(let r=0;r<i.length;r++)t(i[r],n++,e)}r=r.right}},_c=(e,t)=>{let n=[];return gc(e,(r,i)=>{n.push(t(r,i,e))}),n},vc=e=>{let t=e._start,n=null,r=0;return{[Symbol.iterator](){return this},next:()=>{if(n===null){for(;t!==null&&t.deleted;)t=t.right;if(t===null)return{done:!0,value:void 0};n=t.content.getContent(),r=0,t=t.right}let e=n[r++];return n.length<=r&&(n=null),{done:!1,value:e}}}},yc=(e,t)=>{e.doc??rc();let n=uc(e,t),r=e._start;for(n!==null&&(r=n.p,t-=n.index);r!==null;r=r.right)if(!r.deleted&&r.countable){if(t<r.length)return r.content.getContent()[t];t-=r.length}},bc=(e,t,n,r)=>{let i=n,a=e.doc,o=a.clientID,s=a.store,c=n===null?t._start:n.right,l=[],u=()=>{l.length>0&&(i=new Jl($(o,xs(s,o)),i,i&&i.lastId,c,c&&c.id,t,null,new kl(l)),i.integrate(e,0),l=[])};r.forEach(n=>{if(n===null)l.push(n);else switch(n.constructor){case Number:case Object:case Boolean:case Array:case String:l.push(n);break;default:switch(u(),n.constructor){case Uint8Array:case ArrayBuffer:i=new Jl($(o,xs(s,o)),i,i&&i.lastId,c,c&&c.id,t,null,new hl(new Uint8Array(n))),i.integrate(e,0);break;case To:i=new Jl($(o,xs(s,o)),i,i&&i.lastId,c,c&&c.id,t,null,new bl(n)),i.integrate(e,0);break;default:if(n instanceof pc)i=new Jl($(o,xs(s,o)),i,i&&i.lastId,c,c&&c.id,t,null,new Vl(n)),i.integrate(e,0);else throw Error(`Unexpected content type in insert operation`)}}}),u()},xc=()=>$n(`Length exceeded!`),Sc=(e,t,n,r)=>{if(n>t._length)throw xc();if(n===0)return t._searchMarker&&dc(t._searchMarker,n,r.length),bc(e,t,null,r);let i=n,a=uc(t,n),o=t._start;for(a!==null&&(o=a.p,n-=a.index,n===0&&(o=o.prev,n+=o&&o.countable&&!o.deleted?o.length:0));o!==null;o=o.right)if(!o.deleted&&o.countable){if(n<=o.length){n<o.length&&Es(e,$(o.id.client,o.id.clock+n));break}n-=o.length}return t._searchMarker&&dc(t._searchMarker,i,r.length),bc(e,t,o,r)},Cc=(e,t,n)=>{let r=(t._searchMarker||[]).reduce((e,t)=>t.index>e.index?t:e,{index:0,p:t._start}).p;if(r)for(;r.right;)r=r.right;return bc(e,t,r,n)},wc=(e,t,n,r)=>{if(r===0)return;let i=n,a=r,o=uc(t,n),s=t._start;for(o!==null&&(s=o.p,n-=o.index);s!==null&&n>0;s=s.right)!s.deleted&&s.countable&&(n<s.length&&Es(e,$(s.id.client,s.id.clock+n)),n-=s.length);for(;r>0&&s!==null;)s.deleted||(r<s.length&&Es(e,$(s.id.client,s.id.clock+r)),s.delete(e),r-=s.length),s=s.right;if(r>0)throw xc();t._searchMarker&&dc(t._searchMarker,i,-a+r)},Tc=(e,t,n)=>{let r=t._map.get(n);r!==void 0&&r.delete(e)},Ec=(e,t,n,r)=>{let i=t._map.get(n)||null,a=e.doc,o=a.clientID,s;if(r==null)s=new kl([r]);else switch(r.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:s=new kl([r]);break;case Uint8Array:s=new hl(r);break;case To:s=new bl(r);break;default:if(r instanceof pc)s=new Vl(r);else throw Error(`Unexpected content type`)}new Jl($(o,xs(a.store,o)),i,i&&i.lastId,null,null,t,n,s).integrate(e,0)},Dc=(e,t)=>{e.doc??rc();let n=e._map.get(t);return n!==void 0&&!n.deleted?n.content.getContent()[n.length-1]:void 0},Oc=e=>{let t={};return e.doc??rc(),e._map.forEach((e,n)=>{e.deleted||(t[n]=e.content.getContent()[e.length-1])}),t},kc=(e,t)=>{e.doc??rc();let n=e._map.get(t);return n!==void 0&&!n.deleted},Ac=(e,t)=>{let n={};return e._map.forEach((e,r)=>{let i=e;for(;i!==null&&(!t.sv.has(i.id.client)||i.id.clock>=(t.sv.get(i.id.client)||0));)i=i.left;i!==null&&_s(i,t)&&(n[r]=i.content.getContent()[i.length-1])}),n},jc=e=>(e.doc??rc(),co(e._map.entries(),e=>!e[1].deleted)),Mc=class extends tc{},Nc=class e extends pc{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(t){let n=new e;return n.push(t),n}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new e}clone(){let t=new e;return t.insert(0,this.toArray().map(e=>e instanceof pc?e.clone():e)),t}get length(){return this.doc??rc(),this._length}_callObserver(e,t){super._callObserver(e,t),fc(this,e,new Mc(this,e))}insert(e,t){this.doc===null?this._prelimContent.splice(e,0,...t):Ls(this.doc,n=>{Sc(n,this,e,t)})}push(e){this.doc===null?this._prelimContent.push(...e):Ls(this.doc,t=>{Cc(t,this,e)})}unshift(e){this.insert(0,e)}delete(e,t=1){this.doc===null?this._prelimContent.splice(e,t):Ls(this.doc,n=>{wc(n,this,e,t)})}get(e){return yc(this,e)}toArray(){return hc(this)}slice(e=0,t=this.length){return mc(this,e,t)}toJSON(){return this.map(e=>e instanceof pc?e.toJSON():e)}map(e){return _c(this,e)}forEach(e){gc(this,e)}[Symbol.iterator](){return vc(this)}_write(e){e.writeTypeRef(Pl)}},Pc=e=>new Nc,Fc=class extends tc{constructor(e,t,n){super(e,t),this.keysChanged=n}},Ic=class e extends pc{constructor(e){super(),this._prelimContent=null,this._prelimContent=e===void 0?new Map:new Map(e)}_integrate(e,t){super._integrate(e,t),this._prelimContent.forEach((e,t)=>{this.set(t,e)}),this._prelimContent=null}_copy(){return new e}clone(){let t=new e;return this.forEach((e,n)=>{t.set(n,e instanceof pc?e.clone():e)}),t}_callObserver(e,t){fc(this,e,new Fc(this,e,t))}toJSON(){this.doc??rc();let e={};return this._map.forEach((t,n)=>{if(!t.deleted){let r=t.content.getContent()[t.length-1];e[n]=r instanceof pc?r.toJSON():r}}),e}get size(){return[...jc(this)].length}keys(){return lo(jc(this),e=>e[0])}values(){return lo(jc(this),e=>e[1].content.getContent()[e[1].length-1])}entries(){return lo(jc(this),e=>[e[0],e[1].content.getContent()[e[1].length-1]])}forEach(e){this.doc??rc(),this._map.forEach((t,n)=>{t.deleted||e(t.content.getContent()[t.length-1],n,this)})}[Symbol.iterator](){return this.entries()}delete(e){this.doc===null?this._prelimContent.delete(e):Ls(this.doc,t=>{Tc(t,this,e)})}set(e,t){return this.doc===null?this._prelimContent.set(e,t):Ls(this.doc,n=>{Ec(n,this,e,t)}),t}get(e){return Dc(this,e)}has(e){return kc(this,e)}clear(){this.doc===null?this._prelimContent.clear():Ls(this.doc,e=>{this.forEach(function(t,n,r){Tc(e,r,n)})})}_write(e){e.writeTypeRef(Fl)}},Lc=e=>new Ic,Rc=(e,t)=>e===t||typeof e==`object`&&typeof t==`object`&&e&&t&&Hr(e,t),zc=class{constructor(e,t,n,r){this.left=e,this.right=t,this.index=n,this.currentAttributes=r}forward(){switch(this.right===null&&tr(),this.right.content.constructor){case wl:this.right.deleted||Uc(this.currentAttributes,this.right.content);break;default:this.right.deleted||(this.index+=this.right.length)}this.left=this.right,this.right=this.right.right}},Bc=(e,t,n)=>{for(;t.right!==null&&n>0;){switch(t.right.content.constructor){case wl:t.right.deleted||Uc(t.currentAttributes,t.right.content);break;default:t.right.deleted||(n<t.right.length&&Es(e,$(t.right.id.client,t.right.id.clock+n)),t.index+=t.right.length,n-=t.right.length)}t.left=t.right,t.right=t.right.right}return t},Vc=(e,t,n,r)=>{let i=new Map,a=r?uc(t,n):null;return a?Bc(e,new zc(a.p.left,a.p,a.index,i),n-a.index):Bc(e,new zc(null,t._start,0,i),n)},Hc=(e,t,n,r)=>{for(;n.right!==null&&(n.right.deleted===!0||n.right.content.constructor===wl&&Rc(r.get(n.right.content.key),n.right.content.value));)n.right.deleted||r.delete(n.right.content.key),n.forward();let i=e.doc,a=i.clientID;r.forEach((r,o)=>{let s=n.left,c=n.right,l=new Jl($(a,xs(i.store,a)),s,s&&s.lastId,c,c&&c.id,t,null,new wl(o,r));l.integrate(e,0),n.right=l,n.forward()})},Uc=(e,t)=>{let{key:n,value:r}=t;r===null?e.delete(n):e.set(n,r)},Wc=(e,t)=>{for(;e.right!==null&&(e.right.deleted||e.right.content.constructor===wl&&Rc(t[e.right.content.key]??null,e.right.content.value));)e.forward()},Gc=(e,t,n,r)=>{let i=e.doc,a=i.clientID,o=new Map;for(let s in r){let c=r[s],l=n.currentAttributes.get(s)??null;if(!Rc(l,c)){o.set(s,l);let{left:r,right:u}=n;n.right=new Jl($(a,xs(i.store,a)),r,r&&r.lastId,u,u&&u.id,t,null,new wl(s,c)),n.right.integrate(e,0),n.forward()}}return o},Kc=(e,t,n,r,i)=>{n.currentAttributes.forEach((e,t)=>{i[t]===void 0&&(i[t]=null)});let a=e.doc,o=a.clientID;Wc(n,i);let s=Gc(e,t,n,i),c=r.constructor===String?new jl(r):r instanceof pc?new Vl(r):new Sl(r),{left:l,right:u,index:d}=n;t._searchMarker&&dc(t._searchMarker,n.index,c.getLength()),u=new Jl($(o,xs(a.store,o)),l,l&&l.lastId,u,u&&u.id,t,null,c),u.integrate(e,0),n.right=u,n.index=d,n.forward(),Hc(e,t,n,s)},qc=(e,t,n,r,i)=>{let a=e.doc,o=a.clientID;Wc(n,i);let s=Gc(e,t,n,i);iterationLoop:for(;n.right!==null&&(r>0||s.size>0&&(n.right.deleted||n.right.content.constructor===wl));){if(!n.right.deleted)switch(n.right.content.constructor){case wl:{let{key:t,value:a}=n.right.content,o=i[t];if(o!==void 0){if(Rc(o,a))s.delete(t);else{if(r===0)break iterationLoop;s.set(t,a)}n.right.delete(e)}else n.currentAttributes.set(t,a);break}default:r<n.right.length&&Es(e,$(n.right.id.client,n.right.id.clock+r)),r-=n.right.length}n.forward()}if(r>0){let i=``;for(;r>0;r--)i+=`
|
|
4
|
+
`;n.right=new Jl($(o,xs(a.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new jl(i)),n.right.integrate(e,0),n.forward()}Hc(e,t,n,s)},Jc=(e,t,n,r,i)=>{let a=t,o=Kt();for(;a&&(!a.countable||a.deleted);){if(!a.deleted&&a.content.constructor===wl){let e=a.content;o.set(e.key,e)}a=a.right}let s=0,c=!1;for(;t!==a;){if(n===t&&(c=!0),!t.deleted){let n=t.content;switch(n.constructor){case wl:{let{key:a,value:l}=n,u=r.get(a)??null;(o.get(a)!==n||u===l)&&(t.delete(e),s++,!c&&(i.get(a)??null)===l&&u!==l&&(u===null?i.delete(a):i.set(a,u))),!c&&!t.deleted&&Uc(i,n);break}}}t=t.right}return s},Yc=(e,t)=>{for(;t&&t.right&&(t.right.deleted||!t.right.countable);)t=t.right;let n=new Set;for(;t&&(t.deleted||!t.countable);){if(!t.deleted&&t.content.constructor===wl){let r=t.content.key;n.has(r)?t.delete(e):n.add(r)}t=t.left}},Xc=e=>{let t=0;return Ls(e.doc,n=>{let r=e._start,i=e._start,a=Kt(),o=qt(a);for(;i;){if(i.deleted===!1)switch(i.content.constructor){case wl:Uc(o,i.content);break;default:t+=Jc(n,r,i,a,o),a=qt(o),r=i}i=i.right}}),t},Zc=e=>{let t=new Set,n=e.doc;for(let[r,i]of e.afterState.entries()){let a=e.beforeState.get(r)||0;i!==a&&ks(e,n.store.clients.get(r),a,i,e=>{!e.deleted&&e.content.constructor===wl&&e.constructor!==ml&&t.add(e.parent)})}Ls(n,n=>{po(e,e.deleteSet,e=>{if(e instanceof ml||!e.parent._hasFormatting||t.has(e.parent))return;let r=e.parent;e.content.constructor===wl?t.add(r):Yc(n,e)});for(let e of t)Xc(e)})},Qc=(e,t,n)=>{let r=n,i=qt(t.currentAttributes),a=t.right;for(;n>0&&t.right!==null;){if(t.right.deleted===!1)switch(t.right.content.constructor){case Vl:case Sl:case jl:n<t.right.length&&Es(e,$(t.right.id.client,t.right.id.clock+n)),n-=t.right.length,t.right.delete(e)}t.forward()}a&&Jc(e,a,t.right,i,t.currentAttributes);let o=(t.left||t.right).parent;return o._searchMarker&&dc(o._searchMarker,t.index,-r+n),t},$c=class extends tc{constructor(e,t,n){super(e,t),this.childListChanged=!1,this.keysChanged=new Set,n.forEach(e=>{e===null?this.childListChanged=!0:this.keysChanged.add(e)})}get changes(){if(this._changes===null){let 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){let e=this.target.doc,t=[];Ls(e,e=>{let n=new Map,r=new Map,i=this.target._start,a=null,o={},s=``,c=0,l=0,u=()=>{if(a!==null){let e=null;switch(a){case`delete`:l>0&&(e={delete:l}),l=0;break;case`insert`:(typeof s==`object`||s.length>0)&&(e={insert:s},n.size>0&&(e.attributes={},n.forEach((t,n)=>{t!==null&&(e.attributes[n]=t)}))),s=``;break;case`retain`:c>0&&(e={retain:c},zr(o)||(e.attributes=Pr({},o))),c=0}e&&t.push(e),a=null}};for(;i!==null;){switch(i.content.constructor){case Vl:case Sl:this.adds(i)?this.deletes(i)||(u(),a=`insert`,s=i.content.getContent()[0],u()):this.deletes(i)?(a!==`delete`&&(u(),a=`delete`),l+=1):i.deleted||(a!==`retain`&&(u(),a=`retain`),c+=1);break;case jl:this.adds(i)?this.deletes(i)||(a!==`insert`&&(u(),a=`insert`),s+=i.content.str):this.deletes(i)?(a!==`delete`&&(u(),a=`delete`),l+=i.length):i.deleted||(a!==`retain`&&(u(),a=`retain`),c+=i.length);break;case wl:{let{key:t,value:s}=i.content;if(this.adds(i))this.deletes(i)||(Rc(n.get(t)??null,s)?s!==null&&i.delete(e):(a===`retain`&&u(),Rc(s,r.get(t)??null)?delete o[t]:o[t]=s));else if(this.deletes(i)){r.set(t,s);let e=n.get(t)??null;Rc(e,s)||(a===`retain`&&u(),o[t]=e)}else if(!i.deleted){r.set(t,s);let n=o[t];n!==void 0&&(Rc(n,s)?n!==null&&i.delete(e):(a===`retain`&&u(),s===null?delete o[t]:o[t]=s))}i.deleted||(a===`insert`&&u(),Uc(n,i.content));break}}i=i.right}for(u();t.length>0;){let e=t[t.length-1];if(e.retain!==void 0&&e.attributes===void 0)t.pop();else break}}),this._delta=t}return this._delta}},el=class e extends pc{constructor(e){super(),this._pending=e===void 0?[]:[()=>this.insert(0,e)],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??rc(),this._length}_integrate(e,t){super._integrate(e,t);try{this._pending.forEach(e=>e())}catch(e){console.error(e)}this._pending=null}_copy(){return new e}clone(){let t=new e;return t.applyDelta(this.toDelta()),t}_callObserver(e,t){super._callObserver(e,t);let n=new $c(this,e,t);fc(this,e,n),!e.local&&this._hasFormatting&&(e._needFormattingCleanup=!0)}toString(){this.doc??rc();let e=``,t=this._start;for(;t!==null;)!t.deleted&&t.countable&&t.content.constructor===jl&&(e+=t.content.str),t=t.right;return e}toJSON(){return this.toString()}applyDelta(e,{sanitize:t=!0}={}){this.doc===null?this._pending.push(()=>this.applyDelta(e)):Ls(this.doc,n=>{let r=new zc(null,this._start,0,new Map);for(let i=0;i<e.length;i++){let a=e[i];if(a.insert!==void 0){let o=!t&&typeof a.insert==`string`&&i===e.length-1&&r.right===null&&a.insert.slice(-1)===`
|
|
5
|
+
`?a.insert.slice(0,-1):a.insert;(typeof o!=`string`||o.length>0)&&Kc(n,this,r,o,a.attributes||{})}else a.retain===void 0?a.delete!==void 0&&Qc(n,r,a.delete):qc(n,this,r,a.retain,a.attributes||{})}})}toDelta(e,t,n){this.doc??rc();let r=[],i=new Map,a=this.doc,o=``,s=this._start;function c(){if(o.length>0){let e={},t=!1;i.forEach((n,r)=>{t=!0,e[r]=n});let n={insert:o};t&&(n.attributes=e),r.push(n),o=``}}let l=()=>{for(;s!==null;){if(_s(s,e)||t!==void 0&&_s(s,t))switch(s.content.constructor){case jl:{let r=i.get(`ychange`);e!==void 0&&!_s(s,e)?(r===void 0||r.user!==s.id.client||r.type!==`removed`)&&(c(),i.set(`ychange`,n?n(`removed`,s.id):{type:`removed`})):t!==void 0&&!_s(s,t)?(r===void 0||r.user!==s.id.client||r.type!==`added`)&&(c(),i.set(`ychange`,n?n(`added`,s.id):{type:`added`})):r!==void 0&&(c(),i.delete(`ychange`)),o+=s.content.str;break}case Vl:case Sl:{c();let e={insert:s.content.getContent()[0]};if(i.size>0){let t={};e.attributes=t,i.forEach((e,n)=>{t[n]=e})}r.push(e);break}case wl:_s(s,e)&&(c(),Uc(i,s.content))}s=s.right}c()};return e||t?Ls(a,n=>{e&&vs(n,e),t&&vs(n,t),l()},`cleanup`):l(),r}insert(e,t,n){if(t.length<=0)return;let r=this.doc;r===null?this._pending.push(()=>this.insert(e,t,n)):Ls(r,r=>{let i=Vc(r,this,e,!n);n||(n={},i.currentAttributes.forEach((e,t)=>{n[t]=e})),Kc(r,this,i,t,n)})}insertEmbed(e,t,n){let r=this.doc;r===null?this._pending.push(()=>this.insertEmbed(e,t,n||{})):Ls(r,r=>{let i=Vc(r,this,e,!n);Kc(r,this,i,t,n||{})})}delete(e,t){if(t===0)return;let n=this.doc;n===null?this._pending.push(()=>this.delete(e,t)):Ls(n,n=>{Qc(n,Vc(n,this,e,!0),t)})}format(e,t,n){if(t===0)return;let r=this.doc;r===null?this._pending.push(()=>this.format(e,t,n)):Ls(r,r=>{let i=Vc(r,this,e,!1);i.right!==null&&qc(r,this,i,t,n)})}removeAttribute(e){this.doc===null?this._pending.push(()=>this.removeAttribute(e)):Ls(this.doc,t=>{Tc(t,this,e)})}setAttribute(e,t){this.doc===null?this._pending.push(()=>this.setAttribute(e,t)):Ls(this.doc,n=>{Ec(n,this,e,t)})}getAttribute(e){return Dc(this,e)}getAttributes(){return Oc(this)}_write(e){e.writeTypeRef(Il)}},tl=e=>new el,nl=class{constructor(e,t=()=>!0){this._filter=t,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc??rc()}[Symbol.iterator](){return this}next(){let e=this._currentNode,t=e&&e.content&&e.content.type;if(e!==null&&(!this._firstCall||e.deleted||!this._filter(t)))do if(t=e.content.type,!e.deleted&&(t.constructor===al||t.constructor===rl)&&t._start!==null)e=t._start;else for(;e!==null;){let t=e.next;if(t!==null){e=t;break}e=e.parent===this._root?null: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})}},rl=class e extends pc{constructor(){super(),this._prelimContent=[]}get firstChild(){let e=this._first;return e?e.content.getContent()[0]:null}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new e}clone(){let t=new e;return t.insert(0,this.toArray().map(e=>e instanceof pc?e.clone():e)),t}get length(){return this.doc??rc(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(e){return new nl(this,e)}querySelector(e){e=e.toUpperCase();let t=new nl(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e).next();return t.done?null:t.value}querySelectorAll(e){return e=e.toUpperCase(),en(new nl(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e))}_callObserver(e,t){fc(this,e,new sl(this,t,e))}toString(){return _c(this,e=>e.toString()).join(``)}toJSON(){return this.toString()}toDOM(e=document,t={},n){let r=e.createDocumentFragment();return n!==void 0&&n._createAssociation(r,this),gc(this,i=>{r.insertBefore(i.toDOM(e,t,n),null)}),r}insert(e,t){this.doc===null?this._prelimContent.splice(e,0,...t):Ls(this.doc,n=>{Sc(n,this,e,t)})}insertAfter(e,t){if(this.doc!==null)Ls(this.doc,n=>{let r=e&&e instanceof pc?e._item:e;bc(n,this,r,t)});else{let n=this._prelimContent,r=e===null?0:n.findIndex(t=>t===e)+1;if(r===0&&e!==null)throw $n(`Reference item not found`);n.splice(r,0,...t)}}delete(e,t=1){this.doc===null?this._prelimContent.splice(e,t):Ls(this.doc,n=>{wc(n,this,e,t)})}toArray(){return hc(this)}push(e){this.insert(this.length,e)}unshift(e){this.insert(0,e)}get(e){return yc(this,e)}slice(e=0,t=this.length){return mc(this,e,t)}forEach(e){gc(this,e)}_write(e){e.writeTypeRef(Rl)}},il=e=>new rl,al=class e extends rl{constructor(e=`UNDEFINED`){super(),this.nodeName=e,this._prelimAttrs=new Map}get nextSibling(){let e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){let e=this._item?this._item.prev:null;return e?e.content.type:null}_integrate(e,t){super._integrate(e,t),this._prelimAttrs.forEach((e,t)=>{this.setAttribute(t,e)}),this._prelimAttrs=null}_copy(){return new e(this.nodeName)}clone(){let t=new e(this.nodeName);return Ir(this.getAttributes(),(e,n)=>{t.setAttribute(n,e)}),t.insert(0,this.toArray().map(e=>e instanceof pc?e.clone():e)),t}toString(){let e=this.getAttributes(),t=[],n=[];for(let t in e)n.push(t);n.sort();let r=n.length;for(let i=0;i<r;i++){let r=n[i];t.push(r+`="`+e[r]+`"`)}let i=this.nodeName.toLocaleLowerCase();return`<${i}${t.length>0?` `+t.join(` `):``}>${super.toString()}</${i}>`}removeAttribute(e){this.doc===null?this._prelimAttrs.delete(e):Ls(this.doc,t=>{Tc(t,this,e)})}setAttribute(e,t){this.doc===null?this._prelimAttrs.set(e,t):Ls(this.doc,n=>{Ec(n,this,e,t)})}getAttribute(e){return Dc(this,e)}hasAttribute(e){return kc(this,e)}getAttributes(e){return e?Ac(this,e):Oc(this)}toDOM(e=document,t={},n){let r=e.createElement(this.nodeName),i=this.getAttributes();for(let e in i){let t=i[e];typeof t==`string`&&r.setAttribute(e,t)}return gc(this,i=>{r.appendChild(i.toDOM(e,t,n))}),n!==void 0&&n._createAssociation(r,this),r}_write(e){e.writeTypeRef(Ll),e.writeKey(this.nodeName)}},ol=e=>new al(e.readKey()),sl=class extends tc{constructor(e,t,n){super(e,n),this.childListChanged=!1,this.attributesChanged=new Set,t.forEach(e=>{e===null?this.childListChanged=!0:this.attributesChanged.add(e)})}},cl=class e extends Ic{constructor(e){super(),this.hookName=e}_copy(){return new e(this.hookName)}clone(){let t=new e(this.hookName);return this.forEach((e,n)=>{t.set(n,e)}),t}toDOM(e=document,t={},n){let r=t[this.hookName],i;return i=r===void 0?document.createElement(this.hookName):r.createDom(this),i.setAttribute(`data-yjs-hook`,this.hookName),n!==void 0&&n._createAssociation(i,this),i}_write(e){e.writeTypeRef(zl),e.writeKey(this.hookName)}},ll=e=>new cl(e.readKey()),ul=class e extends el{get nextSibling(){let e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){let e=this._item?this._item.prev:null;return e?e.content.type:null}_copy(){return new e}clone(){let t=new e;return t.applyDelta(this.toDelta()),t}toDOM(e=document,t,n){let r=e.createTextNode(this.toString());return n!==void 0&&n._createAssociation(r,this),r}toString(){return this.toDelta().map(e=>{let t=[];for(let n in e.attributes){let r=[];for(let t in e.attributes[n])r.push({key:t,value:e.attributes[n][t]});r.sort((e,t)=>e.key<t.key?-1:1),t.push({nodeName:n,attrs:r})}t.sort((e,t)=>e.nodeName<t.nodeName?-1:1);let n=``;for(let e=0;e<t.length;e++){let r=t[e];n+=`<${r.nodeName}`;for(let e=0;e<r.attrs.length;e++){let t=r.attrs[e];n+=` ${t.key}="${t.value}"`}n+=`>`}n+=e.insert;for(let e=t.length-1;e>=0;e--)n+=`</${t[e].nodeName}>`;return n}).join(``)}toJSON(){return this.toString()}_write(e){e.writeTypeRef(Bl)}},dl=e=>new ul,fl=class{constructor(e,t){this.id=e,this.length=t}get deleted(){throw er()}mergeWith(e){return!1}write(e,t,n){throw er()}integrate(e,t){throw er()}},pl=0,ml=class extends fl{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor===e.constructor&&(this.length+=e.length,!0)}integrate(e,t){t>0&&(this.id.clock+=t,this.length-=t),Ss(e.doc.store,this)}write(e,t){e.writeInfo(pl),e.writeLen(this.length-t)}getMissing(e,t){return null}},hl=class e{constructor(e){this.content=e}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new e(this.content)}splice(e){throw er()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeBuf(this.content)}getRef(){return 3}},gl=e=>new hl(e.readBuf()),_l=class e{constructor(e){this.len=e}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new e(this.len)}splice(t){let n=new e(this.len-t);return this.len=t,n}mergeWith(e){return this.len+=e.len,!0}integrate(e,t){vo(e.deleteSet,t.id.client,t.id.clock,this.len),t.markDeleted()}delete(e){}gc(e){}write(e,t){e.writeLen(this.len-t)}getRef(){return 1}},vl=e=>new _l(e.readLen()),yl=(e,t)=>new To({guid:e,...t,shouldLoad:t.shouldLoad||t.autoLoad||!1}),bl=class e{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;let t={};this.opts=t,e.gc||(t.gc=!1),e.autoLoad&&(t.autoLoad=!0),e.meta!==null&&(t.meta=e.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new e(yl(this.doc.guid,this.opts))}splice(e){throw er()}mergeWith(e){return!1}integrate(e,t){this.doc._item=t,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,t){e.writeString(this.doc.guid),e.writeAny(this.opts)}getRef(){return 9}},xl=e=>new bl(yl(e.readString(),e.readAny())),Sl=class e{constructor(e){this.embed=e}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new e(this.embed)}splice(e){throw er()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeJSON(this.embed)}getRef(){return 5}},Cl=e=>new Sl(e.readJSON()),wl=class e{constructor(e,t){this.key=e,this.value=t}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new e(this.key,this.value)}splice(e){throw er()}mergeWith(e){return!1}integrate(e,t){let n=t.parent;n._searchMarker=null,n._hasFormatting=!0}delete(e){}gc(e){}write(e,t){e.writeKey(this.key),e.writeJSON(this.value)}getRef(){return 6}},Tl=e=>new wl(e.readKey(),e.readJSON()),El=class e{constructor(e){this.arr=e}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new e(this.arr)}splice(t){let n=new e(this.arr.slice(t));return this.arr=this.arr.slice(0,t),n}mergeWith(e){return this.arr=this.arr.concat(e.arr),!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){let n=this.arr.length;e.writeLen(n-t);for(let r=t;r<n;r++){let t=this.arr[r];e.writeString(t===void 0?`undefined`:JSON.stringify(t))}}getRef(){return 2}},Dl=e=>{let t=e.readLen(),n=[];for(let r=0;r<t;r++){let t=e.readString();t===`undefined`?n.push(void 0):n.push(JSON.parse(t))}return new El(n)},Ol=ti(`node_env`)===`development`,kl=class e{constructor(e){this.arr=e,Ol&&Wr(e)}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new e(this.arr)}splice(t){let n=new e(this.arr.slice(t));return this.arr=this.arr.slice(0,t),n}mergeWith(e){return this.arr=this.arr.concat(e.arr),!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){let n=this.arr.length;e.writeLen(n-t);for(let r=t;r<n;r++){let t=this.arr[r];e.writeAny(t)}}getRef(){return 8}},Al=e=>{let t=e.readLen(),n=[];for(let r=0;r<t;r++)n.push(e.readAny());return new kl(n)},jl=class e{constructor(e){this.str=e}getLength(){return this.str.length}getContent(){return this.str.split(``)}isCountable(){return!0}copy(){return new e(this.str)}splice(t){let n=new e(this.str.slice(t));this.str=this.str.slice(0,t);let r=this.str.charCodeAt(t-1);return r>=55296&&r<=56319&&(this.str=this.str.slice(0,t-1)+`�`,n.str=`�`+n.str.slice(1)),n}mergeWith(e){return this.str+=e.str,!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeString(t===0?this.str:this.str.slice(t))}getRef(){return 4}},Ml=e=>new jl(e.readString()),Nl=[Pc,Lc,tl,ol,il,ll,dl],Pl=0,Fl=1,Il=2,Ll=3,Rl=4,zl=5,Bl=6,Vl=class e{constructor(e){this.type=e}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new e(this.type._copy())}splice(e){throw er()}mergeWith(e){return!1}integrate(e,t){this.type._integrate(e.doc,t)}delete(e){let t=this.type._start;for(;t!==null;)t.deleted?t.id.clock<(e.beforeState.get(t.id.client)||0)&&e._mergeStructs.push(t):t.delete(e),t=t.right;this.type._map.forEach(t=>{t.deleted?t.id.clock<(e.beforeState.get(t.id.client)||0)&&e._mergeStructs.push(t):t.delete(e)}),e.changed.delete(this.type)}gc(e){let t=this.type._start;for(;t!==null;)t.gc(e,!0),t=t.right;this.type._start=null,this.type._map.forEach(t=>{for(;t!==null;)t.gc(e,!0),t=t.left}),this.type._map=new Map}write(e,t){this.type._write(e)}getRef(){return 7}},Hl=e=>new Vl(Nl[e.readTypeRef()](e)),Ul=(e,t)=>{let n=t,r=0,i;do r>0&&(n=$(n.client,n.clock+r)),i=ws(e,n),r=n.clock-i.id.clock,n=i.redone;while(n!==null&&i instanceof Jl);return{item:i,diff:r}},Wl=(e,t)=>{for(;e!==null&&e.keep!==t;)e.keep=t,e=e.parent._item},Gl=(e,t,n)=>{let{client:r,clock:i}=t.id,a=new Jl($(r,i+n),t,$(r,i+n-1),t.right,t.rightOrigin,t.parent,t.parentSub,t.content.splice(n));return t.deleted&&a.markDeleted(),t.keep&&(a.keep=!0),t.redone!==null&&(a.redone=$(t.redone.client,t.redone.clock+n)),t.right=a,a.right!==null&&(a.right.left=a),e._mergeStructs.push(a),a.parentSub!==null&&a.right===null&&a.parent._map.set(a.parentSub,a),t.length=n,a},Kl=(e,t)=>nn(e,e=>ho(e.deletions,t)),ql=(e,t,n,r,i,a)=>{let o=e.doc,s=o.store,c=o.clientID,l=t.redone;if(l!==null)return Es(e,l);let u=t.parent._item,d=null,f;if(u!==null&&u.deleted===!0){if(u.redone===null&&(!n.has(u)||ql(e,u,n,r,i,a)===null))return null;for(;u.redone!==null;)u=Es(e,u.redone)}let p=u===null?t.parent:u.content.type;if(t.parentSub===null){for(d=t.left,f=t;d!==null;){let t=d;for(;t!==null&&t.parent._item!==u;)t=t.redone===null?null:Es(e,t.redone);if(t!==null&&t.parent._item===u){d=t;break}d=d.left}for(;f!==null;){let t=f;for(;t!==null&&t.parent._item!==u;)t=t.redone===null?null:Es(e,t.redone);if(t!==null&&t.parent._item===u){f=t;break}f=f.right}}else{if(f=null,t.right&&!i){for(d=t;d!==null&&d.right!==null&&(d.right.redone||ho(r,d.right.id)||Kl(a.undoStack,d.right.id)||Kl(a.redoStack,d.right.id));)for(d=d.right;d.redone;)d=Es(e,d.redone);if(d&&d.right!==null)return null}else d=p._map.get(t.parentSub)||null;d!==null&&d.parent._item!==u&&(d=p._map.get(t.parentSub)||null)}let m=$(c,xs(s,c)),h=new Jl(m,d,d&&d.lastId,f,f&&f.id,p,t.parentSub,t.content.copy());return t.redone=m,Wl(h,!0),h.integrate(e,0),h},Jl=class e extends fl{constructor(e,t,n,r,i,a,o,s){super(e,s.getLength()),this.origin=n,this.left=t,this.right=r,this.rightOrigin=i,this.parent=a,this.parentSub=o,this.redone=null,this.content=s,this.info=this.content.isCountable()?2:0}set marker(e){(this.info&8)>0!==e&&(this.info^=8)}get marker(){return(this.info&8)>0}get keep(){return(this.info&1)>0}set keep(e){this.keep!==e&&(this.info^=1)}get countable(){return(this.info&2)>0}get deleted(){return(this.info&4)>0}set deleted(e){this.deleted!==e&&(this.info^=4)}markDeleted(){this.info|=4}getMissing(t,n){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=xs(n,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=xs(n,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===ns&&this.id.client!==this.parent.client&&this.parent.clock>=xs(n,this.parent.client))return this.parent.client;if(this.origin&&=(this.left=Ds(t,n,this.origin),this.left.lastId),this.rightOrigin&&=(this.right=Es(t,this.rightOrigin),this.right.id),this.left&&this.left.constructor===ml||this.right&&this.right.constructor===ml)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===e?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===e&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===ns){let e=ws(n,this.parent);this.parent=e.constructor===ml?null:e.content.type}return null}integrate(e,t){if(t>0&&(this.id.clock+=t,this.left=Ds(e,e.doc.store,$(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(t),this.length-=t),this.parent){if(!this.left&&(!this.right||this.right.left!==null)||this.left&&this.left.right!==this.right){let t=this.left,n;if(t!==null)n=t.right;else if(this.parentSub!==null)for(n=this.parent._map.get(this.parentSub)||null;n!==null&&n.left!==null;)n=n.left;else n=this.parent._start;let r=new Set,i=new Set;for(;n!==null&&n!==this.right;){if(i.add(n),r.add(n),rs(this.origin,n.origin)){if(n.id.client<this.id.client)t=n,r.clear();else if(rs(this.rightOrigin,n.rightOrigin))break}else if(n.origin!==null&&i.has(ws(e.doc.store,n.origin)))r.has(ws(e.doc.store,n.origin))||(t=n,r.clear());else break;n=n.right}this.left=t}if(this.left!==null){let e=this.left.right;this.right=e,this.left.right=this}else{let e;if(this.parentSub!==null)for(e=this.parent._map.get(this.parentSub)||null;e!==null&&e.left!==null;)e=e.left;else e=this.parent._start,this.parent._start=this;this.right=e}this.right===null?this.parentSub!==null&&(this.parent._map.set(this.parentSub,this),this.left!==null&&this.left.delete(e)):this.right.left=this,this.parentSub===null&&this.countable&&!this.deleted&&(this.parent._length+=this.length),Ss(e.doc.store,this),this.content.integrate(e,this),Ms(e,this.parent,this.parentSub),(this.parent._item!==null&&this.parent._item.deleted||this.parentSub!==null&&this.right!==null)&&this.delete(e)}else new ml(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:$(this.id.client,this.id.clock+this.length-1)}mergeWith(e){if(this.constructor===e.constructor&&rs(e.origin,this.lastId)&&this.right===e&&rs(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)){let t=this.parent._searchMarker;return t&&t.forEach(t=>{t.p===e&&(t.p=this,!this.deleted&&this.countable&&(t.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){let t=this.parent;this.countable&&this.parentSub===null&&(t._length-=this.length),this.markDeleted(),vo(e.deleteSet,this.id.client,this.id.clock,this.length),Ms(e,t,this.parentSub),this.content.delete(e)}}gc(e,t){if(!this.deleted)throw tr();this.content.gc(e),t?Os(e,this,new ml(this.id,this.length)):this.content=new _l(this.length)}write(e,t){let n=t>0?$(this.id.client,this.id.clock+t-1):this.origin,r=this.rightOrigin,i=this.parentSub,a=this.content.getRef()&31|(n===null?0:128)|(r===null?0:64)|(i===null?0:32);if(e.writeInfo(a),n!==null&&e.writeLeftID(n),r!==null&&e.writeRightID(r),n===null&&r===null){let t=this.parent;if(t._item!==void 0){let n=t._item;if(n===null){let n=is(t);e.writeParentInfo(!0),e.writeString(n)}else e.writeParentInfo(!1),e.writeLeftID(n.id)}else t.constructor===String?(e.writeParentInfo(!0),e.writeString(t)):t.constructor===ns?(e.writeParentInfo(!1),e.writeLeftID(t)):tr();i!==null&&e.writeString(i)}this.content.write(e,t)}},Yl=(e,t)=>Xl[t&31](e),Xl=[()=>{tr()},vl,Dl,gl,Ml,Cl,Tl,Hl,Al,xl,()=>{tr()}],Zl=10,Ql=class extends fl{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor===e.constructor&&(this.length+=e.length,!0)}integrate(e,t){tr()}write(e,t){e.writeInfo(Zl),Z(e.restEncoder,this.length-t)}getMissing(e,t){return null}},$l=typeof globalThis<`u`?globalThis:typeof window<`u`?window:typeof global<`u`?global:{},eu=`__ $YJS$ __`;$l[eu]===!0&&console.error(`Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438`),$l[eu]=!0;function tu(e,t,n){let r=[],i=t.contentFrom,a=t.contentFrom;for(;a<=t.contentTo;){if(a<t.contentTo&&ht(e,a)){a=_t(e,a),e[a]===`
|
|
6
|
+
`&&(a+=1);continue}if(a!==t.contentTo&&(!n||e[a]!==`,`)){a+=1;continue}let o=nu(e,i,a);o&&r.push(o),i=a+1,a+=1}return r}function nu(e,t,n){let r=[],i=t;for(;i<n;)ht(e,i)?(i=_t(e,i),e[i]===`
|
|
7
|
+
`&&(i+=1)):(r.push({character:e[i],index:i}),i+=1);let a=0,o=r.length;for(;a<o&&/\s/.test(r[a].character);)a+=1;for(;o>a&&/\s/.test(r[o-1].character);)--o;return a===o?null:{path:r.slice(a,o).map(e=>e.character).join(``),command:``,from:r[a].index,to:r[o-1].index+1}}function ru(e,t){let n=ft(e,t);if(n>=e.length||/[\\{}\[\]#~]/.test(e[n]))return null;let r=n;for(;r<e.length&&!/\s/.test(e[r])&&!ht(e,r)&&!/[\\{}\[\]#~]/.test(e[r]);)r+=1;return r===n?null:{path:e.slice(n,r),command:``,from:n,to:r}}function iu(e){let t=[];return vt(e,n=>{let r=n.name.toLowerCase();if(r===`input`||r===`include`||r===`subfile`){let i=dt(e,n.to,1)[0];if(i)for(let r of tu(e,i,!1))t.push({...r,command:n.name});else if(r===`input`){let r=ru(e,n.to);r&&t.push({...r,command:n.name})}return}if(r!==`import`&&r!==`subimport`&&r!==`includefrom`&&r!==`inputfrom`&&r!==`subinputfrom`&&r!==`subincludefrom`)return;let i=dt(e,n.to,2);if(i.length!==2)return;let a=tu(e,i[0],!1)[0]?.path??``,o=tu(e,i[1],!1)[0];if(!o)return;let s=a&&!a.endsWith(`/`)?`/`:``;t.push({path:a+s+o.path,command:n.name,from:o.from,to:o.to,directory:a})}),t}var au=(e,t)=>e>>>t|e<<32-t,ou=e=>au(e,2)^au(e,13)^au(e,22),su=e=>au(e,6)^au(e,11)^au(e,25),cu=e=>au(e,7)^au(e,18)^e>>>3,lu=e=>au(e,17)^au(e,19)^e>>>10,uu=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]),du=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),fu=class{constructor(){let e=new ArrayBuffer(320);this._H=new Uint32Array(e,0,8),this._H.set(du),this._W=new Uint32Array(e,64,64)}_updateHash(){let e=this._H,t=this._W;for(let e=16;e<64;e++)t[e]=lu(t[e-2])+t[e-7]+cu(t[e-15])+t[e-16];let n=e[0],r=e[1],i=e[2],a=e[3],o=e[4],s=e[5],c=e[6],l=e[7];for(let e=0,u,d;e<64;e++)u=l+su(o)+(o&s^~o&c)+uu[e]+t[e]>>>0,d=ou(n)+(n&r^n&i^r&i)>>>0,l=c,c=s,s=o,o=a+u>>>0,a=i,i=r,r=n,n=u+d>>>0;e[0]+=n,e[1]+=r,e[2]+=i,e[3]+=a,e[4]+=o,e[5]+=s,e[6]+=c,e[7]+=l}digest(e){let t=0;for(;t+56<=e.length;){let n=0;for(;n<16&&t+3<e.length;n++)this._W[n]=e[t++]<<24|e[t++]<<16|e[t++]<<8|e[t++];if(t%64!=0){for(this._W.fill(0,n,16);t<e.length;)this._W[n]|=e[t]<<(3-t%4)*8,t++;this._W[n]|=128<<(3-t%4)*8}this._updateHash()}let n=t%64!=0;this._W.fill(0,0,16);let r=0;for(;t<e.length;r++)for(let n=3;n>=0&&t<e.length;n--)this._W[r]|=e[t++]<<n*8;n||(this._W[r-(t%4==0?0:1)]|=128<<(3-t%4)*8),this._W[14]=e.byteLength/mn,this._W[15]=e.byteLength*8,this._updateHash();let i=new Uint8Array(32);for(let e=0;e<this._H.length;e++)for(let t=0;t<4;t++)i[e*4+t]=this._H[e]>>>(3-t)*8;return i}},pu=e=>new fu().digest(e);function mu(e){return Array.from(pu(new TextEncoder().encode(e)),e=>e.toString(16).padStart(2,`0`)).join(``)}function hu(e){for(let t=0;t<e.length;t+=1)e[t]=Math.floor(Math.random()*256);return e}function gu(e){e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``);return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}function _u(e=globalThis.crypto){if(typeof e?.randomUUID==`function`)return e.randomUUID();let t=new Uint8Array(16);return gu(typeof e?.getRandomValues==`function`?e.getRandomValues(t):hu(t))}function vu(e){return/\.(?:tex|sty|cls|ltx|dtx|ins|txt|md|markdown|rst)$/i.test(e.trim())}function yu(e){return/\.(?:tex|sty|cls)$/i.test(e.trim())}function bu(){let e={status:`loading`,error:``},t=new Set,n=(n,r=``)=>{if(e.status!==n||e.error!==r){e={status:n,error:r};for(let e of t)e()}};return{getSnapshot:()=>e,subscribe:e=>(t.add(e),()=>t.delete(e)),loading:()=>n(`loading`),working:()=>n(`working`),failed:e=>n(`error`,e instanceof Error?e.message:String(e))}}var xu=bu(),Su=/\.(?:tex|bib|cls|sty)$/i,Cu=3e4,wu=null,Tu=!1,Eu=null,Du=1,Ou=new Map,ku=[],Au=null,ju=null,Mu=class extends Error{kind;constructor(e,t){super(t),this.kind=e,this.name=`TexFmtError`}};function Nu(e){return e instanceof Mu}function Pu(e){wu?.terminate(),wu=null,Tu=!1,Eu!==null&&window.clearTimeout(Eu),Eu=null,Au=null,ku.length=0,ju=null,xu.failed(e);for(let t of Ou.values())t.timeout!==null&&window.clearTimeout(t.timeout),t.reject(e);Ou.clear()}function Fu(){if(Au!==null||ku.length===0)return;let e;try{e=Iu()}catch(e){Pu(e instanceof Mu?e:new Mu(`load`,`The bundled tex-fmt formatter could not be loaded.`));return}if(!Tu)return;let t=ku.shift();if(t===void 0)return;let n=Ou.get(t);if(!n)Fu();else{Au=t,n.timeout=window.setTimeout(()=>{Au===t&&Pu(new Mu(`result`,`The formatter did not respond within 30 seconds.`))},Cu);try{e.postMessage({...n.request,id:t})}catch{Pu(new Mu(`load`,`The formatter worker could not receive the source.`))}}}function Iu(){if(wu)return wu;if(typeof Worker>`u`){let e=new Mu(`load`,`This browser does not support formatter workers.`);throw xu.failed(e),e}xu.loading();try{wu=new Worker(new URL(new URL(`latexFormatterWorker-BWiogBYE.js`,import.meta.url).href,``+import.meta.url),{type:`module`,name:`texlite-latex-formatter`}),Eu=window.setTimeout(()=>{Tu||Pu(new Mu(`load`,`The formatter did not finish loading within 30 seconds.`))},Cu)}catch{let e=new Mu(`load`,`The bundled tex-fmt formatter could not be loaded.`);throw xu.failed(e),e}return wu.onmessage=e=>{let t=e.data;if(t&&`type`in t){t.type===`ready`&&(Tu=!0,Eu!==null&&window.clearTimeout(Eu),Eu=null,Fu());return}if(!t||typeof t.id!=`number`){Pu(new Mu(`result`,`The formatter worker returned an invalid response.`));return}let n=Ou.get(t.id);if(n){if(Ou.delete(t.id),n.timeout!==null&&window.clearTimeout(n.timeout),Au===t.id&&(Au=null),t.ok)xu.working(),n.resolve(t.result),Fu();else{let e=new Mu(t.kind,t.message);t.kind===`format`?(xu.working(),n.reject(e),Fu()):(n.reject(e),Pu(e))}}},wu.onerror=()=>{Pu(new Mu(`load`,`The bundled tex-fmt formatter could not be loaded.`))},wu.onmessageerror=()=>{Pu(new Mu(`result`,`The formatter worker returned an unreadable response.`))},wu}function Lu(e){let t=Du++;return new Promise((n,r)=>{Ou.set(t,{request:e,resolve:n,reject:r,timeout:null}),ku.push(t),Fu()})}function Ru(e,t=``){return Lu({action:`format`,source:e,config:t})}async function zu(){wu&&xu.getSnapshot().status===`working`||(ju||=Lu({action:`probe`}).then(()=>void 0).finally(()=>{ju=null}),await ju)}async function Bu(){(wu||Ou.size)&&Pu(new Mu(`load`,`The formatter runtime was reloaded.`)),xu.loading(),await zu()}function Vu(e){return Su.test(e)}function Hu(e){return e.match(/(?:\r?\n)+$/)?.[0]??``}function Uu(e,t){let n=Hu(e),r=(n?e.slice(0,-n.length):e).split(/\r?\n/).find(e=>e.trim())?.match(/^[\t ]*/)?.[0]??``,i=t.replace(/(?:\r?\n)+$/,``);return`${r?i.split(`
|
|
8
|
+
`).map(e=>e&&`${r}${e}`).join(`
|
|
9
|
+
`):i}${n}`}async function Wu(e,t,n=0){return Lu({action:`diff`,source:e,formatted:t,baseOffset:n})}var Gu=null,Ku=1,qu=new Map,Ju=class extends Error{kind;constructor(e){super(`BibTeX formatter: ${e}`),this.kind=e,this.name=`BibtexFormatterError`}};function Yu(e){Gu?.terminate(),Gu=null;for(let t of qu.values())clearTimeout(t.timeout),t.reject(new Ju(e));qu.clear()}function Xu(){if(Gu)return Gu;let e=new Worker(new URL(new URL(`bibtexFormatterWorker-Bp8kjjvw.js`,import.meta.url).href,``+import.meta.url),{type:`module`,name:`texlite-bibtex-formatter`});return Gu=e,e.onmessage=({data:t})=>{if(Gu!==e)return;if(!t||typeof t.id!=`number`||typeof t.ok!=`boolean`){Yu(`unavailable`);return}let n=qu.get(t.id);n&&(t.ok&&(t.action!==n.action||(t.action===`format`?typeof t.result!=`string`:!Zu(t.result)))?Yu(`unavailable`):(clearTimeout(n.timeout),qu.delete(t.id),t.ok?n.resolve(t.result):t.kind===`too-large`||t.kind===`invalid`?n.reject(new Ju(t.kind)):(n.reject(new Ju(`unavailable`)),Yu(`unavailable`))))},e.onerror=e.onmessageerror=()=>{Gu===e&&Yu(`unavailable`)},e}function Zu(e){if(!Array.isArray(e))return!1;let t=0;return e.every(e=>!e||!Number.isSafeInteger(e.from)||!Number.isSafeInteger(e.to)||e.from<t||e.to<e.from||typeof e.replacement!=`string`?!1:(t=e.to,!0))}function Qu(e){return new Promise((t,n)=>{let r;try{r=Xu()}catch{n(new Ju(`unavailable`));return}let i=Ku++,a=setTimeout(()=>Yu(`timeout`),3e4);qu.set(i,{action:e.action,resolve:t,reject:n,timeout:a});try{r.postMessage({...e,id:i})}catch{Yu(`unavailable`)}})}function $u(e,t){return Qu({action:`format`,source:e,maxBytes:t})}function ed(e,t,n=0){return Qu({action:`diff`,source:e,formatted:t,baseOffset:n})}function td(e,t=null){let n=nd(e),r=t===`succeeded`||t===null&&ad(e)?[]:rd(n.filter(od));return{warnings:rd(nd(id(e)).filter(e=>!od(e)&&sd(e))),errors:r}}function nd(e){return e.split(`
|
|
10
|
+
`).map(e=>e.trim()).filter(Boolean)}function rd(e){return[...new Set(e)]}function id(e){let t=/^Running ['"][^\n]*(?:pdf|xe|lua)latex(?:\s|['"])[^\n]*$/gim,n=-1;for(let r of e.matchAll(t))n=r.index;return n>=0?e.slice(n):e}function ad(e){return/Latexmk: All targets .* are up-to-date/i.test(e)&&/Output written on .*\.pdf/i.test(e)}function od(e){return/^!\s/.test(e)||/(?:^|:\s)(?:LaTeX|Package|Class|pdfTeX|XeTeX|LuaTeX)?\s*Error:/i.test(e)||/^Latexmk:.*(?:\bErrors?,|did not complete making targets|failure)/i.test(e)||/^Collected error summary/i.test(e)||/\b(?:fatal error|emergency stop|undefined control sequence|no output pdf|no pages of output)\b/i.test(e)||/\b(?:bibtex|biber) errors?:/i.test(e)||/^error, and then rerun latexmk/i.test(e)}function sd(e){return/\bwarnings?\b|overfull|underfull|badness/i.test(e)}function cd(e){return/\.(?:md|txt)$/i.test(e)}var ld=`\\p{Script=Han}\\p{Script=Hiragana}\\p{Script=Katakana}`,ud=RegExp(`[${ld}]|[^\\s${ld}]+`,`gu`),dd=/[\p{L}\p{N}]/u,fd=/[\p{L}\p{N}]/gu;function pd(e){let t=0;for(let[n]of e.matchAll(ud))dd.test(n)&&(t+=1);return{words:t,characters:e.match(fd)?.length??0}}var md=Object.freeze({}),hd=class{threads=new Map;listeners=new Map;newComments=new Map;getThread(e){return this.threads.get(e)??md}subscribe(e,t){let n=this.listeners.get(e)??new Set;return n.add(t),this.listeners.set(e,n),()=>{n.delete(t),n.size||this.listeners.delete(e)}}publish(e,t){Object.keys(t).length?this.threads.set(e,t):this.threads.delete(e);for(let t of this.listeners.get(e)??[])t()}isPending(e){return Object.values(this.getThread(e)).some(e=>e?.pending)}open(e,t,n=``){if(this.isPending(e))return;let r={...this.getThread(e)};if(t.startsWith(`edit-reply:`))for(let[e,t]of Object.entries(r))e.startsWith(`edit-reply:`)&&t?.open&&(r[e]={...t,open:!1});r[t]={content:n,pending:!1,error:``,...r[t],open:!0},this.publish(e,r)}change(e,t,n){let r=this.getThread(e)[t];r&&!this.isPending(e)&&this.publish(e,{...this.getThread(e),[t]:{...r,content:n}})}discard(e,t){let n={...this.getThread(e)};t===void 0?this.publish(e,md):(delete n[t],this.publish(e,n))}async submit(e,t,n,r){let i=this.getThread(e)[t];if(!i||!i.content.trim()||this.isPending(e))return!1;let a={...i,pending:!0,error:``};this.publish(e,{...this.getThread(e),[t]:a});let o=r;try{if(await n(i.content))return this.getThread(e)[t]===a&&this.discard(e,t),!0}catch(e){o=K(e)}return this.getThread(e)[t]===a&&this.publish(e,{...this.getThread(e),[t]:{...i,pending:!1,error:o}}),!1}getNew(e){return this.newComments.get(e)}setNew(e){this.newComments.set(e.filePath,{...e,selection:{...e.selection},suggestion:e.suggestion?{...e.suggestion}:e.suggestion})}discardNew(e){this.newComments.delete(e)}},gd=q.createContext(void 0),_d=e=>{let t=q.useContext(gd);if(e)return e;if(!t)throw Error(`No QueryClient set, use QueryClientProvider to set one`);return t},vd=({client:e,children:t})=>(q.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,J.jsx)(gd.Provider,{value:e,children:t})),yd={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},bd=new class{#e=yd;setTimeoutProvider(e){this.#e=e}setTimeout(e,t){return this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}};function xd(e){setTimeout(e,0)}var Sd=typeof window>`u`||`Deno`in globalThis;function Cd(){}function wd(e,t){return typeof e==`function`?e(t):e}function Td(e){return typeof e==`number`&&e>=0&&e!==1/0}function Ed(e,t){return Math.max(e+(t||0)-Date.now(),0)}function Dd(e,t){return typeof e==`function`?e(t):e}function Od(e,t){let{type:n=`all`,exact:r,fetchStatus:i,predicate:a,queryKey:o,stale:s}=e;if(o){if(r){if(t.queryHash!==Ad(o,t.options))return!1}else if(!Md(t.queryKey,o))return!1}if(n!==`all`){let e=t.isActive();if(n===`active`&&!e||n===`inactive`&&e)return!1}return!(typeof s==`boolean`&&t.isStale()!==s||i&&i!==t.state.fetchStatus||a&&!a(t))}function kd(e,t){let{exact:n,status:r,predicate:i,mutationKey:a}=e;if(a){if(!t.options.mutationKey)return!1;if(n){if(jd(t.options.mutationKey)!==jd(a))return!1}else if(!Md(t.options.mutationKey,a))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function Ad(e,t){return(t?.queryKeyHashFn||jd)(e)}function jd(e){return JSON.stringify(e,(e,t)=>Ld(t)?Object.keys(t).sort().reduce((e,n)=>(e[n]=t[n],e),{}):t)}function Md(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(e&&t&&typeof e==`object`&&typeof t==`object`){if(Array.isArray(e)&&Array.isArray(t)){if(t.length>e.length)return!1;for(let n=0;n<t.length;n++)if(!Md(e[n],t[n]))return!1;return!0}let n=Object.keys(t);for(let r of n)if(!Md(e[r],t[r]))return!1;return!0}return!1}var Nd=Object.prototype.hasOwnProperty;function Pd(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=Id(e)&&Id(t);if(!r&&!(Ld(e)&&Ld(t)))return t;let i=(r?e:Object.keys(e)).length,a=r?t:Object.keys(t),o=a.length,s=r?Array(o):{},c=0;for(let l=0;l<o;l++){let o=r?l:a[l],u=e[o],d=t[o];if(u===d){s[o]=u,(r?l<i:Nd.call(e,o))&&c++;continue}if(u===null||d===null||typeof u!=`object`||typeof d!=`object`){s[o]=d;continue}let f=Pd(u,d,n+1);s[o]=f,f===u&&c++}return i===o&&c===i?e:s}function Fd(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(let n in e)if(e[n]!==t[n])return!1;return!0}function Id(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Ld(e){if(!Rd(e))return!1;let t=Object.getPrototypeOf(e),n=t?.constructor;if(n===void 0)return!0;if(typeof n!=`function`)return!1;let r=n.prototype;return!(!Rd(r)||!r.hasOwnProperty(`isPrototypeOf`)||t!==Object.prototype)}function Rd(e){return Object.prototype.toString.call(e)===`[object Object]`}function zd(e){return new Promise(t=>{bd.setTimeout(t,e)})}function Bd(e,t,n){return typeof n.structuralSharing==`function`?n.structuralSharing(e,t):n.structuralSharing===!1?t:Pd(e,t)}function Vd(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function Hd(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var Ud=Symbol();function Wd(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===Ud?()=>Promise.reject(Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function Gd(e,t){return typeof e==`function`?e(...t):!!e}function Kd(e,t,n){let r=!1,i;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(i??=t(),r||(r=!0,i.aborted?n():i.addEventListener(`abort`,n,{once:!0})),i)}),e}var qd=()=>Sd,Jd=()=>qd(),Yd=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},Xd=new class extends Yd{#e;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&window.addEventListener){let t=()=>e();return window.addEventListener(`visibilitychange`,t,!1),()=>{window.removeEventListener(`visibilitychange`,t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(e=>{typeof e==`boolean`?this.setFocused(e):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){let e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e==`boolean`?this.#e:globalThis.document?.visibilityState!==`hidden`}},Zd=xd;function Qd(){let e=[],t=0,n=e=>{e()},r=e=>{e()},i=Zd,a=r=>{t?e.push(r):i(()=>{n(r)})},o=()=>{let t=e;e=[],t.length&&i(()=>{r(()=>{t.forEach(e=>{n(e)})})})};return{batch:e=>{let n;t++;try{n=e()}finally{t--,t||o()}return n},batchCalls:e=>(...t)=>{a(()=>{e(...t)})},schedule:a,setNotifyFunction:e=>{n=e},setBatchNotifyFunction:e=>{r=e},setScheduler:e=>{i=e}}}var $d=Qd(),ef=new class extends Yd{#e=!0;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&window.addEventListener){let t=()=>e(!0),n=()=>e(!1);return window.addEventListener(`online`,t,!1),window.addEventListener(`offline`,n,!1),()=>{window.removeEventListener(`online`,t),window.removeEventListener(`offline`,n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(t=>{t(e)}))}isOnline(){return this.#e}};function tf(e){return Math.min(1e3*2**e,3e4)}function nf(e){return(e??`online`)!==`online`||ef.isOnline()}var rf=class extends Error{constructor(e){super(`CancelledError`),this.revert=e?.revert,this.silent=e?.silent}};function af(e){let t=!1,n=0,r,i=`pending`,a,o,s=new Promise((e,t)=>{a=e,o=t});s.catch(Cd);let c=()=>i!==`pending`,l=t=>{if(!c()){let n=new rf(t);h(n),e.onCancel?.(n)}},u=()=>{t=!0},d=()=>{t=!1},f=()=>Xd.isFocused()&&(e.networkMode===`always`||ef.isOnline())&&e.canRun(),p=()=>nf(e.networkMode)&&e.canRun(),m=e=>{c()||(r?.(),i=`resolved`,a(e))},h=e=>{c()||(r?.(),i=`rejected`,o(e))},g=t=>new Promise(n=>{r=e=>{(c()||t())&&n(e)},e.onPause?.()}).then(()=>{r=void 0,c()||e.onContinue?.()}),_=()=>{if(c())return;let r,i=n===0?e.initialPromise:void 0;try{r=i??e.fn()}catch(e){r=Promise.reject(e)}Promise.resolve(r).then(m).catch(r=>{if(c())return;let i=e.retry??(Jd()?0:3),a=e.retryDelay??tf,o=typeof a==`function`?a(n,r):a,s=i===!0||typeof i==`number`&&n<i||typeof i==`function`&&i(n,r);t||!s?h(r):(n++,e.onFail?.(n,r),zd(o).then(()=>f()?void 0:g(f)).then(()=>{t?h(r):_()}))})};return{promise:s,status:()=>i,cancel:l,continue:()=>(r?.(),s),cancelRetry:u,continueRetry:d,canStart:p,start:()=>(p()?_():g(p).then(_),s)}}var of=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Td(this.gcTime)&&(this.#e=bd.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Jd()?1/0:3e5))}clearGcTimeout(){this.#e!==void 0&&(bd.clearTimeout(this.#e),this.#e=void 0)}};function sf(e){return{onFetch:(t,n)=>{let r=t.options,i=t.fetchOptions?.meta?.fetchMore?.direction,a=t.state.data?.pages||[],o=t.state.data?.pageParams||[],s={pages:[],pageParams:[]},c=0,l=async()=>{let n=!1,l=e=>{Kd(e,()=>t.signal,()=>n=!0)},u=Wd(t.options,t.fetchOptions),d=async(e,r,i)=>{if(n)return Promise.reject(t.signal.reason);if(r==null&&e.pages.length)return Promise.resolve(e);let a=(()=>{let e={client:t.client,queryKey:t.queryKey,pageParam:r,direction:i?`backward`:`forward`,meta:t.options.meta};return l(e),e})(),o=await u(a),{maxPages:s}=t.options,c=i?Hd:Vd;return{pages:c(e.pages,o,s),pageParams:c(e.pageParams,r,s)}};if(i&&a.length){let e=i===`backward`,t=e?lf:cf,n={pages:a,pageParams:o};s=await d(n,t(r,n),e)}else{let t=e??a.length;do{let e=c===0?o[0]===void 0?r.initialPageParam:o[0]:cf(r,s);if(c>0&&e==null)break;s=await d(s,e),c++}while(c<t)}return s};t.fetchFn=t.options.persister?()=>t.options.persister?.(l,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):l}}}function cf(e,{pages:t,pageParams:n}){let r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function lf(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}var uf=class extends of{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e){super(),this.#s=!1,this.#o=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#i=e.client,this.#r=this.#i.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=pf(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#e}get promise(){return this.#a?.promise}setOptions(e){if(this.options={...this.#o,...e},e?._type&&(this.#e=e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let e=pf(this.options);e.data!==void 0&&(this.setState(ff(e.data,e.dataUpdatedAt)),this.#t=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus===`idle`&&this.#r.remove(this)}setData(e,t){let n=Bd(this.state.data,e,this.options);return this.#c({data:n,type:`success`,dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e){this.#c({type:`setState`,state:e})}cancel(e){let t=this.#a?.promise;return this.#a?.cancel(e),t?t.then(Cd).catch(Cd):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#t}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>Dd(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Ud||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0&&this.observers.some(e=>Dd(e.options.staleTime,this)===`static`)}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e===`static`?!1:this.state.isInvalidated?!0:!Ed(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(e=>e.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#a?.continue()}onOnline(){this.observers.find(e=>e.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#a?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#r.notify({type:`observerAdded`,query:this,observer:e}))}removeObserver(e){let t=this.observers.indexOf(e);t!==-1&&(this.observers.splice(t,1),this.observers.length||(this.#a&&(this.#s||this.state.fetchStatus===`paused`&&this.state.status===`pending`?this.#a.cancel({revert:!0}):this.#a.cancelRetry()),this.scheduleGc()),this.#r.notify({type:`observerRemoved`,query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#c({type:`invalidate`})}async fetch(e,t){if(this.state.fetchStatus!==`idle`&&this.#a?.status()!==`rejected`){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#a)return this.#a.continueRetry(),this.#a.promise}if(e&&this.setOptions(e),!this.options.queryFn){let e=this.observers.find(e=>e.options.queryFn);e&&this.setOptions(e.options)}let n=new AbortController,r=e=>{Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(this.#s=!0,n.signal)})},i=()=>{let e=Wd(this.options,t),n=(()=>{let e={client:this.#i,queryKey:this.queryKey,meta:this.meta};return r(e),e})();return this.#s=!1,this.options.persister?this.options.persister(e,n,this):e(n)},a=(()=>{let e={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#i,state:this.state,fetchFn:i};return r(e),e})();(this.#e===`infinite`?sf(this.options.pages):this.options.behavior)?.onFetch(a,this),this.#n=this.state,(this.state.fetchStatus===`idle`||this.state.fetchMeta!==a.fetchOptions?.meta)&&this.#c({type:`fetch`,meta:a.fetchOptions?.meta});let o=this.#a=af({initialPromise:t?.initialPromise,fn:a.fetchFn,onCancel:e=>{e instanceof rf&&e.revert&&this.setState({...this.#n,fetchStatus:`idle`}),n.abort()},onFail:(e,t)=>{this.#c({type:`failed`,failureCount:e,error:t})},onPause:()=>{this.#c({type:`pause`})},onContinue:()=>{this.#c({type:`continue`})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0});try{let e=await o.start();if(e===void 0)throw Error(`${this.queryHash} data is undefined`);return this.setData(e),this.#r.config.onSuccess?.(e,this),this.#r.config.onSettled?.(e,this.state.error,this),e}catch(e){if(e instanceof rf){if(e.silent)return this.#a.promise;if(e.revert){if(this.state.data===void 0)throw e;return this.state.data}}throw this.#c({type:`error`,error:e}),this.#r.config.onError?.(e,this),this.#r.config.onSettled?.(this.state.data,e,this),e}finally{this.#a===o&&(this.#a=void 0),this.scheduleGc()}}#c(e){let t=t=>{switch(e.type){case`failed`:return{...t,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case`pause`:return{...t,fetchStatus:`paused`};case`continue`:return{...t,fetchStatus:`fetching`};case`fetch`:return{...t,...df(t.data,this.options),fetchMeta:e.meta??null};case`success`:let n={...t,...ff(e.data,e.dataUpdatedAt),dataUpdateCount:t.dataUpdateCount+1,...!e.manual&&{fetchStatus:`idle`,fetchFailureCount:0,fetchFailureReason:null}};return this.#n=e.manual?n:void 0,n;case`error`:let r=e.error;return{...t,error:r,errorUpdateCount:t.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:t.fetchFailureCount+1,fetchFailureReason:r,fetchStatus:`idle`,status:`error`,isInvalidated:!0};case`invalidate`:return{...t,isInvalidated:!0};case`setState`:return{...t,...e.state}}};this.state=t(this.state),$d.batch(()=>{this.observers.slice().forEach(e=>{e.onQueryUpdate()}),this.#r.notify({query:this,type:`updated`,action:e})})}};function df(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:nf(t.networkMode)?`fetching`:`paused`,...e===void 0&&{error:null,status:`pending`}}}function ff(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:`success`}}function pf(e){let t=typeof e.initialData==`function`?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt==`function`?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?`success`:`pending`,fetchStatus:`idle`}}var mf=class extends Yd{#e;#t=void 0;#n=void 0;#r=void 0;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p=new Set;constructor(e,t){super(),this.options=t,this.#e=e,this.#o=null,this.bindMethods(),this.setOptions(t)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),gf(this.#t,this.options)?this.#m():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return _f(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return _f(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#b(),this.#x(),this.#t.removeObserver(this)}setOptions(e){let t=this.options,n=this.#t;if(this.options=this.#e.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!=`boolean`&&typeof this.options.enabled!=`function`&&typeof Dd(this.options.enabled,this.#t)!=`boolean`)throw Error(`Expected enabled to be a boolean or a callback that returns a boolean`);this.#S(),this.#t.setOptions(this.options),t._defaulted&&!Fd(this.options,t)&&this.#e.getQueryCache().notify({type:`observerOptionsUpdated`,query:this.#t,observer:this});let r=this.hasListeners();r&&vf(this.#t,n,this.options,t)&&this.#m(),this.updateResult(),r&&(this.#t!==n||Dd(this.options.enabled,this.#t)!==Dd(t.enabled,this.#t)||Dd(this.options.staleTime,this.#t)!==Dd(t.staleTime,this.#t))&&this.#g();let i=this.#_();r&&(this.#t!==n||Dd(this.options.enabled,this.#t)!==Dd(t.enabled,this.#t)||i!==this.#f)&&this.#v(i)}getOptimisticResult(e){let t=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(t,e);return Fd(this.getCurrentResult(),n)||(this.#r=n,this.#a=this.options,this.#i=this.#t.state),n}getCurrentResult(){return this.#r}trackResult(e,t){return new Proxy(e,{get:(e,n)=>(this.trackProp(n),t?.(n),Reflect.get(e,n))})}trackProp(e){this.#p.add(e)}getCurrentQuery(){return this.#t}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){let t=this.#e.defaultQueryOptions(e),n=this.#e.getQueryCache().build(this.#e,t),r=()=>{},i,a=new Promise(e=>{i=e,r=this.#e.getQueryCache().subscribe(i=>{i.type===`updated`&&i.query.queryHash===n.queryHash&&n.state.data!==void 0&&(r(),e(this.createResult(n,t)))})});return Promise.race([n.fetch(t).then(()=>{let e=this.createResult(n,t);return i?.(e),e}).finally(()=>{r()}),a])}fetch(e){return this.#m({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#r))}#m(e){this.#S();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch(Cd)),t}#h(e){return!Jd()&&Dd(this.options.enabled,this.#t)!==!1&&Td(e)}#g(){this.#b();let e=Dd(this.options.staleTime,this.#t);if(this.#r.isStale||!this.#h(e))return;let t=Ed(this.#r.dataUpdatedAt,e)+1;this.#u=bd.setTimeout(()=>{this.#r.isStale||this.updateResult()},t)}#_(){return Dd(this.options.refetchInterval,this.#t)??!1}#v(e){this.#x(),this.#f=e,this.#f!==0&&this.#h(this.#f)&&(this.#d=bd.setInterval(()=>{(this.options.refetchIntervalInBackground||Xd.isFocused())&&this.#m()},this.#f))}#y(){this.#g(),this.#v(this.#_())}#b(){this.#u!==void 0&&(bd.clearTimeout(this.#u),this.#u=void 0)}#x(){this.#d!==void 0&&(bd.clearInterval(this.#d),this.#d=void 0)}createResult(e,t){let n=this.#t,r=this.options,i=this.#r,a=this.#i,o=this.#a,s=e===n?this.#n:e.state,{state:c}=e,l={...c},u=!1,d;if(t._optimisticResults){let i=this.hasListeners(),a=!i&&gf(e,t),o=i&&vf(e,n,t,r);(a||o)&&(l={...l,...df(c.data,e.options)}),t._optimisticResults===`isRestoring`&&(l.fetchStatus=`idle`)}let{error:f,errorUpdatedAt:p,status:m}=l;d=l.data;let h=!1;if(t.placeholderData!==void 0&&d===void 0&&m===`pending`){let e;i?.isPlaceholderData&&t.placeholderData===o?.placeholderData?(e=i.data,h=!0):e=typeof t.placeholderData==`function`?t.placeholderData(this.#l?.state.data,this.#l):t.placeholderData,e!==void 0&&(m=`success`,d=Bd(i?.data,e,t),u=!0)}if(t.select&&d!==void 0&&!h){if(i&&d===a?.data&&t.select===this.#s)d=this.#c;else try{this.#s=t.select,d=t.select(d),d=Bd(i?.data,d,t),this.#c=d,this.#o=null}catch(e){this.#o=e}}else d===void 0&&(this.#o=null);this.#o&&(f=this.#o,d=this.#c,p=Date.now(),m=`error`,u=!1);let g=l.fetchStatus===`fetching`,_=m===`pending`,v=m===`error`,y=_&&g,b=d!==void 0;return{status:m,fetchStatus:l.fetchStatus,isPending:_,isSuccess:m===`success`,isError:v,isInitialLoading:y,isLoading:y,data:d,dataUpdatedAt:l.dataUpdatedAt,error:f,errorUpdatedAt:p,failureCount:l.fetchFailureCount,failureReason:l.fetchFailureReason,errorUpdateCount:l.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:l.dataUpdateCount>s.dataUpdateCount||l.errorUpdateCount>s.errorUpdateCount,isFetching:g,isRefetching:g&&!_,isLoadingError:v&&!b,isPaused:l.fetchStatus===`paused`,isPlaceholderData:u,isRefetchError:v&&b,isStale:yf(e,t),refetch:this.refetch,isEnabled:Dd(t.enabled,e)!==!1}}updateResult(){let e=this.#r,t=this.createResult(this.#t,this.options);if(this.#i=this.#t.state,this.#a=this.options,this.#i.data!==void 0&&(this.#l=this.#t),Fd(t,e))return;this.#r=t;let n=(()=>{if(!e)return!0;let{notifyOnChangeProps:t}=this.options,n=typeof t==`function`?t():t;if(n===`all`||!n&&!this.#p.size)return!0;let r=new Set(n??this.#p);return this.options.throwOnError&&r.add(`error`),Object.keys(this.#r).some(t=>{let n=t;return this.#r[n]!==e[n]&&r.has(n)})})();$d.batch(()=>{n&&this.listeners.forEach(e=>{e(this.#r)}),this.#e.getQueryCache().notify({query:this.#t,type:`observerResultsUpdated`})})}#S(){let e=this.#e.getQueryCache().build(this.#e,this.options);if(e===this.#t)return;let t=this.#t;this.#t=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#y()}};function hf(e,t){return Dd(t.enabled,e)!==!1&&e.state.data===void 0&&(e.state.status!==`error`||Dd(t.retryOnMount,e)!==!1)}function gf(e,t){return hf(e,t)||e.state.data!==void 0&&_f(e,t,t.refetchOnMount)}function _f(e,t,n){if(Dd(t.enabled,e)!==!1&&Dd(t.staleTime,e)!==`static`){let r=Dd(n,e);return r===`always`||r!==!1&&yf(e,t)}return!1}function vf(e,t,n,r){return(e!==t||Dd(r.enabled,e)===!1)&&(!n.suspense||e.state.status!==`error`)&&yf(e,n)}function yf(e,t){return Dd(t.enabled,e)!==!1&&e.isStaleByTime(Dd(t.staleTime,e))}var bf=class extends of{#e;#t;#n;#r;constructor(e){super(),this.#e=e.client,this.mutationId=e.mutationId,this.#n=e.mutationCache,this.#t=[],this.state=e.state||xf(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#t.includes(e)||(this.#t.push(e),this.clearGcTimeout(),this.#n.notify({type:`observerAdded`,mutation:this,observer:e}))}removeObserver(e){this.#t=this.#t.filter(t=>t!==e),this.scheduleGc(),this.#n.notify({type:`observerRemoved`,mutation:this,observer:e})}optionalRemove(){this.#t.length||(this.state.status===`pending`?this.scheduleGc():this.#n.remove(this))}continue(){return this.#r?.continue()??(this.state.status===`pending`?this.execute(this.state.variables):Promise.resolve())}async execute(e){let t=()=>{this.#i({type:`continue`})},n={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey},r=this.#r=af({fn:()=>this.options.mutationFn?this.options.mutationFn(e,n):Promise.reject(Error(`No mutationFn found`)),onFail:(e,t)=>{this.#i({type:`failed`,failureCount:e,error:t})},onPause:()=>{this.#i({type:`pause`})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#n.canRun(this)}),i=this.state.status===`pending`,a=!r.canStart();try{if(i)t();else{this.#i({type:`pending`,variables:e,isPaused:a}),this.#n.config.onMutate&&await this.#n.config.onMutate(e,this,n);let t=await this.options.onMutate?.(e,n);t!==this.state.context&&this.#i({type:`pending`,context:t,variables:e,isPaused:a})}let o=await r.start();return await this.#n.config.onSuccess?.(o,e,this.state.context,this,n),await this.options.onSuccess?.(o,e,this.state.context,n),await this.#n.config.onSettled?.(o,null,this.state.variables,this.state.context,this,n),await this.options.onSettled?.(o,null,e,this.state.context,n),this.#i({type:`success`,data:o}),o}catch(t){try{await this.#n.config.onError?.(t,e,this.state.context,this,n)}catch(e){Promise.reject(e)}try{await this.options.onError?.(t,e,this.state.context,n)}catch(e){Promise.reject(e)}try{await this.#n.config.onSettled?.(void 0,t,this.state.variables,this.state.context,this,n)}catch(e){Promise.reject(e)}try{await this.options.onSettled?.(void 0,t,e,this.state.context,n)}catch(e){Promise.reject(e)}throw this.#i({type:`error`,error:t}),t}finally{this.#r===r&&(this.#r=void 0),this.#n.runNext(this)}}#i(e){let t=t=>{switch(e.type){case`failed`:return{...t,failureCount:e.failureCount,failureReason:e.error};case`pause`:return{...t,isPaused:!0};case`continue`:return{...t,isPaused:!1};case`pending`:return{...t,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:`pending`,variables:e.variables,submittedAt:Date.now()};case`success`:return{...t,data:e.data,failureCount:0,failureReason:null,error:null,status:`success`,isPaused:!1};case`error`:return{...t,data:void 0,error:e.error,failureCount:t.failureCount+1,failureReason:e.error,isPaused:!1,status:`error`}}};this.state=t(this.state),$d.batch(()=>{this.#t.forEach(t=>{t.onMutationUpdate(e)}),this.#n.notify({mutation:this,type:`updated`,action:e})})}};function xf(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:`idle`,variables:void 0,submittedAt:0}}var Sf=class extends Yd{#e;#t;#n;constructor(e={}){super(),this.config=e,this.#e=new Set,this.#t=new Map,this.#n=0}build(e,t,n){let r=new bf({client:e,mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(r),r}add(e){this.#e.add(e);let t=Cf(e);if(typeof t==`string`){let n=this.#t.get(t);n?n.push(e):this.#t.set(t,[e])}this.notify({type:`added`,mutation:e})}remove(e){if(this.#e.delete(e)){let t=Cf(e);if(typeof t==`string`){let n=this.#t.get(t);if(n){if(n.length>1){let t=n.indexOf(e);t!==-1&&n.splice(t,1)}else n[0]===e&&this.#t.delete(t)}}}this.notify({type:`removed`,mutation:e})}canRun(e){let t=Cf(e);if(typeof t==`string`){let n=this.#t.get(t)?.find(e=>e.state.status===`pending`);return!n||n===e}return!0}runNext(e){let t=Cf(e);return typeof t==`string`?(this.#t.get(t)?.find(t=>t!==e&&t.state.isPaused))?.continue()??Promise.resolve():Promise.resolve()}clear(){$d.batch(()=>{let e=this.getAll();this.#e.clear(),this.#t.clear(),e.forEach(e=>{this.notify({type:`removed`,mutation:e})})})}getAll(){return Array.from(this.#e)}find(e){let t={exact:!0,...e};return this.getAll().find(e=>kd(t,e))}findAll(e={}){return this.getAll().filter(t=>kd(e,t))}notify(e){$d.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){let e=this.getAll().filter(e=>e.state.isPaused);return $d.batch(()=>Promise.all(e.map(e=>e.continue().catch(Cd))))}};function Cf(e){return e.options.scope?.id}var wf=class extends Yd{#e;#t=void 0;#n;#r;constructor(e,t){super(),this.#e=e,this.setOptions(t),this.bindMethods(),this.#i()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(e){let t=this.options;this.options=this.#e.defaultMutationOptions(e),Fd(this.options,t)||this.#e.getMutationCache().notify({type:`observerOptionsUpdated`,mutation:this.#n,observer:this}),t?.mutationKey&&this.options.mutationKey&&jd(t.mutationKey)!==jd(this.options.mutationKey)?this.reset():this.#n?.state.status===`pending`&&this.#n.setOptions(this.options)}onSubscribe(){this.listeners.size===1&&this.#n&&(this.#n.addObserver(this),this.#i())}onUnsubscribe(){this.hasListeners()||this.#n?.removeObserver(this)}onMutationUpdate(e){this.#i(),this.#a(e)}getCurrentResult(){return this.#t}reset(){this.#n?.removeObserver(this),this.#n=void 0,this.#i(),this.#a()}mutate(e,t){return this.#r=t,this.#n?.removeObserver(this),this.#n=this.#e.getMutationCache().build(this.#e,this.options),this.#n.addObserver(this),this.#n.execute(e)}#i(){let e=this.#n?.state??xf();this.#t={...e,isPending:e.status===`pending`,isSuccess:e.status===`success`,isError:e.status===`error`,isIdle:e.status===`idle`,mutate:this.mutate,reset:this.reset}}#a(e){$d.batch(()=>{let t=this.#r;if(t&&this.hasListeners()){let n=this.#t.variables,r=this.#t.context,i={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};if(e?.type===`success`){try{t.onSuccess?.(e.data,n,r,i)}catch(e){Promise.reject(e)}try{t.onSettled?.(e.data,null,n,r,i)}catch(e){Promise.reject(e)}}else if(e?.type===`error`){try{t.onError?.(e.error,n,r,i)}catch(e){Promise.reject(e)}try{t.onSettled?.(void 0,e.error,n,r,i)}catch(e){Promise.reject(e)}}}this.listeners.forEach(e=>{e(this.#t)})})}},Tf=class extends Yd{#e;constructor(e={}){super(),this.config=e,this.#e=new Map}build(e,t,n){let r=t.queryKey,i=t.queryHash??Ad(r,t),a=this.get(i);return a||(a=new uf({client:e,queryKey:r,queryHash:i,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(r)}),this.add(a)),a}add(e){this.#e.has(e.queryHash)||(this.#e.set(e.queryHash,e),this.notify({type:`added`,query:e}))}remove(e){this.#e.get(e.queryHash)===e&&(e.destroy(),this.#e.delete(e.queryHash),this.notify({type:`removed`,query:e}))}clear(){$d.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#e.get(e)}getAll(){return[...this.#e.values()]}find(e){let t={exact:!0,...e};return this.getAll().find(e=>Od(t,e))}findAll(e={}){let t=this.getAll();return Object.keys(e).length>0?t.filter(t=>Od(e,t)):t}notify(e){$d.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){$d.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){$d.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},Ef=class{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e={}){this.#e=e.queryCache||new Tf,this.#t=e.mutationCache||new Sf,this.#n=e.defaultOptions||{},this.#r=new Map,this.#i=new Map,this.#a=0}mount(){this.#a++,this.#a===1&&(this.#o=Xd.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#s=ef.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#a--,this.#a===0&&(this.#o?.(),this.#o=void 0,this.#s?.(),this.#s=void 0)}isFetching(e){return this.#e.findAll({...e,fetchStatus:`fetching`}).length}isMutating(e){return this.#t.findAll({...e,status:`pending`}).length}getQueryData(e){let t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state.data}ensureQueryData(e){let t=this.defaultQueryOptions(e),n=this.#e.build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(Dd(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return this.#e.findAll(e).map(({queryKey:e,state:t})=>[e,t.data])}setQueryData(e,t,n){let r=this.defaultQueryOptions({queryKey:e}),i=this.#e.get(r.queryHash)?.state.data,a=wd(t,i);if(a!==void 0)return this.#e.build(this,r).setData(a,{...n,manual:!0})}setQueriesData(e,t,n){return $d.batch(()=>this.#e.findAll(e).map(({queryKey:e})=>[e,this.setQueryData(e,t,n)]))}getQueryState(e){let t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state}removeQueries(e){let t=this.#e;$d.batch(()=>{t.findAll(e).forEach(e=>{t.remove(e)})})}resetQueries(e,t){let n=this.#e;return $d.batch(()=>{let r=n.findAll(e),i=new Set(r);return r.forEach(e=>{e.reset()}),this.refetchQueries({type:`active`,predicate:e=>i.has(e)},t)})}cancelQueries(e,t={}){let n={revert:!0,...t},r=$d.batch(()=>this.#e.findAll(e).map(e=>e.cancel(n)));return Promise.all(r).then(Cd).catch(Cd)}invalidateQueries(e,t={}){return $d.batch(()=>(this.#e.findAll(e).forEach(e=>{e.invalidate()}),e?.refetchType===`none`?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??`active`},t)))}refetchQueries(e,t={}){let n={...t,cancelRefetch:t.cancelRefetch??!0},r=$d.batch(()=>this.#e.findAll(e).filter(e=>!e.isDisabled()&&!e.isStatic()).map(e=>{let t=e.fetch(void 0,n);return n.throwOnError||(t=t.catch(Cd)),e.state.fetchStatus===`paused`?Promise.resolve():t}));return Promise.all(r).then(Cd)}async query(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=this.#e.build(this,t),r=n.isStaleByTime(Dd(t.staleTime,n))?await n.fetch(t):n.state.data,i=t.select;return i?i(r):r}fetchQuery(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=this.#e.build(this,t);return n.isStaleByTime(Dd(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Cd).catch(Cd)}infiniteQuery(e){return e._type=`infinite`,this.query(e)}fetchInfiniteQuery(e){return e._type=`infinite`,this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Cd).catch(Cd)}ensureInfiniteQueryData(e){return e._type=`infinite`,this.ensureQueryData(e)}resumePausedMutations(){return ef.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#n}setDefaultOptions(e){this.#n=e}setQueryDefaults(e,t){this.#r.set(jd(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){let t=[...this.#r.values()],n={};return t.forEach(t=>{Md(e,t.queryKey)&&Object.assign(n,t.defaultOptions)}),n}setMutationDefaults(e,t){this.#i.set(jd(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){let t=[...this.#i.values()],n={};return t.forEach(t=>{Md(e,t.mutationKey)&&Object.assign(n,t.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;let t={...this.#n.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||=Ad(t.queryKey,t),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!==`always`),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode=`offlineFirst`),t.queryFn===Ud&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#n.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}},Df=q.createContext(!1),Of=()=>q.useContext(Df);Df.Provider;function kf(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Af=q.createContext(kf()),jf=()=>q.useContext(Af),Mf=(e,t,n)=>{let r=n?.state.status===`error`&&typeof e.throwOnError==`function`?Gd(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||r)&&(t.isReset()||(e.retryOnMount=!1))},Nf=e=>{q.useEffect(()=>{e.clearReset()},[e])},Pf=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||Gd(n,[e.error,r])),Ff=e=>{if(e.suspense){let t=1e3,n=e=>e===`static`?e:Math.max(e??t,t),r=e.staleTime;e.staleTime=typeof r==`function`?(...e)=>n(r(...e)):n(r),typeof e.gcTime==`number`&&(e.gcTime=Math.max(e.gcTime,t))}},If=(e,t)=>e?.suspense&&t.isPending,Lf=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function Rf(e,t,n){let r=Of(),i=jf(),a=_d(n),o=a.defaultQueryOptions(e),s=a.getQueryCache().get(o.queryHash),c=e.subscribed!==!1;o._optimisticResults=r?`isRestoring`:c?`optimistic`:void 0,Ff(o),Mf(o,i,s),Nf(i);let[l]=q.useState(()=>new t(a,o)),u=l.getOptimisticResult(o),d=!r&&c;if(q.useSyncExternalStore(q.useCallback(e=>{let t=d?l.subscribe($d.batchCalls(e)):Cd;return l.updateResult(),t},[l,d]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),q.useEffect(()=>{l.setOptions(o)},[o,l]),If(o,u))throw Lf(o,l,i);if(Pf({result:u,errorResetBoundary:i,throwOnError:o.throwOnError,query:s,suspense:o.suspense}))throw u.error;return o.notifyOnChangeProps?u:l.trackResult(u)}function zf(e,t){return Rf(e,mf,t)}function Bf(e,t){let n=_d(t),[r]=q.useState(()=>new wf(n,e));q.useEffect(()=>{r.setOptions(e)},[r,e]);let i=q.useSyncExternalStore(q.useCallback(e=>r.subscribe($d.batchCalls(e)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),a=q.useCallback((...e)=>{r.mutate(e[0],e[1]).catch(Cd)},[r]);if(i.error&&Gd(r.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:a,mutateAsync:i.mutate}}var Vf={lists:e=>[`discussion`,e,`comments`],file:(e,t)=>[`discussion`,e,`comments`,`file`,t],all:e=>[`discussion`,e,`comments`,`project`],summary:e=>[`discussion`,e,`summary`],mentions:e=>[`discussion`,e,`mentions`],candidates:e=>[`discussion`,e,`candidates`]},Hf=[],Uf=[],Wf=e=>e instanceof Ue&&[401,403,404].includes(e.status);function Gf(){return new Ef({defaultOptions:{queries:{staleTime:3e4,gcTime:3e5,retry:(e,t)=>!Wf(t)&&e<2&&(!(t instanceof Ue)||t.status===0||t.status>=500||t.code===`INVALID_RESPONSE`),retryDelay:e=>Math.min(500*2**e,2e3),refetchOnReconnect:`always`},mutations:{retry:!1}}})}var Kf=new WeakMap;function qf(e){let t=Kf.get(e);return t||(t={next:0,summaries:new Map},Kf.set(e,t)),++t.next}function Jf(e,t,n,r){let i=Kf.get(e);!n||!i||r<(i.summaries.get(t)??0)||(i.summaries.set(t,r),e.setQueryData(Vf.summary(t),n))}function Yf(e,t){if(t.kind===`created`)return e.some(e=>e.id===t.comment.id)?e:[...e,t.comment];let n=t.kind===`edited`?t.comment.id:t.kind===`resolved`?t.resolution.id:t.commentId;return t.kind===`deleted`?e.filter(e=>e.id!==n):e.map(e=>{if(e.id!==n)return e;if(t.kind===`suggestion`)return{...e,suggestion:t.suggestion};if(t.kind===`edited`)return{...e,...t.comment};if(t.kind===`resolved`)return{...e,...t.resolution};if(t.kind===`reply-deleted`)return{...e,replies:e.replies.filter(e=>e.id!==t.replyId)};let r=e.replies.some(e=>e.id===t.reply.id);return{...e,replies:r?e.replies.map(e=>e.id===t.reply.id?t.reply:e):[...e.replies,t.reply]}})}async function Xf(e,t,n){await Promise.all([e.cancelQueries({queryKey:Vf.lists(t)}),e.cancelQueries({queryKey:Vf.mentions(t)})]);let r=n.change,i=r.kind===`created`||r.kind===`edited`?r.comment.filePath:r.kind===`resolved`?r.resolution.filePath:r.filePath;if(e.setQueriesData({queryKey:Vf.lists(t)},e=>{if(!e)return e;let t=e.comments;return r.kind===`created`?e:{...e,comments:Yf(t,r),summary:n.summary}}),r.kind===`created`)for(let a of[Vf.file(t,i),Vf.all(t)])e.setQueryData(a,e=>e&&{...e,comments:Yf(e.comments,r),summary:n.summary});Jf(e,t,n.summary,qf(e)),e.setQueryData(Vf.mentions(t),e=>e&&{mentions:e.mentions.filter(e=>r.kind===`deleted`?e.commentId!==r.commentId:r.kind===`resolved`&&r.resolution.resolved?e.commentId!==r.resolution.id:r.kind===`suggestion`&&e.kind===`review`&&e.commentId===r.commentId?r.suggestion.status===`pending`&&e.readAt===null:r.kind!==`reply-deleted`||e.replyId!==r.replyId)})}async function Zf(e,t){await Promise.all([Vf.lists(t),Vf.mentions(t)].map(async t=>{await e.cancelQueries({queryKey:t}),await e.invalidateQueries({queryKey:t})}))}function Qf(e,t,n,r,i){let a=_d(),o=async(t,n)=>{let r=qf(a),i=await G(t,{signal:n});return n.aborted||Jf(a,e,i.summary,r),i},s=zf({queryKey:Vf.file(e,t),enabled:!!t,queryFn:({signal:n})=>o(`/api/projects/${e}/comments?path=${encodeURIComponent(t)}`,n)}),c=zf({queryKey:Vf.all(e),enabled:n===`project`,queryFn:({signal:t})=>o(`/api/projects/${e}/comments?scope=project`,t)}),l=zf({queryKey:Vf.summary(e),enabled:!1}),u=(0,q.useRef)({projectId:e,revision:r,sourceOrderRevision:i});(0,q.useEffect)(()=>{let t=u.current;if(u.current={projectId:e,revision:r,sourceOrderRevision:i},t.projectId!==e)return;let n=t.revision===r?t.sourceOrderRevision===i?null:Vf.all(e):Vf.lists(e);n&&a.cancelQueries({queryKey:n}).then(()=>a.invalidateQueries({queryKey:n}))},[a,e,r,i]);let d=n===`project`?c:s,f=s.error?K(s.error):``;return{comments:Wf(s.error)?Hf:s.data?.comments??Hf,commentsFilePath:t&&(s.data||s.error)?t:``,commentsReady:!(!t||!s.data||s.isFetching||s.error),fileCommentsLoading:!!(t&&s.isFetching),fileCommentsError:f,reviewComments:Wf(d.error)?Hf:d.data?.comments??Hf,reviewCommentsLoading:!(n!==`project`&&!t||!d.isFetching),reviewCommentsError:d.error?K(d.error):``,projectCommentSummary:Wf(s.error)||Wf(c.error)?null:l.data??null,refreshComments:()=>Zf(a,e)}}function $f(e){let t=_d(),n=Bf({retry:!1,mutationFn:async({id:e,path:n,options:r})=>{let i=await G(`/api/projects/${e}/comments${n}`,r);return await Xf(t,e,i),Zf(t,e),i},onError:(e,{id:n})=>{e instanceof Ue&&[`SUGGESTION_UPDATED`,`SUGGESTION_DECIDED`,`SUGGESTION_APPLYING`].includes(e.code??``)&&Zf(t,n)}});return(t,r)=>n.mutateAsync({id:e,path:t,options:r})}function ep(e,t,n,r){let i=!!e.trim(),a=n&&t&&n.replacementText!==t?n:null;return{hasComment:i,edit:a,issue:!i&&!a?`empty`:a?.reviewerId&&a.reviewerId===r?`selfReview`:a&&!a.reviewerId?`reviewer`:null,kind:a?i?`commentAndEdit`:`editOnly`:`commentOnly`}}function tp({projectId:e,activeFile:t,content:n,permission:r,revision:i,sourceOrderRevision:a,selection:o,save:s,saveFailureMessage:c,onError:l,onAdded:u}){let d=(0,q.useMemo)(()=>new hd,[e]),f=(0,q.useMemo)(()=>({active:!1}),[e]);(0,q.useEffect)(()=>(f.active=!0,()=>{f.active=!1}),[f]);let[p,m]=(0,q.useState)(`file`),h=Qf(e,t,p,i,a),g=$f(e),[_,v]=(0,q.useState)(null),[b,x]=(0,q.useState)(!1),[S,C]=(0,q.useState)(``),[w,T]=(0,q.useState)(null),E=(0,q.useRef)(w);E.current=w;let[D,O]=(0,q.useState)(null),[k,A]=(0,q.useState)(null),[j,M]=(0,q.useState)(!1),[ee,N]=(0,q.useState)(!1),[P,te]=(0,q.useState)(``),F=(0,q.useRef)(!1),ne=(0,q.useRef)(t),I=(0,q.useRef)(s),re=(0,q.useRef)(l),ie=(0,q.useRef)(u),ae=(0,q.useRef)(D),L=(0,q.useRef)(S);ae.current=D,L.current=S,ne.current=t,I.current=s,re.current=l,ie.current=u,(0,q.useEffect)(()=>{v(null),m(`file`),x(!1),O(null),A(null),C(``),T(null),M(!1),te(``)},[e]),(0,q.useEffect)(()=>{x(!1),O(null),A(null),C(``),T(null),M(!1),te(``)},[t]);let R=(e,r)=>{if(!t)return;te(``);let i={filePath:t,selection:{...e??o},sourceHash:mu(r??n)},a=d.getNew(t);O(a??i),C(a?.content??``),T(a?.suggestion??null),A(i),M(!!a),x(!0)},oe=e=>{C(e),D&&(e||w?d.setNew({...D,content:e,suggestion:w}):d.discardNew(D.filePath))},se=e=>{T(e),D&&(S||e?d.setNew({...D,content:S,suggestion:e}):d.discardNew(D.filePath))},ce=()=>{F.current||(x(!1),te(``))},z=()=>{F.current||(D&&d.discardNew(D.filePath),C(``),T(null),O(null),A(null),M(!1),ce())},le=()=>{!F.current&&k&&k.filePath===ne.current&&(O(k),(S||w)&&d.setNew({...k,content:S,suggestion:w}),M(!1),te(``))},B=async()=>{let e=D,t=S,n=w;if(!e||F.current)return;let i=ep(t,e.selection.selectedText,n);if(i.issue)return;let a=i.edit,o=()=>{let r=ae.current;return r?.filePath===e.filePath&&r.sourceHash===e.sourceHash&&r.selection.startOffset===e.selection.startOffset&&r.selection.endOffset===e.selection.endOffset&&L.current===t&&E.current===n};F.current=!0,N(!0),te(``);try{if(r!==`read`&&!await I.current()){o()&&te(c);return}await g(``,{method:`POST`,body:JSON.stringify({path:e.filePath,content:t.trim()||(a?y.t(`suggestions.defaultComment`):t),...e.selection,sourceHash:e.sourceHash,...a?{suggestion:a}:{}})});let i=d.getNew(e.filePath);if(i?.content===t&&JSON.stringify(i.suggestion??null)===JSON.stringify(n)&&i.sourceHash===e.sourceHash&&i.selection.startOffset===e.selection.startOffset&&i.selection.endOffset===e.selection.endOffset&&d.discardNew(e.filePath),!f.active)return;o()&&(x(!1),O(null),C(``),T(null),M(!1)),ie.current()}catch(e){o()&&te(K(e))}finally{F.current=!1,N(!1)}},V=async e=>{try{await g(`/${e.id}`,{method:`PATCH`,body:JSON.stringify({resolved:!e.resolved})})}catch(e){f.active&&re.current(K(e))}},H=async(e,t)=>(await g(`/${e.id}/replies`,{method:`POST`,body:JSON.stringify({content:t})}),!0),ue=async(e,t)=>(await g(`/${e.id}`,{method:`PATCH`,body:JSON.stringify({content:t})}),!0),de=async e=>(await g(`/${e.id}`,{method:`DELETE`}),f.active&&(v(t=>t?.id===e.id?null:t),d.discard(e.id)),!0),fe=async(e,t,n)=>(await g(`/${e.id}/replies/${t}`,{method:`PATCH`,body:JSON.stringify({content:n})}),!0),pe=async(e,t)=>(await g(`/${e.id}/replies/${t}`,{method:`DELETE`}),d.discard(e.id,`edit-reply:${t}`),!0);return{commentDraftStore:d,...h,retryFileComments:h.refreshComments,retryReviewComments:h.refreshComments,commentScope:p,setCommentScope:m,focusComment:_,setFocusComment:v,commentOpen:b,openComment:R,closeComment:ce,cancelComment:z,commentDraftRestored:j,commentDraftCanRetarget:!(!D||!k||D.sourceHash===k.sourceHash&&D.selection.startOffset===k.selection.startOffset&&D.selection.endOffset===k.selection.endOffset),useCurrentCommentSelection:le,commentText:S,commentSuggestion:w,setCommentSuggestion:se,setCommentText:oe,commentSelection:D?.selection??o,commentSubmitting:ee,commentError:P,addComment:B,toggleComment:V,replyToComment:H,editComment:ue,deleteComment:de,editCommentReply:fe,deleteCommentReply:pe}}function np(e){let t=new Map;for(let n of e)for(let e of[n,...n.replies])t.has(e.authorId)||t.set(e.authorId,{authorId:e.authorId,authorUsername:e.authorUsername,authorDisplayName:e.authorDisplayName,authorAvatarStyle:e.authorAvatarStyle});return[...t.values()].sort((e,t)=>(e.authorDisplayName??e.authorUsername??``).localeCompare(t.authorDisplayName??t.authorUsername??``))}function rp(e,t){let n=t.participantIds;return!n?.size||n.has(e.authorId)||!t.topLevelOnly&&e.replies.some(e=>n.has(e.authorId))}function ip(e,t=`source`){return[...e].sort((e,n)=>{if(t===`time`)return Date.parse(n.createdAt)-Date.parse(e.createdAt);let r=e.sourceOrder??1/0,i=n.sourceOrder??1/0;return r===i?e.filePath.localeCompare(n.filePath,`en`,{numeric:!0})||e.startLine-n.startLine||e.startOffset-n.startOffset:r-i})}function ap(e,t){return t.scope===`project`||e.filePath===t.activeFile}function op(e,t){return t===`unresolved`?!e.resolved:e.resolved}function sp(e,t){return t.some(t=>t.commentId===e.id&&t.readAt===null)}function cp(e,t){return e.filter(e=>ap(e,t)&&rp(e,t)&&op(e,t.filter)&&(!t.unreadMentionsOnly||sp(e,t.unreadMentions)))}function lp(e,t,n=[]){let r=new Set(n.filter(e=>!!e));return ip(e.filter(e=>ap(e,t)?r.has(e.id)||rp(e,t)&&op(e,t.filter)&&(!t.unreadMentionsOnly||sp(e,t.unreadMentions)):!1),t.sort)}function up(e,t,n){let r=e.find(e=>e.id===t&&e.filePath===n&&!e.resolved);return r?[r]:[]}function dp(e,t){return e.filter(e=>e.filePath===t)}function fp(e,t,n){return!e||e.filePath!==t||n!==t?null:e}function pp(e,t,n,r,i,a){return!e||e.filePath!==t||n!==t||r!==t||!i?null:a.find(n=>n.id===e.id&&n.filePath===t)??null}function mp(e,t){if(!t)return 0;let n=e.findIndex(e=>e.id===t);return n<0?0:n+1}function hp(e,t,n){if(!e.length)return null;let r=t?e.findIndex(e=>e.id===t):-1;if(r<0)return n===1?e[0]:null;let i=r+n;return i>=0&&i<e.length?e[i]:null}function gp(e,t,n,r){let i=_d(),a=Vf.mentions(e),o=zf({queryKey:a,queryFn:({signal:t})=>G(`/api/projects/${e}/mentions?unread=1&limit=100`,{signal:t})}),s=Wf(o.error)?Uf:o.data?.mentions??Uf,c=(0,q.useRef)({onError:n,onRead:r});c.current={onError:n,onRead:r};let l=(0,q.useMemo)(()=>({active:!1,pending:new Map}),[e]);(0,q.useEffect)(()=>(l.active=!0,()=>{l.active=!1}),[l]);let u=(0,q.useRef)({projectId:e,revision:t}),d=async(e=!1)=>{if(!l.active)return;await i.cancelQueries({queryKey:a});let t=await o.refetch();e&&t.error&&l.active&&c.current.onError(K(t.error))};(0,q.useEffect)(()=>{let n=u.current;u.current={projectId:e,revision:t},n.projectId===e&&n.revision!==t&&d()},[e,t]);let f=t=>{let n=t??`all`,r=l.pending.get(n);if(r)return r;let o=(async()=>{try{let n=await G(`/api/projects/${e}/mentions/${t?`${encodeURIComponent(t)}/read`:`read-all`}`,{method:`POST`});if(!l.active||(await i.cancelQueries({queryKey:a}),!l.active))return!1;i.setQueryData(a,e=>e&&{mentions:t?e.mentions.filter(e=>e.id!==t):[]});let r=Number(n.changed)||0;return(r||!t)&&c.current.onRead?.(r,!t),i.invalidateQueries({queryKey:a}),!0}catch(e){return l.active&&c.current.onError(K(e)),!1}finally{l.pending.delete(n)}})();return l.pending.set(n,o),o};return{unreadMentions:s,mentionsError:o.error?K(o.error):``,refresh:d,markMentionRead:e=>f(e),markAllMentionsRead:()=>f()}}function _p({children:e}){let[t]=(0,q.useState)(Gf);return(0,J.jsx)(vd,{client:t,children:e})}function vp(e){if(!e||typeof e!=`object`)return!1;let t=e;return(t.kind===`update`||t.kind===`move`||t.kind===`delete`)&&typeof t.revision==`string`}function yp(e,t,n,r){let[i,a]=(0,q.useState)(`connecting`),[o,s]=(0,q.useState)(!1),[c,l]=(0,q.useState)([]),[u,d]=(0,q.useState)(null),[f,p]=(0,q.useState)(null),[m,h]=(0,q.useState)(``),[g,_]=(0,q.useState)(!1),[v,y]=(0,q.useState)(``),[b,x]=(0,q.useState)(``),[S,C]=(0,q.useState)([]),[w,T]=(0,q.useState)(!1),[E,D]=(0,q.useState)(n),[O,k]=(0,q.useState)(null),[A,j]=(0,q.useState)(!1),M=(0,q.useRef)(t),ee=(0,q.useRef)(r);M.current=t,ee.current=r,(0,q.useEffect)(()=>{let n=e.compileStates();d(n[t]??null)},[t,e]),(0,q.useEffect)(()=>{let t=()=>l(e.sessions()),n=()=>{s(!1),l([]),d(null),p(null),h(``),_(!1),y(``),x(``),C([])},r=({status:t})=>{a(t),t===`connected`?s(e.synced):n()},i=e=>{s(e),e&&(t(),c())},o=()=>{a(`disconnected`),n()},c=()=>{_(e.meta.get(`historyWarning`)===!0);let t=e.meta.get(`filesEvent`);vp(t)&&p(t);let n=e.meta.get(`commentsRevision`);typeof n==`string`&&h(n);let r=e.meta.get(`dictionaryRevision`);typeof r==`string`&&y(r);let i=e.meta.get(`chktexSettingsRevision`);typeof i==`string`&&x(i);let a=e.compileStates();d(a[M.current]??null)},u=()=>{let t=e.compileStates();d(t[M.current]??null)};e.awareness.on(`change`,t),e.provider.on(`status`,r),e.provider.on(`sync`,i),e.provider.on(`connection-close`,o),e.provider.on(`connection-error`,o),e.meta.observe(c);let f=e.onCompileStates(u),m=e.onProtocolUpgrade(()=>{j(!0),a(`disconnected`),n()}),g=e.onFormatLeaseState(()=>C(e.formatLeaseStates())),v=()=>{if(!ee.current||e.currentPermission!==`read`)return;let t=e.hasWritableDraft,n=e.hasOtherWritableDraft;(t||n)&&k({previous:`edit`,localDraftReady:t,otherTabDraft:n})},b=e.onDraftReady(()=>{T(!0),v()}),S=e.onPermissionChanged((t,r)=>{t===`revoked`?(a(`disconnected`),n()):(D(t),t===`read`&&r!==`read`?k({previous:r,localDraftReady:e.hasWritableDraft,otherTabDraft:e.hasOtherWritableDraft}):t!==`read`&&k(null))});return t(),c(),a(e.connected?`connected`:`connecting`),s(e.synced),()=>{e.awareness.off(`change`,t),e.provider.off(`status`,r),e.provider.off(`sync`,i),e.provider.off(`connection-close`,o),e.provider.off(`connection-error`,o),e.meta.unobserve(c),f(),m(),g(),b(),S()}},[e]),(0,q.useEffect)(()=>{e.setPermission(n),D(n),r&&n===`read`&&(e.hasWritableDraft||e.hasOtherWritableDraft)?k({previous:`edit`,localDraftReady:e.hasWritableDraft,otherTabDraft:e.hasOtherWritableDraft}):n!==`read`&&k(null)},[e,n,r]),(0,q.useEffect)(()=>{r&&e.connect()},[e,r]);let N=O!==null;return(0,q.useEffect)(()=>{if(!N)return;let t=()=>{if(e.currentPermission!==`read`)return;let t=e.hasWritableDraft,n=e.hasOtherWritableDraft;k(e=>!e||e.localDraftReady===t&&e.otherTabDraft===n?e:{...e,localDraftReady:t,otherTabDraft:n})};t();let n=window.setInterval(t,2e3);return()=>window.clearInterval(n)},[e,N]),{collaboration:e,status:i===`connected`&&!o?`syncing`:i,synced:i===`connected`&&o,activeSessions:c,compileState:u,setCompileState:d,formatLeaseStates:S,filesEvent:f,commentsRevision:m,historyWarning:g,dictionaryRevision:v,chktexSettingsRevision:b,localDraftReady:w,permission:E,protocolUpgradeRequired:A,reconnect:()=>{A||(a(`connecting`),s(!1),l([]),d(null),C([]),e.reconnect())},permissionDowngrade:O,dismissPermissionDowngrade:()=>k(null),discardLocalDraft:async()=>await e.discardLocalDraft()?(k(null),window.location.reload(),!0):(k(e=>e&&{...e,otherTabDraft:!0}),!1)}}var bp=new Map,xp=class{constructor(e){this.room=e,this.onmessage=null,this._onChange=t=>t.key===e&&this.onmessage!==null&&this.onmessage({data:pi(t.newValue||``)}),kr(this._onChange)}postMessage(e){Or.setItem(this.room,fi(si(e)))}close(){Ar(this._onChange)}},Sp=typeof BroadcastChannel>`u`?xp:BroadcastChannel,Cp=e=>Jt(bp,e,()=>{let t=Zt(),n=new Sp(e);return n.onmessage=e=>t.forEach(t=>t(e.data,`broadcastchannel`)),{bc:n,subs:t}}),wp=(e,t)=>(Cp(e).subs.add(t),t),Tp=(e,t)=>{let n=Cp(e),r=n.subs.delete(t);return r&&n.subs.size===0&&(n.bc.close(),bp.delete(e)),r},Ep=(e,t,n=null)=>{let r=Cp(e);r.bc.postMessage(t),r.subs.forEach(e=>e(t,n))},Dp=(e,t)=>{Z(e,0),zn(e,Xo(t))},Op=(e,t,n)=>{Z(e,1),zn(e,Wo(t,n))},kp=(e,t,n)=>Op(t,n,cr(e)),Ap=(e,t,n,r)=>{try{Vo(t,cr(e),n)}catch(e){r?.(e),console.error(`Caught error while handling a Yjs update`,e)}},jp=(e,t)=>{Z(e,2),zn(e,t)},Mp=Ap,Np=(e,t,n,r,i)=>{let a=Q(e);switch(a){case 0:kp(e,t,n);break;case 1:Ap(e,n,r,i);break;case 2:Mp(e,n,r,i);break;default:throw Error(`Unknown message type`)}return a},Pp=(e,t,n)=>{Q(e)===0&&n(t,dr(e))},Fp=3e4,Ip=class extends sn{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{let e=Cr();this.getLocalState()!==null&&15e3<=e-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());let t=[];this.meta.forEach((n,r)=>{r!==this.clientID&&3e4<=e-n.lastUpdated&&this.states.has(r)&&t.push(r)}),t.length>0&&Lp(this,t,`timeout`)},cn(Fp/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){let t=this.clientID,n=this.meta.get(t),r=n===void 0?0:n.clock+1,i=this.states.get(t);e===null?this.states.delete(t):this.states.set(t,e),this.meta.set(t,{clock:r,lastUpdated:Cr()});let a=[],o=[],s=[],c=[];e===null?c.push(t):i==null?e!=null&&a.push(t):(o.push(t),qr(i,e)||s.push(t)),(a.length>0||s.length>0||c.length>0)&&this.emit(`change`,[{added:a,updated:s,removed:c},`local`]),this.emit(`update`,[{added:a,updated:o,removed:c},`local`])}setLocalStateField(e,t){let n=this.getLocalState();n!==null&&this.setLocalState({...n,[e]:t})}getStates(){return this.states}},Lp=(e,t,n)=>{let r=[];for(let n=0;n<t.length;n++){let i=t[n];if(e.states.has(i)){if(e.states.delete(i),i===e.clientID){let t=e.meta.get(i);e.meta.set(i,{clock:t.clock+1,lastUpdated:Cr()})}r.push(i)}}r.length>0&&(e.emit(`change`,[{added:[],updated:[],removed:r},n]),e.emit(`update`,[{added:[],updated:[],removed:r},n]))},Rp=(e,t,n=e.states)=>{let r=t.length,i=An();Z(i,r);for(let a=0;a<r;a++){let r=t[a],o=n.get(r)||null,s=e.meta.get(r).clock;Z(i,r),Z(i,s),Ln(i,JSON.stringify(o))}return Y(i)},zp=(e,t,n)=>{let r=ar(t),i=Cr(),a=[],o=[],s=[],c=[],l=Q(r);for(let t=0;t<l;t++){let t=Q(r),n=Q(r),l=JSON.parse(dr(r)),u=e.meta.get(t),d=e.states.get(t),f=u===void 0?0:u.clock;(f<n||f===n&&l===null&&e.states.has(t))&&(l===null?t===e.clientID&&e.getLocalState()!=null?n++:e.states.delete(t):e.states.set(t,l),e.meta.set(t,{clock:n,lastUpdated:i}),u===void 0&&l!==null?a.push(t):u!==void 0&&l===null?c.push(t):l!==null&&(qr(l,d)||s.push(t),o.push(t)))}(a.length>0||s.length>0||c.length>0)&&e.emit(`change`,[{added:a,updated:s,removed:c},n]),(a.length>0||o.length>0||c.length>0)&&e.emit(`update`,[{added:a,updated:o,removed:c},n])},Bp=e=>Lr(e,(e,t)=>`${encodeURIComponent(t)}=${encodeURIComponent(e)}`).join(`&`),Vp=[];Vp[0]=(e,t,n,r,i)=>{Z(e,0);let a=Np(t,e,n.doc,n);r&&a===1&&!n.synced&&(n.synced=!0)},Vp[3]=(e,t,n,r,i)=>{Z(e,1),zn(e,Rp(n.awareness,Array.from(n.awareness.getStates().keys())))},Vp[1]=(e,t,n,r,i)=>{zp(n.awareness,cr(t),n)},Vp[2]=(e,t,n,r,i)=>{Pp(t,n.doc,(e,t)=>Up(n,t))};var Hp=3e4,Up=(e,t)=>console.warn(`Permission denied to access ${e.url}.\n${t}`),Wp=(e,t,n)=>{let r=ar(t),i=An(),a=Q(r),o=e.messageHandlers[a];return o?o(i,r,e,n,a):console.error(`Unable to compute message`),i},Gp=(e,t,n)=>{t===e.ws&&(e.emit(`connection-close`,[n,e]),e.ws=null,t.close(),e.wsconnecting=!1,e.wsconnected?(e.wsconnected=!1,e.synced=!1,Lp(e.awareness,Array.from(e.awareness.getStates().keys()).filter(t=>t!==e.doc.clientID),e),e.emit(`status`,[{status:`disconnected`}])):e.wsUnsuccessfulReconnects++,setTimeout(Kp,un(fn(2,e.wsUnsuccessfulReconnects)*100,e.maxBackoffTime),e))},Kp=e=>{if(e.shouldConnect&&e.ws===null){let t=new e._WS(e.url,e.protocols);t.binaryType=`arraybuffer`,e.ws=t,e.wsconnecting=!0,e.wsconnected=!1,e.synced=!1,t.onmessage=n=>{e.wsLastMessageReceived=Cr();let r=Wp(e,new Uint8Array(n.data),!0);jn(r)>1&&t.send(Y(r))},t.onerror=t=>{e.emit(`connection-error`,[t,e])},t.onclose=n=>{Gp(e,t,n)},t.onopen=()=>{e.wsLastMessageReceived=Cr(),e.wsconnecting=!1,e.wsconnected=!0,e.wsUnsuccessfulReconnects=0,e.emit(`status`,[{status:`connected`}]);let n=An();if(Z(n,0),Dp(n,e.doc),t.send(Y(n)),e.awareness.getLocalState()!==null){let n=An();Z(n,1),zn(n,Rp(e.awareness,[e.doc.clientID])),t.send(Y(n))}},e.emit(`status`,[{status:`connecting`}])}},qp=(e,t)=>{let n=e.ws;e.wsconnected&&n&&n.readyState===n.OPEN&&n.send(t),e.bcconnected&&Ep(e.bcChannel,t,e)},Jp=class extends on{constructor(e,t,n,{connect:r=!0,awareness:i=new Ip(n),params:a={},protocols:o=[],WebSocketPolyfill:s=WebSocket,resyncInterval:c=-1,maxBackoffTime:l=2500,disableBc:u=!1}={}){for(super();e[e.length-1]===`/`;)e=e.slice(0,e.length-1);this.serverUrl=e,this.bcChannel=e+`/`+t,this.maxBackoffTime=l,this.params=a,this.protocols=o,this.roomname=t,this.doc=n,this._WS=s,this.awareness=i,this.wsconnected=!1,this.wsconnecting=!1,this.bcconnected=!1,this.disableBc=u,this.wsUnsuccessfulReconnects=0,this.messageHandlers=Vp.slice(),this._synced=!1,this.ws=null,this.wsLastMessageReceived=0,this.shouldConnect=r,this._resyncInterval=0,c>0&&(this._resyncInterval=setInterval(()=>{if(this.ws&&this.ws.readyState===WebSocket.OPEN){let e=An();Z(e,0),Dp(e,n),this.ws.send(Y(e))}},c)),this._bcSubscriber=(e,t)=>{if(t!==this){let t=Wp(this,new Uint8Array(e),!1);jn(t)>1&&Ep(this.bcChannel,Y(t),this)}},this._updateHandler=(e,t)=>{if(t!==this){let t=An();Z(t,0),jp(t,e),qp(this,Y(t))}},this.doc.on(`update`,this._updateHandler),this._awarenessUpdateHandler=({added:e,updated:t,removed:n},r)=>{let a=e.concat(t).concat(n),o=An();Z(o,1),zn(o,Rp(i,a)),qp(this,Y(o))},this._exitHandler=()=>{Lp(this.awareness,[n.clientID],`app closed`)},Yr&&typeof process<`u`&&process.on(`exit`,this._exitHandler),i.on(`update`,this._awarenessUpdateHandler),this._checkInterval=setInterval(()=>{this.wsconnected&&Hp<Cr()-this.wsLastMessageReceived&&Gp(this,this.ws,null)},Hp/10),r&&this.connect()}get url(){let e=Bp(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(),Yr&&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||=(wp(this.bcChannel,this._bcSubscriber),!0);let e=An();Z(e,0),Dp(e,this.doc),Ep(this.bcChannel,Y(e),this);let t=An();Z(t,0),Op(t,this.doc),Ep(this.bcChannel,Y(t),this);let n=An();Z(n,3),Ep(this.bcChannel,Y(n),this);let r=An();Z(r,1),zn(r,Rp(this.awareness,[this.doc.clientID])),Ep(this.bcChannel,Y(r),this)}disconnectBc(){let e=An();Z(e,1),zn(e,Rp(this.awareness,[this.doc.clientID],new Map)),qp(this,Y(e)),this.bcconnected&&=(Tp(this.bcChannel,this._bcSubscriber),!1)}disconnect(){this.shouldConnect=!1,this.disconnectBc(),this.ws!==null&&Gp(this,this.ws,null)}connect(){this.shouldConnect=!0,!this.wsconnected&&this.ws===null&&(Kp(this),this.connectBc())}},Yp=e=>wr((t,n)=>{e.onerror=e=>n(Error(e.target.error)),e.onsuccess=e=>t(e.target.result)}),Xp=(e,t)=>wr((n,r)=>{let i=indexedDB.open(e);i.onupgradeneeded=e=>t(e.target.result),i.onerror=e=>r($n(e.target.error)),i.onsuccess=e=>{let t=e.target.result;t.onversionchange=()=>{t.close()},n(t)}}),Zp=e=>Yp(indexedDB.deleteDatabase(e)),Qp=(e,t)=>t.forEach(t=>e.createObjectStore.apply(e,t)),$p=(e,t,n=`readwrite`)=>{let r=e.transaction(t,n);return t.map(e=>um(r,e))},em=(e,t)=>Yp(e.count(t)),tm=(e,t)=>Yp(e.get(t)),nm=(e,t)=>Yp(e.delete(t)),rm=(e,t,n)=>Yp(e.put(t,n)),im=(e,t)=>Yp(e.add(t)),am=(e,t,n)=>Yp(e.getAll(t,n)),om=(e,t,n)=>{let r=null;return lm(e,t,e=>(r=e,!1),n).then(()=>r)},sm=(e,t=null)=>om(e,t,`prev`),cm=(e,t)=>wr((n,r)=>{e.onerror=r,e.onsuccess=async e=>{let r=e.target.result;if(r===null||await t(r)===!1)return n();r.continue()}}),lm=(e,t,n,r=`next`)=>cm(e.openKeyCursor(t,r),e=>n(e.key)),um=(e,t)=>e.objectStore(t),dm=(e,t)=>IDBKeyRange.upperBound(e,t),fm=(e,t)=>IDBKeyRange.lowerBound(e,t),pm=`custom`,mm=`updates`,hm=(e,t=()=>{},n=()=>{})=>{let[r]=$p(e.db,[mm]);return am(r,fm(e._dbref,!1)).then(i=>{e._destroyed||(t(r),Ls(e.doc,()=>{i.forEach(t=>Vo(e.doc,t))},e,!1),n(r))}).then(()=>sm(r).then(t=>{e._dbref=t+1})).then(()=>em(r).then(t=>{e._dbsize=t})).then(()=>r)},gm=(e,t=!0)=>hm(e).then(n=>{(t||e._dbsize>=500)&&im(n,Wo(e.doc)).then(()=>nm(n,dm(e._dbref,!0))).then(()=>em(n).then(t=>{e._dbsize=t}))}),_m=class extends sn{constructor(e,t){super(),this.doc=t,this.name=e,this._dbref=0,this._dbsize=0,this._destroyed=!1,this.db=null,this.synced=!1,this._db=Xp(e,e=>Qp(e,[[`updates`,{autoIncrement:!0}],[`custom`]])),this.whenSynced=wr(e=>this.on(`synced`,()=>e(this))),this._db.then(e=>{this.db=e,hm(this,e=>im(e,Wo(t)),()=>{if(this._destroyed)return this;this.synced=!0,this.emit(`synced`,[this])})}),this._storeTimeout=1e3,this._storeTimeoutId=null,this._storeUpdate=(e,t)=>{if(this.db&&t!==this){let[t]=$p(this.db,[mm]);im(t,e),++this._dbsize>=500&&(this._storeTimeoutId!==null&&clearTimeout(this._storeTimeoutId),this._storeTimeoutId=setTimeout(()=>{gm(this,!1),this._storeTimeoutId=null},this._storeTimeout))}},t.on(`update`,this._storeUpdate),this.destroy=this.destroy.bind(this),t.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(()=>{Zp(this.name)})}get(e){return this._db.then(t=>{let[n]=$p(t,[pm],`readonly`);return tm(n,e)})}set(e,t){return this._db.then(n=>{let[r]=$p(n,[pm]);return rm(r,t,e)})}del(e){return this._db.then(t=>{let[n]=$p(t,[pm]);return nm(n,e)})}},vm={Sync:0,Awareness:1,QueryAwareness:3,Flush:4,Protocol:5,Maintenance:6,Permission:7,CompileStates:8,FormatLease:9},ym=[`queued`,`running`,`succeeded`,`failed`,`cleaned`],bm=[`cache`,`artifacts`];function xm(e){return typeof e==`string`&&ym.includes(e)}function Sm(e){return typeof e==`string`&&bm.includes(e)}var Cm=[[`#1677c8`,`#1677c833`],[`#d65745`,`#d6574533`],[`#16866a`,`#16866a33`],[`#9a58b5`,`#9a58b533`],[`#d27b18`,`#d27b1833`],[`#3f7d20`,`#3f7d2033`],[`#be3e7b`,`#be3e7b33`],[`#4964c6`,`#4964c633`],[`#8a6a14`,`#8a6a1433`],[`#087f8c`,`#087f8c33`]],{Sync:wm,Awareness:Tm,Flush:Em,Protocol:Dm,Maintenance:Om,Permission:km,CompileStates:Am,FormatLease:jm}=vm,Mm=6e4,Nm=2592e6,Pm=15e3,Fm=3e5;function Im(e){if(!e||typeof e!=`object`)return null;let t=e,n=t.requestedBy;return typeof t.mainFile!=`string`||typeof t.runId!=`string`||!xm(t.status)||t.status===`cleaned`&&!Sm(t.cleanMode)||t.stale!==void 0&&typeof t.stale!=`boolean`||typeof t.updatedAt!=`string`||!n||typeof n.id!=`string`||typeof n.username!=`string`||typeof n.name!=`string`?null:t}function Lm(e){if(!e||typeof e!=`object`||Array.isArray(e))return{};let t={};for(let[n,r]of Object.entries(e)){let e=Im(r);e&&e.mainFile===n&&(t[n]=e)}return t}function Rm(e,t,n){return e<=n&&t<=n}function zm(e,t,n){let r=e=>e>0&&n-e<=Fm;return{recoverable:e.some(e=>e.tabId===t||!r(e.activeAt)),otherActive:e.some(e=>e.tabId!==t&&r(e.activeAt))}}var Bm=class{projectId;user;doc=new To;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;constructor(e,t){this.projectId=e,this.user=t;let n=window.location.protocol===`https:`?`wss:`:`ws:`;this.draftTabId=Um(b(`texlite:collaboration-tab:${t.id}:${e}`));let 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 _m(b(`texlite:${t.id}:${e}`),this.doc),this.localDraftTransactionObserver=e=>{if(e.local){for(let[t,n]of this.doc.share)if(t.startsWith(`source:`)&&(e.changed.has(n)||e.changedParentTypes.has(n))){this.markWritableDraft();return}}},this.doc.on(`afterTransaction`,this.localDraftTransactionObserver),this.persistence.on(`synced`,()=>{this.localDraftReady=!0;for(let e of this.draftListeners)e()}),this.provider=new Jp(`${n}//${window.location.host}${x(`/api/collaboration`)}`,e,this.doc,{connect:!1,disableBc:!0,maxBackoffTime:2500}),this.awareness=this.provider.awareness;let i=this.doc.getMap(`texlite:meta`);this.metaObserver=(e,t)=>{t.origin===this.provider&&e.keysChanged.has(`compileStates`)&&(this.authoritativeCompileStates=null,this.notifyCompileStateListeners())},i.observe(this.metaObserver),this.provider.messageHandlers[Em]=(e,t)=>{let n=dr(t),r=this.flushRequests.get(n);if(!r)return;let i=Q(t)===1,a=Q(t),o=dr(t),s=Q(t),c=[];for(let e=0;e<s;e++)c.push(dr(t));if(window.clearTimeout(r.timer),this.flushRequests.delete(n),i)this.clearOwnWritableDraftMarker(r.draftGeneration),r.resolve({revision:a,persistedAt:o,ok:!0,failedPaths:[]});else{let e=Object.assign(Error(c.length?`保存失败:${c.join(`, `)}`:`源码保存到服务器磁盘失败`),{failedPaths:c});r.reject(e)}},this.provider.messageHandlers[Dm]=(e,t)=>{let n=dr(t),r=this.epochStorageKey(),i=qe(r),a=/^([0-9]+):/.exec(n)?.[1]??null,o=i?/^([0-9]+):/.exec(i)?.[1]??null:null,s=!this.epoch&&a===`3`&&o!==null&&o!==a;if((this.epoch&&this.epoch!==n||i&&i!==n)&&!s){this.provider.disconnect(),this.rejectFlushes(Error(`Collaboration state changed`));let e=n.endsWith(`:reload`)||a!==null&&a!==`3`,t=()=>{$e(r,n.replace(/:reload$/,``)),window.location.reload()};if(e)for(let e of this.protocolUpgradeListeners)e();else this.persistence.clearData().then(()=>{this.clearWritableDraftMarkers(),t()});return}this.epoch=n,$e(r,n);let c=this.provider.ws;if(!c||c.readyState!==WebSocket.OPEN)return;let l=An();Z(l,Dm),Ln(l,n),Z(l,3),c.send(Y(l));let u=An();Z(u,wm),Dp(u,this.doc),c.send(Y(u));let d=An();Z(d,Tm),zn(d,Rp(this.awareness,[this.doc.clientID])),c.send(Y(d))},this.provider.messageHandlers[km]=(e,t)=>{let n=dr(t),r=dr(t);if(n!==this.user.id)return;if(r===`revoked`){this.rejectFlushes(Error(`Project access revoked`)),this.provider.disconnect();for(let e of this.permissionListeners)e(`revoked`,this.permission);return}if(r!==`read`&&r!==`edit`&&r!==`owner`)return;let i=this.permission;if(this.setPermission(r),i!==r){r===`read`&&this.rejectFlushes(Error(`Project permission changed to read-only`));for(let e of this.permissionListeners)e(r,i)}},this.provider.messageHandlers[Om]=(e,t)=>{dr(t)},this.provider.messageHandlers[Am]=(e,t)=>{let n={};try{n=Lm(JSON.parse(dr(t)))}catch{}this.authoritativeCompileStates=n,this.notifyCompileStateListeners()},this.provider.messageHandlers[jm]=(e,t)=>{let n=dr(t),r=dr(t),i=dr(t),a=dr(t),o=dr(t),s=dr(t);if(n===`state`){let e=or(t)?dr(t):``,n=or(t)?dr(t):``,r=Number(o);if(!e||!Number.isFinite(r)||r<=Date.now())this.removeFormatLeaseState(i),this.notifyFormatLeaseListeners(null);else{let t={path:i,holderUserId:e,holderName:n,expiresAt:r};this.formatLeaseStatesByPath.set(i,t);let a=this.formatLeaseExpiryTimers.get(i);a!==void 0&&window.clearTimeout(a);let o=window.setTimeout(()=>{let e=this.formatLeaseStatesByPath.get(i);!e||e.expiresAt>Date.now()||(this.removeFormatLeaseState(i),this.notifyFormatLeaseListeners(null))},Math.max(0,r-Date.now())+25);this.formatLeaseExpiryTimers.set(i,o),this.notifyFormatLeaseListeners(t)}return}let c=this.formatLeaseRequests.get(r);c&&(window.clearTimeout(c.timer),this.formatLeaseRequests.delete(r),n===`denied`?c.reject(Error(s||`Format lease request was denied`)):c.resolve({status:n,filePath:i,token:a,expiresAt:Number(o)}))},this.provider.on(`status`,({status:e})=>{e===`disconnected`&&(this.authoritativeCompileStates=null,this.notifyCompileStateListeners(),this.rejectFlushes(Error(`Collaboration connection closed`)),this.rejectFormatLeaseRequests(Error(`Collaboration connection closed`)),this.clearFormatLeaseStates())}),this.updateLocalAwareness()}connect(){this.destroyed||(this.provider.connect(),this.updateLocalAwareness())}getText(e){return this.doc.getText(`source:${e}`)}getUndoManager(e){let t=this.undoManagers.get(e);if(t)return t;let n=new Vs(this.getText(e));return this.undoManagers.set(e,n),n}applyTextEdits(e,t){if(this.permission===`read`)throw Error(`Read-only collaborators cannot edit source files`);let n=this.getText(e),r=0;for(let e of t){if(!Number.isInteger(e.from)||!Number.isInteger(e.to)||e.from<r||e.to<e.from||e.to>n.length)throw RangeError(`Invalid collaborative text edits`);r=e.to}this.doc.transact(()=>{for(let e=t.length-1;e>=0;--e){let r=t[e];r.to>r.from&&n.delete(r.from,r.to-r.from),r.replacement&&n.insert(r.from,r.replacement)}})}get meta(){return this.doc.getMap(`texlite:meta`)}compileStates(){return this.authoritativeCompileStates??Lm(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 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&&(await this.persistence.clearData(),this.localDraftReady=!1,this.clearWritableDraftMarkers(),!0)}get hasWritableDraft(){return zm(this.readWritableDraftMarkers().map(({tabId:e,marker:t})=>({tabId:e,activeAt:t.activeAt})),this.draftTabId,Date.now()).recoverable}get hasOtherWritableDraft(){return zm(this.readWritableDraftMarkers().map(({tabId:e,marker:t})=>({tabId:e,activeAt:t.activeAt})),this.draftTabId,Date.now()).otherActive}setPermission(e,t=!1){let n=this.permission;if(this.permission=e,e===`read`&&(n!==`read`&&this.rejectFlushes(Error(`Project permission changed to read-only`)),this.destroyUndoManagers(),this.clearFormatLeaseStates()),this.updateLocalAwareness(),t&&n!==e)for(let t of this.permissionListeners)t(e,n)}setActiveFile(e){this.activeFile!==e&&(this.activeFile=e,this.awareness.setLocalStateField(`cursor`,null),this.updateLocalAwareness())}sessions(){let e=[];return this.awareness.getStates().forEach((t,n)=>{let r=t?.user;r&&typeof r.id==`string`&&typeof r.name==`string`&&e.push({clientId:n,userId:r.id,username:typeof r.username==`string`?r.username:r.name,name:r.name,avatarStyle:L(r.avatarStyle)?r.avatarStyle:null,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 t.filePath==`string`?t.filePath:``,editing:!!t.cursor,local:n===this.doc.clientID})}),e.sort((e,t)=>Number(t.local)-Number(e.local)||e.name.localeCompare(t.name))}flush(){let e=this.provider.ws;if(!this.provider.synced||!e||e.readyState!==WebSocket.OPEN)return Promise.reject(Error(`Collaboration connection is unavailable`));let t=_u(),n=this.draftGeneration,r=An();return Z(r,Em),Ln(r,t),new Promise((i,a)=>{let o=window.setTimeout(()=>{this.flushRequests.delete(t),a(Error(`Collaboration save timed out`))},5e3);this.flushRequests.set(t,{resolve:i,reject:a,timer:o,draftGeneration:n}),e.send(Y(r))})}onFormatLeaseState(e){this.formatLeaseListeners.add(e);for(let t of this.formatLeaseStatesByPath.values())e(t);return()=>this.formatLeaseListeners.delete(e)}formatLeaseStates(){let e=Date.now();for(let[t,n]of this.formatLeaseStatesByPath)n.expiresAt<=e&&this.removeFormatLeaseState(t);return[...this.formatLeaseStatesByPath.values()]}async acquireFormatLease(e){if(this.permission===`read`)throw Error(`Formatting requires write permission`);let t=await this.requestFormatLease(`acquire`,e);if(t.status!==`grant`||!t.token||!Number.isFinite(t.expiresAt))throw Error(`Format lease was not granted`);let n=t.token,r=t.expiresAt,i=!1,a=async()=>{if(i)throw Error(`Format lease has already been released`);let t=await this.requestFormatLease(`renew`,e,n);if(t.status!==`renewed`||!Number.isFinite(t.expiresAt))throw Error(`Format lease renewal failed`);n=t.token||n,r=t.expiresAt};return{path:e,get token(){return n},get expiresAt(){return r},confirm:a,renew:a,release:async()=>{if(i)return;i=!0;let t=this.provider.ws;if(t&&t.readyState===WebSocket.OPEN)try{await this.requestFormatLease(`release`,e,n)}catch{}}}}reconnect(){this.destroyed||(this.rejectFlushes(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(Error(`Collaboration connection closed`)),this.provider.destroy(),this.persistence.destroy(),this.draftListeners.clear(),this.protocolUpgradeListeners.clear(),this.compileStateListeners.clear(),this.rejectFormatLeaseRequests(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(let e of this.undoManagers.values())e.destroy();this.undoManagers.clear()}notifyCompileStateListeners(){for(let e of this.compileStateListeners)e()}rejectFlushes(e){for(let t of this.flushRequests.values())window.clearTimeout(t.timer),t.reject(e);this.flushRequests.clear()}requestFormatLease(e,t,n=``){let r=this.provider.ws;if(!this.provider.synced||!r||r.readyState!==WebSocket.OPEN)return Promise.reject(Error(`Collaboration connection is unavailable`));let i=_u(),a=An();return Z(a,jm),Ln(a,e),Ln(a,i),Ln(a,t),Ln(a,n),new Promise((n,o)=>{let s=window.setTimeout(()=>{if(this.formatLeaseRequests.delete(i),e===`acquire`){let e=this.provider.ws;if(e?.readyState===WebSocket.OPEN){let n=An();Z(n,jm),Ln(n,`cancel`),Ln(n,i),Ln(n,t),Ln(n,``),e.send(Y(n))}}o(Error(`Format lease request timed out`))},e===`acquire`?Mm:5e3);this.formatLeaseRequests.set(i,{resolve:n,reject:o,timer:s}),r.send(Y(a))})}rejectFormatLeaseRequests(e){for(let t of this.formatLeaseRequests.values())window.clearTimeout(t.timer),t.reject(e);this.formatLeaseRequests.clear()}clearFormatLeaseStates(){for(let e of this.formatLeaseExpiryTimers.values())window.clearTimeout(e);this.formatLeaseExpiryTimers.clear(),this.formatLeaseStatesByPath.size&&(this.formatLeaseStatesByPath.clear(),this.notifyFormatLeaseListeners(null))}removeFormatLeaseState(e){let t=this.formatLeaseExpiryTimers.get(e);t!==void 0&&window.clearTimeout(t),this.formatLeaseExpiryTimers.delete(e),this.formatLeaseStatesByPath.delete(e)}notifyFormatLeaseListeners(e){for(let t of this.formatLeaseListeners)t(e)}updateLocalAwareness(){let[e,t]=Cm[Math.abs(this.doc.clientID)%Cm.length],n=this.awareness.getLocalState()?.user,r=n&&Object.hasOwn(n,`avatarStyle`)?n.avatarStyle:this.user.avatarStyle;this.awareness.setLocalStateField(`user`,{id:this.user.id,username:this.user.username,name:this.user.displayName,avatarStyle:L(r)?r:null,color:e,colorLight:t,permission:this.permission,sessionId:String(this.doc.clientID)}),this.awareness.setLocalStateField(`filePath`,this.activeFile)}epochStorageKey(){return b(`texlite:collaboration-epoch:${this.user.id}:${this.projectId}`)}writableDraftStoragePrefix(){return`${b(`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(let{key:e}of this.readWritableDraftMarkers())tt(e);this.draftMarkerPresent=!1,this.stopDraftHeartbeat(),tt(this.writableDraftStoragePrefix().slice(0,-1))}clearOwnWritableDraftMarker(e){let t=this.readOwnWritableDraftMarker();t&&Rm(t.generation,this.draftGeneration,e)&&(tt(this.ownWritableDraftStorageKey()),this.draftMarkerPresent=!1,this.stopDraftHeartbeat())}readOwnWritableDraftMarker(){return this.readWritableDraftMarker(this.ownWritableDraftStorageKey())}readWritableDraftMarkers(){let e=this.writableDraftStoragePrefix(),t=[];for(let n of Je()){if(!n.startsWith(e))continue;let r=this.readWritableDraftMarker(n);r&&t.push({key:n,tabId:n.slice(e.length),marker:r})}return t}readWritableDraftMarker(e){let t=qe(e);if(!t)return null;try{let n=JSON.parse(t);if(!n||typeof n!=`object`||Array.isArray(n))return null;let r=n,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>Nm)return tt(e),null;let a=typeof r.activeAt==`number`&&Number.isFinite(r.activeAt)?Math.max(0,r.activeAt):0;return{generation:r.generation,updatedAt:r.updatedAt,activeAt:a}}catch{return tt(e),null}}writeOwnWritableDraftMarker(e){if(!this.draftMarkerPresent&&this.draftUpdatedAt<=0)return;let t={generation:this.draftGeneration,updatedAt:this.draftUpdatedAt||Date.now(),activeAt:e?Date.now():0};$e(this.ownWritableDraftStorageKey(),JSON.stringify(t)),this.draftMarkerPresent=!0}setOwnDraftActivity(e){this.draftMarkerPresent&&(this.writeOwnWritableDraftMarker(e),e?this.startDraftHeartbeat():this.stopDraftHeartbeat())}resumeOwnDraftActivity(){let e=this.readOwnWritableDraftMarker();e?(this.draftGeneration=Math.max(this.draftGeneration,e.generation),this.draftUpdatedAt=e.updatedAt,this.draftMarkerPresent=!0,this.setOwnDraftActivity(!0)):(this.draftMarkerPresent=!1,this.stopDraftHeartbeat())}startDraftHeartbeat(){this.draftHeartbeatTimer===null&&this.draftMarkerPresent&&(this.draftHeartbeatTimer=window.setInterval(()=>{this.writeOwnWritableDraftMarker(!0)},Pm))}stopDraftHeartbeat(){this.draftHeartbeatTimer!==null&&(window.clearInterval(this.draftHeartbeatTimer),this.draftHeartbeatTimer=null)}};function Vm(e){try{return window.sessionStorage.getItem(e)}catch{return null}}function Hm(e,t){try{window.sessionStorage.setItem(e,t)}catch{}}function Um(e){let t=Vm(e);if(t)return t;let n=_u();return Hm(e,n),n}function Wm({projectId:e,user:t,children:n}){let{t:r}=v(),i=(0,q.useRef)(t);i.current=t;let[a,o]=(0,q.useState)(null),s=(0,q.useRef)(null),c=(0,q.useRef)(null),l=t.id;return(0,q.useEffect)(()=>{c.current=null;let t=s.current;return(!t||t.projectId!==e||t.userId!==l)&&(t?.collaboration.destroy(),t={projectId:e,userId:l,collaboration:new Bm(e,i.current)},s.current=t),o(t),()=>{let e={};c.current=e,queueMicrotask(()=>{c.current===e&&s.current===t&&(c.current=null,s.current=null,t.collaboration.destroy())})}},[e,l]),!a||a.projectId!==e||a.userId!==l?(0,J.jsx)(`div`,{className:`center-card`,role:`status`,children:r(`common.loading`)}):(0,J.jsx)(q.Fragment,{children:n(a.collaboration)},a.collaboration.doc.guid)}var Gm=2500,Km=[`pdflatex`,`xelatex`,`lualatex`];function qm({projectId:e,userId:t,projectEngine:n,allowedEngines:r,compile:i,onError:a}){let o=b(`texlite.tikzPdfEngine:${encodeURIComponent(t)}:${encodeURIComponent(e)}`),[s,c]=(0,q.useState)(()=>qe(o));(0,q.useEffect)(()=>c(qe(o)),[o]);let l=r?.length?r:[...Km],u=l.find(e=>e===s)??(n&&l.includes(n)?n:l[0]),d=e=>{c(e),$e(o,e)},[f,p]=(0,q.useState)(null),m=(0,q.useRef)(void 0);return(0,q.useEffect)(()=>()=>window.clearTimeout(m.current),[]),{state:f,run:async t=>{window.clearTimeout(m.current),p({path:t,status:`compiling`});try{let n=await i(u);if(!n?.ok||n.cancelled||n.mainFile!==t){p(null);return}let r=await G(`/api/projects/${e}/compile/export-pdf`,{method:`POST`,body:JSON.stringify({mainFile:t})});p({path:t,status:`saved`,file:r.path.split(`/`).at(-1)??r.path}),m.current=window.setTimeout(()=>p(null),Gm)}catch(e){p(null),a(K(e))}},engine:u,engines:l,setEngine:d}}function Jm(e){if(!e.includes(`standalone`))return!1;let t=gt(mt(e)),n=/\\documentclass(?![A-Za-z@])\s*(?:\[([^\]]*)\]\s*)?\{\s*standalone\s*\}/.exec(t);return n?(n[1]??``).split(`,`).some(e=>e.trim()===`tikz`)||/\\begin\s*\{tikzpicture\}/.test(t):!1}var Ym=class{selection;restoreRetained;value;sharedAllowed;initialAllowed;constructor(e,t){this.selection=e,this.restoreRetained=t,this.value={selection:e,run:null,pdf:null},this.sharedAllowed=t,this.initialAllowed=t}get snapshot(){return this.value}get sharedCompletionAllowed(){return this.sharedAllowed}observeRunning(){this.sharedAllowed=!0}hasRun(e){return this.snapshot.run?.identity.runId===e&&this.snapshot.run.outcome!==null}beginCompile(){this.initialAllowed=!1,this.sharedAllowed=!0,this.value={...this.snapshot,run:null}}clean(e){this.initialAllowed=!1,e===`artifacts`&&(this.value={selection:this.selection,run:null,pdf:null})}receiveLatest(e,t){if(e.mainFile!==this.selection.mainFile||(t===`initial`?!this.initialAllowed:!this.sharedCompletionAllowed)||t===`shared`&&(!e.latestRun||this.hasRun(e.latestRun.id)))return null;let n=e.latestRun,r=n?.status===`succeeded`?`succeeded`:n?.log.includes(`Compilation was cancelled.`)?`cancelled`:n?.status===`failed`?`failed`:null;return this.receive(e,n?{identity:{...this.selection,runId:n.id},log:n.log,diagnostics:n.diagnostics,outcome:r}:null,t!==`initial`)}receiveLocal(e){return e.mainFile===this.selection.mainFile?this.receive(e,{identity:{...this.selection,runId:e.runId},log:e.log,diagnostics:e.diagnostics,outcome:e.cancelled?`cancelled`:e.ok?`succeeded`:`failed`},!0,e.skipped):null}receive(e,t,n,r=!1){let i=this.snapshot,a=t?this.hasRun(t.identity.runId):!1,o=i.pdf;if(e.pdfUrl){let t=new URL(e.pdfUrl,`https://texlite.invalid/`).searchParams.get(`run`);if(!t)throw Error(`PDF response is missing its compile run identity`);o={identity:{...this.selection,runId:t},url:e.pdfUrl,compiledAt:e.pdfCompiledAt,sizeBytes:e.pdfSizeBytes,loadingMode:e.pdfLoadingMode??`full`}}else n||(o=null);return this.initialAllowed=!1,this.value={selection:this.selection,run:t,pdf:o},{snapshot:this.snapshot,pdfChanged:i.pdf?.url!==o?.url,focusPdf:n&&t?.outcome===`succeeded`&&!!e.pdfUrl&&(r||!a)}}},Xm=(e,t)=>`${e}\0${t}`;function Zm(e,t){e.current&&(!t||e.current.owner===t)&&(e.current.controller.abort(),e.current=null)}function Qm(e){return e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement||e instanceof Element&&!!e.closest(`[role="dialog"], [role="alertdialog"], [data-agent-terminal]`)}function $m(e){let{projectId:t,project:n,mainFile:r,initialLatest:i,collaborationSynced:a,pdfVisible:o,sharedState:s}=e,{t:c}=v(),l=(0,q.useRef)({...e,t:c});l.current={...e,t:c};let u=(0,q.useRef)(!1),d=(0,q.useRef)(null),f=d.current;(!f||f.selection.projectId!==t||f.selection.mainFile!==r)&&(d.current=new Ym({projectId:t,mainFile:r},!f||f.selection.projectId!==t||!f.selection.mainFile));let p=d.current,[m,h]=(0,q.useState)(p.snapshot),[g,_]=(0,q.useState)(null),[y,b]=(0,q.useState)(null),[x,S]=(0,q.useState)([]),[C,w]=(0,q.useState)(null),[T,E]=(0,q.useState)(!1),[D,O]=(0,q.useState)(null),[k,A]=(0,q.useState)(()=>new Set),[j,M]=(0,q.useState)(()=>new Set),[ee,N]=(0,q.useState)(``),P=(0,q.useRef)(null),te=(0,q.useRef)(null),F=(0,q.useRef)(null),ne=(0,q.useRef)(null),I=(0,q.useRef)(null),re=(0,q.useRef)(new Map),ie=(0,q.useRef)(new Map),ae=(0,q.useRef)(new Set),L=(0,q.useRef)({projectId:t,promise:i});L.current.projectId!==t&&(L.current={projectId:t,promise:i});let R=(0,q.useRef)(null),oe=(0,q.useRef)(null),se=(0,q.useRef)(()=>void 0),ce=()=>l.current.getCurrentMainFile?.()||d.current.selection.mainFile,z=(e,t)=>u.current&&!t?.aborted&&d.current===e&&ce()===e.selection.mainFile,le=Xm(t,r),B=m.selection===p.selection,V=k.has(le),H=D===p,ue=e=>{for(let t of[P,te,F,ne])Zm(t,e);for(let t of ae.current)t.owner===e&&(t.controller.abort(),ae.current.delete(t));_(t=>t?.owner===e?null:t),b(t=>t?.owner===e?null:t),E(!1)},de=()=>{oe.current=null,R.current=null,S([]),w(null),E(!1),N(``),l.current.onPdfChanged()},fe=async(e,t)=>{if(!z(e))return;let n=t??{owner:e,controller:new AbortController};t||(Zm(F),F.current=n);let r=e.snapshot.pdf?.url,i=()=>z(e,n.controller.signal)&&e.snapshot.pdf?.url===r;try{let t=await G(`/api/projects/${e.selection.projectId}/compile/artifacts?mainFile=${encodeURIComponent(e.selection.mainFile)}`,{signal:n.controller.signal});i()&&(S(t.artifacts),w(null))}catch(e){!We(e)&&i()&&(S([]),w(null))}finally{F.current===n&&(F.current=null)}},pe=()=>{let e=oe.current;e&&(oe.current=null,z(e.owner)&&e.owner.snapshot.pdf?.url===e.url&&fe(e.owner))},me=e=>{let t=e.snapshot.pdf?.url;t&&(oe.current={owner:e,url:t},(!l.current.pdfVisible||R.current?.owner===e&&R.current.url===t)&&pe())},he=e=>{z(p)&&p.snapshot.pdf?.url===e&&(R.current={owner:p,url:e},oe.current?.owner===p&&oe.current.url===e&&pe())},ge=(e,t)=>!t||!z(e)?!1:(h(t.snapshot),t.pdfChanged&&l.current.onPdfChanged(),t.focusPdf&&l.current.onCompileSuccess(),!0),_e=(e,t)=>{ue(e),oe.current=null,e.clean(t),h(e.snapshot),t===`artifacts`&&(de(),l.current.onPreviewTab(`pdf`)),N(l.current.t(t===`cache`?`editor.cleanCacheComplete`:`editor.cleanArtifactsComplete`))};(0,q.useEffect)(()=>(u.current=!0,()=>{u.current=!1;for(let e of[P,te,F,ne,I])Zm(e);for(let e of[...ae.current,...ie.current.values(),...re.current.values()])e.controller.abort();ae.current.clear(),ie.current.clear(),re.current.clear()}),[]),(0,q.useEffect)(()=>{o||pe()},[o]),(0,q.useEffect)(()=>{h(p.snapshot),de();for(let e of[ie.current,re.current])for(let[n,r]of e)r.owner.selection.projectId!==t&&(r.controller.abort(),e.delete(n));let e=Xm(t,``),n=t=>{let n=new Set([...t].filter(t=>t.startsWith(e)));return n.size===t.size?t:n};if(A(n),M(n),I.current?.owner!==p&&Zm(I),!r)return;if(!p.restoreRetained){l.current.onPreviewTab(`pdf`);let e={owner:p,controller:new AbortController};return l.current.loadOutline(e.controller.signal,r).catch(()=>void 0),()=>{e.controller.abort(),ue(p)}}let i={owner:p,controller:new AbortController};P.current=i,_(i);let a=null,o,s=()=>(o=l.current.sharedState,G(`/api/projects/${t}/compile/latest?mainFile=${encodeURIComponent(r)}`,{signal:i.controller.signal})),c=L.current.promise;return L.current.promise=null,(c?c.then(e=>z(p,i.controller.signal)?e.mainFile===r?e:s():null,()=>z(p,i.controller.signal)?s():null):s()).then(e=>{if(e&&z(p,i.controller.signal)&&ge(p,p.receiveLatest(e,`initial`))){if(e.latestRun?.requestedBy&&(e.latestRun.status===`queued`||e.latestRun.status===`running`)){let t={mainFile:r,runId:e.latestRun.id,status:e.latestRun.status,requestedBy:e.latestRun.requestedBy,updatedAt:new Date().toISOString()};l.current.onSharedState(e=>!z(p,i.controller.signal)||e?.mainFile===r&&(e!==o||e.runId===t.runId&&(e.status!==`queued`||t.status===`queued`))?e:t)}e.pdfUrl&&l.current.onPreviewTab(`pdf`)}}).catch(e=>{!We(e)&&z(p,i.controller.signal)&&l.current.onError(K(e))}).finally(()=>{P.current===i&&(P.current=null),_(e=>e===i?null:e),z(p,i.controller.signal)&&(ae.current.add(i),a=window.setTimeout(()=>{z(p,i.controller.signal)?Promise.all([fe(p,i),l.current.loadOutline(i.controller.signal,r).catch(()=>void 0)]).finally(()=>ae.current.delete(i)):ae.current.delete(i)},0))}),()=>{a!==null&&window.clearTimeout(a),i.controller.abort(),ue(p)}},[p]),(0,q.useEffect)(()=>{s&&s.mainFile===r&&s.status===`cleaned`&&s.cleanMode&&_e(p,s.cleanMode)},[p,s?.runId,s?.status,s?.cleanMode,s?.mainFile]),(0,q.useEffect)(()=>{s?.mainFile===r&&(s.status===`queued`||s.status===`running`)?p.observeRunning():M(e=>{if(!e.has(le))return e;let t=new Set(e);return t.delete(le),t})},[p,s?.mainFile,s?.status,s?.runId]),(0,q.useEffect)(()=>{if(!s||s.mainFile!==r||s.status!==`succeeded`&&s.status!==`failed`||P.current?.owner===p||I.current?.owner===p||H||V||!p.sharedCompletionAllowed||p.hasRun(s.runId))return;let e={owner:p,controller:new AbortController};return Zm(te),Zm(ne),E(!1),te.current=e,b(e),G(`/api/projects/${t}/compile/latest?mainFile=${encodeURIComponent(r)}`,{signal:e.controller.signal}).then(t=>{z(p,e.controller.signal)&&t.latestRun?.id===s.runId&&ge(p,p.receiveLatest(t,`shared`))&&(s.status===`succeeded`&&s.stale&&N(l.current.t(`editor.compileSnapshotStale`)),s.status===`succeeded`&&t.pdfUrl?(l.current.onPreviewTab(`pdf`),me(p)):s.status===`failed`&&l.current.onPreviewTab(t.latestRun.diagnostics.errors.length?`errors`:`log`))}).catch(t=>{!We(t)&&z(p,e.controller.signal)&&l.current.onError(K(t))}).finally(()=>{te.current===e&&(te.current=null),b(t=>t===e?null:t)}),()=>{e.controller.abort(),te.current===e&&(te.current=null)}},[p,s?.runId,s?.status,s?.mainFile,s?.stale,V,g,H]);let ve=async e=>{if(!n||n.permission===`read`||!a)return null;let r=l.current.resolveCompileMainFile?.()||ce(),i=Xm(t,r),o=l.current.sharedState;if(!r||ie.current.has(i)||o?.mainFile===r&&(o.status===`queued`||o.status===`running`))return null;let s=d.current;s.selection.mainFile!==r&&(ue(s),s=new Ym({projectId:t,mainFile:r},!1),d.current=s,de()),ue(s),N(``),l.current.onCompileStart(),l.current.onPreviewTab(s.snapshot.pdf?`pdf`:`log`);let c={owner:s,controller:new AbortController};ie.current.set(i,c),A(e=>new Set([...e,i]));try{if(!await l.current.save()||!z(s,c.controller.signal))return null;s.beginCompile(),h(s.snapshot);let n=await G(`/api/projects/${t}/compile`,{method:`POST`,signal:c.controller.signal,body:JSON.stringify({mainFile:r,engine:e})});return!z(s,c.controller.signal)||!ge(s,s.receiveLocal(n))?null:(n.cancelled&&N(l.current.t(`compileControls.cancelled`)),n.skipped&&N(l.current.t(`editor.upToDate`)),n.ok&&n.stale&&N(l.current.t(`editor.compileSnapshotStale`)),n.pdfUrl?(me(s),l.current.onPreviewTab(`pdf`)):l.current.onPreviewTab(n.diagnostics.errors.length?`errors`:`log`),n)}catch(e){return!We(e)&&z(s,c.controller.signal)&&l.current.onError(K(e)),null}finally{ie.current.get(i)===c&&(ie.current.delete(i),A(e=>{let t=new Set(e);return t.delete(i),t}),M(e=>{let t=new Set(e);return t.delete(i),t}))}},ye=async()=>{if(!n||n.permission===`read`||!a||!z(p))return;let e=Xm(t,r);if(!r||re.current.has(e))return;let i={owner:p,controller:new AbortController};re.current.set(e,i),M(t=>new Set([...t,e]));try{!(await G(`/api/projects/${t}/compile/cancel`,{method:`POST`,signal:i.controller.signal,body:JSON.stringify({mainFile:r})})).cancelled&&z(p,i.controller.signal)&&M(t=>{let n=new Set(t);return n.delete(e),n})}catch(t){z(p,i.controller.signal)&&(M(t=>{let n=new Set(t);return n.delete(e),n}),We(t)||l.current.onError(K(t)))}finally{re.current.get(e)===i&&re.current.delete(e)}},be=async e=>{if(!n||n.permission===`read`||!a||!z(p)||!r||I.current||ie.current.has(le)||s?.mainFile===r&&(s.status===`queued`||s.status===`running`))return;let i={owner:p,controller:new AbortController},o=l.current.sharedState;I.current=i,O(p),ue(p);try{let n=await G(`/api/projects/${t}/compile/clean`,{method:`POST`,signal:i.controller.signal,body:JSON.stringify({mainFile:r,mode:e})});if(!z(p,i.controller.signal)||n.mainFile!==r)return;l.current.sharedState===o&&l.current.onSharedState(null),_e(p,e)}catch(e){!We(e)&&z(p,i.controller.signal)&&l.current.onError(K(e))}finally{I.current===i&&(I.current=null),O(e=>e===p?null:e)}},xe=async e=>{if(!e.viewable||!z(p))return;Zm(ne);let n={owner:p,controller:new AbortController},i=p.snapshot.pdf?.url;ne.current=n,E(!0);try{let a=await G(`/api/projects/${t}/compile/artifacts?mainFile=${encodeURIComponent(r)}&path=${encodeURIComponent(e.path)}`,{signal:n.controller.signal});z(p,n.controller.signal)&&p.snapshot.pdf?.url===i&&w(a)}catch(e){!We(e)&&z(p,n.controller.signal)&&p.snapshot.pdf?.url===i&&l.current.onError(K(e))}finally{ne.current===n&&(ne.current=null,E(!1))}};se.current=()=>void ve(),(0,q.useEffect)(()=>{if(!ee)return;let e=window.setTimeout(()=>N(``),3e3);return()=>window.clearTimeout(e)},[ee,p]),(0,q.useEffect)(()=>{let e=e=>{(e.ctrlKey||e.metaKey)&&e.key.toLocaleLowerCase()===`s`&&(e.preventDefault(),!Qm(e.target)&&(e.stopPropagation(),e.repeat||se.current()))};return window.addEventListener(`keydown`,e,!0),()=>window.removeEventListener(`keydown`,e,!0)},[]);let Se=B?m:null;return{pdfUrl:Se?.pdf?.url??``,pdfCompiledAt:Se?.pdf?.compiledAt??null,pdfSizeBytes:Se?.pdf?.sizeBytes??null,pdfLoadingMode:Se?.pdf?.loadingMode??`full`,pdfLoading:g?.owner===p&&!g.controller.signal.aborted||y?.owner===p&&!y.controller.signal.aborted,compileLog:Se?.run?.log??``,compileDiagnostics:Se?.run?.diagnostics??null,compileOutcome:Se?.run?.outcome??null,artifacts:B?x:[],artifactPreview:B?C:null,artifactLoading:B&&T,editorNotice:B?ee:``,localCompiling:V,cancelling:j.has(le),cleaning:H,pdfDisplayed:he,compile:ve,cancelCompile:ye,cleanCompile:be,viewArtifact:xe}}var eh=10485760;function th(e){let t=e.split(`/`).filter(Boolean);return t.pop(),t.map((e,n)=>t.slice(0,n+1).join(`/`))}function nh(e,t){return!!(e&&t)&&(t===e||t.startsWith(`${e}/`))}function rh(e,t){let n=ve(e);return n===`binary`||n===`other`||n===`text`&&t===!1?`unsupported`:n}function ih(e,t){let n=rh(e.path,e.textContent);return n===`unsupported`?n:(e.size??0)>10485760||n===`text`&&(e.size??0)>t?`large`:n===`text`?`editor`:n}function ah(e,t){return x(`/api/projects/${e}/file/raw?path=${encodeURIComponent(t)}`)}function oh({projectId:e,site:t,activeFile:n,dirty:r,save:i,onError:a,onProject:o,onActiveFile:s,onActiveMainFile:c}){let{t:l}=v(),[u,d]=(0,q.useState)([]),[f,p]=(0,q.useState)(!1),[m,h]=(0,q.useState)(``),[g,_]=(0,q.useState)(null),[y,b]=(0,q.useState)(!1),[x,S]=(0,q.useState)(!1),[C,w]=(0,q.useState)(``),[T,E]=(0,q.useState)(``),[D,O]=(0,q.useState)(null),[k,A]=(0,q.useState)(``),[j,M]=(0,q.useState)(new Set),[ee,N]=(0,q.useState)(null),[P,te]=(0,q.useState)(``),[F,ne]=(0,q.useState)(``),[I,re]=(0,q.useState)(null),[ie,ae]=(0,q.useState)(!1),[L,R]=(0,q.useState)(null),[oe,se]=(0,q.useState)(!1),[ce,z]=(0,q.useState)(null),le=(0,q.useRef)(!1),B=(0,q.useRef)(null),V=(0,q.useRef)(null),H=(0,q.useRef)(null),ue=async(t={})=>{V.current?.abort(),V.current=null;let n=t.signal?null:new AbortController;n&&(V.current=n);try{let r=await G(`/api/projects/${e}/files`,{signal:t.signal??n?.signal});return(!t.isCurrent||t.isCurrent())&&d(r.files),r.files}catch(e){if(!We(e))throw e;return}finally{n&&V.current===n&&(V.current=null)}},de=async(t,n)=>{await G(`/api/projects/${e}/file`,{method:`POST`,body:JSON.stringify({path:t,content:n})});let r=(await ue())?.find(e=>e.path===t);r&&await ve(r),O(null),M(e=>new Set([...e,...th(t)]))},fe=async()=>{if(m.trim()&&!m.trim().endsWith(`/`)){E(``);try{await de(m,``),p(!1),h(``)}catch(e){E(K(e))}}},pe=async()=>{if(!C.trim())return;E(``);let t=D?`${D}/${C.trim()}`:C.trim();try{let n=await G(`/api/projects/${e}/folders`,{method:`POST`,body:JSON.stringify({path:t})});await ue(),M(e=>new Set([...e,...th(n.path),n.path])),O(n.path),S(!1),w(``)}catch(e){E(K(e))}},me=async(n,r=new Set,i=D)=>{if(!n.length||le.current)return;let a=t.maxUploadSizeMB;if(n.find(e=>e.size>a*1024*1024)){z({kind:`error`,message:l(`errors.fileTooLarge`,{size:a})});return}let o=i??``,s=n.map(e=>o?`${o}/${e.name}`:e.name),c=new Map;for(let e of s)c.set(e,(c.get(e)??0)+1);let d=[...c.entries()].filter(([,e])=>e>1).map(([e])=>e);if(d.length){z({kind:`error`,message:l(`errors.duplicateUploadNames`,{files:d.join(`, `)})});return}let f=new Set(u.map(e=>e.path)),p=[...new Set(s.filter(e=>f.has(e)&&!r.has(e)))];if(p.length){z(null),R({files:n,directory:o,collisions:p});return}R(null),B.current!==null&&window.clearTimeout(B.current),B.current=null,z(null),le.current=!0,se(!0);let m=0;try{let i=new URLSearchParams;o&&i.set(`directory`,o);let a=``;for(let[t,c]of n.entries()){let l=s[t];i.delete(`overwrite`),r.has(l)&&i.set(`overwrite`,`1`);let u=i.toString()?`?${i.toString()}`:``,d=new FormData;d.append(`file`,c);try{z({kind:`uploading`,fileName:c.name,current:t+1,total:n.length});let r=await G(`/api/projects/${e}/upload${u}`,{method:`POST`,body:d});m+=1,typeof r.path==`string`&&Ne(r.path)&&(a=r.path)}catch(e){if(e instanceof Ue&&e.status===409&&!r.has(l)&&e.code===`FILE_EXISTS`){if(z(null),t>0)try{await ue()}catch{}R({files:n.slice(t),directory:o,collisions:[l]});return}throw e}}let c;try{c=(await ue())?.find(e=>e.path===a&&Ne(e.path,e.textContent)&&(e.size??0)<=t.maxCollaborativeFileSizeMB*1024*1024)}catch(e){z({kind:`error`,message:l(`editor.uploadSucceededRefreshFailed`,{message:K(e)})});return}c&&await ve(c),z({kind:`success`,count:m}),B.current=window.setTimeout(()=>{z(e=>e?.kind===`success`?null:e),B.current=null},3e3)}catch(e){try{await ue()}catch{}let t=m>0?l(`editor.uploadFailedPartial`,{count:n.length,uploaded:m,total:n.length,message:K(e)}):l(`editor.uploadFailed`,{message:K(e)});z({kind:`error`,message:t})}finally{le.current=!1,se(!1)}},he=()=>{B.current!==null&&window.clearTimeout(B.current),B.current=null,z(null)},ge=async e=>{await me(Array.from(e.target.files??[])),e.target.value=``},_e=async n=>{H.current?.abort(),H.current=null,b(!1);let r=ah(e,n.path);if(ih(n,t.maxCollaborativeFileSizeMB*1024*1024)===`large`){let e=Ne(n.path,n.textContent)?Math.min(eh,t.maxCollaborativeFileSizeMB*1024*1024):eh;_({path:n.path,kind:`large`,size:n.size??0,url:r,limitBytes:e});return}let i=rh(n.path,n.textContent);if(i!==`text`){_({path:n.path,kind:i,size:n.size??0,url:r});return}_({path:n.path,kind:i,size:n.size??0,url:r,content:``}),b(!0);let o=new AbortController;H.current=o;try{let e;try{e=await fetch(r,{signal:o.signal})}catch(e){throw Ge(e)}let t=e.headers.get(`content-type`)??``;if(!e.ok){let n=null;try{n=t.includes(`application/json`)?await e.json():await e.text()}catch{}throw new Ue(U(n,e.status),e.status,Qe(n))}let i=new Uint8Array(await e.arrayBuffer());if(!Ie(i)){_(e=>e?.path===n.path?{...e,kind:`unsupported`,content:void 0}:e);return}let a=new TextDecoder().decode(i);_(e=>e?.path===n.path?{...e,content:a}:e)}catch(e){We(e)||(_(null),a(K(e)))}finally{H.current===o&&(H.current=null,b(!1))}},ve=async n=>{if(H.current?.abort(),H.current=null,b(!1),O(null),A(n.path),ih(n,t.maxCollaborativeFileSizeMB*1024*1024)!==`editor`){await _e(n);return}let r=new AbortController;H.current=r;try{if(await G(`/api/projects/${e}/file?path=${encodeURIComponent(n.path)}&validate=1`,{signal:r.signal}),r.signal.aborted||H.current!==r)return;s(n.path)}catch(t){if(r.signal.aborted||H.current!==r||We(t))return;t instanceof Ue&&t.code===`FILE_CONTENT_INVALID`?(d(e=>e.map(e=>e.path===n.path?{...e,textContent:!1}:e)),_({path:n.path,kind:`unsupported`,size:n.size??0,url:ah(e,n.path)})):a(K(t))}finally{H.current===r&&(H.current=null)}},ye=async(t,n,r)=>{if(!await i())return null;let a=await G(`/api/projects/${e}/path`,{method:`PATCH`,body:JSON.stringify({source:t.path,destinationDirectory:n,destinationName:r})}),l=e=>e===t.path?a.path:e.startsWith(`${t.path}/`)?`${a.path}${e.slice(t.path.length)}`:e;s(e=>l(e)),c(e=>l(e)),O(e=>e&&l(e)),A(e=>e&&l(e));let[u,f]=await Promise.all([G(`/api/projects/${e}/files`),G(`/api/projects/${e}`)]);return d(u.files),o(f.project),M(e=>new Set([...e,...th(a.path),n].filter(Boolean))),a.path};return(0,q.useEffect)(()=>()=>{V.current?.abort(),H.current?.abort(),B.current!==null&&window.clearTimeout(B.current)},[]),(0,q.useEffect)(()=>{H.current?.abort(),H.current=null,b(!1)},[n]),(0,q.useEffect)(()=>{D!==null&&(H.current?.abort(),H.current=null,b(!1))},[D]),(0,q.useEffect)(()=>{n&&A(n)},[n]),{files:u,setFiles:d,loadFiles:ue,newFileOpen:f,setNewFileOpen:p,newFilePath:m,setNewFilePath:h,resourcePreview:g,setResourcePreview:_,resourcePreviewLoading:y,setResourcePreviewLoading:b,newFolderOpen:x,setNewFolderOpen:S,newFolderName:C,setNewFolderName:w,fileDialogError:T,setFileDialogError:E,selectedFolder:D,setSelectedFolder:O,selectedFile:k,setSelectedFile:A,expandedFolders:j,setExpandedFolders:M,moveEntry:ee,setMoveEntry:N,moveName:P,setMoveName:te,moveDestination:F,setMoveDestination:ne,deleteEntry:I,setDeleteEntry:re,fileDragActive:ie,setFileDragActive:ae,uploadConflict:L,setUploadConflict:R,uploadingFiles:oe,uploadFeedback:ce,dismissUploadFeedback:he,directoryEntries:u.filter(e=>e.type===`directory`),visibleEntries:u.filter(e=>th(e.path).every(e=>j.has(e))),createFile:fe,addFile:de,createFolder:pe,uploadFiles:me,upload:ge,openFile:ve,movePath:async()=>{if(!ee)return;let e=P.trim();if(e){E(``);try{if(!await ye(ee,F,e))return;N(null),te(``),ne(``)}catch(e){E(K(e))}}},movePathToFolder:async(e,t)=>{if(sh(e.path)!==t&&(e.type!==`directory`||t!==e.path&&!t.startsWith(`${e.path}/`)))try{await ye(e,t,e.path.split(`/`).at(-1)??e.path)}catch(e){a(K(e))}},removePath:async()=>{if(I){E(``);try{if(r&&!await i())return;await G(`/api/projects/${e}/file?path=${encodeURIComponent(I.path)}`,{method:`DELETE`}),re(null)}catch(e){E(K(e))}}}}}function sh(e){let t=e.lastIndexOf(`/`);return t<0?``:e.slice(0,t)}var ch=[];function lh({active:e,harperEnabled:t=!0,projectId:n,activeFile:r,content:i,dictionaryWords:a,additionalIssues:o=ch,additionalIssuesReady:s=!0}){let[c,l]=(0,q.useState)([]),[u,d]=(0,q.useState)(``),[f,p]=(0,q.useState)(``),[m,h]=(0,q.useState)(0),[g,_]=(0,q.useState)(null),[v,y]=(0,q.useState)(null),[b,x]=(0,q.useState)(!1),[C,w]=(0,q.useState)(0),T=(0,q.useRef)(0),E=(0,q.useRef)(!1),D=(0,q.useRef)(!1),O=(0,q.useRef)(i),k=(0,q.useRef)(r),A=(0,q.useRef)(0);O.current=i,k.current=r,D.current=b,(0,q.useEffect)(()=>{l([]),d(``),p(``),_(null),y(null),x(!1)},[r,a,t]),(0,q.useEffect)(()=>{y(null),x(!1)},[n]),(0,q.useEffect)(()=>{let o=++T.current;if(!e||!r){l([]),d(``),p(``),_(null);return}if(!t||v){l([]),d(``),p(``);return}let s=i,c=r,u=!1,f=window.setTimeout(()=>{y(null),(async()=>{try{let{lintLatex:e,isHarperLintSupersededError:t}=await S(async()=>{let{lintLatex:e,isHarperLintSupersededError:t}=await import(`./spellCheck-kxvnxrvw.js`);return{lintLatex:e,isHarperLintSupersededError:t}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13]),import.meta.url);if(u||o!==T.current||O.current!==s||k.current!==c)return;let r;try{r=await e(n,c,s,a)}catch(e){if(t(e))return;throw e}if(u||o!==T.current||O.current!==s||k.current!==c)return;E.current=!1,x(!1),l(r),d(s),p(c),h(0),_(null)}catch(e){if(u||o!==T.current||O.current!==s||k.current!==c)return;l([]),d(``),p(``),y(e instanceof Error?e.message:String(e));let t=E.current;E.current=!1,x(t?D.current:!1)}})()},700);return()=>{u=!0,window.clearTimeout(f)}},[e,t,n,r,i,a,C,v]),(0,q.useEffect)(()=>{if(!v||!e||!t)return;let n=!1,r=()=>{n||(n=!0,E.current=!0,y(null),w(e=>e+1))},i=window.setTimeout(r,15e3);return window.addEventListener(`online`,r,{once:!0}),()=>{window.clearTimeout(i),window.removeEventListener(`online`,r)}},[v,e,t]);let j=t&&e&&f===r&&u===i,M=(0,q.useMemo)(()=>{if(!e)return[];let t=[...j?c:[],...o].sort((e,t)=>e.from-t.from||e.to-t.to),n=new Set;return t.filter(e=>{let t=`${e.from}:${e.to}:${e.kind}:${e.message}`;return!n.has(t)&&(n.add(t),!0)})},[e,o,j,c]),ee=(0,q.useMemo)(()=>e&&(!t||j)&&s?{total:M.length,unique:new Set(M.map(e=>`${e.kind}:${e.word.toLocaleLowerCase(`en-US`)}`)).size}:null,[e,s,t,j,M]);return(0,q.useEffect)(()=>{h(e=>M.length?Math.min(e,M.length-1):0)},[M]),{issues:M,jump:e?g:null,index:m,summary:ee,jumpToIssue:e=>{if(!M.length)return;let t=Math.max(0,Math.min(e,M.length-1)),n=M[t];h(t),_({from:n.from,to:n.to,nonce:++A.current})},error:e&&t&&!b?v:null,nativeFallback:e&&t&&!!v,retry:()=>{E.current=!1,y(null),x(!1),w(e=>e+1)},dismissError:()=>{E.current=!1,x(!0)}}}var uh=[];function dh({active:e,projectId:t,activeFile:n,content:r}){let[i,a]=(0,q.useState)([]),[o,s]=(0,q.useState)(``),[c,l]=(0,q.useState)(``),[u,d]=(0,q.useState)(null),[f,p]=(0,q.useState)(!1),[m,h]=(0,q.useState)(0),g=(0,q.useRef)(0),_=(0,q.useRef)(r),v=(0,q.useRef)(n);_.current=r,v.current=n,(0,q.useEffect)(()=>{a([]),s(``),l(``),d(null),p(!1)},[t,n]),(0,q.useEffect)(()=>{let i=++g.current;if(!e||!n){a([]),s(``),l(``);return}let o=r,c=n,u=!1,f=window.setTimeout(()=>{(async()=>{try{let{lintChktex:e,isChktexLintSupersededError:n}=await S(async()=>{let{lintChktex:e,isChktexLintSupersededError:t}=await import(`./chktex-22lKGvKa.js`);return{lintChktex:e,isChktexLintSupersededError:t}},__vite__mapDeps([14,1,2,3,4,5,6,7,8,9,10,11,12,13]),import.meta.url);if(u||i!==g.current||_.current!==o||v.current!==c)return;let r;try{r=await e(t,c,o)}catch(e){if(n(e))return;throw e}if(u||i!==g.current||_.current!==o||v.current!==c)return;a(r),s(o),l(c),d(null),p(!1)}catch(e){if(u||i!==g.current||_.current!==o||v.current!==c)return;a([]),s(``),l(``),d(e instanceof Error?e.message:String(e))}})()},2e3);return()=>{u=!0,window.clearTimeout(f)}},[e,t,n,r,m]);let y=e&&c===n&&o===r;return{issues:y?i:uh,checked:y,error:e&&!f?u:null,retry:()=>{d(null),p(!1),h(e=>e+1)},dismissError:()=>p(!0)}}function fh(e,t){return/\.tex$/i.test(e)&&/\.tex$/i.test(t)}function ph({projectId:e,mainFile:t,activeFile:n,onOpenSourceFile:r,onError:i,onShowPdf:a,onShowEditor:o}){let[s,c]=(0,q.useState)(null),[l,u]=(0,q.useState)(null),[d,f]=(0,q.useState)(null),p=(0,q.useRef)(null),m=(0,q.useRef)(0),h=(0,q.useRef)(n),g=(0,q.useRef)(r),_=(0,q.useRef)(i),v=(0,q.useRef)(a),y=(0,q.useRef)(o);h.current=n,g.current=r,_.current=i,v.current=a,y.current=o,(0,q.useEffect)(()=>(p.current?.abort(),p.current=null,c(null),u(null),f(null),()=>p.current?.abort()),[e,t]);let b=(e,t,n)=>{f({path:e,line:t,column:n,nonce:++m.current}),g.current(e)},x=async(n,r,i,a={})=>{if(!fh(n,t))return;p.current?.abort();let o=new AbortController;p.current=o;try{let a=await G(`/api/projects/${e}/sync/pdf?mainFile=${encodeURIComponent(t)}&path=${encodeURIComponent(n)}&line=${r}&column=${i}`,{signal:o.signal});if(p.current!==o||!a)return;c({...a,nonce:++m.current}),v.current()}catch(e){!We(e)&&!a.silent&&_.current(K(e))}finally{p.current===o&&(p.current=null)}},S=async(n,r,i)=>{let a=h.current;p.current?.abort();let o=new AbortController;p.current=o;try{let s=await G(`/api/projects/${e}/sync/source?mainFile=${encodeURIComponent(t)}&page=${n}&x=${r}&y=${i}`,{signal:o.signal});if(p.current!==o||h.current!==a)return;y.current(),b(s.path,s.line,s.column)}catch(e){We(e)||_.current(K(e))}finally{p.current===o&&(p.current=null)}};return{pdfTarget:s,pdfViewport:l,sourceJump:d,setPdfViewport:u,resetPdfViewport:()=>u(null),clearPdfViewport:()=>{p.current?.abort(),p.current=null,u(null),c(null)},jumpToSource:b,syncSourceToPdf:x,syncPdfToSource:S,syncVisiblePdfToSource:()=>l?S(l.page,l.x,l.y):Promise.resolve()}}function mh(e,t,n){return b(`texlite.workspaceLayout:${encodeURIComponent(e)}:${encodeURIComponent(t)}${n?`:phone`:``}`)}function hh(e,t,n){let r=qe(mh(e,t,n));return r===`editor-only`||r===`pdf-only`||!n&&r===`editor-pdf`?r:n?`editor-only`:`editor-pdf`}function gh(e,t){let n=be(),[r,i]=(0,q.useState)(()=>hh(e,t,n));return(0,q.useEffect)(()=>{i(hh(e,t,n))},[e,t,n]),{workspaceLayout:n&&r===`editor-pdf`?`editor-only`:r,setWorkspaceLayout:r=>{let a=n&&r===`editor-pdf`?`editor-only`:r;i(a),$e(mh(e,t,n),a)},phone:n}}function _h(e,t){let n=0;for(let r=t-1;r>=0&&e[r]===`\\`;--r)n+=1;return n%2==1}function vh(e){let t=gt(mt(e));for(let e of t.matchAll(/\\documentclass(?![A-Za-z@])\s*(?:\[[^\]]*\]\s*)?\{/g))if(e.index!==void 0&&!_h(t,e.index))return!0;return!1}function yh(e){return/\.(?:md|markdown|mdown|mkdn)$/i.test(e)}function bh(e,t,n){return e===`diagnostics`?`diagnostics`:t&&n?`markdown`:`pdf`}function xh(e,t){if(t.startsWith(`#`))return{kind:`anchor`,id:Sh(t.slice(1))};if(/^[a-z][a-z\d+.-]*:/i.test(t)||t.startsWith(`//`))return{kind:`external`};let n=t.replace(/[?#].*$/s,``);if(!n)return{kind:`invalid`};let r=Sh(n),i=e.includes(`/`)?e.slice(0,e.lastIndexOf(`/`)).split(`/`):[],a=r.startsWith(`/`)?[]:[...i];for(let e of r.split(`/`))if(e!==``&&e!==`.`){if(e===`..`){if(!a.length)return{kind:`invalid`};a.pop()}else a.push(e)}return a.length?{kind:`project`,path:a.join(`/`)}:{kind:`invalid`}}function Sh(e){try{return decodeURIComponent(e)}catch{return e}}function Ch(e){let t=new Map;return e.map(e=>{let n=e.trim().toLowerCase().replace(/[^\p{L}\p{N}\s_-]/gu,``).replace(/\s/g,`-`),r=t.get(n)??0;return t.set(n,r+1),r?`${n}-${r}`:n})}function wh({site:e,project:t,activeFile:n,saveStateLabel:r,editorPreferences:i,activeSessions:a,collaborationStatus:o,reconnectCollaboration:s,protocolUpgradeRequired:c,showEditor:l,filesCollapsed:u,toggleFilesPanel:d,workspaceLayout:f,changeWorkspaceLayout:p,onBack:h,onShare:g,showCitationLibrary:y,citationLibraryOpen:b,onCitationLibrary:x,onHistory:S,onGit:C,canManageGit:w,formatting:T,readOnly:E,collaborationSynced:O,onToggleComments:k,commentsOpen:A,unresolvedCommentCount:M,onToggleSettings:ee,settingsOpen:N,compileBusy:P,sharedCompiling:te,localCompiling:F,cancelling:ne,onCompile:ie,onCancelCompile:ae,agentTerminal:L}){let{t:R}=v(),{showExecutionReminder:oe}=m();return(0,J.jsxs)(Ae,{siteName:e.siteName,projectName:t.name,subtitle:(0,J.jsxs)(J.Fragment,{children:[n,` · `,r]}),onBack:h,accessory:(0,J.jsxs)(J.Fragment,{children:[i.vimMode&&(0,J.jsxs)(`span`,{className:`vim-status-badge`,title:R(`editor.vimOnHint`),children:[(0,J.jsx)(Nt,{size:14}),R(`editor.vimOn`)]}),(0,J.jsx)(ye,{sessions:a,status:o}),o===`disconnected`&&!c&&(0,J.jsxs)(`div`,{className:`collaboration-recovery`,role:`status`,children:[(0,J.jsx)(`span`,{children:R(`editor.collaboration.disconnected`)}),(0,J.jsx)(`button`,{type:`button`,onClick:s,children:R(`editor.collaboration.reconnect`)})]})]}),children:[l&&(0,J.jsxs)(`button`,{className:`files-action${u?``:` active`}`,"aria-label":R(`common.files`),title:R(`common.files`),"aria-expanded":!u,onClick:d,children:[u?(0,J.jsx)(fe,{size:15}):(0,J.jsx)(Pe,{size:15}),(0,J.jsx)(`span`,{className:`workspace-action-label`,children:R(`common.files`)})]}),(0,J.jsx)(we,{value:f,onChange:p,workspacePrimary:!0,previewLabel:yh(n)?R(`editor.mobilePreview`):void 0}),(0,J.jsxs)(`button`,{type:`button`,className:`share-action`,title:R(`projectSettings.share`),"aria-label":t.sharedMemberCount?`${R(`projectSettings.share`)} (${t.sharedMemberCount})`:R(`projectSettings.share`),onClick:g,children:[(0,J.jsx)(j,{size:15}),(0,J.jsx)(`span`,{className:`workspace-action-label`,children:R(`projectSettings.share`)}),(t.sharedMemberCount??0)>0&&(0,J.jsx)(`sup`,{className:`share-action-count`,children:t.sharedMemberCount})]}),y&&(0,J.jsxs)(`button`,{className:`citation-action${b?` active`:``}`,"aria-label":R(`citationProject.button`),title:R(`citationProject.button`),onClick:x,children:[(0,J.jsx)(_,{size:15}),(0,J.jsx)(`span`,{className:`workspace-action-label`,children:R(`citationProject.button`)})]}),(0,J.jsxs)(`button`,{type:`button`,className:`snapshots-action`,"aria-label":R(`history.projectSnapshots`),title:R(`history.projectSnapshots`),onClick:S,children:[(0,J.jsx)(he,{size:15}),(0,J.jsx)(`span`,{className:`workspace-action-label`,children:R(`history.projectSnapshotsButton`)})]}),(0,J.jsxs)(`button`,{type:`button`,className:`comments-action${A?` active`:``}`,title:R(`editor.commentsAll`),"aria-label":M>0?`${R(`common.comments`)} (${M})`:R(`common.comments`),onClick:k,children:[(0,J.jsx)(re,{size:15}),(0,J.jsx)(`span`,{className:`workspace-action-label`,children:R(`common.comments`)}),M>0&&(0,J.jsx)(`sup`,{className:`comments-action-count`,children:M})]}),(0,J.jsxs)(`button`,{className:`git-action`,"aria-label":R(`git.title`),title:R(w?`git.title`:`git.ownerOnly`),disabled:!w,onClick:C,children:[(0,J.jsx)(I,{size:15}),(0,J.jsx)(`span`,{className:`workspace-action-label`,children:`Git`})]}),L&&(0,J.jsxs)(`button`,{type:`button`,className:L.open?`active`:``,"aria-expanded":L.open,"aria-label":oe&&L.activeCount>0?`${R(`agents.terminal`)}: ${R(`agents.activeCount`,{count:L.activeCount})}`:R(`agents.terminal`),title:R(`agents.terminal`),onClick:L.toggle,children:[(0,J.jsx)(D,{size:15}),(0,J.jsx)(`span`,{className:`workspace-action-label`,children:R(`agents.terminal`)}),oe&&L.activeCount>0&&(0,J.jsx)(`sup`,{className:`agent-active-count`,"aria-label":R(`agents.activeCount`,{count:L.activeCount}),children:L.activeCount})]}),(0,J.jsxs)(`button`,{className:N?`active`:``,"aria-label":R(`common.settings`),title:R(`common.settings`),onClick:ee,children:[(0,J.jsx)(Fe,{size:15}),(0,J.jsx)(`span`,{className:`workspace-action-label workspace-action-label-persistent`,children:R(`common.settings`)})]}),te||F?(0,J.jsxs)(`button`,{className:`compile cancel-compile`,"aria-label":R(ne?`compileControls.cancelling`:`compileControls.cancel`),title:R(`compileControls.cancel`),onClick:ae,disabled:ne||T||E||!O,children:[ne?(0,J.jsx)(Re,{className:`spin`,size:15}):(0,J.jsx)(z,{size:15}),(0,J.jsx)(`span`,{className:`workspace-action-label workspace-action-label-persistent`,children:R(ne?`compileControls.cancelling`:`compileControls.cancel`)})]}):(0,J.jsxs)(`button`,{className:`compile`,"aria-label":R(`editor.compile`,{engine:t.engine}),title:R(`editor.compileShortcut`),onClick:ie,disabled:P||T||E||!O,children:[P?(0,J.jsx)(Re,{className:`spin`,size:15}):(0,J.jsx)(ge,{size:15}),(0,J.jsxs)(`span`,{className:`workspace-action-label workspace-action-label-persistent`,children:[R(`editor.compileShort`),(0,J.jsxs)(`span`,{className:`compile-engine-label`,children:[` · `,t.engine]})]})]})]})}function Th(e,t,n){return e===`connected`?t:e===`disconnected`&&n?`editor.offlineDraft`:`editor.collaboration.${e}`}function Eh({state:e,disabled:t,engine:n,engines:r,onEngineChange:i,onCompile:a}){let{t:o}=v(),s=e?.status===`compiling`;return(0,J.jsxs)(`div`,{className:`tikz-compile-pdf`,children:[(0,J.jsxs)(`button`,{type:`button`,disabled:t||s,onClick:a,children:[s?(0,J.jsx)(Re,{className:`spin`,size:13,"aria-hidden":!0}):e?.status===`saved`?(0,J.jsx)(V,{className:`save-button-confirmation`,size:13,"aria-hidden":!0}):(0,J.jsx)(jt,{size:13,"aria-hidden":!0}),(0,J.jsx)(`span`,{role:`status`,"aria-live":`polite`,children:e?.status===`saved`?o(`editor.tikz.pdfSaved`,{file:e.file}):o(`editor.tikz.compilePdf`)})]}),(0,J.jsxs)(ut,{modal:!1,children:[(0,J.jsx)(at,{asChild:!0,children:(0,J.jsxs)(`button`,{type:`button`,className:`tikz-engine-trigger`,disabled:s,"aria-label":o(`editor.tikz.chooseEngine`),title:o(`editor.tikz.chooseEngine`),children:[n,(0,J.jsx)(H,{size:12,"aria-hidden":!0})]})}),(0,J.jsx)(rt,{children:(0,J.jsx)(ot,{className:`file-actions-menu`,align:`end`,sideOffset:5,collisionPadding:8,children:(0,J.jsx)(st,{value:n,onValueChange:e=>i(e),children:r.map(e=>(0,J.jsxs)(lt,{value:e,children:[(0,J.jsx)(`span`,{className:`tikz-engine-check`,children:(0,J.jsx)(it,{children:(0,J.jsx)(V,{size:14,"aria-hidden":!0})})}),e]},e))})})})]})]})}function Dh({children:e,tabs:t,terminal:n}){let{t:r}=v(),i=Ce(),[a,o]=(0,q.useState)(!1),s=!!n,c=(0,q.useRef)(s),l=s&&a;return(0,q.useLayoutEffect)(()=>{c.current&&!s&&i.current?.resize(`100%`),c.current=s},[i,s]),(0,J.jsx)(`main`,{className:`source-panel`,children:(0,J.jsxs)(Te,{orientation:`vertical`,className:`agent-editor-group`,children:[(0,J.jsx)(xe,{id:`source-editor`,panelRef:i,minSize:`20%`,collapsible:!!n,collapsedSize:`0%`,onResize:e=>o(e.asPercentage===0),children:(0,J.jsxs)(`div`,{className:`source-editor-pane`,inert:l,children:[t,e]})}),n&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(Oe,{className:`agent-terminal-resizer`,"aria-label":r(`agents.resizeTerminal`)}),(0,J.jsx)(xe,{id:`agent-terminal`,defaultSize:`35%`,minSize:`20%`,children:n({maximized:l,toggleMaximized:()=>{let e=i.current;e?.isCollapsed()?e.expand():e?.collapse()}})})]})]})})}function Oh({direction:e,disabled:t,onClick:n,label:r}){let{t:i}=v(),[a,o]=(0,q.useState)(!1),s=e===`pdf`?xt:ee,c=r??i(e===`pdf`?`editor.showInPdf`:`editor.showInSource`);return(0,J.jsx)(`button`,{type:`button`,className:`workspace-mobile-sync workspace-mobile-sync-${e}`,title:c,"aria-label":c,"aria-busy":a,disabled:t||a,onClick:async()=>{o(!0);try{await n()}finally{o(!1)}},children:a?(0,J.jsx)(Re,{className:`spin`,size:18,"aria-hidden":`true`}):(0,J.jsx)(s,{size:18,"aria-hidden":`true`})})}var kh=(0,q.lazy)(()=>S(()=>import(`./LatexEditor-vNOVTIl7.js`).then(e=>({default:e.LatexEditor})),__vite__mapDeps([15,2,3,4,5,8,16,7,9,17,12,1,6,10,11,13,18,19,20,21,22,23,24,25]),import.meta.url));function Ah({project:e,projectId:t,activeFile:n,mainFile:r,openTabs:i,content:a,loadedFile:o,readOnly:s,comments:c,focusComment:l,editorPreferences:u,completionIndex:d,nativeSpellCheck:f,spellCheckIssues:p,spellCheckJump:m,sourceJump:g,collaborativeText:_,collaborationAwareness:y,undoManager:b,editorNotice:x,activateTab:S,closeTab:C,handleTabKeyDown:w,updateEditorContent:T,setSelection:E,onAddComment:D,onSelectionHistory:O,onCommentClick:A,onSpellCheckReplace:j,onReferenceNavigate:M,onCursor:ee,terminal:N,mobileSync:P,figurePdf:te=null,agentChanges:F=null,activeAgentChangeId:ne=null,agentChangeReveal:I=null,onAgentChangesStale:re,onOpenAgentChange:ie}){let{t:ae}=v(),L=dp(c,n),R=fp(l,n,o);return(0,J.jsx)(xe,{id:`source`,minSize:`22%`,children:(0,J.jsx)(Dh,{terminal:N,tabs:u.openFilesInTabs&&i.length>0&&(0,J.jsx)(`div`,{className:`editor-tabs-bar`,role:`tablist`,"aria-label":ae(`editor.openFiles`),children:(0,J.jsx)(`div`,{className:`editor-tabs-scroll`,children:i.map((t,r)=>{let i=t===n,a=t===e.mainFile,o=t.split(`/`).at(-1)||t;return(0,J.jsxs)(`div`,{className:`editor-tab-item${i?` active`:``}`,role:`presentation`,children:[(0,J.jsxs)(`button`,{id:`editor-tab-${encodeURIComponent(t)}`,type:`button`,role:`tab`,"aria-selected":i,"aria-controls":`editor-source-content`,tabIndex:i?0:-1,className:`editor-tab${i?` active`:``}${a?` main-tab`:``}`,onClick:()=>S(t),onKeyDown:e=>w(e,r),title:t,children:[(0,J.jsx)(`span`,{className:`editor-tab-icon`,children:a?(0,J.jsx)(h,{size:13}):(0,J.jsx)(k,{size:13})}),(0,J.jsx)(`span`,{className:`editor-tab-title`,children:o}),a&&(0,J.jsx)(`small`,{className:`editor-tab-badge`,children:ae(`editor.currentMainShort`)})]}),(0,J.jsx)(`button`,{type:`button`,className:`editor-tab-close`,title:ae(`common.close`),"aria-label":`${ae(`common.close`)} ${o}`,onClick:()=>C(t),children:(0,J.jsx)(z,{size:12})})]},t)})})}),children:(0,J.jsxs)(`div`,{id:`editor-source-content`,className:`editor-content-container editor-content-column`,children:[te&&(0,J.jsx)(`div`,{className:`figure-pdf-bar`,children:(0,J.jsx)(Eh,{...te})}),(0,J.jsx)(`div`,{className:`editor-content-fill`,children:(0,J.jsx)(q.Suspense,{fallback:(0,J.jsxs)(`div`,{className:`preview-empty`,children:[(0,J.jsx)(Re,{className:`spin`,size:22}),(0,J.jsx)(`span`,{children:ae(`common.loading`)})]}),children:(0,J.jsx)(kh,{value:a,projectId:t,filePath:n,mainFile:r,readOnly:s,comments:L,focusComment:R,preferences:u,nativeSpellCheck:f,completionIndex:d,spellCheckIssues:p,spellCheckJump:m,jumpTo:o===n&&g?.path===n?g:null,searchRequest:0,collaboration:_?{text:_,awareness:y,undoManager:s?void 0:b}:void 0,onChange:T,onSelection:E,onAddComment:D,onSelectionHistory:O,onCommentClick:A,onSpellCheckReplace:j,onReferenceNavigate:M,onCursor:ee,agentChanges:F,activeAgentChangeId:ne,agentChangeReveal:I,onAgentChangesStale:re,onOpenAgentChange:ie},n)})}),x&&(0,J.jsx)(`div`,{className:`editor-centered-notice`,role:`status`,"aria-live":`polite`,children:x}),P&&(0,J.jsx)(Oh,{direction:`pdf`,...P})]})})})}var jh=4e3,Mh=2e3,Nh=3;function Ph(e,t){return b(`texlite-agent-review:${encodeURIComponent(e)}:${encodeURIComponent(t)}`)}function Fh(e){let t=et(e);return new Set(Array.isArray(t)?t.filter(e=>typeof e==`string`):[])}function Ih(e,t){nt(e,[...t])}function Lh(e,t,n){let r=Ph(e,t),[i,a]=(0,q.useState)([]),[o,s]=(0,q.useState)(()=>Fh(r)),[c,l]=(0,q.useState)(!1),[u,d]=(0,q.useState)(``),f=(0,q.useRef)(null),p=(0,q.useRef)(void 0),m=(0,q.useRef)(0),h=(0,q.useCallback)(e=>{e||(m.current=0),f.current?.abort();let n=new AbortController;f.current=n,l(!0),G(`/api/projects/${encodeURIComponent(t)}/agent-changes`,{signal:n.signal}).then(e=>{if(n.signal.aborted)return;a(e.files),d(``);let t=new Set(e.files.flatMap(e=>e.changes.flatMap(e=>e.ids)));s(e=>{let n=new Set([...e].filter(e=>t.has(e)));return n.size!==e.size&&Ih(r,n),n})}).catch(e=>{n.signal.aborted||d(K(e))}).finally(()=>{f.current===n&&l(!1)})},[t,r]),g=(0,q.useCallback)(()=>h(!1),[h]),_=(0,q.useCallback)(()=>{p.current!==void 0||m.current>=Nh||(m.current+=1,p.current=window.setTimeout(()=>{p.current=void 0,h(!0)},Mh))},[h]);(0,q.useEffect)(()=>{s(Fh(r)),a([]),g();let e=()=>g();return window.addEventListener(`texlite:agent-tasks`,e),()=>{window.removeEventListener(`texlite:agent-tasks`,e),f.current?.abort(),window.clearTimeout(p.current),p.current=void 0}},[r,g]),(0,q.useEffect)(()=>{if(!n)return;let e=window.setInterval(()=>{document.visibilityState!==`hidden`&&g()},jh);return()=>window.clearInterval(e)},[n,g]);let v=(0,q.useCallback)(e=>e.ids.some(e=>!o.has(e)),[o]),y=(0,q.useMemo)(()=>i.flatMap(e=>e.changes.filter(v).map(t=>({...t,path:e.path,sourceHash:e.sourceHash}))),[i,v]),b=(0,q.useCallback)(e=>{let t=i.find(t=>t.path===e);return t?{sourceHash:t.sourceHash,changes:t.changes.filter(v)}:null},[i,v]),x=(0,q.useCallback)(e=>s(t=>{let n=new Set(t);for(let t of e)n.add(t);return Ih(r,n),n}),[r]);return{pending:y,forFile:b,loading:c,error:u,refresh:g,refreshSoon:_,markReviewed:(0,q.useCallback)(e=>x(e.ids),[x]),markAllReviewed:(0,q.useCallback)(()=>x(i.flatMap(e=>e.changes.flatMap(e=>e.ids))),[x,i])}}var Rh=t(r(),1);function zh({children:e,showControls:t=!0}){let[n,r]=(0,q.useState)(null),[i,a]=(0,q.useState)(null);return(0,q.useLayoutEffect)(()=>{if(!n||!t)return;let e=()=>{let e=n.getBoundingClientRect(),t=e.left+e.width/2,r=e.top+e.height/2;a(e=>e?.left===t&&e.top===r?e:{left:t,top:r})},r=new ResizeObserver(e);r.observe(n);let i=n.parentElement;if(i){r.observe(i);for(let e of i.children)e.hasAttribute(`data-panel`)&&r.observe(e)}return window.addEventListener(`resize`,e),window.addEventListener(`scroll`,e,!0),e(),()=>{r.disconnect(),window.removeEventListener(`resize`,e),window.removeEventListener(`scroll`,e,!0)}},[n,t]),(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(Oe,{className:`resize-handle sync-resize-handle`,elementRef:r,children:(0,J.jsx)(me,{className:`resize-grip`,size:12})}),t&&i&&(0,Rh.createPortal)((0,J.jsx)(`span`,{className:`sync-direction-buttons`,style:{position:`fixed`,...i},children:e}),document.body)]})}var Bh=360,Vh=280,Hh=640,Uh=()=>b(`texlite-comments-width`);function Wh(){let e=Number(qe(Uh()));return Number.isFinite(e)&&e>=Vh&&e<=Hh?e:Bh}var Gh=(e,{min:t,max:n})=>Math.min(n,Math.max(t,Math.round(e)));function Kh({open:e,onHost:t}){let{t:n}=v(),r=(0,q.useId)(),i=(0,q.useRef)(null),a=(0,q.useRef)(null),o=(0,q.useRef)(null),[s,c]=(0,q.useState)(Wh),l=(0,q.useRef)(s),[u,d]=(0,q.useState)(!1),[f,p]=(0,q.useState)({now:s,min:Vh,max:Hh}),m=(0,q.useCallback)(e=>{i.current=e,t?.(e)},[t]),h=()=>{let e=i.current,t=Number.parseFloat(getComputedStyle(e).getPropertyValue(`--comments-preview-reserve`))||0,n=Math.max(0,Math.min(Hh,Math.floor(e.parentElement.getBoundingClientRect().width-t)));return{min:Math.min(Vh,n),max:n}},g=e=>{l.current=e,c(e)},_=e=>{$e(Uh(),String(Math.max(Vh,e)))};(0,q.useEffect)(()=>{if(!e){d(!1);return}let t=i.current,n=a.current,r=()=>{let e={now:Math.round(t.getBoundingClientRect().width),...h()};p(t=>t.now===e.now&&t.min===e.min&&t.max===e.max?t:e)};r();let s=new ResizeObserver(r);return s.observe(t),s.observe(t.parentElement),()=>{s.disconnect();let e=o.current;o.current=null,e&&n.hasPointerCapture(e.pointerId)&&n.releasePointerCapture(e.pointerId)}},[e]);let y=e=>{e.button!==0||o.current||(e.preventDefault(),e.stopPropagation(),o.current={pointerId:e.pointerId,x:e.clientX,width:i.current.getBoundingClientRect().width,preferred:l.current},e.currentTarget.setPointerCapture(e.pointerId),d(!0))},b=e=>{let t=o.current;t&&t.pointerId===e.pointerId&&(e.preventDefault(),e.stopPropagation(),g(Gh(t.width+e.clientX-t.x,h())))},x=(e,t=!1)=>{let n=o.current;n&&n.pointerId===e.pointerId&&(o.current=null,t?g(n.preferred):l.current!==n.preferred&&_(l.current),d(!1),e.currentTarget.hasPointerCapture(e.pointerId)&&e.currentTarget.releasePointerCapture(e.pointerId))};return(0,J.jsx)(`div`,{ref:m,id:r,className:`workspace-comments-slot`,hidden:!e,"data-resizing":u||void 0,style:{"--workspace-comments-width":`${s}px`},children:e&&(0,J.jsx)(`div`,{ref:a,className:`comments-resize-handle`,role:`separator`,tabIndex:0,"aria-orientation":`vertical`,"aria-label":n(`editor.resizeComments`),"aria-controls":r,"aria-valuemin":f.min,"aria-valuemax":f.max,"aria-valuenow":f.now,"aria-valuetext":`${f.now} px`,onPointerDown:y,onPointerMove:b,onPointerUp:x,onPointerCancel:e=>x(e,!0),onLostPointerCapture:e=>x(e,!0),onKeyDown:e=>{let t=h(),n=i.current.getBoundingClientRect().width,r=e.shiftKey?48:16,a=e.key===`ArrowLeft`?n-r:e.key===`ArrowRight`?n+r:e.key===`Home`?t.min:e.key===`End`?t.max:null;if(a===null)return;e.preventDefault(),e.stopPropagation();let o=Gh(a,t);g(o),_(o)},onDoubleClick:e=>{e.preventDefault(),e.stopPropagation(),g(Bh),_(Bh)}})})}function qh({diagnostics:e,files:t,empty:n,tone:r,onJump:i}){let{t:a}=v(),o=r===`error`?Dt:ce;return e.length?(0,J.jsx)(`div`,{className:`compile-diagnostic-list compile-${r}`,children:e.map((e,n)=>{let r=Zh(e.file,t),s=!!(r&&e.line);return(0,J.jsxs)(`button`,{type:`button`,disabled:!s,className:`compile-diagnostic-row`,onClick:()=>{r&&e.line&&i(r,e.line,e.column??1)},children:[(0,J.jsx)(o,{size:15}),(0,J.jsxs)(`span`,{children:[(0,J.jsx)(`strong`,{children:e.message}),(0,J.jsxs)(`small`,{children:[e.phase,r?` · ${r}${e.line?`:${e.line}`:``}`:e.line?` · ${a(`editor.lineNumber`,{line:e.line})}`:``]})]})]},`${e.phase}-${e.file??``}-${e.line??0}-${n}`)})}):(0,J.jsxs)(`div`,{className:`compile-empty compile-${r}`,children:[(0,J.jsx)(o,{size:26}),(0,J.jsx)(`span`,{children:n})]})}function Jh({lines:e,empty:t,tone:n=`log`}){let r=n===`error`?Dt:n===`warning`?ce:E;return e.length?(0,J.jsx)(`pre`,{className:`compile-output compile-${n}`,children:e.join(`
|
|
11
|
+
`)}):(0,J.jsxs)(`div`,{className:`compile-empty compile-${n}`,children:[(0,J.jsx)(r,{size:26}),(0,J.jsx)(`span`,{children:t})]})}function Yh({projectId:e,mainFile:t,artifacts:n,preview:r,loading:i,onView:a}){let{t:o}=v(),s=n=>x(`/api/projects/${e}/compile/artifacts?mainFile=${encodeURIComponent(t)}&path=${encodeURIComponent(n)}&download=1`);return n.length?(0,J.jsxs)(`div`,{className:`artifact-browser`,children:[(0,J.jsx)(`div`,{className:`artifact-list`,children:n.map(e=>(0,J.jsxs)(`div`,{className:`artifact-row${r?.path===e.path?` active`:``}`,children:[(0,J.jsxs)(`button`,{type:`button`,disabled:!e.viewable,title:e.viewable?o(`editor.viewArtifact`):o(`editor.downloadToView`),onClick:()=>a(e),children:[(0,J.jsx)(Se,{path:e.path,size:14}),(0,J.jsxs)(`span`,{children:[(0,J.jsx)(`strong`,{children:e.path}),(0,J.jsx)(`small`,{children:oe(e.size,{maximumUnit:`MB`})})]})]}),(0,J.jsx)(`a`,{href:s(e.path),title:o(`editor.downloadArtifact`),"aria-label":o(`editor.downloadArtifact`),children:(0,J.jsx)(T,{size:14})})]},e.path))}),(0,J.jsx)(`div`,{className:`artifact-preview`,children:i?(0,J.jsxs)(`div`,{className:`compile-empty`,children:[(0,J.jsx)(Re,{className:`spin`,size:24}),(0,J.jsx)(`span`,{children:o(`common.loading`)})]}):r?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`header`,{children:[(0,J.jsx)(`strong`,{children:r.path}),(0,J.jsxs)(`a`,{href:s(r.path),children:[(0,J.jsx)(T,{size:13}),o(`projects.download`)]})]}),(0,J.jsx)(`pre`,{children:r.content})]}):(0,J.jsxs)(`div`,{className:`compile-empty`,children:[(0,J.jsx)(k,{size:24}),(0,J.jsx)(`span`,{children:o(`editor.selectArtifact`)})]})})]}):(0,J.jsxs)(`div`,{className:`compile-empty`,children:[(0,J.jsx)(Vt,{size:26}),(0,J.jsx)(`span`,{children:o(`editor.noArtifacts`)})]})}function Xh({mainFile:e,disabled:t,cleaning:n,onCleanCache:r,onCleanArtifacts:i}){let{t:a}=v();return(0,J.jsxs)(`div`,{className:`compile-clean-panel`,children:[(0,J.jsxs)(`div`,{className:`compile-clean-intro`,children:[(0,J.jsx)(ce,{size:28}),(0,J.jsxs)(`div`,{children:[(0,J.jsx)(`strong`,{children:a(`editor.cleanTitle`)}),(0,J.jsx)(`p`,{children:a(`editor.cleanDescription`,{file:e})})]})]}),(0,J.jsxs)(`div`,{className:`compile-clean-actions`,children:[(0,J.jsxs)(`article`,{children:[(0,J.jsx)(`div`,{className:`compile-clean-action-icon`,children:(0,J.jsx)(kt,{size:19})}),(0,J.jsxs)(`div`,{children:[(0,J.jsxs)(`div`,{className:`compile-clean-action-heading`,children:[(0,J.jsx)(`strong`,{children:a(`editor.cleanCache`)}),(0,J.jsx)(Le,{className:`compile-clean-help`,content:a(`editor.cleanCacheDescription`),icon:Tt,size:13})]}),(0,J.jsxs)(`button`,{type:`button`,className:`compile-clean-operation`,disabled:t||n,onClick:r,children:[n?(0,J.jsx)(Re,{className:`spin`,size:14}):(0,J.jsx)(kt,{size:14}),a(`editor.cleanCache`)]})]})]}),(0,J.jsxs)(`article`,{className:`danger`,children:[(0,J.jsx)(`div`,{className:`compile-clean-action-icon`,children:(0,J.jsx)(M,{size:19})}),(0,J.jsxs)(`div`,{children:[(0,J.jsxs)(`div`,{className:`compile-clean-action-heading`,children:[(0,J.jsx)(`strong`,{children:a(`editor.cleanArtifacts`)}),(0,J.jsx)(Le,{className:`compile-clean-help`,content:a(`editor.cleanArtifactsDescription`),icon:Tt,size:13})]}),(0,J.jsxs)(`button`,{type:`button`,className:`compile-clean-operation danger`,disabled:t||n,onClick:i,children:[n?(0,J.jsx)(Re,{className:`spin`,size:14}):(0,J.jsx)(M,{size:14}),a(`editor.cleanArtifacts`)]})]})]})]})]})}function Zh(e,t){if(!e)return null;let n=t.filter(e=>e.type===`file`).map(e=>e.path),r=e.replaceAll(`\\`,`/`).replace(/^\.\//,``);if(n.includes(r))return r;let i=n.filter(e=>r.endsWith(`/${e}`));if(i.length===1)return i[0];let a=r.split(`/`).at(-1),o=n.filter(e=>e.split(`/`).at(-1)===a);return o.length===1?o[0]:null}var Qh=(0,q.lazy)(()=>Ke().then(e=>({default:e.PdfPreview}))),$h=(0,q.lazy)(()=>S(()=>import(`./MarkdownPreview-BJPqGTcw.js`),__vite__mapDeps([26,2,3,4,5,16,7,9,17,12,1,6,8,10,11,13,27,28,29,30]),import.meta.url));function eg({commentsOpen:e=!1,onCommentsHost:t,mobileSync:n=!1,projectId:r,activeMainFile:i,previewTab:a,diagnosticTab:o,pdfUrl:s,pdfLoadingMode:c,pdfLoading:l,pdfCompiledAt:u,pdfSizeBytes:d,pdfCompiledLabel:f,pdfTargetLabel:p,pdfDownloadUrl:m,pdfTarget:h,pdfViewport:g,activeFile:_,compileBusy:y,compileLog:b,compileDiagnostics:x,compileMessages:S,artifacts:C,artifactPreview:w,artifactLoading:T,cleaning:E,readOnly:D,collaborationSynced:O,workspaceLayout:k,showSyncResize:A,diagnosticCount:j,selectPreviewTab:M,changeWorkspaceLayout:ee,onSetPdfViewport:N,onResetPdfViewport:P,onPdfDisplayed:te,syncVisiblePdfToSource:F,syncCurrentSourceToPdf:ne,syncPdfToSource:I,canSyncWithPdf:re,canSyncPdfToSource:ie,files:ae,jumpToSource:L,onSetCleanMode:R,viewArtifact:oe,markdown:se=null}){let{t:z}=v(),[le,B]=(0,q.useState)(``),V=(0,q.useRef)(``),H=e=>{V.current!==e&&(V.current=e,B(e),P(),te(e))},ue=ie&&!!s&&le===s,de=(0,q.useRef)(null),fe=a===`markdown`?se:null,pe=()=>{let e=de.current?.visibleLine();return e&&se&&se.onShowLine(e),Promise.resolve()};return(0,J.jsxs)(J.Fragment,{children:[A&&(0,J.jsx)(zh,{showControls:!e,children:fe?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`button`,{disabled:fe.source===null,title:z(`editor.markdown.showInSource`),"aria-label":z(`editor.markdown.showInSource`),onClick:e=>{e.stopPropagation(),pe()},children:(0,J.jsx)(`span`,{"aria-hidden":!0,children:`←`})}),(0,J.jsx)(`button`,{disabled:fe.source===null,title:z(`editor.markdown.showInPreview`),"aria-label":z(`editor.markdown.showInPreview`),onClick:e=>{e.stopPropagation(),fe.onShowCursor()},children:(0,J.jsx)(`span`,{"aria-hidden":!0,children:`→`})})]}):(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`button`,{disabled:!s||!g||!ue,title:z(ie?ue?`editor.showInSource`:`editor.syncTexWaitingForPdf`:`editor.syncTexOnlyForMain`),"aria-label":z(`editor.showInSource`),onClick:e=>{e.stopPropagation(),ue&&F()},children:(0,J.jsx)(`span`,{"aria-hidden":!0,children:`←`})}),(0,J.jsx)(`button`,{disabled:!_||!s||!re,title:z(re?`editor.showInPdf`:`editor.syncTexOnlyForTex`),"aria-label":z(`editor.showInPdf`),onClick:e=>{e.stopPropagation(),_&&s&&re&&ne()},children:(0,J.jsx)(`span`,{"aria-hidden":!0,children:`→`})})]})}),(0,J.jsx)(xe,{id:`preview`,minSize:`22%`,children:(0,J.jsx)(`div`,{className:`workspace-preview-region`,children:(0,J.jsxs)(`div`,{className:`workspace-output-layout${e?` has-comments`:``}`,children:[n&&!e&&a===`pdf`&&(0,J.jsx)(Oh,{direction:`source`,disabled:!g||!ue,onClick:F}),n&&!e&&fe&&(0,J.jsx)(Oh,{direction:`source`,label:z(`editor.markdown.showInSource`),disabled:fe.source===null,onClick:pe}),(0,J.jsx)(Kh,{open:e,onHost:t}),(0,J.jsxs)(`section`,{className:`preview-panel`,children:[(0,J.jsx)(Ee,{mainFile:i,targetLabel:p,compiledAt:u,compiledLabel:f,sizeBytes:d,downloadUrl:m,activeSurface:a,onSelect:M,diagnosticCount:j,markdownFile:se?.path}),a===`diagnostics`&&(0,J.jsxs)(`div`,{className:`preview-subtabs`,role:`tablist`,"aria-label":z(`editor.outputTabs`),children:[(0,J.jsxs)(`button`,{role:`tab`,"aria-selected":o===`log`,className:o===`log`?`active`:``,onClick:()=>M(`log`),children:[(0,J.jsx)(Lt,{size:13}),z(`editor.log`)]}),(0,J.jsxs)(`button`,{role:`tab`,"aria-selected":o===`warnings`,className:o===`warnings`?`active`:``,onClick:()=>M(`warnings`),children:[(0,J.jsx)(ce,{size:13}),z(`editor.warnings`),(0,J.jsx)(`span`,{children:S.warnings.length})]}),(0,J.jsxs)(`button`,{role:`tab`,"aria-selected":o===`errors`,className:o===`errors`?`active`:``,onClick:()=>M(`errors`),children:[(0,J.jsx)(Dt,{size:13}),z(`editor.errors`),(0,J.jsx)(`span`,{children:S.errors.length})]}),(0,J.jsxs)(`button`,{role:`tab`,"aria-selected":o===`artifacts`,className:o===`artifacts`?`active`:``,onClick:()=>M(`artifacts`),children:[(0,J.jsx)(Vt,{size:13}),z(`editor.artifacts`),(0,J.jsx)(`span`,{children:C.length})]}),(0,J.jsxs)(`button`,{role:`tab`,"aria-selected":o===`clean`,className:o===`clean`?`active`:``,onClick:()=>M(`clean`),children:[(0,J.jsx)(kt,{size:13}),z(`editor.clean`)]})]}),(0,J.jsxs)(`div`,{className:`preview-content preview-${a} ${a===`diagnostics`?`preview-${o}`:``}`,children:[a===`pdf`&&(s?(0,J.jsx)(q.Suspense,{fallback:(0,J.jsxs)(`div`,{className:`pdf-loading-state`,role:`status`,"aria-live":`polite`,children:[(0,J.jsx)(Re,{className:`spin`,size:24}),(0,J.jsx)(`span`,{children:z(`editor.loadingPdf`)})]}),children:(0,J.jsx)(Qh,{url:s,loadingMode:c,target:h,compiling:y,onDisplayedUrlChange:H,onViewportLocation:(e,t,n)=>{V.current===s&&N({page:e,x:t,y:n})},onDoubleClickLocation:(e,t,n)=>{V.current===s&&ue&&(N({page:e,x:t,y:n}),I(e,t,n))}})}):l?(0,J.jsxs)(`div`,{className:`pdf-loading-state`,role:`status`,"aria-live":`polite`,children:[(0,J.jsx)(Re,{className:`spin`,size:24}),(0,J.jsx)(`span`,{children:z(`editor.loadingPdf`)})]}):(0,J.jsxs)(`div`,{className:`preview-empty preview-empty-uncompiled`,role:`status`,"aria-live":`polite`,children:[(0,J.jsx)(`span`,{className:`preview-empty-icon`,"aria-hidden":`true`,children:y?(0,J.jsx)(Re,{className:`spin`,size:26}):(0,J.jsx)(_e,{size:32})}),(0,J.jsx)(`strong`,{children:z(y?`editor.compiling`:`editor.previewEmptyTitle`)}),(0,J.jsx)(`p`,{children:z(y?`editor.previewCompilingHint`:`editor.previewHint`)})]})),fe&&(fe.source===null?(0,J.jsxs)(`div`,{className:`preview-empty markdown-preview-empty`,role:`status`,children:[(0,J.jsx)(Re,{className:`spin`,size:22}),(0,J.jsx)(`span`,{children:z(`common.loading`)})]}):(0,J.jsx)(q.Suspense,{fallback:(0,J.jsxs)(`div`,{className:`preview-empty markdown-preview-empty`,role:`status`,children:[(0,J.jsx)(Re,{className:`spin`,size:22}),(0,J.jsx)(`span`,{children:z(`common.loading`)})]}),children:(0,J.jsx)($h,{ref:de,projectId:r,path:fe.path,source:fe.source,reveal:fe.reveal,onOpenPath:fe.onOpenPath,onJumpToLine:fe.onShowLine},fe.path)})),a===`diagnostics`&&o===`log`&&(0,J.jsx)(Jh,{lines:b?b.split(`
|
|
12
|
+
`):[],empty:z(y?`editor.compiling`:`editor.noLog`)}),a===`diagnostics`&&o===`warnings`&&(x?(0,J.jsx)(qh,{tone:`warning`,diagnostics:x.warnings,files:ae,empty:z(`editor.noWarnings`),onJump:(e,t,n)=>{k===`pdf-only`&&ee(`editor-pdf`),L(e,t,n)}}):(0,J.jsx)(Jh,{tone:`warning`,lines:S.warnings,empty:z(`editor.noWarnings`)})),a===`diagnostics`&&o===`errors`&&(x?(0,J.jsx)(qh,{tone:`error`,diagnostics:x.errors,files:ae,empty:z(`editor.noErrors`),onJump:(e,t,n)=>{k===`pdf-only`&&ee(`editor-pdf`),L(e,t,n)}}):(0,J.jsx)(Jh,{tone:`error`,lines:S.errors,empty:z(`editor.noErrors`)})),a===`diagnostics`&&o===`artifacts`&&(0,J.jsx)(Yh,{projectId:r,mainFile:i,artifacts:C,preview:w,loading:T,onView:e=>void oe(e)}),a===`diagnostics`&&o===`clean`&&(0,J.jsx)(Xh,{mainFile:i,disabled:D||!O||y,cleaning:E,onCleanCache:()=>R(`cache`),onCleanArtifacts:()=>R(`artifacts`)})]})]})]})})})]})}function tg({kind:e,onEdit:t,onDelete:n,onSuggest:r,disabled:i=!1}){let{t:a}=v(),o=(0,q.useRef)(!1);return(0,J.jsx)(`span`,{className:`comment-actions-menu`,onClick:e=>e.stopPropagation(),children:(0,J.jsxs)(ut,{modal:!1,children:[(0,J.jsx)(at,{asChild:!0,children:(0,J.jsx)(`button`,{type:`button`,disabled:i,className:`comment-actions-menu-trigger`,"aria-label":a(e===`comment`?`editor.commentActions`:`editor.replyActions`),children:(0,J.jsx)(B,{size:16,"aria-hidden":!0})})}),(0,J.jsx)(rt,{children:(0,J.jsxs)(ot,{className:`comment-actions-menu-content`,align:`end`,sideOffset:4,collisionPadding:8,onCloseAutoFocus:e=>{o.current&&e.preventDefault(),o.current=!1},children:[(0,J.jsxs)(ct,{onSelect:()=>{o.current=!0,t()},children:[(0,J.jsx)(u,{size:13,"aria-hidden":!0}),a(e===`comment`?`editor.editComment`:`editor.editReply`)]}),e===`comment`&&r&&(0,J.jsxs)(ct,{onSelect:()=>{o.current=!0,r()},children:[(0,J.jsx)(c,{size:13,"aria-hidden":!0}),a(`suggestions.attach`)]}),(0,J.jsxs)(ct,{className:`danger-text`,onSelect:()=>{o.current=!0,n()},children:[(0,J.jsx)(M,{size:13,"aria-hidden":!0}),a(e===`comment`?`editor.deleteComment`:`editor.deleteReply`)]})]})})]})})}function ng(e,t){let n=e.slice(0,t),r=/(^|[^\p{L}\p{N}_.-])@([\p{L}\p{N}_.-]*)$/u.exec(n);return r?{start:t-r[2].length-1,end:t,query:r[2]}:null}function rg({projectId:e,value:t,onChange:n,onKeyDown:r,onFocus:i,...a}){let{t:s}=v(),c=(0,q.useRef)(null),[l,u]=(0,q.useState)(null),d=zf({queryKey:Vf.candidates(e),enabled:!!l,queryFn:({signal:t})=>G(`/api/projects/${e}/mention-candidates`,{signal:t})}),f=Wf(d.error)?void 0:d.data?.users,[p,m]=(0,q.useState)(0),h=(0,q.useMemo)(()=>{if(!l||!f)return[];let e=l.query.toLocaleLowerCase();return(e?f.filter(t=>t.username.toLocaleLowerCase().includes(e)||t.displayName.toLocaleLowerCase().includes(e)):f).slice(0,8)},[f,l]),g=!!(l&&h.length),_=(e,t)=>{let n=ng(e,t);u(n),m(0),n&&!d.isFetching&&(d.isError||d.isStale)&&d.refetch()},y=e=>{if(!l)return;let r=`@${e.username} `,i=`${t.slice(0,l.start)}${r}${t.slice(l.end)}`,a=l.start+r.length;n(i),u(null),m(0),window.requestAnimationFrame(()=>{c.current?.focus(),c.current?.setSelectionRange(a,a)})},b=e=>{if(!e.nativeEvent.isComposing&&g){if(e.key===`ArrowDown`){e.preventDefault(),m(e=>(e+1)%h.length);return}if(e.key===`ArrowUp`){e.preventDefault(),m(e=>(e-1+h.length)%h.length);return}if(e.key===`Enter`&&!e.ctrlKey&&!e.metaKey&&!e.shiftKey){e.preventDefault(),y(h[p]??h[0]);return}if(e.key===`Escape`){u(null);return}}r?.(e)};return(0,J.jsxs)(`span`,{className:`mention-textarea`,children:[(0,J.jsx)(`textarea`,{...a,ref:c,value:t,onFocus:e=>{i?.(e),_(t,e.currentTarget.selectionStart??t.length)},onClick:e=>_(t,e.currentTarget.selectionStart??t.length),onChange:e=>{let t=e.currentTarget.value;n(t),_(t,e.currentTarget.selectionStart??t.length)},onKeyDown:b}),g&&(0,J.jsx)(`span`,{className:`mention-menu`,role:`listbox`,"aria-label":s(`editor.mentionUsers`),children:h.map((e,t)=>(0,J.jsxs)(`button`,{type:`button`,role:`option`,"aria-selected":t===p,className:t===p?`active`:``,onMouseDown:e=>e.preventDefault(),onClick:()=>y(e),children:[(0,J.jsx)(o,{"aria-hidden":!0,size:13}),(0,J.jsxs)(`span`,{children:[(0,J.jsx)(`strong`,{children:e.displayName}),(0,J.jsxs)(`small`,{children:[`(`,e.username,`)`]})]})]},e.id))})]})}function ig({projectId:e,value:t,onChange:n,onSubmit:r,onCancel:i,pending:a=!1,error:o=``,label:s,editing:c=!1,originalValue:l,disabled:u=!1,autoFocus:d=!0}){let{t:f}=v(),p=(0,q.useId)(),m=a||u,h=!!t.trim()&&(!c||l===void 0||t.trim()!==l.trim()),g=e=>{e?.preventDefault(),!m&&h&&r()};return(0,J.jsxs)(`form`,{className:`comment-reply-form${c?` comment-edit-form`:``}`,"aria-busy":a,onSubmit:e=>void g(e),onClick:e=>e.stopPropagation(),children:[(0,J.jsx)(rg,{projectId:e,autoFocus:d,rows:c?4:3,value:t,onChange:n,disabled:m,"aria-label":s,"aria-invalid":!!o,"aria-describedby":o?p:void 0,placeholder:c?void 0:f(`editor.replyPlaceholder`),onKeyDown:e=>{(e.ctrlKey||e.metaKey)&&e.key===`Enter`&&!e.nativeEvent.isComposing&&(e.preventDefault(),e.stopPropagation(),g())}}),o&&(0,J.jsx)(`p`,{id:p,className:`comment-form-error`,role:`alert`,children:o}),(0,J.jsxs)(`div`,{className:`comment-form-actions`,children:[(0,J.jsx)(`button`,{type:`button`,disabled:m,onClick:i,children:f(`common.cancel`)}),c?(0,J.jsx)(Ve,{type:`submit`,saving:a,disabled:u||!h,iconSize:13,children:f(`common.save`)}):(0,J.jsxs)(`button`,{className:`primary`,type:`submit`,disabled:m||!h,children:[a?(0,J.jsx)(Re,{className:`spin`,"aria-hidden":!0,size:13}):(0,J.jsx)(Gt,{"aria-hidden":!0,size:13}),f(a?`editor.commentSending`:`editor.sendReply`)]})]})]})}var ag=5e4,og=new Intl.Segmenter(void 0,{granularity:`word`}),sg=55296,cg=2048,lg=63487;function ug(e,t){if(e===t)return e?[[0,e]]:[];let n=[``],r=new Map,i=e=>{let t=[];for(let{segment:i}of og.segment(e)){let e=r.get(i);if(e===void 0){let t=n.length;if(t>lg)return null;e=String.fromCharCode(t<sg?t:t+cg),n.push(i),r.set(i,e)}t.push(e)}return t.join(``)},a=i(e),o=i(t);return a===null||o===null?[[-1,e],[1,t]].filter(([,e])=>e!==``):yt(a,o,{checkLines:!1,timeout:1}).map(([e,t])=>[e,Array.from(t,e=>{let t=e.charCodeAt(0);return n[t<sg?t:t-cg]}).join(``)])}function dg({original:e,replacement:t}){let{t:n}=v(),[r,i]=(0,q.useState)(!1),a=(0,q.useMemo)(()=>ug(e,t),[e,t]),o=!r&&a.some(([e,t])=>e===0&&t.length>192);return(0,J.jsxs)(`div`,{className:`suggestion-diff-view`,children:[(0,J.jsx)(`pre`,{className:`suggestion-diff`,"aria-label":n(`suggestions.diff`),children:a.map(([e,t],n)=>e<0?(0,J.jsx)(`del`,{children:t},n):e>0?(0,J.jsx)(`ins`,{children:t},n):(0,J.jsx)(`span`,{children:r||t.length<=192?t:n===0?`…${t.slice(-96)}`:n===a.length-1?`${t.slice(0,96)}…`:`${t.slice(0,48)}…${t.slice(-48)}`},n))}),(o||r)&&(0,J.jsx)(`button`,{type:`button`,className:`suggestion-text-action`,onClick:()=>i(!r),children:n(r?`suggestions.collapse`:`suggestions.showFull`)})]})}function fg({projectId:e,authorId:t,commentId:n,value:r,onChange:i,disabled:a=!1}){let{t:o}=v(),[s,c]=(0,q.useState)([]),[l,u]=(0,q.useState)(``),[d,f]=(0,q.useState)(!1),[p,m]=(0,q.useState)(0);return(0,q.useEffect)(()=>{let r=new AbortController;u(``),c([]),f(!1);let i=n?`?${new URLSearchParams({commentId:n})}`:``;return G(`/api/projects/${e}/suggestion-reviewers${i}`,{signal:r.signal}).then(e=>{r.signal.aborted||(c(e.users.filter(e=>e.id!==t)),f(!0))}).catch(e=>{r.signal.aborted||u(K(e))}),()=>r.abort()},[e,t,n,p]),(0,J.jsxs)(`div`,{className:`suggestion-reviewer-picker`,children:[(0,J.jsxs)(`label`,{className:`form-field`,children:[o(`suggestions.reviewer`),(0,J.jsxs)(`select`,{value:r===t?``:r,disabled:a||s.length===0,onChange:e=>i(e.target.value),children:[(0,J.jsx)(`option`,{value:``,children:o(`suggestions.chooseReviewer`)}),s.map(e=>(0,J.jsxs)(`option`,{value:e.id,children:[e.displayName,` (@`,e.username,`)`]},e.id))]})]}),d&&s.length===0&&(0,J.jsx)(`p`,{className:`field-hint`,children:o(`suggestions.noReviewers`)}),l&&(0,J.jsxs)(`p`,{className:`comment-form-error`,role:`alert`,children:[l,` `,(0,J.jsx)(`button`,{type:`button`,disabled:a,onClick:()=>m(e=>e+1),children:o(`common.retry`)})]})]})}function pg({projectId:e,authorId:t,commentId:n,original:r,value:i,onChange:a,disabled:o=!1,autoFocus:s=!1}){let{t:l}=v();return(0,J.jsxs)(`section`,{className:`suggestion-editor`,"aria-label":l(`suggestions.title`),children:[(0,J.jsxs)(`header`,{children:[(0,J.jsxs)(`strong`,{children:[(0,J.jsx)(c,{size:14}),l(`suggestions.title`)]}),(0,J.jsx)(`button`,{type:`button`,disabled:o,"aria-label":l(`suggestions.removeAttachment`),onClick:()=>a(null),children:(0,J.jsx)(z,{size:14})})]}),(0,J.jsx)(mg,{original:r,replacement:i.replacementText,onChange:e=>a({...i,replacementText:e}),disabled:o,autoFocus:s}),(0,J.jsx)(fg,{projectId:e,authorId:t,commentId:n,value:i.reviewerId,disabled:o,onChange:e=>a({...i,reviewerId:e})})]})}function mg({original:e,replacement:t,onChange:n,disabled:r=!1,autoFocus:i=!1}){let{t:a}=v();return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`label`,{className:`form-field`,children:[a(`suggestions.replacement`),(0,J.jsx)(`textarea`,{autoFocus:i,rows:4,maxLength:ag,spellCheck:!1,disabled:r,value:t,onChange:e=>n(e.target.value)})]}),t===``&&(0,J.jsx)(`p`,{className:`field-hint`,children:a(`suggestions.deletionHint`)}),t!==e&&(0,J.jsxs)(`details`,{className:`suggestion-preview`,children:[(0,J.jsx)(`summary`,{children:a(`suggestions.preview`)}),(0,J.jsx)(dg,{original:e,replacement:t})]})]})}function hg(e,t){return!e.suggestion&&e.authorId===t&&!e.resolved&&!e.orphaned&&!!e.anchorSourceHash&&e.selectedText.length>0&&e.selectedText.length<=5e4}function gg({projectId:e,ownerId:t,currentUserId:n,canEdit:r,comment:i,draftTarget:a,onCloseComposer:o}){let{t:s,i18n:c}=v(),l=$f(e),[d,f]=(0,q.useState)(!1),[p,m]=(0,q.useState)(()=>a?{replacementText:a.original,reviewerId:t===n?``:t}:null),[h,_]=(0,q.useState)(null),[y,b]=(0,q.useState)(null),[x,S]=(0,q.useState)(!1),C=(0,q.useRef)(!1),[w,T]=(0,q.useState)(``),E=i.suggestion,D=async(e,t,n)=>{if(!C.current){C.current=!0,S(!0),T(``);try{let r=await l(`/${i.id}/suggestion${e}`,{method:t,body:JSON.stringify(n)});m(null),_(null),t===`PATCH`&&r.change.kind===`suggestion`&&b(r.change.suggestion.replacementText),t===`POST`&&e===``&&o?.()}catch(e){T(K(e))}finally{C.current=!1,S(!1)}}};if(!E)return!a||!p||i.authorId!==n||i.resolved?null:(0,J.jsxs)(`div`,{className:`suggestion-new`,onClick:e=>e.stopPropagation(),children:[(0,J.jsx)(pg,{projectId:e,authorId:n,commentId:i.id,original:a.original,value:p,disabled:x,autoFocus:!0,onChange:e=>{m(e),e||o?.()}}),w&&(0,J.jsx)(`p`,{className:`comment-form-error`,role:`alert`,children:w}),(0,J.jsxs)(`button`,{type:`button`,className:`suggestion-submit`,disabled:x||!p.reviewerId||p.reviewerId===i.authorId||p.replacementText===a.original,onClick:()=>void D(``,`POST`,{...p,sourceHash:a.sourceHash}),children:[x&&(0,J.jsx)(Re,{size:13,className:`spin`}),s(p.replacementText===``?`suggestions.submitDeletion`:`suggestions.submit`)]})]});let k=E.status===`pending`,A=E.reviewerDisplayName??E.reviewerUsername??s(`editor.deletedUser`),j=E.reviewerId!==null&&E.reviewerId===i.authorId,M=r&&!j&&E.reviewerId===n&&E.reviewerAvailable,ee=k&&!E.applying&&i.authorId===n,N=!!(h&&h.expectedReplacementText!==E.replacementText&&h.replacementText!==E.replacementText),P=k?M?s(`suggestions.awaitingYou`):(0,J.jsx)(g,{i18nKey:`suggestions.awaiting`,values:{name:A},components:{reviewer:(0,J.jsx)(`strong`,{className:`suggestion-reviewer-name`,"data-tooltip":E.reviewerUsername?`@${E.reviewerUsername}`:void 0,"data-texlite-tooltip-always":!0})}}):s(`suggestions.${E.status}`);return(0,J.jsxs)(`section`,{className:`comment-suggestion ${E.status}`,onClick:e=>e.stopPropagation(),children:[(0,J.jsxs)(`button`,{type:`button`,className:`suggestion-toggle`,"aria-expanded":d,onClick:()=>f(!d),children:[d?(0,J.jsx)(H,{size:13}):(0,J.jsx)(O,{size:13}),(0,J.jsx)(`strong`,{children:s(`suggestions.title`)}),(0,J.jsx)(`span`,{children:P})]}),d&&(0,J.jsxs)(`div`,{className:`suggestion-details`,children:[ee&&h?(0,J.jsxs)(`section`,{className:`suggestion-editor suggestion-revision-editor`,"aria-label":s(`suggestions.edit`),children:[(0,J.jsx)(mg,{original:E.originalText,replacement:h.replacementText,autoFocus:!0,disabled:x,onChange:e=>_({...h,replacementText:e})}),N&&(0,J.jsx)(`p`,{className:`suggestion-warning`,role:`alert`,children:s(`suggestions.updatedWhileEditing`)}),(0,J.jsxs)(`div`,{className:`suggestion-actions comment-form-actions`,children:[(0,J.jsx)(`button`,{type:`button`,disabled:x,onClick:()=>{_(null),T(``)},children:s(`common.cancel`)}),(0,J.jsx)(Ve,{saving:x,iconSize:13,disabled:N||h.replacementText===E.originalText||h.replacementText===h.expectedReplacementText,onClick:()=>void D(``,`PATCH`,h),children:s(`common.save`)})]})]}):(0,J.jsx)(dg,{original:E.originalText,replacement:E.replacementText}),k&&!E.applicable&&!E.applying&&(0,J.jsx)(`p`,{className:`suggestion-warning`,children:s(`suggestions.sourceChanged`)}),k&&(j||!E.reviewerAvailable)&&(0,J.jsx)(`p`,{className:`suggestion-warning`,children:s(j?`errors.codes.SUGGESTION_SELF_REVIEW`:`suggestions.reviewerUnavailable`)}),E.applying&&(0,J.jsx)(`p`,{className:`suggestion-warning`,children:s(`suggestions.saving`)}),!k&&(0,J.jsxs)(`p`,{className:`suggestion-decision`,children:[(0,J.jsx)(`span`,{children:(0,J.jsx)(g,{i18nKey:`suggestions.decidedBy`,values:{name:E.decidedByDisplayName??E.decidedByUsername??s(`editor.deletedUser`)},components:{reviewer:(0,J.jsx)(`strong`,{className:`suggestion-reviewer-name`,"data-tooltip":E.decidedByUsername?`@${E.decidedByUsername}`:void 0,"data-texlite-tooltip-always":!0})}})}),E.decidedAt&&(0,J.jsx)(`time`,{dateTime:E.decidedAt,children:te(E.decidedAt,c.resolvedLanguage)})]}),w&&(0,J.jsx)(`p`,{className:`comment-form-error`,role:`alert`,children:w}),k&&M&&(0,J.jsxs)(`div`,{className:`suggestion-actions`,children:[(0,J.jsxs)(`button`,{type:`button`,className:`primary`,disabled:x||!E.applicable&&!E.applying,onClick:()=>void D(`/review`,`POST`,{action:`accept`,expectedReplacementText:E.replacementText}),children:[x?(0,J.jsx)(Re,{className:`spin`,size:13}):(0,J.jsx)(V,{size:13}),s(`suggestions.accept`)]}),(0,J.jsxs)(`button`,{type:`button`,disabled:x||E.applying,onClick:()=>void D(`/review`,`POST`,{action:`reject`,expectedReplacementText:E.replacementText}),children:[(0,J.jsx)(z,{size:13}),s(`suggestions.reject`)]})]}),ee&&!h&&(0,J.jsxs)(`div`,{className:`suggestion-revision-action`,children:[(0,J.jsxs)(`button`,{type:`button`,className:`suggestion-text-action`,disabled:x,onClick:()=>{_({replacementText:E.replacementText,expectedReplacementText:E.replacementText}),b(null),T(``)},children:[(0,J.jsx)(u,{size:12,"aria-hidden":!0}),s(`suggestions.edit`)]}),y===E.replacementText&&(0,J.jsxs)(`span`,{className:`suggestion-edit-saved`,role:`status`,children:[(0,J.jsx)(V,{size:12,"aria-hidden":!0}),s(`suggestions.saved`)]})]})]})]})}function _g(e,t={}){let n=e.slice(0,Math.max(0,e.length-2)),r=!!(t.activeDraft||t.targetReplyId&&e.some(e=>e.id===t.targetReplyId)||n.some(e=>t.unreadReplyMentionIds?.has(e.id)||t.highlightReplyParticipants&&t.selectedParticipantIds?.has(e.authorId))),i=r||(t.expansion??!!t.current),a=i?0:n.length;return{replies:a?e.slice(-2):e,hiddenCount:a,expanded:i,canToggle:n.length>0&&!r}}var vg=1100;function yg(e){let t=()=>{};if(!e||window.matchMedia?.(`(prefers-reduced-motion: reduce)`).matches)return t;let n=e.closest(`.comments`)??e.parentElement,r=e.getBoundingClientRect(),i=e.closest(`.context-panel`)?.getBoundingClientRect(),a=Math.max(0,r.left,i?.left??0),o=Math.max(0,r.top,i?.top??0),s=Math.min(window.innerWidth,r.right,i?.right??window.innerWidth)-a,c=Math.min(180,Math.min(window.innerHeight,r.bottom,i?.bottom??window.innerHeight)-o);if(!n||s<=0||c<=0)return t;let l=!1;return()=>{if(l||!n.isConnected||window.matchMedia?.(`(prefers-reduced-motion: reduce)`).matches)return;l=!0;let e=document.createElement(`div`);e.className=`comment-paper-shred`,e.setAttribute(`aria-hidden`,`true`),e.inert=!0,Object.assign(e.style,{left:`${a}px`,top:`${o}px`,width:`${s}px`,height:`${c}px`}),e.style.setProperty(`--shred-duration`,`${vg}ms`),e.style.setProperty(`--shred-height`,`${c}px`);let t=Math.min(12,Math.max(8,Math.round(s/22))),r=c<96?1:2;for(let n=0;n<t*r;n++){let i=document.createElement(`span`),a=n%t,o=Math.floor(n/t),s=a/(t-1)*2-1,l=n*37;i.style.left=`${a/t*100}%`,i.style.top=`${o/r*100}%`,i.style.width=`${100/t}%`,i.style.height=`${c/r}px`,i.style.setProperty(`--shred-x`,`${s*14+l%7-3}px`),i.style.setProperty(`--shred-y`,`${48+o*16+l%31}px`),i.style.setProperty(`--shred-angle`,`${s*12+l%13-6}deg`),i.style.setProperty(`--shred-flip`,`${(n%2?1:-1)*(18+l%23)}deg`),i.style.setProperty(`--shred-line-offset`,`${-o*c/r}px`),i.style.animationDuration=`${780+l%4*25}ms`,i.style.animationDelay=`${80+a*7+o*35+l%3*9}ms`,e.append(i)}let i=()=>{window.clearTimeout(d),u.disconnect(),window.removeEventListener(`resize`,i),e.remove()},u=new MutationObserver(()=>{n.isConnected||i()}),d=window.setTimeout(i,1300);e.addEventListener(`animationend`,t=>{t.target===e&&!t.pseudoElement&&i()}),window.addEventListener(`resize`,i),u.observe(document.body,{childList:!0,subtree:!0}),document.body.append(e)}}var bg=e=>`${e.displayName?.trim()||e.username} (@${e.username})`;function xg({users:e,value:t,onChange:n,disabled:r=!1}){let{t:i}=v(),a=(0,q.useId)(),[o,s]=(0,q.useState)(``),[c,l]=(0,q.useState)(!1),[u,d]=(0,q.useState)(0),f=(0,q.useRef)(null),p=(0,q.useRef)(null),m=(0,q.useRef)(null),h=e.find(e=>e.id===t),g=h?``:o.trim().replace(/^@/,``).toLowerCase(),_=g?e.filter(e=>e.username.toLowerCase().includes(g)||(e.displayName??``).toLowerCase().includes(g)):e,y=Math.min(u,Math.max(0,_.length-1)),b=c&&!r;(0,q.useEffect)(()=>{b&&m.current?.querySelector(`[data-index="${y}"]`)?.scrollIntoView?.({block:`nearest`})},[y,b,o]);let x=e=>{let t=_[e];t&&!r&&(n(t.id),s(``),l(!1))},S=()=>{d(Math.max(0,_.findIndex(e=>e.id===t))),l(!0)},C=`${a}-user`;return(0,J.jsxs)(`div`,{className:`share-user-picker`,children:[(0,J.jsx)(`label`,{htmlFor:C,children:i(`common.user`)}),(0,J.jsxs)(ie,{open:b,onOpenChange:l,children:[(0,J.jsx)(ne,{asChild:!0,children:(0,J.jsxs)(`div`,{className:`share-user-search`,ref:p,onClick:()=>{r||(f.current?.focus(),S())},children:[(0,J.jsx)(`input`,{id:C,ref:f,role:`combobox`,value:h?bg(h):o,disabled:r,placeholder:i(`projectSettings.searchUsersPlaceholder`),autoComplete:`off`,spellCheck:!1,"aria-autocomplete":`list`,"aria-expanded":b,"aria-controls":b?`${a}-list`:void 0,"aria-activedescendant":b&&_[y]?`${a}-user-${_[y].id}`:void 0,onClick:e=>{h&&e.currentTarget.select()},onFocus:e=>{S(),h&&e.currentTarget.select()},onChange:e=>{s(e.target.value),n(``),d(0),l(!0)},onKeyDown:e=>{if(!e.nativeEvent.isComposing){if(e.key===`ArrowDown`||e.key===`ArrowUp`){e.preventDefault(),l(!0);let n=e.key===`ArrowDown`?1:-1;if(b)d(e=>_.length?(e+n+_.length)%_.length:0);else{let e=_.findIndex(e=>e.id===t);d(e>=0?e:n===1?0:Math.max(0,_.length-1))}}else e.key===`Enter`?(e.preventDefault(),b&&x(y)):e.key===`Escape`&&b&&(e.preventDefault(),e.stopPropagation(),l(!1))}}}),(0,J.jsx)(H,{className:`share-user-chevron`,size:14,"aria-hidden":!0})]})}),(0,J.jsx)(se,{container:f.current?.closest(`[role="dialog"]`),children:(0,J.jsxs)(N,{className:`share-user-popover`,"aria-label":i(`projectSettings.chooseUser`),align:`start`,side:`bottom`,sideOffset:5,collisionPadding:12,avoidCollisions:!1,collisionBoundary:f.current?.closest(`[role="dialog"]`)??void 0,onOpenAutoFocus:e=>e.preventDefault(),onCloseAutoFocus:e=>e.preventDefault(),onInteractOutside:e=>{p.current?.contains(e.target)&&e.preventDefault()},onEscapeKeyDown:e=>{e.preventDefault(),e.stopPropagation(),l(!1)},children:[(0,J.jsx)(`div`,{id:`${a}-list`,ref:m,role:`listbox`,"aria-label":i(`projectSettings.chooseUser`),children:_.map((e,n)=>(0,J.jsxs)(`button`,{type:`button`,role:`option`,tabIndex:-1,id:`${a}-user-${e.id}`,"data-index":n,"data-active":n===y||void 0,"aria-selected":e.id===t,onMouseDown:e=>e.preventDefault(),onMouseMove:()=>d(n),onClick:()=>x(n),children:[(0,J.jsxs)(`span`,{children:[(0,J.jsx)(`strong`,{children:e.displayName?.trim()||e.username}),(0,J.jsxs)(`small`,{children:[`@`,e.username]})]}),e.id===t&&(0,J.jsx)(V,{size:14,"aria-hidden":!0})]},e.id))}),_.length===0&&(0,J.jsx)(`p`,{className:`share-user-no-results`,role:`status`,children:i(e.length?`projectSettings.noMatchingUsers`:`projectSettings.noAvailableUsers`)})]})})]})]})}function Sg({projectId:e,onBusyChange:t}){let{t:n,i18n:r}=v(),[i,a]=(0,q.useState)([]),[o,c]=(0,q.useState)(``),[l,u]=(0,q.useState)(`168`),[d,p]=(0,q.useState)(null),[m,h]=(0,q.useState)(null),[g,_]=(0,q.useState)(``),[y,b]=(0,q.useState)(!0),[x,S]=(0,q.useState)(!1),[C,w]=(0,q.useState)(null),[T,E]=(0,q.useState)(Date.now),D=(0,q.useRef)(null),O=(0,q.useRef)(null),k=(0,q.useRef)(!1),A=(0,q.useRef)(!1),j=(0,q.useRef)(void 0),ee=(0,q.useRef)(t);ee.current=t,(0,q.useEffect)(()=>{let t=new AbortController;return O.current=t,b(!0),a([]),_(``),w(null),p(null),E(Date.now()),G(`/api/projects/${e}/view-links`,{signal:t.signal}).then(e=>{t.signal.aborted||a(e.links)}).catch(e=>{t.signal.aborted||_(K(e))}).finally(()=>{t.signal.aborted||b(!1)}),()=>{t.abort(),clearTimeout(j.current),ee.current(!1)}},[e]),(0,q.useEffect)(()=>{let e=i.flatMap(e=>e.expiresAt&&Date.parse(e.expiresAt)>T?[Date.parse(e.expiresAt)]:[]);if(!e.length)return;let t=setTimeout(()=>E(Date.now()),Math.min(Math.max(1,Math.min(...e)-Date.now()),2147483647));return()=>clearTimeout(t)},[i,T]);let N=i.some(e=>!e.expiresAt||Date.parse(e.expiresAt)>T),P=async e=>{let t=O.current;if(!(!t||t.signal.aborted||k.current||A.current)){k.current=!0,S(!0),ee.current(!0),_(``);try{await e(t.signal)}catch(e){t.signal.aborted||_(K(e))}finally{k.current=!1,t.signal.aborted||(S(!1),ee.current(!1))}}},F=()=>P(async t=>{if(!N)try{let n=await G(`/api/projects/${e}/view-links`,{method:`POST`,signal:t,body:JSON.stringify({label:o,expiresAt:l===`never`?null:new Date(Date.now()+Number(l)*36e5).toISOString()})});t.aborted||(a(e=>[n.link,...e]),c(``))}catch(n){if(n instanceof Ue&&n.code===`VIEW_LINK_EXISTS`){let n=await G(`/api/projects/${e}/view-links`,{signal:t});t.aborted||a(n.links)}throw n}}),ne=()=>{if(!C)return;let t=C;P(async n=>{await G(`/api/projects/${e}/view-links/${t.id}`,{method:`DELETE`,signal:n}),n.aborted||a(e=>e.filter(e=>e.id!==t.id)),n.aborted||w(null)})},I=async e=>{let t=O.current;if(!(!t||t.signal.aborted||k.current||A.current)&&e.path){A.current=!0,h(e.id),p(null),_(``),clearTimeout(j.current);try{await pt(new URL(e.path,window.location.origin).href,()=>D.current),t.signal.aborted||(p(e.id),j.current=setTimeout(()=>p(null),2e3))}catch{t.signal.aborted||_(n(`viewLinks.copyFailed`))}finally{A.current=!1,t.signal.aborted||h(null)}}};return(0,J.jsxs)(`div`,{className:`view-link-manager`,ref:D,"aria-busy":y||x,children:[(0,J.jsxs)(`p`,{className:`view-link-description`,children:[(0,J.jsx)(f,{size:17,"aria-hidden":!0}),n(`viewLinks.description`)]}),!y&&!N&&(0,J.jsxs)(`div`,{className:`view-link-create`,children:[(0,J.jsxs)(`label`,{className:`form-field`,children:[n(`viewLinks.label`),(0,J.jsx)(`input`,{maxLength:80,value:o,disabled:x,onChange:e=>c(e.target.value)})]}),(0,J.jsxs)(`label`,{className:`form-field`,children:[n(`viewLinks.expiry`),(0,J.jsx)(`select`,{value:l,disabled:x,onChange:e=>u(e.target.value),children:[[`1`,`hour`],[`24`,`day`],[`168`,`week`],[`720`,`month`],[`never`,`never`]].map(([e,t])=>(0,J.jsx)(`option`,{value:e,children:n(`viewLinks.${t}`)},e))})]}),(0,J.jsxs)(`button`,{className:`primary icon-button`,disabled:x||y||m!==null,onClick:()=>void F(),children:[(0,J.jsx)(ze,{size:15}),n(`viewLinks.create`)]})]}),g&&(0,J.jsx)(`p`,{className:`error`,role:`alert`,children:g}),y?(0,J.jsxs)(`div`,{className:`share-empty`,role:`status`,children:[(0,J.jsx)(Re,{size:20,className:`spin`}),n(`common.loading`)]}):(0,J.jsxs)(`div`,{className:`view-link-list`,children:[i.map(e=>{let t=e.expiresAt&&Date.parse(e.expiresAt)<=T?`expired`:`active`,i=e.path?new URL(e.path,window.location.origin).href:``;return(0,J.jsxs)(`div`,{className:`view-link-item ${t}`,children:[(0,J.jsxs)(`div`,{className:`view-link-heading`,children:[(0,J.jsx)(Ft,{size:16,"aria-hidden":!0}),(0,J.jsxs)(`div`,{className:`view-link-identity`,children:[(0,J.jsx)(`strong`,{children:e.label||n(`viewLinks.untitled`)}),(0,J.jsx)(`small`,{children:e.expiresAt?n(`viewLinks.expires`,{time:te(e.expiresAt,r.resolvedLanguage)}):n(`viewLinks.never`)})]}),(0,J.jsx)(`span`,{className:`view-link-status`,children:n(`viewLinks.${t}`)}),(0,J.jsx)(`div`,{className:`view-link-actions`,children:(0,J.jsx)(`button`,{className:`icon-only danger-text`,disabled:x||m!==null,"aria-label":n(`viewLinks.delete`),"data-tooltip":n(`viewLinks.delete`),onClick:()=>{_(``),w(e)},children:(0,J.jsx)(M,{size:15})})})]}),(0,J.jsxs)(`div`,{className:`view-link-address`,children:[(0,J.jsx)(`input`,{readOnly:!0,spellCheck:!1,autoComplete:`off`,"aria-label":n(`viewLinks.address`,{name:e.label||n(`viewLinks.untitled`)}),value:i,placeholder:n(`viewLinks.addressUnavailable`),onFocus:e=>e.target.select()}),(0,J.jsxs)(`button`,{type:`button`,className:`save-button view-link-copy`,disabled:x||m!==null||t!==`active`||!e.path,"aria-busy":m===e.id,onClick:()=>void I(e),children:[m===e.id?(0,J.jsx)(Re,{className:`spin`,size:14}):d===e.id?(0,J.jsx)(V,{className:`save-button-confirmation`,size:14}):(0,J.jsx)(s,{size:14}),(0,J.jsx)(`span`,{role:`status`,"aria-live":`polite`,children:n(d===e.id?`viewLinks.copied`:`viewLinks.copy`)})]})]})]},e.id)}),i.length===0&&(0,J.jsxs)(`div`,{className:`share-empty`,children:[(0,J.jsx)(Ft,{size:24}),(0,J.jsx)(`span`,{children:n(`viewLinks.empty`)})]})]}),(0,J.jsx)(Ze,{open:!!C,title:n(`viewLinks.delete`),description:n(`viewLinks.deleteConfirm`),confirmLabel:n(`viewLinks.delete`),danger:!0,busy:x,error:g,onCancel:()=>{x||(w(null),_(``))},onConfirm:ne})]})}function Cg(e){let t=/(^|\s)(@[\p{L}\p{N}_.-]+)/gu,n=[],r=0;for(let i of e.matchAll(t)){let t=i.index??0,a=i[1],o=i[2],s=t+a.length;s>r&&n.push(e.slice(r,s)),n.push((0,J.jsx)(`span`,{className:`comment-inline-mention`,children:o},`${s}:${o}`)),r=s+o.length}return n.length?(r<e.length&&n.push(e.slice(r)),n):e}function wg({userId:e,avatarStyle:t,name:n,username:r,highlighted:i,children:a}){return(0,J.jsxs)(`span`,{className:`comment-identity`,children:[(0,J.jsx)(F,{userId:e,name:n,username:r,avatarStyle:t,className:`comment-avatar`}),(0,J.jsxs)(`span`,{className:`comment-author-details`,children:[(0,J.jsx)(`span`,{className:`comment-author${i?` participant-match`:``}`,children:(0,J.jsx)(`strong`,{"data-tooltip":r?`@${r}`:void 0,"data-texlite-tooltip-always":!0,children:n})}),a]})]})}function Tg({projectOwnerId:e=``,canEditSource:t=!1,unreadCommentMentionKind:n,projectId:r,comment:i,draftStore:a,currentUserId:s,unreadCommentMentionId:c,unreadReplyMentionIds:l,highlightedComment:u,highlightedReplyId:f,currentComment:m,showFilePath:h,onMarkMentionRead:_,onFocus:y,onActivate:b,onToggle:x,onReply:S,onEdit:C,onDelete:w,onEditReply:T,onDeleteReply:E,selectedParticipantIds:D,highlightReplyParticipants:k,replyExpansion:A,onReplyExpansionChange:j}){let{t:M,i18n:ee}=v(),N=d(),[P,F]=(0,q.useState)(!1),[ne,I]=(0,q.useState)(null),re=(0,q.useCallback)(e=>a.subscribe(i.id,e),[a,i.id]),ie=(0,q.useCallback)(()=>a.getThread(i.id),[a,i.id]),ae=(0,q.useSyncExternalStore)(re,ie,ie),L=ae.reply,R=ae[`edit-comment`],oe=(0,q.useId)(),se=_g(i.replies,{expansion:A,current:m,targetReplyId:f,unreadReplyMentionIds:l,selectedParticipantIds:D,highlightReplyParticipants:k,activeDraft:!!(L?.open||L?.pending||i.authorId===s&&R?.open||i.replies.some(e=>e.authorId===s&&ae[`edit-reply:${e.id}`]?.open))}),ce=a.isPending(i.id),[z,le]=(0,q.useState)(null),[B,H]=(0,q.useState)(!1),[fe,pe]=(0,q.useState)(null),[me,he]=(0,q.useState)(``),ge=(0,q.useRef)(null),_e=(0,q.useRef)(!1),[ve,ye]=(0,q.useState)(!1),be=async e=>{if(_e.current)return;_e.current=!0,ye(!0),he(``);let t=yg(e?ge.current?.querySelector(`[data-comment-reply-id="${e}"]`)??null:ge.current);try{if(!(e?await E(e):await w())){he(M(`editor.commentDeleteFailed`));return}e?pe(null):H(!1),t()}catch(e){he(K(e))}finally{_e.current=!1,ye(!1)}},xe=(e,t=``)=>{b(),j(!0),le(e),a.open(i.id,e,t)},Se=(e,t,n,o)=>{let s=ae[e];return s?.open?(0,J.jsx)(ig,{projectId:r,editing:e!==`reply`,originalValue:o,label:t,value:s.content,pending:s.pending,error:s.error,disabled:ce||P,autoFocus:z===e,onChange:t=>a.change(i.id,e,t),onSubmit:()=>a.submit(i.id,e,n,M(`editor.commentSubmitFailed`)),onCancel:()=>a.discard(i.id,e)},e):null},Ce=i.authorUsername,we=e=>p(e,ee.resolvedLanguage??`en`,N,(e,t)=>M(e,t)),Te=e=>te(e,ee.resolvedLanguage,{year:`numeric`,month:`short`,day:`numeric`,hour:`2-digit`,minute:`2-digit`}),Ee=e=>(0,J.jsx)(`time`,{dateTime:e,"data-tooltip":Te(e),"data-texlite-tooltip-always":!0,children:we(e)}),De=(e,t)=>(0,J.jsxs)(`span`,{className:`comment-times`,children:[Ee(e),t&&(0,J.jsx)(`small`,{"data-tooltip":M(`editor.editedAt`,{time:Te(t)}),"data-texlite-tooltip-always":!0,children:M(`editor.commentEdited`)})]}),Oe=!i.resolved&&i.suggestion?.status===`pending`&&(i.suggestion.reviewerAvailable||i.suggestion.applying),ke=async(e,t)=>{t.stopPropagation(),j(!0),await _(e)};return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`article`,{ref:ge,"data-comment-id":i.id,className:`comment-thread${i.resolved?` resolved`:``}${i.orphaned?` orphaned`:``}${u?` mention-target`:``}${m?` review-current`:``}`,onFocusCapture:b,onClick:()=>{window.getSelection()?.toString()||y()},children:[(0,J.jsxs)(`header`,{className:`comment-header`,children:[(0,J.jsx)(wg,{userId:i.authorId,avatarStyle:i.authorAvatarStyle,name:i.authorDisplayName??Ce??M(`editor.deletedUser`),username:Ce,highlighted:D?.has(i.authorId),children:De(i.createdAt,i.editedAt)}),(0,J.jsxs)(`span`,{className:`comment-header-actions`,children:[(0,J.jsx)(`button`,{type:`button`,className:`resolve`,disabled:P||ce||Oe,"aria-busy":P,"aria-label":M(i.resolved?`editor.reopen`:`editor.resolve`),"data-tooltip":M(Oe?`suggestions.reviewBeforeResolve`:i.resolved?`editor.reopen`:`editor.resolve`),"data-texlite-tooltip-always":!0,onClick:e=>{e.stopPropagation(),!P&&(F(!0),x().finally(()=>F(!1)))},children:P?(0,J.jsx)(Re,{className:`spin`,size:15,"aria-hidden":!0}):i.resolved?(0,J.jsx)(Ut,{size:15,"aria-hidden":!0}):(0,J.jsx)(V,{size:16,"aria-hidden":!0})}),i.authorId===s&&!R?.open&&(0,J.jsx)(tg,{kind:`comment`,disabled:ce||P,onSuggest:e&&!ne&&hg(i,s)?()=>{b(),I({original:i.selectedText,sourceHash:i.anchorSourceHash})}:void 0,onEdit:()=>xe(`edit-comment`,i.content),onDelete:()=>{he(``),H(!0)}})]})]}),(0,J.jsx)(`div`,{className:`comment-location`,children:i.orphaned?M(`editor.orphaned`):h?M(`editor.commentLocation`,{path:i.filePath,line:i.startLine}):M(`editor.line`,{line:i.startLine})}),i.selectedText&&(0,J.jsx)(`blockquote`,{className:`comment-selected-text`,children:i.selectedText}),R?.open&&i.authorId===s?Se(`edit-comment`,M(`editor.editComment`),C,i.content):(0,J.jsx)(`p`,{className:`comment-content`,children:Cg(i.content)}),e&&(i.suggestion||ne)&&(0,J.jsx)(gg,{projectId:r,ownerId:e,currentUserId:s,canEdit:t,comment:i,draftTarget:ne,onCloseComposer:()=>I(null)}),c&&(0,J.jsxs)(`div`,{className:`comment-mention`,children:[(0,J.jsxs)(`span`,{children:[(0,J.jsx)(o,{"aria-hidden":!0,size:12}),M(n===`review`?`suggestions.reviewRequested`:`editor.mentionedYou`)]}),(0,J.jsx)(`button`,{type:`button`,onClick:e=>void ke(c,e),children:M(`editor.markMentionRead`)})]}),i.replies.length>0&&(0,J.jsxs)(`div`,{className:`comment-replies`,children:[se.canToggle&&(0,J.jsxs)(`button`,{type:`button`,className:`comment-replies-toggle`,"aria-expanded":se.expanded,"aria-controls":oe,onClick:e=>{e.stopPropagation(),j(!se.expanded)},children:[se.expanded?(0,J.jsx)(ue,{size:12,"aria-hidden":!0}):(0,J.jsx)(O,{size:12,"aria-hidden":!0}),se.expanded?M(`editor.hideEarlierReplies`):M(`editor.showEarlierReplies`,{count:se.hiddenCount})]}),(0,J.jsx)(`div`,{className:`comment-replies-list`,id:oe,children:se.replies.map(e=>{let t=l?.get(e.id),n=`edit-reply:${e.id}`,r=ae[n]?.open&&e.authorId===s;return(0,J.jsxs)(`div`,{"data-comment-reply-id":e.id,className:`comment-reply${f===e.id?` mention-target`:``}`,children:[(0,J.jsxs)(`header`,{children:[(0,J.jsx)(wg,{userId:e.authorId,avatarStyle:e.authorAvatarStyle,name:e.authorDisplayName??e.authorUsername??M(`editor.deletedUser`),username:e.authorUsername,highlighted:k&&D?.has(e.authorId),children:De(e.createdAt,e.editedAt)}),(0,J.jsx)(`span`,{className:`comment-header-actions`,children:e.authorId===s&&!r&&(0,J.jsx)(tg,{kind:`reply`,disabled:ce||P,onEdit:()=>xe(n,e.content),onDelete:()=>{he(``),pe(e.id)}})})]}),r?Se(n,M(`editor.editReply`),t=>T(e.id,t),e.content):(0,J.jsx)(`p`,{className:`comment-content`,children:Cg(e.content)}),t&&(0,J.jsxs)(`div`,{className:`comment-mention`,children:[(0,J.jsxs)(`span`,{children:[(0,J.jsx)(o,{"aria-hidden":!0,size:12}),M(`editor.mentionedYou`)]}),(0,J.jsx)(`button`,{type:`button`,onClick:e=>void ke(t,e),children:M(`editor.markMentionRead`)})]})]},e.id)})})]}),i.resolved&&i.resolvedAt&&(0,J.jsxs)(`div`,{className:`comment-resolution`,children:[(0,J.jsx)(de,{size:12,"aria-hidden":!0}),(0,J.jsxs)(`span`,{children:[(0,J.jsx)(g,{i18nKey:`editor.resolvedBy`,values:{user:i.resolvedByDisplayName??i.resolvedByUsername??M(`editor.deletedUser`)},components:{user:(0,J.jsx)(`strong`,{className:`comment-resolution-user`,"data-tooltip":i.resolvedByUsername?`@${i.resolvedByUsername}`:void 0,"data-texlite-tooltip-always":!0})}}),` · `,Ee(i.resolvedAt)]})]}),!L?.open&&(0,J.jsx)(`button`,{type:`button`,className:`reply-action`,disabled:ce||P,onClick:e=>{e.stopPropagation(),xe(`reply`)},children:M(`editor.replyPrompt`)}),Se(`reply`,M(`editor.reply`),S)]}),(0,J.jsx)(Ze,{open:B,title:M(`editor.deleteCommentTitle`),description:M(`editor.deleteCommentDescription`),confirmLabel:M(`common.delete`),danger:!0,busy:ve,error:me,onCancel:()=>H(!1),onConfirm:()=>void be(null)}),(0,J.jsx)(Ze,{open:!!fe,title:M(`editor.deleteReplyTitle`),description:M(`editor.deleteReplyDescription`),confirmLabel:M(`common.delete`),danger:!0,busy:ve,error:me,onCancel:()=>pe(null),onConfirm:()=>{fe&&be(fe)}})]})}function Eg({open:e,onOpenChange:t,project:n,projectId:r,onMemberCountChange:i}){let{t:a}=v(),[o,s]=(0,q.useState)([]),[c,l]=(0,q.useState)([]),[u,d]=(0,q.useState)(`members`),[f,p]=(0,q.useState)(!1),[m,h]=(0,q.useState)(``),[g,_]=(0,q.useState)(`read`),[y,b]=(0,q.useState)(null),[x,S]=(0,q.useState)(``),[C,w]=(0,q.useState)(!1),[T,E]=(0,q.useState)(!1),D=(0,q.useRef)(null),O=(0,q.useRef)(null),k=(0,q.useRef)(null),A=n.permission===`owner`,ee=(0,q.useCallback)(async e=>{let[t,a]=await Promise.all([G(`/api/projects/${r}/members`,{signal:e}),A?G(`/api/users`,{signal:e}):Promise.resolve({users:[]})]);if(e.aborted)return;let o=t.members.filter(e=>e.id!==n.ownerId);s(o),i?.(r,o.length),l(a.users.filter(e=>e.id!==n.ownerId))},[r,n.ownerId,A,i]);(0,q.useEffect)(()=>{if(!e)return;let t=new AbortController;return D.current=t,h(``),_(`read`),b(null),S(``),d(`members`),l([]),s([]),E(!1),w(!0),ee(t.signal).catch(e=>{t.signal.aborted||S(K(e))}).finally(()=>{t.signal.aborted||w(!1)}),()=>{t.abort(),D.current===t&&(D.current=null)}},[e,ee]);let N=async e=>{let t=D.current;if(A&&t&&!t.signal.aborted&&O.current!==t){O.current=t,E(!0),S(``);try{await e(t.signal),t.signal.aborted||await ee(t.signal)}catch(e){t.signal.aborted||S(K(e))}finally{O.current===t&&(O.current=null),t.signal.aborted||E(!1)}}},P=c.filter(e=>!o.some(t=>t.id===e.id)),te=async()=>{P.some(e=>e.id===m)&&await N(async e=>{await G(`/api/projects/${r}/members/${m}`,{method:`PUT`,body:JSON.stringify({permission:g}),signal:e}),e.aborted||(h(``),_(`read`))})},ne=async(e,t)=>{await N(n=>G(`/api/projects/${r}/members/${e.id}`,{method:`PUT`,body:JSON.stringify({permission:t}),signal:n}))},I=async()=>{y&&await N(async e=>{await G(`/api/projects/${r}/members/${y.id}`,{method:`DELETE`,signal:e}),e.aborted||b(null)})};return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(Xe,{open:e,wide:!0,className:`share-dialog-modal`,title:a(`projectSettings.share`),onOpenChange:e=>{!T&&!f&&t(e)},onEscapeKeyDown:e=>{k.current?.querySelector(`[role="combobox"][aria-expanded="true"]`)&&e.preventDefault()},footer:(0,J.jsx)(`button`,{disabled:T||f,onClick:()=>t(!1),children:a(`common.close`)}),children:(0,J.jsxs)(`div`,{className:`share-dialog`,ref:k,"aria-busy":C||T,children:[A&&(0,J.jsxs)(`div`,{className:`share-scope-tabs`,role:`tablist`,"aria-label":a(`projectSettings.share`),children:[(0,J.jsx)(`button`,{role:`tab`,"aria-selected":u===`members`,disabled:T||f,onClick:()=>d(`members`),children:a(`projectSettings.members`)}),(0,J.jsx)(`button`,{role:`tab`,"aria-selected":u===`links`,disabled:T||f,onClick:()=>d(`links`),children:a(`viewLinks.tab`)})]}),u===`links`&&A?(0,J.jsx)(Sg,{projectId:r,onBusyChange:p},r):(0,J.jsxs)(J.Fragment,{children:[x&&!y&&(0,J.jsx)(`p`,{className:`error`,role:`alert`,children:x}),(0,J.jsxs)(`div`,{className:`share-owner`,children:[(0,J.jsx)(j,{size:17}),(0,J.jsxs)(`span`,{children:[(0,J.jsx)(`small`,{children:a(`projects.owner`)}),(0,J.jsx)(`strong`,{children:n.ownerDisplayName??n.ownerUsername})]})]}),A&&(0,J.jsxs)(`div`,{className:`share-add`,children:[(0,J.jsx)(xg,{users:P,value:m,onChange:h,disabled:C||T},r),(0,J.jsxs)(`label`,{className:`form-field`,children:[a(`common.permission`),(0,J.jsxs)(`select`,{disabled:C||T,value:g,onChange:e=>_(e.target.value),children:[(0,J.jsx)(`option`,{value:`read`,children:a(`common.readOnly`)}),(0,J.jsx)(`option`,{value:`edit`,children:a(`common.readWrite`)})]})]}),(0,J.jsxs)(`button`,{className:`primary icon-button`,disabled:C||T||!P.some(e=>e.id===m),onClick:()=>void te(),children:[T?(0,J.jsx)(Re,{className:`spin`,size:15}):(0,J.jsx)(He,{size:15}),a(`projectSettings.addMember`)]})]}),(0,J.jsxs)(`div`,{className:`shared-members-heading`,children:[(0,J.jsx)(`strong`,{children:a(`projectSettings.members`)}),(0,J.jsx)(`span`,{children:o.length})]}),(0,J.jsxs)(`div`,{className:`shared-members`,children:[o.map(e=>(0,J.jsxs)(`div`,{className:`shared-member`,children:[(0,J.jsxs)(`span`,{className:`member-identity`,children:[(0,J.jsx)(F,{userId:e.id,name:e.displayName,username:e.username,avatarStyle:e.avatarStyle,className:`member-avatar`}),(0,J.jsxs)(`span`,{children:[(0,J.jsx)(`strong`,{children:e.displayName??e.username}),(0,J.jsxs)(`small`,{children:[`@`,e.username]})]})]}),(0,J.jsxs)(`span`,{className:`member-controls`,children:[(0,J.jsxs)(`select`,{"aria-label":a(`common.permission`),disabled:!A||T,value:e.permission,onChange:t=>void ne(e,t.target.value),children:[(0,J.jsx)(`option`,{value:`read`,children:a(`common.readOnly`)}),(0,J.jsx)(`option`,{value:`edit`,children:a(`common.readWrite`)})]}),A&&(0,J.jsx)(`button`,{disabled:T,className:`icon-only danger-text`,title:a(`common.remove`),"aria-label":a(`common.remove`),onClick:()=>{S(``),b(e)},children:(0,J.jsx)(M,{size:15})})]})]},e.id)),C?(0,J.jsxs)(`div`,{className:`share-empty`,role:`status`,children:[(0,J.jsx)(Re,{className:`spin`,size:20}),(0,J.jsx)(`span`,{children:a(`common.loading`)})]}):o.length===0&&(0,J.jsxs)(`div`,{className:`share-empty`,children:[(0,J.jsx)(j,{size:24}),(0,J.jsx)(`span`,{children:a(`projectSettings.noMembers`)})]})]})]})]})}),(0,J.jsx)(Ze,{open:!!y,title:a(`projectSettings.removeTitle`),description:a(`projectSettings.removeDescription`,{username:y?.username??``}),confirmLabel:a(`common.remove`),danger:!0,busy:T,error:x,onCancel:()=>{T||(b(null),S(``))},onConfirm:()=>void I()})]})}function Dg({open:e,projectId:t,ownerId:n,authorId:r,selection:i,text:a,onText:o,suggestion:s,onSuggestion:l,submitting:u,error:d,onSubmit:f,onClose:p,onCancel:m,draftRestored:h,canRetarget:g,onRetarget:_}){let{t:y}=v(),b=(0,q.useId)(),[x,S]=(0,q.useState)(!1),[C,w]=(0,q.useState)(!1),T=(0,q.useRef)(null);(0,q.useEffect)(()=>{e||(S(!1),w(!1),T.current=null)},[e]);let E=ep(a,i.selectedText,s,r),D=!!(i.selectedText&&i.selectedText.length<=5e4),O=E.issue===`selfReview`?`errors.codes.SUGGESTION_SELF_REVIEW`:E.issue===`reviewer`?`commentComposer.chooseReviewer`:D?`commentComposer.empty`:`commentComposer.emptyComment`,k=!!(d||x&&E.issue),A=d||(E.issue?y(O):`${y(`commentComposer.${E.kind}`)}${E.edit?` · ${y(`commentComposer.reviewRequested`)}`:``}`),j=()=>{u||(S(!0),E.issue||f())};return(0,J.jsxs)(Xe,{open:e,draggable:!0,wide:!0,className:`comment-compose-modal`,title:y(`editor.addComment`),description:i.selectedText?y(`editor.commentDescription`,{count:i.endOffset-i.startOffset}):y(`editor.pointComment`),onOpenChange:e=>{!e&&!u&&p()},footer:(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`p`,{className:`comment-compose-status${k?` has-error`:``}`,role:k?`alert`:`status`,"aria-live":`polite`,children:u?y(`editor.commentSending`):A}),(0,J.jsxs)(`div`,{className:`comment-compose-actions`,children:[(0,J.jsx)(`button`,{type:`button`,disabled:u,onClick:m,children:y(`common.cancel`)}),(0,J.jsxs)(`button`,{type:`button`,className:`primary`,"aria-busy":u,disabled:u,onClick:j,children:[u&&(0,J.jsx)(Re,{className:`spin`,size:14}),y(u?`editor.commentSending`:`editor.addComment`)]})]})]}),children:[h&&(0,J.jsxs)(`p`,{className:`comment-draft-restored`,children:[(0,J.jsx)(`span`,{children:y(`editor.commentDraftRestored`)}),g&&(0,J.jsx)(`button`,{type:`button`,disabled:u,onClick:_,children:y(`editor.commentDraftUseSelection`)})]}),i.selectedText&&(0,J.jsxs)(`section`,{className:`comment-compose-original`,"aria-label":y(`commentComposer.original`),children:[(0,J.jsx)(`span`,{children:y(`commentComposer.original`)}),(0,J.jsx)(`blockquote`,{children:i.selectedText})]}),(0,J.jsxs)(`label`,{className:`form-field comment-compose-note`,children:[y(`editor.commentContent`),(0,J.jsx)(rg,{projectId:t,autoFocus:!0,rows:3,disabled:u,value:a,placeholder:y(`commentComposer.placeholder`),onChange:o,onKeyDown:e=>{(e.ctrlKey||e.metaKey)&&e.key===`Enter`&&!e.nativeEvent.isComposing&&(e.preventDefault(),e.stopPropagation(),j())}})]}),D&&(0,J.jsxs)(`div`,{className:`comment-compose-edit`,children:[(0,J.jsxs)(`label`,{className:`comment-compose-edit-toggle`,children:[(0,J.jsx)(`input`,{type:`checkbox`,role:`switch`,disabled:u,checked:!!s,"aria-controls":s?`${b}-edit`:void 0,onChange:e=>{e.target.checked?(w(!0),l(T.current??{replacementText:i.selectedText,reviewerId:n===r?``:n})):(T.current=s,w(!1),l(null))}}),(0,J.jsx)(c,{size:16,"aria-hidden":!0}),(0,J.jsx)(`span`,{children:y(`commentComposer.suggestEdit`)})]}),s&&(0,J.jsx)(`div`,{className:`comment-compose-edit-fields`,id:`${b}-edit`,children:(0,J.jsx)(mg,{original:i.selectedText,replacement:s.replacementText,onChange:e=>l({...s,replacementText:e}),disabled:u,autoFocus:C})})]}),s&&(0,J.jsx)(`div`,{className:`comment-compose-reviewer`,children:(0,J.jsx)(fg,{projectId:t,authorId:r,value:s.reviewerId,onChange:e=>l({...s,reviewerId:e}),disabled:u})})]})}var Og=(0,q.lazy)(()=>S(()=>import(`./CitationLibraryDialog-DqO9e0GV.js`).then(e=>({default:e.CitationLibraryDialog})),__vite__mapDeps([31,2,3,32,5,4,7,9,16,17,12,1,6,8,10,11,13,33,34,35,36,37,38,39,40,41,42,21,22,23,43,20,18,24,44,45]),import.meta.url)),kg=(0,q.lazy)(()=>S(()=>import(`./GitDialog-CA68baSd.js`).then(e=>({default:e.GitDialog})),__vite__mapDeps([46,2,3,4,5,9,16,7,17,12,1,6,8,10,11,13,47,48,36,49,50,38]),import.meta.url)),Ag=(0,q.lazy)(()=>S(()=>import(`./HistoryDialog-c2EEaFsl.js`).then(e=>({default:e.HistoryDialog})),__vite__mapDeps([51,2,3,4,5,9,16,7,17,12,1,6,8,10,11,13,40,52,53,33,37,41,42,54,49,50,38,39,44,55]),import.meta.url)),jg=(0,q.lazy)(()=>S(()=>import(`./SelectionHistoryDialog-BhOyneNx.js`).then(e=>({default:e.SelectionHistoryDialog})),__vite__mapDeps([56,2,3,4,5,16,7,9,17,12,1,6,8,10,11,13,57,52,54,55]),import.meta.url)),Mg=(0,q.lazy)(()=>S(()=>import(`./TikzGalleryDialog-CLAmKmS6.js`).then(e=>({default:e.TikzGalleryDialog})),__vite__mapDeps([58,2,3,4,5,7,10,9,41,1,6,8,11,12,13,59]),import.meta.url)),Ng=(0,q.lazy)(()=>S(()=>import(`./QuickOpenDialog-B7NTqOpu.js`).then(e=>({default:e.QuickOpenDialog})),__vite__mapDeps([60,2,3,4,5,33,9,53,7,16,17,12,1,6,8,10,11,13,40,37,41,42]),import.meta.url)),Pg=(0,q.lazy)(()=>S(()=>import(`./ProjectSearchDialog-DxgjbnmY.js`).then(e=>({default:e.ProjectSearchDialog})),__vite__mapDeps([61,2,3,4,5,6,9,16,7,17,12,1,8,10,11,13,33,53,40,37,41,42]),import.meta.url));function Fg({projectSearchOpen:e,setProjectSearchOpen:t,onSearchNavigate:n,commentSuggestion:r,setCommentSuggestion:i,user:a,project:o,projectId:s,activeFile:c,content:l,maxCitationBibtexBytes:u,files:d,directoryEntries:f,readOnly:p,resourcePreview:m,resourcePreviewLoading:h,setResourcePreview:_,setResourcePreviewLoading:y,uploadConflict:b,setUploadConflict:x,dismissUploadFeedback:S,uploadFiles:C,cleanMode:w,setCleanMode:E,cleanCompile:D,tikzGalleryOpen:O,setTikzGalleryOpen:k,tikzGalleryFolder:j,addFile:ee,newFileOpen:N,setNewFileOpen:P,newFilePath:te,setNewFilePath:F,newFolderOpen:ne,setNewFolderOpen:I,newFolderName:re,setNewFolderName:ie,selectedFolder:ae,fileDialogError:L,setFileDialogError:R,createFile:se,createFolder:z,moveEntry:le,setMoveEntry:B,moveName:V,setMoveName:H,moveDestination:ue,setMoveDestination:de,movePath:fe,deleteEntry:me,setDeleteEntry:he,deleteActiveSessions:ge,removePath:_e,commentOpen:ve,closeComment:ye,commentSelection:be,commentText:xe,setCommentText:Se,commentSubmitting:Ce,commentError:we,addComment:Te,cancelComment:Ee,commentDraftRestored:De,commentDraftCanRetarget:Oe,useCurrentCommentSelection:ke,shareOpen:Ae,setShareOpen:je,onSharedMemberCountChange:Me,citationLibraryOpen:Ne,setCitationLibraryOpen:Pe,insertCitationAtCursor:Fe,quickOpen:Ie,setQuickOpen:Le,openFile:ze,selectionHistoryTarget:Ve,closeSelectionHistory:He,historyOpen:Ue,setHistoryOpen:U,gitOpen:We,setGitOpen:Ge,save:Ke,permissionDowngrade:qe,permissionDowngradeBusy:Je,dismissPermissionDowngrade:Qe,discardPermissionDraft:$e}){let{t:W}=v();return(0,J.jsxs)(J.Fragment,{children:[qe&&(0,J.jsx)(Xe,{open:!0,title:W(`editor.collaboration.permissionDowngradeTitle`),description:qe.localDraftReady&&qe.otherTabDraft?W(`editor.collaboration.permissionDowngradeMultipleDrafts`):qe.otherTabDraft?W(`editor.collaboration.permissionDowngradeOtherTab`):qe.localDraftReady?W(`editor.collaboration.permissionDowngradeDescription`,{previous:W(`common.readWrite`)}):W(`editor.collaboration.permissionDowngradeNoDraft`),onOpenChange:e=>{!e&&!Je&&Qe()},footer:(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`button`,{type:`button`,disabled:Je,onClick:Qe,children:qe.localDraftReady?W(`editor.collaboration.permissionDowngradeKeep`):W(`common.close`)}),!qe.otherTabDraft&&(0,J.jsxs)(`button`,{type:`button`,className:`danger`,disabled:Je,onClick:()=>void $e(),children:[Je?(0,J.jsx)(Re,{className:`spin`,size:14}):qe.localDraftReady?(0,J.jsx)(M,{size:14}):(0,J.jsx)(Be,{size:14}),qe.localDraftReady?W(`editor.collaboration.permissionDowngradeDiscard`):W(`editor.collaboration.permissionDowngradeReload`)]})]}),children:(0,J.jsx)(`div`,{})}),(0,J.jsxs)(Xe,{open:!!m,extraWide:m?.kind===`image`||m?.kind===`pdf`||m?.kind===`text`,title:m?.path??``,description:m?.kind===`large`?W(`editor.resourceTooLarge`,{size:oe(m.size,{maximumUnit:`MB`}),limit:oe(m.limitBytes??10485760,{maximumUnit:`MB`})}):W(`editor.resourcePreview.${m?.kind??`text`}`),onOpenChange:e=>{e||(_(null),y(!1))},footer:m&&(0,J.jsxs)(`a`,{className:`primary resource-download`,href:`${m.url}&download=1`,download:!0,children:[(0,J.jsx)(T,{size:14}),W(`editor.downloadResource`)]}),children:[m?.kind===`large`&&(0,J.jsxs)(`div`,{className:`resource-preview-message`,children:[(0,J.jsx)(A,{size:34}),(0,J.jsx)(`strong`,{children:W(`editor.resourceTooLargeTitle`)}),(0,J.jsx)(`span`,{children:W(`editor.resourceTooLargeDescription`)})]}),m?.kind===`unsupported`&&(0,J.jsxs)(`div`,{className:`resource-preview-message`,children:[(0,J.jsx)(pe,{size:34}),(0,J.jsx)(`strong`,{children:W(`editor.resourceUnsupportedTitle`)}),(0,J.jsx)(`span`,{children:W(`editor.resourceUnsupportedDescription`)})]}),m?.kind===`image`&&(0,J.jsx)(`div`,{className:`resource-image-wrap`,children:(0,J.jsx)(`img`,{className:`resource-image`,src:m.url,alt:m.path})}),m?.kind===`pdf`&&(0,J.jsx)(`iframe`,{className:`resource-pdf`,src:m.url,title:m.path}),m?.kind===`text`&&(h?(0,J.jsxs)(`div`,{className:`resource-preview-message`,children:[(0,J.jsx)(Re,{className:`spin`,size:24}),(0,J.jsx)(`span`,{children:W(`common.loading`)})]}):(0,J.jsx)(`pre`,{className:`resource-text`,children:m.content}))]}),(0,J.jsx)(Ze,{open:!!b,title:W(`editor.uploadOverwriteTitle`),description:W(`editor.uploadOverwriteDescription`,{count:b?.collisions.length??0,files:b?.collisions.join(`, `)??``}),confirmLabel:W(`editor.uploadOverwrite`),danger:!0,onCancel:()=>{x(null),S()},onConfirm:()=>{let e=b;x(null),e&&C(e.files,new Set(e.collisions),e.directory)}}),(0,J.jsx)(Ze,{open:!!w,title:W(w===`cache`?`editor.cleanCacheConfirmTitle`:`editor.cleanArtifactsConfirmTitle`),description:W(w===`cache`?`editor.cleanCacheConfirmDescription`:`editor.cleanArtifactsConfirmDescription`),confirmLabel:W(`editor.cleanConfirm`),danger:w===`artifacts`,onCancel:()=>E(null),onConfirm:()=>{let e=w;E(null),e&&D(e)}}),(0,J.jsx)(Xe,{open:N,title:W(`editor.newFile`),description:W(`editor.newFileDescription`),onOpenChange:e=>{P(e),e||R(``)},footer:(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`button`,{onClick:()=>P(!1),children:W(`common.cancel`)}),(0,J.jsx)(`button`,{className:`primary`,onClick:()=>void se(),children:W(`common.create`)})]}),children:(0,J.jsxs)(J.Fragment,{children:[L&&(0,J.jsx)(`p`,{className:`error dialog-error`,children:L}),(0,J.jsxs)(`label`,{className:`form-field`,children:[W(`editor.filePath`),(0,J.jsx)(`input`,{autoFocus:!0,value:te,onChange:e=>F(e.target.value),onKeyDown:e=>{e.key===`Enter`&&!e.nativeEvent.isComposing&&(e.preventDefault(),se())}})]})]})}),(0,J.jsx)(Xe,{open:ne,title:W(`editor.newFolder`),description:(0,J.jsx)(g,{i18nKey:`editor.folderDestination`,values:{folder:ae||W(`editor.projectRoot`)},components:{path:(0,J.jsx)(`strong`,{className:`folder-destination-path`})}}),onOpenChange:e=>{I(e),e||R(``)},footer:(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`button`,{onClick:()=>I(!1),children:W(`common.cancel`)}),(0,J.jsx)(`button`,{className:`primary`,onClick:()=>void z(),children:W(`common.create`)})]}),children:(0,J.jsxs)(J.Fragment,{children:[L&&(0,J.jsx)(`p`,{className:`error dialog-error`,children:L}),(0,J.jsxs)(`label`,{className:`form-field`,children:[W(`editor.folderName`),(0,J.jsx)(`input`,{autoFocus:!0,value:re,onChange:e=>ie(e.target.value),onKeyDown:e=>{e.key===`Enter`&&z()}})]})]})}),(0,J.jsx)(Xe,{open:!!le,title:W(`editor.moveTitle`,{name:le?.path.split(`/`).at(-1)??``}),description:W(`editor.moveDescription`),onOpenChange:e=>{e||(B(null),H(``),R(``))},footer:(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`button`,{onClick:()=>B(null),children:W(`common.cancel`)}),(0,J.jsx)(`button`,{className:`primary`,disabled:!V.trim(),onClick:()=>void fe(),children:W(`editor.moveApply`)})]}),children:(0,J.jsxs)(J.Fragment,{children:[L&&(0,J.jsx)(`p`,{className:`error dialog-error`,children:L}),(0,J.jsxs)(`label`,{className:`form-field`,children:[W(`editor.pathName`),(0,J.jsx)(`input`,{autoFocus:!0,value:V,onChange:e=>H(e.target.value),onKeyDown:e=>{e.key===`Enter`&&fe()}})]}),(0,J.jsxs)(`label`,{className:`form-field`,children:[W(`editor.destinationFolder`),(0,J.jsxs)(`select`,{value:ue,onChange:e=>de(e.target.value),children:[(0,J.jsx)(`option`,{value:``,children:W(`editor.projectRoot`)}),f.filter(e=>le?.type!==`directory`||e.path!==le.path&&!e.path.startsWith(`${le.path}/`)).map(e=>(0,J.jsx)(`option`,{value:e.path,children:e.path},e.path))]})]})]})}),(0,J.jsx)(Xe,{open:!!me,title:W(`editor.deletePathTitle`,{name:me?.path.split(`/`).at(-1)??``}),description:ge.length?W(`editor.deletePathActiveDescription`,{count:ge.length,path:me?.path??``,users:[...new Set(ge.map(e=>e.name))].join(`, `)}):W(`editor.deletePathDescription`,{path:me?.path??``}),onOpenChange:e=>{e||(he(null),R(``))},footer:(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(`button`,{onClick:()=>he(null),children:W(`common.cancel`)}),(0,J.jsx)(`button`,{className:`danger`,onClick:()=>void _e(),children:W(`common.delete`)})]}),children:(0,J.jsxs)(J.Fragment,{children:[L&&(0,J.jsx)(`p`,{className:`error dialog-error`,children:L}),ge.length>0&&(0,J.jsxs)(`p`,{className:`warning`,children:[(0,J.jsx)(ce,{size:15}),W(`editor.deletePathWillClose`)]})]})}),(0,J.jsx)(Dg,{open:ve,projectId:s,ownerId:o.ownerId,authorId:a.id,selection:be,text:xe,onText:Se,suggestion:r,onSuggestion:i,submitting:Ce,error:we,onSubmit:Te,onClose:ye,onCancel:Ee,draftRestored:De,canRetarget:Oe,onRetarget:ke}),(0,J.jsx)(Eg,{open:Ae,onOpenChange:je,project:o,projectId:s,onMemberCountChange:Me}),Ne&&(0,J.jsx)(Ye,{title:W(`citationLibrary.title`),onClose:()=>Pe(!1),children:(0,J.jsx)(Og,{open:!0,onOpenChange:Pe,currentFile:c,currentSource:l,readOnly:p,currentUserId:a.id,maxBibtexBytes:u,onInsert:Fe})}),O&&(0,J.jsx)(Ye,{title:W(`gallery.title`),onClose:()=>k(!1),children:(0,J.jsx)(Mg,{folder:j,onClose:()=>k(!1),onImport:ee})}),Ie&&(0,J.jsx)(q.Suspense,{fallback:null,children:(0,J.jsx)(Ng,{open:!0,files:d,onOpenChange:Le,onOpenFile:e=>{let t=d.find(t=>t.path===e);t&&ze(t)}})}),e&&(0,J.jsx)(Ye,{title:W(`projectSearch.title`),onClose:()=>t(!1),children:(0,J.jsx)(Pg,{projectId:s,readOnly:p,onClose:()=>t(!1),onNavigate:n})}),Ve&&(0,J.jsx)(q.Suspense,{fallback:null,children:(0,J.jsx)(jg,{open:!0,onOpenChange:e=>{e||He()},project:o,filePath:Ve.filePath,selection:Ve.selection,currentSource:Ve.source})}),Ue&&(0,J.jsx)(q.Suspense,{fallback:null,children:(0,J.jsx)(Ag,{open:!0,onOpenChange:U,project:o,onBeforeMutation:o.permission===`read`?async()=>!0:Ke})}),o.ownerId===a.id&&We&&(0,J.jsx)(q.Suspense,{fallback:null,children:(0,J.jsx)(kg,{open:!0,onOpenChange:Ge,project:o,onBeforeMutation:Ke})})]})}function Ig({participants:e,selectedIds:t,topLevelOnly:n,onToggle:r,onClear:i,onTopLevelOnlyChange:a}){let{t:o}=v(),[s,c]=(0,q.useState)(!1),l=(0,q.useRef)(null),u=t.size>0,d=e.find(e=>t.has(e.authorId)),f=e=>e.authorDisplayName??e.authorUsername??o(`editor.deletedUser`),p=u?d?t.size===1?f(d):o(`editor.commentParticipantsSelected`,{name:f(d),count:t.size-1}):o(`editor.commentParticipantsCount`,{count:t.size}):o(`editor.commentParticipantsAll`);return(0,J.jsx)(`div`,{className:`comment-participant-filter`,children:(0,J.jsxs)(`div`,{className:`comment-participants-trigger-group${u?` active`:``}`,children:[(0,J.jsxs)(ie,{open:s,onOpenChange:c,children:[(0,J.jsx)(P,{asChild:!0,children:(0,J.jsxs)(`button`,{type:`button`,className:`comment-participants-toggle`,"aria-label":`${o(`editor.commentParticipants`)}: ${p}`,children:[(0,J.jsx)(j,{size:13,"aria-hidden":!0}),(0,J.jsx)(`span`,{className:`comment-participants-summary`,children:u&&d?f(d):p}),u&&d&&t.size>1&&(0,J.jsxs)(`span`,{className:`comment-participants-extra-count`,children:[`+`,t.size-1]}),(0,J.jsx)(H,{size:12,"aria-hidden":!0,className:s?`expanded`:``})]})}),(0,J.jsx)(se,{children:(0,J.jsxs)(N,{ref:l,className:`comment-participants-popover`,side:`bottom`,align:`end`,sideOffset:6,collisionPadding:10,"aria-label":o(`editor.commentParticipants`),onOpenAutoFocus:e=>{e.preventDefault();let t=l.current?.querySelector(`input[type="checkbox"]:not(:disabled)`);t?t.focus():l.current?.focus()},children:[(0,J.jsxs)(`div`,{className:`comment-participants-heading`,children:[(0,J.jsx)(le,{children:o(`editor.commentParticipants`)}),u&&(0,J.jsx)(`button`,{type:`button`,onClick:i,children:o(`editor.commentParticipantsClear`)})]}),(0,J.jsxs)(`div`,{className:`comment-participants-list`,children:[e.map(e=>{let n=f(e),i=t.has(e.authorId);return(0,J.jsxs)(`label`,{className:`comment-participant-option${i?` selected`:``}`,children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:i,onChange:()=>r(e.authorId)}),(0,J.jsx)(F,{userId:e.authorId,name:n,username:e.authorUsername,avatarStyle:e.authorAvatarStyle,className:`comment-participant-avatar`}),(0,J.jsxs)(`span`,{className:`comment-participant-identity`,children:[(0,J.jsx)(`strong`,{children:n}),e.authorUsername&&(0,J.jsxs)(`small`,{children:[`@`,e.authorUsername]})]})]},e.authorId??`deleted`)}),e.length===0&&(0,J.jsx)(`p`,{className:`comment-participants-empty`,children:o(`editor.commentNoParticipants`)})]}),(0,J.jsxs)(`label`,{className:`comment-participants-root-only`,children:[(0,J.jsx)(`input`,{type:`checkbox`,checked:n,disabled:!u,onChange:e=>a(e.target.checked)}),o(`editor.commentTopLevelOnly`)]})]})})]}),u&&(0,J.jsx)(`button`,{type:`button`,className:`comment-participants-clear`,"aria-label":o(`editor.commentParticipantsClear`),onClick:i,children:(0,J.jsx)(z,{size:12,"aria-hidden":!0})})]})})}function Lg(e,t,n,r,i){let a=t.map(e=>({comment:e,exitAt:null})),o=new Set(t.map(e=>e.id)),s=new Map(n.map(e=>[e.id,e]));return e.forEach((e,t)=>{let n=s.get(e.comment.id);o.has(e.comment.id)||!n||op(n,r)||a.splice(Math.min(t,a.length),0,{comment:n,exitAt:e.exitAt??i+280+50})}),a}function Rg(e,t,n,r){let[i,a]=(0,q.useState)(()=>({contextKey:r,visible:e,comments:t,entries:e.map(e=>({comment:e,exitAt:null}))}));(i.contextKey!==r||i.visible!==e||i.comments!==t)&&a({contextKey:r,visible:e,comments:t,entries:i.contextKey===r?Lg(i.entries,e,t,n,Date.now()):e.map(e=>({comment:e,exitAt:null}))});let o=(0,q.useCallback)(e=>{a(t=>({...t,entries:t.entries.filter(t=>t.comment.id!==e||t.exitAt===null)}))},[]);return(0,q.useEffect)(()=>{let e=i.entries.flatMap(e=>e.exitAt===null?[]:[e.exitAt]);if(!e.length)return;let t=window.setTimeout(()=>{let e=Date.now();a(t=>({...t,entries:t.entries.filter(t=>t.exitAt===null||t.exitAt>e)}))},Math.max(0,Math.min(...e)-Date.now()));return()=>window.clearTimeout(t)},[i.entries]),{entries:i.entries,finishExit:o}}function zg(e,t,n,r){let[i,a]=(0,q.useState)(()=>({contextKey:n,limit:50})),o=i.contextKey===n?i.limit:50;if(t)for(let t of r){if(!t)continue;let n=e.findIndex(e=>e.id===t)+1;o=Math.max(o,Math.ceil(n/50)*50)}(i.contextKey!==n||i.limit!==o)&&a({contextKey:n,limit:o});let s=(0,q.useMemo)(()=>t?e.slice(0,o):e,[e,t,o]),c=(0,q.useCallback)(()=>{a(e=>({contextKey:n,limit:(e.contextKey===n?e.limit:50)+50}))},[n]);return{shown:s,hasMore:s.length<e.length,loadMore:c}}var Bg=(0,q.lazy)(()=>S(()=>import(`./ProjectSettings-BwQTbXhh.js`).then(e=>({default:e.ProjectSettings})),__vite__mapDeps([62,2,3,32,5,4,7,9,16,17,12,1,6,8,10,11,13,40,53,33,37,41,42,63,64,39,65,66,44]),import.meta.url));function Vg({phone:e=!1,commentsHost:t,sidePanel:n,onClose:r,project:i,projectId:s,site:c,files:l,currentUserId:u,comments:d,commentDraftStore:f,commentsLoading:p,commentsError:m,onRetryComments:h,unreadMentions:g,activeFile:_,singleCommentId:y,onShowAllComments:b,hasProjectCommentsScope:x,commentScope:S,onCommentScopeChange:C,focusedCommentId:T,commentFocusNonce:E,onMarkMentionRead:D,onMarkAllMentionsRead:k,onClearFocusComment:A,targetCommentId:j,targetReplyId:M,onFocusComment:ee,onToggleComment:N,onReplyComment:P,onEditComment:te,onDeleteComment:F,onEditCommentReply:ne,onDeleteCommentReply:I,dictionaryWords:re,onDictionaryChange:ie,editorPreferences:ae,onEditorPreferences:L,spellCheckCount:R,spellCheckUniqueCount:oe,spellCheckIndex:se,onSpellCheckNavigate:ce,onProject:le}){let{t:B}=v(),V=!!y,[H,ue]=(0,q.useState)(`unresolved`),[de,fe]=(0,q.useState)(!1),[pe,me]=(0,q.useState)(`source`),he=B(pe===`time`?`editor.commentSortTime`:S===`project`?`editor.commentSortSourceProject`:`editor.commentSortSource`),[ge,_e]=(0,q.useState)(()=>new Set),[ve,ye]=(0,q.useState)(!0),[be,Se]=(0,q.useState)(()=>new Map),[Ce,we]=(0,q.useState)(null),Te=(0,q.useRef)(new Map(d.map(e=>[e.id,e.resolved]))),Ee=(0,q.useMemo)(()=>np(d),[d]),ke=(0,q.useMemo)(()=>{let e=d.filter(e=>ap(e,{activeFile:_,scope:S})),t=e.filter(e=>e.resolved).length;return{unresolved:e.length-t,resolved:t}},[_,S,d]),Ae=(0,q.useMemo)(()=>cp(d,{activeFile:_,scope:S,unreadMentions:g,participantIds:ge,topLevelOnly:ve,filter:H,unreadMentionsOnly:!0}).length,[_,S,d,g,ge,ve,H]),je=(0,q.useMemo)(()=>y?up(d,y,_):lp(d,{activeFile:_,scope:S,filter:H,unreadMentions:g,sort:pe,participantIds:ge,topLevelOnly:ve,unreadMentionsOnly:de},[j,T]),[_,y,H,S,d,T,j,g,pe,ge,ve,de]),Me=T&&je.some(e=>e.id===T)?T:j&&je.some(e=>e.id===j)?j:null,Ne=V?je[0]?.id??null:Ce&&je.some(e=>e.id===Ce)?Ce:Me;(0,q.useEffect)(()=>{we(null)},[T,E,j,M,_,S]),(0,q.useEffect)(()=>{Ce&&!je.some(e=>e.id===Ce)&&we(null)},[Ce,je]);let Pe=mp(je,Ne),Fe=JSON.stringify([n,y,S,S===`file`?_:``,H,pe,[...ge].sort(),ve,de]),Ie=JSON.stringify([s,S,S===`file`?_:``,H,pe,[...ge].sort(),ve,de]),{shown:Le,hasMore:Re,loadMore:ze}=zg(je,!V&&H===`resolved`,Ie,[j,T,Ce]),{entries:Be,finishExit:Ve}=Rg(Le,d,V?`unresolved`:H,Fe);(0,q.useEffect)(()=>{let e=d.some(e=>(e.id===T||e.id===j)&&Te.current.has(e.id)&&Te.current.get(e.id)!==e.resolved);Te.current=new Map(d.map(e=>[e.id,e.resolved])),e&&A()},[d,T,j,A]),(0,q.useEffect)(()=>{if(n!==`comments`||Ce)return;let e=j&&M?`.comments [data-comment-reply-id="${M}"]`:j?`.comments .comment-thread[data-comment-id="${j}"]`:Me?`.comments .comment-thread[data-comment-id="${Me}"]`:``;if(!e)return;let t=document.querySelector(e);if(!t)return;let r=window.requestAnimationFrame(()=>t.scrollIntoView({block:j?`center`:`nearest`,behavior:`smooth`}));return()=>window.cancelAnimationFrame(r)},[n,Ce,Me,E,j,M,je]);let He=e=>{we(null),ee(e)},Ue=e=>{let t=hp(je,Ne,e);t?He(t):A()},U=async e=>{let t=await D(e);if(!t||V||!de)return t;let n=g.find(t=>t.id===e)?.commentId;return n&&(g.some(t=>t.id!==e&&t.commentId===n)||(T===n||j===n)&&A()),t},We=async()=>{await k()&&de&&A()},Ge=e=>{e!==S&&(we(null),A(),C(e))},Ke=e=>{e!==H&&(we(null),A(),ue(e))},qe=()=>{we(null),A()},Je=e=>{qe(),ge.size===1&&ge.has(e)&&ye(!0),_e(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})};if(!n)return null;let Ye=(0,J.jsxs)(`aside`,{className:`context-panel`,"aria-label":B(n===`comments`?`editor.sourceComments`:`editor.projectSettings`),children:[n===`comments`&&(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(`div`,{className:`drawer-title`,children:[(0,J.jsx)(`strong`,{children:B(V?`editor.currentComment`:`editor.sourceComments`)}),(0,J.jsxs)(`span`,{className:`drawer-title-actions`,children:[!V&&g.length>0&&(0,J.jsxs)(`button`,{className:`drawer-mention-read-all`,type:`button`,onClick:()=>void We(),title:B(`editor.markAllMentionsRead`),children:[(0,J.jsx)(o,{"aria-hidden":!0,size:13}),(0,J.jsx)(`span`,{children:B(`editor.markAllMentionsRead`)})]}),(0,J.jsx)(`button`,{"aria-label":B(`common.close`),onClick:r,children:(0,J.jsx)(z,{size:17})})]})]}),V?(0,J.jsx)(`div`,{className:`comment-current-controls`,children:(0,J.jsxs)(`button`,{type:`button`,onClick:b,children:[(0,J.jsx)(zt,{size:14,"aria-hidden":!0}),B(`editor.viewAllComments`)]})}):(0,J.jsxs)(`div`,{className:`comment-review-controls`,children:[(0,J.jsxs)(`div`,{className:`comment-review-queue-row`,children:[x&&(0,J.jsxs)(`div`,{className:`comment-review-group`,role:`group`,"aria-label":B(`editor.commentScope`),children:[(0,J.jsx)(`button`,{type:`button`,className:S===`file`?`active`:``,"aria-pressed":S===`file`,onClick:()=>Ge(`file`),children:B(`editor.commentScopeFile`)}),(0,J.jsx)(`button`,{type:`button`,className:S===`project`?`active`:``,"aria-pressed":S===`project`,onClick:()=>Ge(`project`),children:B(`editor.commentScopeProject`)})]}),(0,J.jsxs)(`div`,{className:`comment-review-group`,role:`group`,"aria-label":B(`editor.commentFilter`),children:[(0,J.jsx)(`button`,{type:`button`,className:H===`unresolved`?`active`:``,"aria-pressed":H===`unresolved`,onClick:()=>Ke(`unresolved`),children:B(`editor.commentFilterUnresolved`,{count:ke.unresolved})}),(0,J.jsx)(`button`,{type:`button`,className:H===`resolved`?`active`:``,"aria-pressed":H===`resolved`,onClick:()=>Ke(`resolved`),children:B(`editor.commentFilterResolved`,{count:ke.resolved})})]}),(0,J.jsxs)(`div`,{className:`comment-review-navigation`,children:[(0,J.jsx)(`button`,{type:`button`,disabled:Pe<=1,"aria-label":B(`editor.commentPrevious`),title:B(`editor.commentPrevious`),onClick:()=>Ue(-1),children:(0,J.jsx)(a,{size:14})}),(0,J.jsx)(`output`,{"aria-live":`polite`,children:B(`editor.commentPosition`,{current:Pe,total:je.length})}),(0,J.jsx)(`button`,{type:`button`,disabled:je.length===0||Pe>0&&Pe>=je.length,"aria-label":B(`editor.commentNext`),title:B(`editor.commentNext`),onClick:()=>Ue(1),children:(0,J.jsx)(O,{size:14})})]})]}),(0,J.jsxs)(`div`,{className:`comment-review-sort-row`,children:[(0,J.jsx)(Ig,{participants:Ee,selectedIds:ge,topLevelOnly:ve,onToggle:Je,onClear:()=>{qe(),_e(new Set),ye(!0)},onTopLevelOnlyChange:e=>{qe(),ye(e)}},`${S}:${S===`file`?_:`project`}`),(0,J.jsxs)(`button`,{type:`button`,className:`comment-unread-toggle${de?` active`:``}`,"aria-pressed":de,"aria-label":B(`editor.commentUnreadMentionsHint`),title:B(`editor.commentUnreadMentionsHint`),onClick:()=>{qe(),fe(e=>!e)},children:[(0,J.jsx)(o,{size:12,"aria-hidden":!0}),B(`editor.commentUnreadMentionsOnly`),(0,J.jsx)(`span`,{children:Ae})]}),(0,J.jsxs)(`label`,{className:`comment-review-sort`,"data-texlite-tooltip-always":!0,"data-tooltip":he,children:[(0,J.jsx)(`span`,{className:`sr-only`,children:B(`editor.commentSort`)}),pe===`source`?(0,J.jsx)(w,{size:12,"aria-hidden":!0}):(0,J.jsx)(Ct,{size:12,"aria-hidden":!0}),(0,J.jsxs)(`select`,{value:pe,"aria-label":`${B(`editor.commentSort`)}: ${he}`,onChange:e=>{qe(),me(e.target.value)},children:[(0,J.jsx)(`option`,{value:`source`,children:B(`editor.commentSortSourceShort`)}),(0,J.jsx)(`option`,{value:`time`,children:B(`editor.commentSortTimeShort`)})]})]})]})]}),m&&(0,J.jsxs)(`div`,{className:`comment-review-error`,role:`alert`,children:[(0,J.jsx)(`span`,{children:m}),(0,J.jsx)(`button`,{type:`button`,onClick:()=>void h(),children:B(`common.retry`)})]}),p&&(0,J.jsx)(`div`,{className:`comment-review-loading`,role:`status`,children:B(`common.loading`)}),(0,J.jsxs)(`div`,{className:`comments`,children:[Be.map(({comment:e,exitAt:t})=>{let n=g.find(t=>t.commentId===e.id&&!t.replyId)?.id,r=new Map(g.filter(t=>t.commentId===e.id&&t.replyId).map(e=>[e.replyId,e.id]));return(0,J.jsx)(`div`,{className:`comment-thread-slot${t===null?``:` is-exiting`}`,inert:t!==null||void 0,"aria-hidden":t!==null||void 0,style:{"--comment-exit-duration":`280ms`},onAnimationEnd:n=>{n.target===n.currentTarget&&t!==null&&Ve(e.id)},children:(0,J.jsx)(`div`,{className:`comment-thread-slot-content`,children:(0,J.jsx)(Tg,{projectId:s,comment:e,draftStore:f,currentUserId:u,projectOwnerId:i.ownerId,canEditSource:i.permission!==`read`,unreadCommentMentionKind:g.find(e=>e.id===n)?.kind,unreadCommentMentionId:n,unreadReplyMentionIds:r,highlightedComment:j===e.id&&!M,highlightedReplyId:j===e.id?M:null,currentComment:Ne===e.id,showFilePath:!V&&S===`project`&&x,replyExpansion:be.get(e.id),onReplyExpansionChange:t=>{Se(n=>n.get(e.id)===t?n:new Map(n).set(e.id,t))},selectedParticipantIds:V?void 0:ge,highlightReplyParticipants:!V&&!ve,onMarkMentionRead:U,onFocus:()=>He(e),onActivate:()=>we(e.id),onToggle:()=>N(e),onReply:t=>P(e,t),onEdit:t=>te(e,t),onDelete:()=>F(e),onEditReply:(t,n)=>ne(e,t,n),onDeleteReply:t=>I(e,t)})})},e.id)}),Be.length===0&&!p&&!m&&(0,J.jsxs)(`div`,{className:`comment-review-empty`,role:`status`,children:[(0,J.jsx)(`span`,{className:`comment-review-empty-icon`,"aria-hidden":`true`,children:(0,J.jsx)(zt,{size:23,strokeWidth:1.5})}),(0,J.jsx)(`p`,{children:V?B(d.some(e=>e.id===y&&e.resolved)?`editor.currentCommentResolved`:`editor.currentCommentUnavailable`):ke.unresolved+ke.resolved>0?B(`editor.commentNoMatches`):B(`editor.noComments`)})]}),!V&&H===`resolved`&&Re&&(0,J.jsx)(`div`,{className:`comment-review-pagination`,children:(0,J.jsx)(`button`,{type:`button`,onClick:ze,children:B(`editor.commentLoadMore`)})})]})]}),n===`settings`&&(0,J.jsx)(W,{onClose:r,children:(0,J.jsx)(Bg,{onClose:r,project:i,projectId:s,site:c,files:l,dictionaryWords:re,onDictionaryChange:ie,editorPreferences:ae,onEditorPreferences:L,spellCheckCount:R,spellCheckUniqueCount:oe,spellCheckIndex:se,onSpellCheckNavigate:ce,onProject:le},s)})]});return e?(0,J.jsx)(De,{open:!0,title:B(n===`comments`?`editor.sourceComments`:`editor.projectSettings`),onClose:r,children:Ye}):n===`comments`&&t!==void 0?t?(0,Rh.createPortal)(Ye,t):null:(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(Oe,{className:`resize-handle`}),(0,J.jsx)(xe,{id:`context`,defaultSize:`20%`,minSize:`15%`,maxSize:`38%`,children:Ye})]})}function Hg(e,t){return b(`texlite.markdownPreview:${encodeURIComponent(e)}:${encodeURIComponent(t)}`)}function Ug(e,t){let n=()=>qe(Hg(e,t))!==`pdf`,[r,i]=(0,q.useState)(n);return(0,q.useEffect)(()=>i(n()),[e,t]),[r,n=>{i(n),$e(Hg(e,t),n?`markdown`:`pdf`)}]}function Wg(e,t,n){return e.mainFile===t?e.items:!t||n.filePath!==t?[]:Gg(n.content).map(e=>({...e,path:t}))}function Gg(e){let t=[],n=/^\s*\\(part|chapter|section|subsection|subsubsection)\*?(?:\[[^\]]*\])?\{([^}]*)\}/,r={part:0,chapter:0,section:1,subsection:2,subsubsection:3};return e.split(`
|
|
13
|
+
`).forEach((e,i)=>{let a=e.match(n);a&&t.push({level:r[a[1]],title:a[2],line:i+1})}),t}var Kg=e({ProjectWorkspace:()=>Qg}),qg=(0,q.lazy)(()=>S(()=>import(`./AgentTerminal-DZo-22RN.js`).then(e=>({default:e.AgentTerminal})),__vite__mapDeps([67,2,3,32,5,4,7,9,16,17,12,1,6,8,10,11,13,33,34,68,69,53,40,37,41,42,48,36,38,64,39]),import.meta.url)),Jg=(0,q.lazy)(()=>S(()=>import(`./WordCountDialog-ByxE-RUs.js`).then(e=>({default:e.WordCountDialog})),__vite__mapDeps([70,3,2,4,5,16,7,9,17,12,1,6,8,10,11,13,53,33,40,37,41,42,66]),import.meta.url)),Yg=null;function Xg(){return Yg||=S(()=>import(`./citationLibrary-DxGdbZEQ.js`),__vite__mapDeps([43,20,18,21,24]),import.meta.url).catch(e=>{throw Yg=null,e}),Yg}var Zg=300;function Qg(e){return(0,J.jsx)(_p,{children:(0,J.jsx)(Wm,{projectId:e.projectId,user:e.user,children:t=>(0,J.jsx)($g,{...e,collaboration:t})})},`${e.user.id}:${e.projectId}`)}function $g({site:e,user:t,projectId:n,preload:r,mentionId:i=null,onMentionTargeted:a,onMentionsRead:o,onBack:s,collaboration:c}){let{t:u}=v(),d=(0,q.useRef)(n),f=l(t.id,n),[p,m]=(0,q.useState)(!1),h=Lh(t.id,n,f.activeCount>0),[g,_]=(0,q.useState)(null),[b,x]=(0,q.useState)(null),S=(0,q.useRef)(0),[C,w]=(0,q.useState)(null);d.current=n;let[T,E]=(0,q.useState)(null),D=(0,q.useCallback)((e,t)=>{E(n=>n?.id===e&&n.sharedMemberCount!==t?{...n,sharedMemberCount:t}:n)},[]);(0,q.useEffect)(()=>(document.title=T?.name?`${e.siteName} | ${T.name}`:e.siteName,()=>{document.title=e.siteName}),[T?.name,e.siteName]);let[O,k]=(0,q.useState)([]),[A,j]=(0,q.useState)(null),[M,ee]=(0,q.useState)({mainFile:``,items:[]}),[N,P]=(0,q.useState)(``),[F,ne]=(0,q.useState)(``),[I,re]=(0,q.useState)(``),[ie,L]=(0,q.useState)({filePath:``,content:``}),[oe,se]=(0,q.useState)({path:``,hasIncludes:!1}),[le,B]=(0,q.useState)(``),[V,H]=(0,q.useState)(!1),[ue,de]=(0,q.useState)(`editor.saved`),[fe,pe]=(0,q.useState)(null),he=(0,q.useRef)(fe);he.current=fe;let ge=(0,q.useRef)(null);ge.current||=je();let _e=ge.current,[ve,ye]=(0,q.useState)(`pdf`),[be,xe]=(0,q.useState)(`log`),Se=e=>{e===`pdf`?ye(`pdf`):(e===`diagnostics`||xe(e),ye(`diagnostics`))},{workspaceLayout:Ce,setWorkspaceLayout:we,phone:Ee}=gh(t.id,n),[De,Ae]=Ug(t.id,n),Pe=yh(N),Fe=bh(ve,Pe,De),Ie=e=>{e===`markdown`?Ae(!0):e===`pdf`&&Pe&&Ae(!1),Se(e===`markdown`?`pdf`:e)},[Le,ze]=(0,q.useState)(null),[Be,Ve]=(0,q.useState)(!1),[He,U]=(0,q.useState)(``),[Ge,qe]=(0,q.useState)(``),[Je,Xe]=(0,q.useState)({selectedText:``,startOffset:0,endOffset:0}),Ze=(0,q.useRef)({selectedText:``,startOffset:0,endOffset:0}),Qe=e=>{let t=Ze.current;(t.selectedText!==e.selectedText||t.startOffset!==e.startOffset||t.endOffset!==e.endOffset)&&(Ze.current=e,Xe(e))},[$e,W]=(0,q.useState)(null),[et,tt]=(0,q.useState)(null),[nt,rt]=(0,q.useState)(null),[it,at]=(0,q.useState)(null),[ot,st]=(0,q.useState)(null),[ct,lt]=(0,q.useState)(null),[ut,dt]=(0,q.useState)(!1),[ft,pt]=(0,q.useState)(!1),[mt,ht]=(0,q.useState)(!1),[gt,_t]=(0,q.useState)(!1),[vt,yt]=(0,q.useState)(null),[bt,xt]=(0,q.useState)(!1),[St,Ct]=(0,q.useState)(null),[wt,Tt]=(0,q.useState)(!1),[Et,Dt]=(0,q.useState)(!1),[Ot,kt]=(0,q.useState)(!1),[At,jt]=(0,q.useState)(!1),[Mt,Nt]=(0,q.useState)(`full`),[Pt,Ft]=(0,q.useState)(``),[It,Lt]=(0,q.useState)(!1),[Rt,zt]=(0,q.useState)(``),[Bt,Vt]=(0,q.useState)(null),[Ht,Ut]=(0,q.useState)(null),[Wt,Gt]=(0,q.useState)(!1),[Kt,qt]=(0,q.useState)(null),[Jt,Yt]=(0,q.useState)(!1),[Xt,Zt]=(0,q.useState)(()=>ae(t.id,n));(0,q.useEffect)(()=>{let e=document.documentElement,t=Xt.showTooltips?`on`:`off`;return e.setAttribute(`data-texlite-tooltips`,t),()=>{e.getAttribute(`data-texlite-tooltips`)===t&&e.removeAttribute(`data-texlite-tooltips`)}},[Xt.showTooltips]);let[Qt,$t]=(0,q.useState)([]),en=(0,q.useRef)([]);en.current=Qt;let tn=(0,q.useRef)(null),nn=(0,q.useRef)(null),rn=(0,q.useRef)(0),an=(0,q.useRef)(0),on=(0,q.useRef)(``),sn=(0,q.useRef)(``),cn=(0,q.useRef)(()=>void 0),ln=(0,q.useRef)(Ce),un=(0,q.useRef)(0),dn=(0,q.useRef)(null),fn=(0,q.useRef)(null),pn=(0,q.useRef)(null),mn=(0,q.useRef)(null),hn=(0,q.useRef)(null),gn=(0,q.useRef)(null),_n=(0,q.useRef)(null),vn=(0,q.useRef)(null),yn=(0,q.useRef)(null),bn=(0,q.useRef)(!1),xn=(0,q.useRef)(null),Sn=(0,q.useRef)(s),Cn=(0,q.useRef)(a),wn=(0,q.useRef)(o);Sn.current=s,Cn.current=a,wn.current=o,on.current=N,sn.current=F,ln.current=Ce,(0,q.useEffect)(()=>{if(!Ge)return;let e=window.setTimeout(()=>qe(``),3e3);return()=>window.clearTimeout(e)},[Ge]);let Tn=(0,q.useCallback)((e,t,n=0)=>{_e.update(e,t,n)},[_e]);(0,q.useEffect)(()=>()=>_e.dispose(),[_e]),(0,q.useEffect)(()=>()=>{vn.current?.abort(),vn.current=null},[]);let En=e=>{let t=en.current,n=e(t);n!==t&&(en.current=n,$t(n))};(0,q.useEffect)(()=>{en.current=[],$t([]),qt(null),yt(null),gn.current?.abort(),gn.current=null,_n.current?.abort(),_n.current=null,vn.current?.abort(),vn.current=null,yn.current=null,at(null),st(null),lt(null),jt(!1),Lt(!1),zt(``),Vt(null),Ut(null)},[n]);let Dn=e=>{let t=en.current,n=t.indexOf(e);if(n<0)return;let r=t.filter(t=>t!==e);if(en.current=r,$t(r),on.current!==e)return;let i=r.length>0?r[Math.min(n,r.length-1)]:T?.mainFile??``;P(i)},{status:On,synced:kn,activeSessions:An,formatLeaseStates:jn,compileState:Y,setCompileState:Mn,filesEvent:X,commentsRevision:Nn,historyWarning:Z,dictionaryRevision:Pn,chktexSettingsRevision:Fn,localDraftReady:In,permission:Ln,reconnect:Rn,protocolUpgradeRequired:zn,permissionDowngrade:Bn,dismissPermissionDowngrade:Vn,discardLocalDraft:Hn}=yp(c,F,T?.permission??`read`,T?.id===n),{unreadMentions:Un,mentionsError:Wn,markMentionRead:Gn,markAllMentionsRead:Kn}=gp(n,Nn,U,(e,t)=>wn.current?.(e,t)),{pdfTarget:qn,pdfViewport:Jn,sourceJump:Yn,setPdfViewport:Xn,resetPdfViewport:Zn,clearPdfViewport:Qn,jumpToSource:$n,syncSourceToPdf:er,syncPdfToSource:tr,syncVisiblePdfToSource:nr}=ph({projectId:n,mainFile:F,activeFile:N,onOpenSourceFile:e=>cn.current(e),onError:U,onShowPdf:()=>{Se(`pdf`),Ee&&we(`pdf-only`)},onShowEditor:()=>{ln.current===`pdf-only`&&we(`editor-pdf`)}}),rr=!!(T&&T.chktexEnabled&&N&&kn&&yu(N)),ir=dh({active:rr,projectId:n,activeFile:N,content:I}),ar=lh({active:!!(T&&N&&kn&&vu(N)&&(Xt.spellCheck||T.chktexEnabled&&yu(N))),harperEnabled:Xt.spellCheck,projectId:n,activeFile:N,content:I,dictionaryWords:O,additionalIssues:ir.issues,additionalIssuesReady:!rr||ir.checked});(0,q.useEffect)(()=>{Zt(ae(t.id,n))},[t.id,n]);let or=e=>{re(e)};(0,q.useEffect)(()=>{if(!N||le!==N){L(e=>e.filePath||e.content?{filePath:``,content:``}:e);return}let e=N,t=I,n=window.setTimeout(()=>{L(n=>n.filePath===e&&n.content===t?n:{filePath:e,content:t})},Zg);return()=>window.clearTimeout(n)},[N,le,I]),(0,q.useEffect)(()=>{on.current=N,_e.reset(),Qe({selectedText:``,startOffset:0,endOffset:0}),Xt.openFilesInTabs?N&&En(e=>e.includes(N)?e:[...e,N]):en.current.length>0&&(en.current=[],$t([]))},[N,Xt.openFilesInTabs,n,_e]),(0,q.useEffect)(()=>{if(!V)return;let e=e=>{e.preventDefault(),e.returnValue=``};return window.addEventListener(`beforeunload`,e),()=>window.removeEventListener(`beforeunload`,e)},[V]),(0,q.useEffect)(()=>{if(On!==`disconnected`)return;let e=new AbortController;return G(`/api/projects/${n}`,{signal:e.signal}).then(({project:t})=>{e.signal.aborted||(E(t),U(``))}).catch(e=>{We(e)||(e instanceof Ue&&[401,403,404].includes(e.status)?(U(K(e)),Sn.current()):U(u(`errors.collaborationUnavailable`)))}),()=>e.abort()},[On,n,u]);let sr=async(e={},t=sn.current)=>{dn.current?.abort(),dn.current=null;let r=e.signal?null:new AbortController;r&&(dn.current=r);try{let i=t?`?mainFile=${encodeURIComponent(t)}`:``,a=await G(`/api/projects/${n}/completions${i}`,{signal:e.signal??r?.signal});(!e.isCurrent||e.isCurrent())&&j(a.index)}catch(t){if(We(t))return;(!e.isCurrent||e.isCurrent())&&j(null)}finally{r&&dn.current===r&&(dn.current=null)}},cr=async(e={},t=sn.current)=>{pn.current?.abort(),pn.current=null;let r=e.signal?null:new AbortController;r&&(pn.current=r);try{let i=t?`?mainFile=${encodeURIComponent(t)}`:``,a=await G(`/api/projects/${n}/outline${i}`,{signal:e.signal??r?.signal});(!e.isCurrent||e.isCurrent())&&sn.current===t&&ee({mainFile:t,items:a.outline})}catch(e){if(We(e))return}finally{r&&pn.current===r&&(pn.current=null)}},lr=async(e={})=>{mn.current?.abort(),mn.current=null;let t=e.signal?null:new AbortController;t&&(mn.current=t);try{let r=await G(`/api/projects/${n}/dictionary`,{signal:e.signal??t?.signal});(!e.isCurrent||e.isCurrent())&&k(r.words)}catch(t){if(We(t))return;(!e.isCurrent||e.isCurrent())&&k([])}finally{t&&mn.current===t&&(mn.current=null)}};(0,q.useEffect)(()=>{let e=!1,t=++un.current,i=new AbortController,a=()=>!e&&un.current===t,o=!1,s=``;E(null),xr([]),ee({mainFile:``,items:[]}),P(``),ne(``),se({path:``,hasIncludes:!1}),re(``),B(``),Mn(null),Qn(),j(null),k([]),Ke();let c=(r?.projectId===n?r.project:G(`/api/projects/${n}`,{signal:i.signal})).then(e=>{a()&&(o=!0,s=e.project.mainFile,E(e.project),P(e.project.mainFile),sn.current=e.project.mainFile,ne(e.project.mainFile),Hr(new Set(th(e.project.mainFile))))}).catch(e=>{a()&&U(K(e))}),l=G(`/api/projects/${n}/files`,{signal:i.signal}).then(e=>{a()&&xr(e.files)}).catch(e=>{a()&&U(K(e))}),u=null;return Promise.allSettled([c,l]).then(()=>{a()&&o&&(u=window.setTimeout(()=>{a()&&Promise.all([sr({signal:i.signal,isCurrent:a},sn.current||s),lr({signal:i.signal,isCurrent:a})])},0))}),()=>{e=!0,u!==null&&window.clearTimeout(u),i.abort(),dn.current?.abort(),dn.current=null,pn.current?.abort(),pn.current=null,mn.current?.abort(),mn.current=null,hn.current?.abort(),hn.current=null}},[n,r]),(0,q.useEffect)(()=>{T&&F&&(fn.current===n?sr({},F):fn.current=n)},[F,T?.id,n]),(0,q.useEffect)(()=>{if(!i||!T)return;_n.current?.abort();let e=new AbortController;return _n.current=e,G(`/api/projects/${n}/mentions/${encodeURIComponent(i)}`,{signal:e.signal}).then(({mention:t})=>{e.signal.aborted||(at(t),rt(null),W(`comments`),P(t.filePath),Cn.current?.(t.id))}).catch(t=>{We(t)||e.signal.aborted||(U(K(t)),Cn.current?.(i))}).finally(()=>{_n.current===e&&(_n.current=null)}),()=>e.abort()},[i,T?.id,n]),(0,q.useEffect)(()=>{Pn&&lr()},[Pn,n]),(0,q.useEffect)(()=>{if(!Fn)return;let e=new AbortController;return G(`/api/projects/${n}`,{signal:e.signal}).then(({project:t})=>{e.signal.aborted||E(e=>e?{...e,chktexEnabled:t.chktexEnabled}:t)}).catch(e=>{We(e)||U(K(e))}),()=>e.abort()},[Fn,n]),(0,q.useEffect)(()=>{T&&On===`connected`&&Ln!==T.permission&&E(e=>e&&{...e,permission:Ln})},[Ln,T?.permission]),(0,q.useEffect)(()=>{if(!X)return;let t=X.kind===`delete`&&!!X.path&&nh(X.path,on.current),r=X.kind===`delete`&&!!X.path&&nh(X.path,sn.current);if(X.kind===`move`&&X.source&&X.destination){let e=X.source,t=X.destination,n=n=>n===e?t:n.startsWith(`${e}/`)?`${t}${n.slice(e.length)}`:n;P(e=>n(e)),ne(e=>n(e)),Rr(e=>e&&n(e)),Br(e=>e&&n(e)),En(e=>e.map(n))}t&&(P(``),B(``),or(``),qe(u(`editor.fileDeletedByCollaborator`,{path:X.path}))),X.kind===`delete`&&X.path&&(Rr(e=>e&&nh(X.path,e)?null:e),Br(e=>nh(X.path,e)?``:e),Or(e=>e&&nh(X.path,e.path)?null:e),En(e=>e.filter(e=>!nh(X.path,e)))),hn.current?.abort();let i=new AbortController;hn.current=i,Promise.all([Sr({signal:i.signal}),G(`/api/projects/${n}`,{signal:i.signal})]).then(([n,a])=>{if(E(a.project),r&&ne(a.project.mainFile),t&&n){let t=n.find(e=>e.type===`file`&&e.path===a.project.mainFile)??n.find(t=>t.type===`file`&&Ne(t.path,t.textContent)&&(t.size??0)<=e.maxCollaborativeFileSizeMB*1024*1024);P(t?.path??``)}sr({signal:i.signal}),cr({signal:i.signal},r?a.project.mainFile:sn.current)}).catch(e=>{We(e)}).finally(()=>{hn.current===i&&(hn.current=null)})},[X?.revision]),(0,q.useEffect)(()=>{if(c.setActiveFile(N),!N)return;B(``),de(`editor.loading`);let e=c.getText(N),t=(t,n)=>{or(e.toString()),B(N),n?.local&&T?.permission!==`read`?(rn.current+=1,H(!0),de(`editor.pending`)):rn.current<=an.current&&de(he.current?`editor.savedAt`:`editor.saved`)};return e.observe(t),(kn||In)&&t(),()=>{e.unobserve(t)}},[N,c,kn,In,T?.permission]);let Q=async()=>{if(!kn)throw Error(`Collaboration is not synchronized`);let e=rn.current,t=await c.flush();return an.current=Math.max(an.current,e),pe(t.persistedAt),/\.tex$/i.test(on.current)&&cr(),rn.current===e?(H(!1),de(`editor.savedAt`)):de(`editor.pending`),t};(0,q.useEffect)(()=>{if(!V||!N||!kn)return;de(`editor.pending`);let e=window.setTimeout(()=>{de(`editor.saving`),Q().catch(()=>{de(`editor.saveFailed`)})},750);return()=>window.clearTimeout(e)},[I,V,N,kn]);let ur=async()=>{if(!T||T.permission===`read`||!kn||!N)return!1;de(`editor.saving`);try{return await Q(),sr(),!0}catch(e){return de(`editor.saveFailed`),U(K(e)||u(`errors.collaborationUnavailable`)),!1}},dr=cd(N),fr=async e=>{if(!T||It)return;let t=e===`full`&&!dr?sn.current||T.mainFile:on.current,r=e===`selection`?Ze.current.selectedText:``;if(!t)return;if(e===`selection`&&(!r.trim()||!(dr||/\.(?:tex|sty|cls)$/i.test(t)))){qe(u(`editor.wordCountSelectionEmpty`));return}if(dr){if(e===`full`&&le!==N)return;Nt(e),Ft(t),Vt(null),zt(``),Ut(pd(e===`full`?I:r)),jt(!0);return}gn.current?.abort();let i=new AbortController;gn.current=i,Nt(e),Ft(t),Vt(null),Ut(null),zt(``),jt(!0),Lt(!0);try{if(e===`full`&&V&&T.permission!==`read`&&!await ur())throw Error(u(`editor.wordCountSaveRequired`));let a=e===`selection`?{mode:e,path:t,source:r}:{mode:e,mainFile:t},o=await G(`/api/projects/${n}/word-count`,{method:`POST`,body:JSON.stringify(a),signal:i.signal});if(i.signal.aborted)return;Vt(o)}catch(e){if(We(e))return;i.signal.aborted||zt(K(e))}finally{gn.current===i&&(gn.current=null,Lt(!1))}},pr=async(t,n,r=Xt.texFmtConfig)=>{if(/\.bib$/i.test(t))try{return{formatted:await $u(n,e.maxCitationBibtexBytes)}}catch(t){throw t instanceof Ju?t.kind===`too-large`?Error(u(`citationLibrary.fileTooLarge`,{size:`${Math.round(e.maxCitationBibtexBytes/1024)} KB`})):t.kind===`invalid`?Error(u(`citationLibrary.fileInvalid`)):Error(u(t.kind===`timeout`?`editor.bibtexFormatterTimeout`:`editor.bibtexFormatterUnavailable`)):t}return{formatted:(await Ru(n,r)).output}},mr=async(e,t,n,r=0)=>{if(!/\.bib$/i.test(e))return Wu(t,n,r);try{return await ed(t,n,r)}catch(e){throw e instanceof Ju?Error(u(e.kind===`timeout`?`editor.bibtexFormatterTimeout`:`editor.bibtexFormatterUnavailable`)):e}},hr=async e=>{if(!T||T.permission===`read`||!kn||bn.current||!Vu(on.current))return;let t=on.current,n=c.getText(t);bn.current=!0,Gt(!0);let r=()=>{},i=new Promise(e=>{r=e});xn.current=i;let a=null;try{a=await c.acquireFormatLease(t);let r=n.toString(),{formatted:i}=await pr(t,r,e);if(on.current!==t||n.toString()!==r){U(u(`editor.formatSourceChanged`));return}await a.confirm();let o=await mr(t,r,i);if(on.current!==t||n.toString()!==r||(await a.confirm(),on.current!==t||n.toString()!==r)){U(u(`editor.formatSourceChanged`));return}o.length&&c.applyTextEdits(t,o),o.length&&await Q(),qt(null),U(``),qe(u(`editor.formatFileComplete`))}catch(e){Nu(e)?(qt({action:`file`,kind:e.kind,detail:e.message}),U(``)):U(u(`editor.formatFileFailed`,{message:K(e)}))}finally{a&&await a.release(),bn.current=!1,Gt(!1),r(),xn.current===i&&(xn.current=null)}},gr=async()=>{if(!Xt.formatOnCompile||!T||T.permission===`read`||!kn||!Vu(on.current)||bn.current)return;let e=on.current,t=c.getText(e);bn.current=!0,Gt(!0);let n=null;try{n=await c.acquireFormatLease(e);let r=t.toString(),{formatted:i}=await pr(e,r);await n.confirm();let a=await mr(e,r,i);if(on.current!==e||t.toString()!==r||(await n.confirm(),on.current!==e||t.toString()!==r))throw Error(u(`editor.formatSourceChanged`));a.length&&c.applyTextEdits(e,a),a.length&&await c.flush(),qt(null)}catch(e){Nu(e)?(qt({action:`file`,kind:e.kind,detail:e.message}),U(``)):U(u(`editor.formatFailedContinue`,{message:K(e)}))}finally{n&&await n.release(),bn.current=!1,Gt(!1)}},_r=async()=>(xn.current&&await xn.current,await gr(),ur()),vr=async e=>{if(!T||T.permission===`read`||!kn||bn.current||!Vu(on.current))return;let t=Ze.current;if(!t.selectedText.trim()){qe(u(`editor.formatSelectionRequired`));return}let n=on.current,{startOffset:r,endOffset:i,selectedText:a}=t,o=c.getText(n);if(o.toString().slice(r,i)!==a){U(u(`editor.formatSelectionChanged`));return}bn.current=!0,Gt(!0);let s=()=>{},l=new Promise(e=>{s=e});xn.current=l;let d=null;try{if(d=await c.acquireFormatLease(n),o.toString().slice(r,i)!==a){U(u(`editor.formatSelectionChanged`));return}let t=Uu(a,(await pr(n,a,e)).formatted);await d.confirm();let s=await mr(n,a,t,r);if(on.current!==n||o.toString().slice(r,i)!==a||(await d.confirm(),on.current!==n||o.toString().slice(r,i)!==a)){U(u(`editor.formatSelectionChanged`));return}s.length&&c.applyTextEdits(n,s),s.length&&await Q(),qt(null),U(``),qe(u(`editor.formatSelectionComplete`))}catch(e){Nu(e)?(qt({action:`selection`,kind:e.kind,detail:e.message}),U(``)):U(u(`editor.formatFailed`,{message:K(e)}))}finally{d&&await d.release(),bn.current=!1,Gt(!1),s(),xn.current===l&&(xn.current=null)}},yr=async t=>{let n=on.current;if(!/\.bib$/i.test(n)||T?.permission===`read`||!kn)return qe(u(`citationLibrary.importRequiresWrite`)),!1;let r=c.getText(n),i;try{i=await Xg()}catch(e){return U(K(e)),!1}if(on.current!==n||!kn)return!1;let a=r.toString(),o=i.parseBibEntriesResult(a,e.maxCitationBibtexBytes);if(o.status===`too-large`)return qe(u(`citationLibrary.fileTooLarge`,{size:i.citationBibtexLimitLabel(e.maxCitationBibtexBytes)})),!1;if(o.status===`invalid`)return qe(u(`citationLibrary.fileInvalid`)),!1;if(o.entries.some(e=>e.citationKey.toLowerCase()===t.citationKey.toLowerCase()))return qe(u(`citationErrors.alreadyInFile`,{key:t.citationKey})),!1;let s=Math.max(0,Math.min(a.length,_e.getCursor().offset)),l=a.slice(0,s),d=a.slice(s),f=l?l.endsWith(`
|
|
14
|
+
|
|
15
|
+
`)?``:l.endsWith(`
|
|
16
|
+
`)?`
|
|
17
|
+
`:`
|
|
18
|
+
|
|
19
|
+
`:``,p=d?d.startsWith(`
|
|
20
|
+
|
|
21
|
+
`)?``:d.startsWith(`
|
|
22
|
+
`)?`
|
|
23
|
+
`:`
|
|
24
|
+
|
|
25
|
+
`:``;return c.applyTextEdits(n,[{from:s,to:s,replacement:`${f}${t.bibtex.trim()}${p}`}]),qe(u(`citationLibrary.imported`,{key:t.citationKey})),!0},{files:br,setFiles:xr,loadFiles:Sr,newFileOpen:Cr,setNewFileOpen:wr,newFilePath:Tr,setNewFilePath:Er,resourcePreview:Dr,setResourcePreview:Or,resourcePreviewLoading:kr,setResourcePreviewLoading:Ar,newFolderOpen:jr,setNewFolderOpen:Mr,newFolderName:Nr,setNewFolderName:Pr,fileDialogError:Fr,setFileDialogError:Ir,selectedFolder:Lr,setSelectedFolder:Rr,selectedFile:zr,setSelectedFile:Br,expandedFolders:Vr,setExpandedFolders:Hr,moveEntry:Ur,setMoveEntry:Wr,moveName:Gr,setMoveName:Kr,moveDestination:qr,setMoveDestination:Jr,deleteEntry:Yr,setDeleteEntry:Xr,fileDragActive:Zr,setFileDragActive:Qr,uploadConflict:$r,setUploadConflict:ei,uploadingFiles:ti,uploadFeedback:ni,dismissUploadFeedback:ri,directoryEntries:ii,visibleEntries:ai,createFile:oi,addFile:si,createFolder:ci,uploadFiles:li,upload:ui,openFile:di,movePath:fi,movePathToFolder:pi,removePath:mi}=oh({projectId:n,site:e,activeFile:N,dirty:V,save:ur,onError:U,onProject:E,onActiveFile:P,onActiveMainFile:ne});cn.current=e=>{Rr(null),Br(e),Hr(t=>new Set([...t,...th(e)])),P(e)};let hi=e=>{if(e.id!==d.current)return;let t=e.mainFile!==T?.mainFile;E(e),t&&(sn.current=e.mainFile,on.current=e.mainFile,ne(e.mainFile),P(e.mainFile),Rr(null),Br(e.mainFile),Hr(t=>new Set([...t,...th(e.mainFile)])))},gi=()=>sn.current||T?.mainFile||``,_i=()=>{let e=gi(),t=on.current;if(!t||!/\.tex$/i.test(t))return e;let n=br.filter(e=>e.type===`file`&&/\.tex$/i.test(e.path)).length;return vh(c.getText(t).toString())||n===1?(e!==t&&(sn.current=t,ne(t)),t):e===t&&T?.mainFile&&T.mainFile!==t?(sn.current=T.mainFile,ne(T.mainFile),T.mainFile):e};(0,q.useEffect)(()=>{N&&N===F&&le===N&&ie.filePath===N&&N.toLocaleLowerCase().endsWith(`.tex`)&&br.filter(e=>e.type===`file`&&/\.tex$/i.test(e.path)).length!==0&&N!==T?.mainFile&&!vh(ie.content)&&T?.mainFile&&(sn.current=T.mainFile,ne(T.mainFile))},[N,F,le,ie,br,T?.mainFile]),(0,q.useEffect)(()=>{if(!Xt.openFilesInTabs||br.length===0)return;let t=new Set(br.filter(t=>t.type===`file`&&Ne(t.path,t.textContent)&&(t.size??0)<=e.maxCollaborativeFileSizeMB*1024*1024).map(e=>e.path));En(e=>{let n=e.filter(e=>t.has(e));return n.length===e.length?e:n})},[br,Xt.openFilesInTabs]);let{comments:vi,projectCommentSummary:yi,commentsFilePath:bi,commentsReady:xi,fileCommentsLoading:Si,fileCommentsError:Ci,retryFileComments:wi,reviewComments:Ti,reviewCommentsLoading:Ei,reviewCommentsError:Di,retryReviewComments:Oi,commentScope:ki,setCommentScope:Ai,focusComment:ji,setFocusComment:Mi,commentOpen:Ni,openComment:Pi,closeComment:Fi,commentText:Ii,setCommentText:Li,commentSelection:Ri,commentSuggestion:zi,setCommentSuggestion:Bi,commentSubmitting:Vi,commentError:Hi,addComment:Ui,toggleComment:Wi,replyToComment:Gi,editComment:Ki,deleteComment:qi,editCommentReply:Ji,deleteCommentReply:Yi,commentDraftStore:Xi,cancelComment:Zi,commentDraftRestored:Qi,commentDraftCanRetarget:$i,useCurrentCommentSelection:ea}=tp({projectId:n,activeFile:N,content:I,permission:T?.permission,revision:Nn,sourceOrderRevision:`${T?.mainFile??``}\0${X?.revision??``}`,selection:Je,save:ur,saveFailureMessage:u(`errors.collaborationUnavailable`),onError:U,onAdded:()=>{rt(null),W(`comments`)}});(0,q.useEffect)(()=>{if(!F||ie.filePath!==F)return;let e=iu(ie.content).length>0;se(t=>t.path===F&&t.hasIncludes===e?t:{path:F,hasIncludes:e})},[F,ie]),(0,q.useEffect)(()=>{if(!F||!kn||N===F)return;let e=c.getText(F),t=null,n=()=>{let t=iu(e.toString()).length>0;se(e=>e.path===F&&e.hasIncludes===t?e:{path:F,hasIncludes:t})},r=()=>{t!==null&&window.clearTimeout(t),t=window.setTimeout(()=>{t=null,n()},Zg)};return n(),e.observe(r),()=>{t!==null&&window.clearTimeout(t),e.unobserve(r)}},[N,F,c,kn]);let ta=(0,q.useMemo)(()=>oe.path===F&&oe.hasIncludes||!!yi?.filePaths.some(e=>e!==N),[F,oe,yi,N]),na=e=>{lt(null),W(`comments`),Mi(null),st(e),on.current!==e.filePath&&$n(e.filePath,e.startLine,1)},ra=(e,t=!1)=>{let n=vi.find(t=>t.id===e&&t.filePath===N);!n||n.resolved||n.orphaned||(st(null),Mi(null),at(null),t&&$e===`comments`&&nt===n.id?(rt(null),lt(null),W(null)):(rt(n.id),lt(e=>({id:n.id,filePath:n.filePath,nonce:(e?.nonce??0)+1})),W(`comments`)))};(0,q.useEffect)(()=>{lt(null),rt(null)},[N]),(0,q.useEffect)(()=>{if(!ot)return;let e=pp(ot,N,le,bi,xi,vi);e?(Mi({...e}),st(null)):ot.filePath===N&&le===N&&bi===N&&xi&&st(null)},[N,vi,bi,xi,le,ot,Mi]),(0,q.useEffect)(()=>{if(!it||N!==it.filePath||$e!==`comments`)return;let e=vi.find(e=>e.id===it.commentId);if(!e||it.replyId&&!e.replies.some(e=>e.id===it.replyId)||yn.current===it.id)return;yn.current=it.id,na(e);let t=window.setTimeout(()=>at(e=>e?.id===it.id?null:e),3e3);return()=>window.clearTimeout(t)},[N,vi,$e,it]);let{pdfUrl:ia,pdfCompiledAt:aa,pdfSizeBytes:oa,pdfLoadingMode:sa,pdfLoading:ca,compileLog:la,compileDiagnostics:ua,compileOutcome:da,artifacts:fa,artifactPreview:pa,artifactLoading:ma,editorNotice:ha,localCompiling:ga,cancelling:_a,cleaning:va,compile:ya,cancelCompile:ba,cleanCompile:xa,viewArtifact:Sa,pdfDisplayed:Ca}=$m({projectId:n,project:T,mainFile:F,resolveCompileMainFile:_i,getCurrentMainFile:gi,initialLatest:r?.projectId===n?r.latestCompile:null,collaborationSynced:kn,pdfVisible:Fe===`pdf`&&Ce!==`editor-only`,sharedState:Y,onSharedState:Mn,save:_r,loadOutline:(e,t)=>cr({signal:e},t),onPreviewTab:Se,onError:U,onCompileStart:()=>{U(``),qe(``)},onCompileSuccess:()=>{let e=on.current;if(e){let t=_e.getCursor();er(e,t.line,t.column,{silent:!0})}},onPdfChanged:Qn}),wa=qm({projectId:n,userId:t.id,projectEngine:T?.engine,allowedEngines:e.allowedEngines,compile:ya,onError:U}),Ta=(0,q.useMemo)(()=>le===N&&/\.tex$/i.test(N)&&Jm(I),[N,le,I]);(0,q.useEffect)(()=>{let e=e=>{(e.ctrlKey||e.metaKey)&&!e.shiftKey&&e.key.toLocaleLowerCase()===`p`&&(e.preventDefault(),Tt(!0))};return window.addEventListener(`keydown`,e,!0),()=>window.removeEventListener(`keydown`,e,!0)},[]);let Ea=e=>{R(t.id,n,e),Zt(e)},Da=(e=!1)=>{let t=Kt;if(!t)return;qt(null),U(``),e&&Ea({...Xt,texFmtConfig:``});let n=e?``:void 0;t.action===`selection`?vr(n):hr(n)},Oa=async()=>{Yt(!0);try{await Hn()||(U(u(`editor.collaboration.permissionDowngradeOtherTabBlocked`)),Yt(!1))}catch(e){U(K(e)),Yt(!1)}},ka=()=>{Ee?Ve(e=>!e):nn.current?.isCollapsed()?nn.current.expand():nn.current?.collapse()},Aa=(0,q.useMemo)(()=>Wg(M,F,ie),[M,F,ie]),ja=(0,q.useMemo)(()=>td(la,da),[la,da]),Ma=Ce!==`pdf-only`,Na=Ce!==`editor-only`,Pa=Me(Ma,Na,$e===`settings`||$e===`comments`&&!Na,Ee),Fa=e=>{we(e),e===`pdf-only`&&Se(`pdf`)},Ia=(0,q.useCallback)((e,t)=>{_(e.id),t?$n(e.path,e.line,1):(e.path!==N&&cn.current(e.path),x({id:e.id,path:e.path,nonce:++S.current}))},[N,$n]),La=!!(Ma&&f.visible&&T?.permission!==`read`),Ra=(0,q.useCallback)(e=>{m(!0),_(e),w({id:e,nonce:++S.current})},[]),za=(0,q.useMemo)(()=>N?h.forFile(N):null,[N,h.forFile]),Ba=(0,q.useCallback)(e=>{vn.current?.abort();let t=new AbortController;vn.current=t;let r=on.current,i=sn.current,a=new URLSearchParams({kind:e.kind,key:e.key,...r?{path:r}:{},...i?{mainFile:i}:{}});G(`/api/projects/${n}/references/resolve?${a}`,{signal:t.signal}).then(({target:n})=>{t.signal.aborted||on.current!==r||sn.current!==i||(n?(ln.current===`pdf-only`&&Fa(`editor-pdf`),$n(n.path,n.line,n.column)):U(u(e.kind===`citation`?`editor.citationTargetNotFound`:`editor.labelTargetNotFound`,{key:e.key})))}).catch(e=>{!t.signal.aborted&&!We(e)&&U(K(e))}).finally(()=>{vn.current===t&&(vn.current=null)})},[$n,n,u]),Va=Yr?An.filter(e=>e.filePath&&nh(Yr.path,e.filePath)):[];if(!T)return(0,J.jsxs)(`div`,{className:`center-card`,children:[(0,J.jsx)(`p`,{children:He||u(`common.loading`)}),He&&(0,J.jsx)(`button`,{className:`primary`,onClick:s,children:u(`editor.backToProjects`)})]});let Ha=T.permission===`read`||!kn,Ua=jn.find(e=>e.path===N),Wa=Ua&&!Wt?Ua:null,Ga=(e,t)=>{if(Ha)return;let n=on.current;if(n){if(c.getText(n).toString().slice(e.from,e.to)!==e.word)U(u(`editor.spellCheckSourceChanged`));else try{c.applyTextEdits(n,[{from:e.from,to:e.to,replacement:t}])}catch(e){U(K(e))}}},Ka=Y?.mainFile===F&&(Y.status===`queued`||Y.status===`running`),qa=ga||Ka||va,Ja=N?c.getText(N):null,Ya=aa?te(aa,y.resolvedLanguage,{month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`}):``,Xa=F.split(`/`).at(-1)??F,Za=ja.warnings.length+ja.errors.length+fa.length,Qa=ia?`${ia}${ia.includes(`?`)?`&`:`?`}download=1`:``,$a=F||T.mainFile,eo=fh(N,$a),to=!!($a&&/\.tex$/i.test($a)),no=()=>{let e=on.current;if(!e)return Promise.resolve();let t=_e.getCursor();return er(e,t.line,t.column)},ro=Ta&&!Ha?{state:wa.state?.path===N?wa.state:null,disabled:qa||!kn,engine:wa.engine,engines:wa.engines,onEngineChange:wa.setEngine,onCompile:()=>void wa.run(N)}:null,io=()=>(Ie(`markdown`),Ee&&we(`pdf-only`),ze(e=>({line:_e.getCursor().line,nonce:(e?.nonce??0)+1})),Promise.resolve()),ao=Pe?{path:N,source:le===N?I:null,reveal:Le,onOpenPath:e=>{let t=br.find(t=>t.path===e);t?(!yh(e)&&Ne(t.path,t.textContent)&&Ce===`pdf-only`&&we(`editor-pdf`),di(t)):U(u(`editor.markdown.linkMissing`,{path:e}))},onShowLine:e=>{ln.current===`pdf-only`&&we(`editor-pdf`),$n(N,e,1)},onShowCursor:()=>void io()}:null,oo=e=>{let t=br.find(t=>t.path===e);t&&Ne(t.path,t.textContent)?di(t):Dn(e)},so=e=>{document.getElementById(`editor-tab-${encodeURIComponent(e)}`)?.focus()},co=(e,t)=>{if(![`ArrowLeft`,`ArrowRight`,`Home`,`End`].includes(e.key))return;e.preventDefault();let n=e.key===`Home`?0:e.key===`End`?Qt.length-1:(t+(e.key===`ArrowLeft`?-1:1)+Qt.length)%Qt.length,r=Qt[n];r&&(oo(r),window.requestAnimationFrame(()=>so(r)))},lo=qa?Ka?Y?.status===`queued`?u(`editor.compileQueued`):u(`editor.compilingBy`,{name:Y?.requestedBy.name??u(`common.user`)}):u(`editor.compiling`):da===`failed`?ia&&aa?u(`editor.compileFailedRetained`,{time:te(aa,y.resolvedLanguage)}):u(`editor.compileFailedNoPdf`):da===`cancelled`?u(`compileControls.cancelled`):``,uo=Th(On,ue,On===`disconnected`&&(V||c.hasWritableDraft)),fo=uo===`editor.savedAt`&&fe?u(`editor.savedAt`,{time:te(fe,y.resolvedLanguage,{hour:`2-digit`,minute:`2-digit`,second:`2-digit`})}):u(uo);return(0,J.jsxs)(`div`,{className:`workspace`,"data-texlite-tooltips":Xt.showTooltips?`on`:`off`,children:[(0,J.jsx)(wh,{agentTerminal:Ma&&f.visible&&T.permission!==`read`?{open:p,activeCount:f.activeCount,toggle:()=>m(e=>!e)}:void 0,site:e,project:T,activeFile:N,saveStateLabel:fo,editorPreferences:Xt,activeSessions:An,collaborationStatus:On,reconnectCollaboration:Rn,protocolUpgradeRequired:zn,showEditor:Ma,filesCollapsed:Ee?!Be:ut,toggleFilesPanel:ka,workspaceLayout:Ce,changeWorkspaceLayout:Fa,onBack:s,onShare:()=>pt(!0),showCitationLibrary:Ma&&/\.bib$/i.test(N),citationLibraryOpen:bt,onCitationLibrary:()=>xt(!0),onHistory:()=>_t(!0),onGit:()=>ht(!0),canManageGit:T.ownerId===t.id,formatting:Wt,readOnly:Ha,collaborationSynced:kn,onToggleComments:()=>{let e=$e!==`comments`||!!nt;rt(null),e&&Ai(`project`),W(e?`comments`:null)},commentsOpen:$e===`comments`,unresolvedCommentCount:yi?.unresolvedCount??T.unresolvedCommentCount??0,onToggleSettings:()=>W($e===`settings`?null:`settings`),settingsOpen:$e===`settings`,compileBusy:qa,sharedCompiling:Ka,localCompiling:ga,cancelling:_a,onCompile:()=>void ya(),onCancelCompile:()=>void ba()}),zn&&(0,J.jsxs)(`div`,{className:`workspace-update-banner`,role:`alert`,children:[(0,J.jsx)(ce,{size:15}),(0,J.jsx)(`span`,{children:u(`workspaceUpdates.protocolUpgrade`)}),(0,J.jsx)(`button`,{type:`button`,onClick:()=>window.location.reload(),children:u(`common.reload`)})]}),lo&&(0,J.jsxs)(`div`,{className:`compile-status-strip${da===`failed`?` failed`:``}`,role:`status`,"aria-live":`polite`,children:[(0,J.jsx)(Re,{className:qa?`spin`:``,size:14}),(0,J.jsx)(`span`,{children:lo})]}),(ar.error||ir.error||Kt||Wa)&&(0,J.jsxs)(`div`,{className:`client-tool-recoveries`,children:[ar.error&&(0,J.jsxs)(`div`,{className:`client-tool-recovery`,role:`alert`,title:ar.error,children:[(0,J.jsx)(ce,{size:15}),(0,J.jsxs)(`span`,{children:[(0,J.jsx)(`strong`,{children:u(`editor.harperRecoveryTitle`)}),u(`editor.harperFallbackHint`)]}),(0,J.jsx)(`div`,{className:`client-tool-recovery-actions`,children:(0,J.jsx)(`button`,{type:`button`,onClick:ar.retry,children:u(`common.retry`)})}),(0,J.jsx)(`button`,{type:`button`,className:`formatter-diagnostics-dismiss`,title:u(`common.close`),"aria-label":u(`common.close`),onClick:ar.dismissError,children:(0,J.jsx)(z,{size:13})})]}),ir.error&&(0,J.jsxs)(`div`,{className:`client-tool-recovery`,role:`alert`,title:ir.error,children:[(0,J.jsx)(ce,{size:15}),(0,J.jsxs)(`span`,{children:[(0,J.jsx)(`strong`,{children:u(`chktex.recoveryTitle`)}),u(`chktex.recoveryHint`)]}),(0,J.jsx)(`div`,{className:`client-tool-recovery-actions`,children:(0,J.jsx)(`button`,{type:`button`,onClick:ir.retry,children:u(`common.retry`)})}),(0,J.jsx)(`button`,{type:`button`,className:`formatter-diagnostics-dismiss`,title:u(`common.close`),"aria-label":u(`common.close`),onClick:ir.dismissError,children:(0,J.jsx)(z,{size:13})})]}),Kt&&(0,J.jsxs)(`div`,{className:`client-tool-recovery`,role:`alert`,title:Kt.detail,children:[(0,J.jsx)(ce,{size:15}),(0,J.jsxs)(`span`,{children:[(0,J.jsx)(`strong`,{children:u(Kt.kind===`format`?`editor.texFmtOptionsRecoveryTitle`:Kt.kind===`load`?`editor.texFmtRecoveryTitle`:`editor.texFmtRuntimeRecoveryTitle`)}),u(`editor.clientToolRecoveryHint`)]}),(0,J.jsxs)(`div`,{className:`client-tool-recovery-actions`,children:[(0,J.jsx)(`button`,{type:`button`,disabled:Wt||Ha,onClick:()=>Da(),children:u(`common.retry`)}),Kt.kind===`format`&&Xt.texFmtConfig.trim()&&(0,J.jsx)(`button`,{type:`button`,disabled:Wt||Ha,onClick:()=>Da(!0),children:u(`editor.resetFormatterOptions`)}),(0,J.jsx)(`button`,{type:`button`,onClick:()=>window.location.reload(),children:u(`common.reload`)})]}),(0,J.jsx)(`button`,{type:`button`,className:`formatter-diagnostics-dismiss`,title:u(`common.close`),"aria-label":u(`common.close`),onClick:()=>qt(null),children:(0,J.jsx)(z,{size:13})})]}),Wa&&(0,J.jsxs)(`div`,{className:`client-tool-recovery format-lease-status`,role:`status`,children:[(0,J.jsx)(Re,{className:`spin`,size:15}),(0,J.jsx)(`span`,{children:u(`editor.formattingBy`,{name:Wa.holderName})})]})]}),Z&&(0,J.jsxs)(`div`,{className:`client-tool-recovery`,role:`status`,children:[(0,J.jsx)(ce,{size:15}),(0,J.jsx)(`span`,{children:u(`history.saveWarning`)})]}),He&&(0,J.jsx)(`div`,{className:`toast`,onClick:()=>U(``),children:He}),Ge&&(0,J.jsx)(`div`,{className:`toast success`,onClick:()=>qe(``),children:Ge}),(0,J.jsxs)(Te,{orientation:`horizontal`,className:`work-grid`,...Pa,children:[Ma&&(0,J.jsx)(ke,{tikzGalleryEnabled:e.tikzGalleryEnabled===!0,setTikzGalleryOpen:Dt,phoneDrawer:Ee?{open:Be,onClose:()=>Ve(!1)}:void 0,project:T,filesPanel:nn,visibleEntries:ai,deletedPath:X?.kind===`delete`?X.path:null,activeFile:N,activeMainFile:F,selectedFile:zr,selectedFolder:Lr,expandedFolders:Vr,fileDragActive:Zr,uploadingFiles:ti,uploadFeedback:ni,readOnly:Ha,formatting:Wt,canFormat:Vu(N),activeFormatLease:!!Ua,collaborationSynced:kn,editorFontSize:Xt.fontSize,outline:Aa,sourceCursorStore:_e,wordCountBusy:It,plainWordCount:dr,canCountFull:dr?le===N:!!F,hasSelection:!!Je.selectedText.trim()&&(dr||/\.(?:tex|sty|cls)$/i.test(N)),hasFormatSelection:!!Je.selectedText.trim(),uploadInput:tn,setSelectedFolder:Rr,setExpandedFolders:Hr,setMoveEntry:Wr,setMoveName:Kr,setMoveDestination:Jr,setDeleteEntry:Xr,setFileDialogError:Ir,setNewFolderName:Pr,setNewFolderOpen:Mr,setNewFilePath:Er,setNewFileOpen:wr,setQuickOpen:Tt,onProjectSearch:()=>kt(!0),setFileDragActive:Qr,dismissUploadFeedback:ri,setFilesCollapsed:dt,onError:U,uploadFiles:li,upload:ui,openFile:e=>{di(e),Ee&&Ve(!1)},movePathToFolder:pi,onFormatFile:()=>void hr(),onFormatSelection:()=>void vr(),jumpToSource:(...e)=>{$n(...e),Ee&&Ve(!1)},syncSourceToPdf:er,onWordCount:e=>void fr(e)}),Ma&&!Ee&&(0,J.jsx)(Oe,{className:`resize-handle`,children:(0,J.jsx)(me,{size:12})}),Ma&&(0,J.jsx)(Ah,{figurePdf:ro,mobileSync:Ee&&$e!==`comments`?Pe?{disabled:le!==N,onClick:io,label:u(`editor.markdown.showInPreview`)}:{disabled:!ia||!eo,onClick:no}:void 0,terminal:p?({maximized:e,toggleMaximized:t})=>(0,J.jsx)(q.Suspense,{fallback:(0,J.jsx)(`div`,{className:`agent-task-empty`,children:(0,J.jsx)(Re,{className:`spin`,size:18})}),children:(0,J.jsx)(qg,{projectId:n,readOnly:Ha,onHide:()=>m(!1),maximized:e,onToggleMaximized:t,review:h,activeChangeId:g,onShowChange:Ia,reviewFocus:C})}):null,project:T,projectId:n,activeFile:N,mainFile:F,openTabs:Qt,content:I,loadedFile:le,readOnly:Ha,comments:vi,focusComment:ji,editorPreferences:Xt,completionIndex:A,nativeSpellCheck:ar.nativeFallback,spellCheckIssues:ar.issues,spellCheckJump:ar.jump,sourceJump:Yn,collaborativeText:Ja,collaborationAwareness:c.awareness,undoManager:N?c.getUndoManager(N):void 0,editorNotice:ha,activateTab:oo,closeTab:Dn,handleTabKeyDown:co,updateEditorContent:or,setSelection:(e,t,n)=>Qe({selectedText:e,startOffset:t,endOffset:n}),onAddComment:(e,t,n,r)=>Pi({selectedText:e,startOffset:t,endOffset:n},r),onSelectionHistory:(e,t,n,r)=>{yt({filePath:N,selection:{selectedText:e,startOffset:t,endOffset:n},source:r})},onCommentClick:ra,onSpellCheckReplace:Ga,onReferenceNavigate:Ba,onCursor:Tn,agentChanges:za,activeAgentChangeId:g,agentChangeReveal:b?.path===N?b:null,onAgentChangesStale:h.refreshSoon,onOpenAgentChange:La?Ra:void 0}),Na&&(0,J.jsx)(eg,{mobileSync:Ee,commentsOpen:$e===`comments`,onCommentsHost:tt,projectId:n,activeMainFile:F,previewTab:Fe,diagnosticTab:be,pdfUrl:ia,pdfLoadingMode:sa,pdfLoading:ca,pdfCompiledAt:aa,pdfSizeBytes:oa,pdfCompiledLabel:Ya,pdfTargetLabel:Xa,pdfDownloadUrl:Qa,pdfTarget:qn,pdfViewport:Jn,activeFile:N,compileBusy:qa,compileLog:la,compileDiagnostics:ua,compileMessages:ja,artifacts:fa,artifactPreview:pa,artifactLoading:ma,cleaning:va,readOnly:Ha,collaborationSynced:kn,workspaceLayout:Ce,showSyncResize:Ma&&Na,diagnosticCount:Za,selectPreviewTab:Ie,markdown:ao,changeWorkspaceLayout:Fa,onSetPdfViewport:Xn,onResetPdfViewport:Zn,onPdfDisplayed:Ca,syncVisiblePdfToSource:nr,syncCurrentSourceToPdf:no,syncPdfToSource:tr,canSyncWithPdf:eo,canSyncPdfToSource:to,files:br,jumpToSource:$n,onSetCleanMode:Ct,viewArtifact:Sa}),(0,J.jsx)(Vg,{phone:Ee,commentsHost:Na?et:void 0,sidePanel:$e,onClose:()=>W(null),project:T,projectId:n,site:e,files:br,currentUserId:t.id,comments:nt?vi:Ti,commentDraftStore:Xi,commentsLoading:nt?Si:Ei,commentsError:(nt?Ci:Di)||Wn,onRetryComments:nt?wi:Oi,activeFile:N,singleCommentId:nt,onShowAllComments:()=>{rt(null),Ai(`project`)},hasProjectCommentsScope:ta,commentScope:ki,onCommentScopeChange:Ai,focusedCommentId:ct?.filePath===N?ct.id:ji?.id,commentFocusNonce:ct?.nonce,onClearFocusComment:()=>{lt(null),Mi(null),at(null)},unreadMentions:Un,onMarkMentionRead:Gn,onMarkAllMentionsRead:Kn,targetCommentId:it?.commentId,targetReplyId:it?.replyId,onFocusComment:na,onToggleComment:Wi,onReplyComment:Gi,onEditComment:Ki,onDeleteComment:qi,onEditCommentReply:Ji,onDeleteCommentReply:Yi,dictionaryWords:O,onDictionaryChange:k,editorPreferences:Xt,onEditorPreferences:Ea,spellCheckCount:ar.summary?.total??null,spellCheckUniqueCount:ar.summary?.unique??null,spellCheckIndex:ar.summary?ar.index:-1,onSpellCheckNavigate:ar.jumpToIssue,onProject:hi},n)]}),At&&(0,J.jsx)(Ye,{title:u(`editor.wordCountTitle`),onClose:()=>jt(!1),children:(0,J.jsx)(Jg,{open:!0,mode:Mt,path:Pt,busy:It,error:Rt,result:Bt,plainResult:Ht,onOpenChange:jt})}),(0,J.jsx)(Fg,{projectSearchOpen:Ot,setProjectSearchOpen:kt,onSearchNavigate:(e,t,n)=>{Ce===`pdf-only`&&Fa(Ee?`editor-only`:`editor-pdf`),Ee&&Ve(!1),$n(e,t,n)},user:t,project:T,projectId:n,activeFile:N,content:I,maxCitationBibtexBytes:e.maxCitationBibtexBytes,files:br,directoryEntries:ii,readOnly:Ha,resourcePreview:Dr,resourcePreviewLoading:kr,setResourcePreview:Or,setResourcePreviewLoading:Ar,uploadConflict:$r,setUploadConflict:ei,dismissUploadFeedback:ri,uploadFiles:li,cleanMode:St,setCleanMode:Ct,cleanCompile:xa,newFileOpen:Cr,setNewFileOpen:wr,newFilePath:Tr,setNewFilePath:Er,newFolderOpen:jr,setNewFolderOpen:Mr,newFolderName:Nr,setNewFolderName:Pr,selectedFolder:Lr,fileDialogError:Fr,setFileDialogError:Ir,createFile:oi,createFolder:ci,moveEntry:Ur,setMoveEntry:Wr,moveName:Gr,setMoveName:Kr,moveDestination:qr,setMoveDestination:Jr,movePath:fi,deleteEntry:Yr,setDeleteEntry:Xr,deleteActiveSessions:Va,removePath:mi,commentOpen:Ni,closeComment:Fi,commentSelection:Ri,commentSuggestion:zi,setCommentSuggestion:Bi,commentText:Ii,setCommentText:Li,commentSubmitting:Vi,cancelComment:Zi,commentDraftRestored:Qi,commentDraftCanRetarget:$i,useCurrentCommentSelection:ea,commentError:Hi,addComment:Ui,shareOpen:ft,setShareOpen:pt,onSharedMemberCountChange:D,citationLibraryOpen:bt,setCitationLibraryOpen:xt,insertCitationAtCursor:yr,tikzGalleryOpen:Et,setTikzGalleryOpen:Dt,tikzGalleryFolder:Lr,addFile:si,quickOpen:wt,setQuickOpen:Tt,openFile:di,selectionHistoryTarget:vt,closeSelectionHistory:()=>yt(null),historyOpen:gt,setHistoryOpen:_t,gitOpen:mt,setGitOpen:ht,save:ur,permissionDowngrade:Bn,permissionDowngradeBusy:Jt,dismissPermissionDowngrade:Vn,discardPermissionDraft:Oa})]})}export{un as C,Qg as ProjectWorkspace,dn as S,Nt as T,fs as _,ah as a,Ra as b,xu as c,_u as d,mu as f,cs as g,ms as h,xh as i,yu as l,hs as m,dg as n,zu as o,Vs as p,Ch as r,Bu as s,Kg as t,vu as u,ss as v,Ut as w,gi as x,La as y};
|