@yuriai/web 0.3.2-beta.7 → 0.3.3-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (140) hide show
  1. package/dist/assets/{AgentAvatar-Dy2D4-W_.js → AgentAvatar-tFfpSF5F.js} +1 -1
  2. package/dist/assets/{AssistantConversationSurface-BZwQoBD0.js → AssistantConversationSurface-B-iO-AUW.js} +3 -3
  3. package/dist/assets/{AssistantSessionCard-Cb5O68ez.js → AssistantSessionCard-DTPufGP2.js} +2 -2
  4. package/dist/assets/{AssistantUnreadBadge-Dv9HXPrS.js → AssistantUnreadBadge-BV2cbiJo.js} +1 -1
  5. package/dist/assets/{AssistantView-3fIzHGoU.js → AssistantView-iKt4ZcoR.js} +1 -1
  6. package/dist/assets/{DiagramView-zlrPK3wP.js → DiagramView-SHoXhtXa.js} +1 -1
  7. package/dist/assets/{FadeInOnReveal-Cb2cgQyM.js → FadeInOnReveal-4E61VUmD.js} +1 -1
  8. package/dist/assets/{GuiPluginPage-DX446Fgg.js → GuiPluginPage-Bt5j7vkr.js} +1 -1
  9. package/dist/assets/{GuiPluginSurface-C34vXd2R.js → GuiPluginSurface-Bs9Pauc8.js} +1 -1
  10. package/dist/assets/{GuiPluginWindow-BUM2P90L.js → GuiPluginWindow-cnUkWFge.js} +1 -1
  11. package/dist/assets/{Icon-o1bRhUil.js → Icon-DebSeH2D.js} +1 -1
  12. package/dist/assets/{ImageLoadingPlaceholder-BS9Swwfz.js → ImageLoadingPlaceholder-BBMhxtKr.js} +1 -1
  13. package/dist/assets/{LoadingImage-DDafrpn6.js → LoadingImage-6BZsPXXb.js} +1 -1
  14. package/dist/assets/{MarkdownRenderer-BOLzT07h.js → MarkdownRenderer-Bjl6sXps.js} +2 -2
  15. package/dist/assets/{MarkdownRendererImpl-BWmWJyQD.js → MarkdownRendererImpl-tZSoVcrU.js} +1 -1
  16. package/dist/assets/{MarkstreamRendererImpl-MwrM60DK.js → MarkstreamRendererImpl-Br2_lE4f.js} +1 -1
  17. package/dist/assets/{MobileDetailNavigation-CS3FdXMF.js → MobileDetailNavigation-B7vAsqVU.js} +1 -1
  18. package/dist/assets/MobileResizableSheet-BJs0jEqn.js +1 -0
  19. package/dist/assets/{MobileShareBridge-C7SsPeA-.js → MobileShareBridge-Cb9GvxGv.js} +1 -1
  20. package/dist/assets/{MobileSurface-BkMJ0lqS.js → MobileSurface-BaT1L70D.js} +1 -1
  21. package/dist/assets/{MultiRunWindow-BkVFZYQl.js → MultiRunWindow-DPM25lxz.js} +1 -1
  22. package/dist/assets/{OnboardingScreen-EMj1BesS.js → OnboardingScreen-D7ns1Tb2.js} +1 -1
  23. package/dist/assets/{OverlayScrollbar-mTdNvI2t.js → OverlayScrollbar-B1PH1Jtv.js} +1 -1
  24. package/dist/assets/{RemoteAssistantSessionCard-CNBayb0p.js → RemoteAssistantSessionCard-BLp9NZhL.js} +1 -1
  25. package/dist/assets/{SettingsView-BkXX1yqx.js → SettingsView-CaC2DI4Z.js} +3 -3
  26. package/dist/assets/{SettingsWindow-DEVIOawn.js → SettingsWindow-gVPRXQDh.js} +1 -1
  27. package/dist/assets/{SetupTourDialog-DpDXKEev.js → SetupTourDialog-BoQIvdEP.js} +1 -1
  28. package/dist/assets/{TerminalView-BwZd8np-.js → TerminalView-CxlIRxha.js} +1 -1
  29. package/dist/assets/{ToolOutputDialog-C7FT1uPc.js → ToolOutputDialog-Bsx1wpVW.js} +1 -1
  30. package/dist/assets/{VoiceSettings-BrAyJv-I.js → VoiceSettings-DhA9feRU.js} +1 -1
  31. package/dist/assets/{YuriLogo-DNvrroBa.js → YuriLogo-BKdnDJwl.js} +1 -1
  32. package/dist/assets/{YuriWordmark-bJX68f2Y.js → YuriWordmark-D2e-o9nW.js} +1 -1
  33. package/dist/assets/{assistant-attachment-cache-zu9sz4ex.js → assistant-attachment-cache-BYvIyn1x.js} +1 -1
  34. package/dist/assets/{capgoAdapter-CPyV4o5H.js → capgoAdapter-vj-M8YQp.js} +1 -1
  35. package/dist/assets/{checkbox-BcJaF7Fw.js → checkbox-DVMeOiMB.js} +1 -1
  36. package/dist/assets/{client-CgAFd1ew.js → client-CzjApAA4.js} +4 -4
  37. package/dist/assets/{collapsible-ChjJre3f.js → collapsible-D_R6x2Q_.js} +1 -1
  38. package/dist/assets/{context-menu-BRBPOV2F.js → context-menu-BFDbtdmK.js} +1 -1
  39. package/dist/assets/{desktopHosts-135cuRCE.js → desktopHosts-BsTrBVja.js} +1 -1
  40. package/dist/assets/{desktopRelayRestore-1aUztDPU.js → desktopRelayRestore-BxbRKak_.js} +1 -1
  41. package/dist/assets/{device-C8ZHblkr.js → device-BlmHHWT1.js} +1 -1
  42. package/dist/assets/{diagram-BhOF-6FQ.js → diagram-CrjNCLmc.js} +1 -1
  43. package/dist/assets/{dialog-BSyXr9ua.js → dialog-CHzvxSP4.js} +1 -1
  44. package/dist/assets/{fileMentionTouchSelection-DSXpR_Hq.js → fileMentionTouchSelection-D9GbR7zD.js} +1 -1
  45. package/dist/assets/{fileReferenceActions-DX-Stroq.js → fileReferenceActions-DLTUzjwi.js} +1 -1
  46. package/dist/assets/{gitApi--F7MdPg9.js → gitApi-i_uT8MNk.js} +1 -1
  47. package/dist/assets/gitApiHttp-BgUDBfaJ.js +3 -0
  48. package/dist/assets/{gui-BMN3-WPc.js → gui-KxRdG4j0.js} +1 -1
  49. package/dist/assets/{historyImportQueries-eR7Bj6VN.js → historyImportQueries-DiGQ8duS.js} +1 -1
  50. package/dist/assets/{host-iM7aLAip.js → host-BBp7NPZz.js} +1 -1
  51. package/dist/assets/{i18n-OsFhnlRH.js → i18n-BvjeIWrT.js} +1 -1
  52. package/dist/assets/{image-loading-ZB1bYt51.js → image-loading-Dlh4FIPJ.js} +1 -1
  53. package/dist/assets/{input-Daki_y8O.js → input-Ck9_Qln_.js} +1 -1
  54. package/dist/assets/{input-store-DRTu4uZc.js → input-store-wWToFdzi.js} +1 -1
  55. package/dist/assets/{insertionBoundaries-CnhjXWsd.js → insertionBoundaries-BFmZupL3.js} +1 -1
  56. package/dist/assets/main-RbzEHxam.js +169 -0
  57. package/dist/assets/{main-CALE45ey.js → main-_RMi6lwy.js} +2 -2
  58. package/dist/assets/{markdownHeightCache-Dn_Jkp0n.js → markdownHeightCache-CnLR3-I2.js} +1 -1
  59. package/dist/assets/{mcpQueries-DB6aJ5RI.js → mcpQueries-MmcRk0_G.js} +1 -1
  60. package/dist/assets/miniChat-CEE6OnLk.js +2 -0
  61. package/dist/assets/mobile-Cc6EYN5S.js +2 -0
  62. package/dist/assets/{mobileBackNavigation-CeY46TEx.js → mobileBackNavigation-C6UPWCkI.js} +1 -1
  63. package/dist/assets/{mobileConnections-BjLYzK32.js → mobileConnections-D8TC3-vN.js} +2 -2
  64. package/dist/assets/{multirun-DV_l3huB.js → multirun-BJgG4Ymw.js} +1 -1
  65. package/dist/assets/{native-config-CaDwggks.js → native-config-JMwpif8a.js} +1 -1
  66. package/dist/assets/{navigation-BjCFktgT.js → navigation-toBhZ-X8.js} +2 -2
  67. package/dist/assets/{openRemoteProjectSession-C3jFz6kb.js → openRemoteProjectSession-BD2tHXKw.js} +1 -1
  68. package/dist/assets/{platform-wF65ZFgV.js → platform-CiUKDeXd.js} +1 -1
  69. package/dist/assets/{project-preview-BhNspxqe.js → project-preview-BjTq299L.js} +1 -1
  70. package/dist/assets/{projectActions-50e_f9dI.js → projectActions-BPmI9_mW.js} +1 -1
  71. package/dist/assets/{projectMeta-CwdDc3V4.js → projectMeta-Bh7dUtdB.js} +1 -1
  72. package/dist/assets/{prompt-attachment-upload-8bssUUT3.js → prompt-attachment-upload-Bem87nmm.js} +1 -1
  73. package/dist/assets/{pwa-QoTHytgl.js → pwa-B2AKIaf6.js} +2 -2
  74. package/dist/assets/qoder-zGvP_RLr.svg +5 -0
  75. package/dist/assets/queue-abort-optimistic-BizaMpYT.js +1 -0
  76. package/dist/assets/{react-ChbBD2fG.js → react-DeCzn0Uc.js} +1 -1
  77. package/dist/assets/readiness-CekKZ6au.js +2 -0
  78. package/dist/assets/{reference-history-BBLJypsd.js → reference-history-cPgFTsku.js} +1 -1
  79. package/dist/assets/{remote-input-store-DFBMyVS-.js → remote-input-store-BvlOGMu_.js} +1 -1
  80. package/dist/assets/{remoteProjectQueries-8giIAvzL.js → remoteProjectQueries-yX3kOkR6.js} +1 -1
  81. package/dist/assets/{remoteSessionReference-BHBerOUy.js → remoteSessionReference-Da4ThgtH.js} +1 -1
  82. package/dist/assets/{renderElectronMiniChatApp-Yryt2r9g.js → renderElectronMiniChatApp-CmmEVsXV.js} +2 -2
  83. package/dist/assets/renderMobileApp-D1D1s_ia.js +29 -0
  84. package/dist/assets/{runtime-auth-mjIpsk3N.js → runtime-auth-DA-qfGHk.js} +1 -1
  85. package/dist/assets/{runtime-fetch-DKZOpfzo.js → runtime-fetch-V-iMWR8t.js} +1 -1
  86. package/dist/assets/{runtime-file-download-Dc459c9e.js → runtime-file-download-DxL4XbME.js} +1 -1
  87. package/dist/assets/{runtime-file-resource-DnhWnndu.js → runtime-file-resource-CKQQEwNv.js} +1 -1
  88. package/dist/assets/{runtime-switch-BMjl5Y5W.js → runtime-switch-DEPKHgdL.js} +1 -1
  89. package/dist/assets/{runtimeConfig-CsJ6iub-.js → runtimeConfig-CPU1CoUI.js} +1 -1
  90. package/dist/assets/runtimeEndpointReset-Bwa7I9vS.js +151 -0
  91. package/dist/assets/{scheduledTaskNavigation-Bi7sRiFW.js → scheduledTaskNavigation-CdBHn9ti.js} +1 -1
  92. package/dist/assets/{select-D_jd65HO.js → select-BnDfHG_T.js} +1 -1
  93. package/dist/assets/{sessionLookup-BUyzfxAJ.js → sessionLookup-mQtUvdep.js} +1 -1
  94. package/dist/assets/{sortable-tabs-strip-DMwkOrM-.js → sortable-tabs-strip-BwnT5maB.js} +1 -1
  95. package/dist/assets/{speechSettingsQueries-CJ3jPRqV.js → speechSettingsQueries-mH-OoFPq.js} +1 -1
  96. package/dist/assets/src-2lmG4z55.css +2 -0
  97. package/dist/assets/{terminalApi-eR_918UZ.js → terminalApi-CwTOFYhX.js} +1 -1
  98. package/dist/assets/{textarea-DwisQCE_.js → textarea-CVswImHY.js} +1 -1
  99. package/dist/assets/{tooltip-DloXgI9f.js → tooltip-DovnVenD.js} +1 -1
  100. package/dist/assets/{types-sn47BK8u.js → types-CnPxR5yQ.js} +1 -1
  101. package/dist/assets/{useAppFontEffects-zienz2u_.js → useAppFontEffects-wm0ojvh7.js} +62 -62
  102. package/dist/assets/{useAssistantUIStore-CphyXHEY.js → useAssistantUIStore-CI42fWZh.js} +1 -1
  103. package/dist/assets/{useDesktopWindowControlsLayout-VfqGsgdB.js → useDesktopWindowControlsLayout-BBizNJUb.js} +1 -1
  104. package/dist/assets/{useDictation-Do12BpsS.js → useDictation-OLmxagFb.js} +1 -1
  105. package/dist/assets/{useEffectiveDirectory-DtDqspBR.js → useEffectiveDirectory-BN5qbhev.js} +1 -1
  106. package/dist/assets/{useFontPreferences-DFF-uEAD.js → useFontPreferences-DN1mCOsX.js} +1 -1
  107. package/dist/assets/{useMobileHtmlPreviewStore-DUquFMmd.js → useMobileHtmlPreviewStore-DzzgY1eS.js} +1 -1
  108. package/dist/assets/{useMobileNavigationStore-BkVbj6Lg.js → useMobileNavigationStore-oveTY29a.js} +12 -12
  109. package/dist/assets/{usePluginsStore-BRtWcKUj.js → usePluginsStore-DErHgEFY.js} +1 -1
  110. package/dist/assets/{useProjectRuntimeAPIs-BbjZTtP4.js → useProjectRuntimeAPIs-B-ShHy6s.js} +1 -1
  111. package/dist/assets/{useStreamingTextThrottle-DMhoKnTy.js → useStreamingTextThrottle-BOvHQRrH.js} +1 -1
  112. package/dist/assets/{useUIStore-CYex4rbF.js → useUIStore-DjizmHAt.js} +1 -1
  113. package/dist/index.html +20 -20
  114. package/dist/mini-chat.html +20 -20
  115. package/dist/mobile.html +2 -2
  116. package/package.json +1 -1
  117. package/server/lib/gui-network/DOCUMENTATION.md +9 -1
  118. package/server/lib/realtime-proxy.js +4 -2
  119. package/server/lib/realtime-proxy.test.js +5 -4
  120. package/server/lib/relay/tunnel-host.js +15 -5
  121. package/server/lib/relay/tunnel-host.test.js +24 -0
  122. package/server/lib/remote-hosts/DOCUMENTATION.md +15 -2
  123. package/server/lib/remote-hosts/gateway.js +14 -4
  124. package/server/lib/remote-hosts/routes.js +9 -1
  125. package/server/lib/remote-hosts/routes.test.js +137 -7
  126. package/server/lib/remote-hosts/transport.js +1 -1
  127. package/server/lib/session-index/DOCUMENTATION.md +3 -0
  128. package/server/lib/session-index/service.js +4 -4
  129. package/server/lib/ui-auth/ui-auth.js +1 -1
  130. package/server/lib/ui-auth/ui-auth.test.js +3 -0
  131. package/dist/assets/MobileResizableSheet-Dkx27OGR.js +0 -1
  132. package/dist/assets/gitApiHttp-BEMPJCIG.js +0 -3
  133. package/dist/assets/main-DEQdAD0s.js +0 -169
  134. package/dist/assets/miniChat-VUMSA5V6.js +0 -2
  135. package/dist/assets/mobile-CiuyBKXM.js +0 -2
  136. package/dist/assets/queue-abort-optimistic-Bvno7WIB.js +0 -1
  137. package/dist/assets/readiness-C9buUgS7.js +0 -2
  138. package/dist/assets/renderMobileApp-f7DiCkl1.js +0 -29
  139. package/dist/assets/runtimeEndpointReset-CWAGENV5.js +0 -151
  140. package/dist/assets/src-DRyZ4dLj.css +0 -2
@@ -1 +1 @@
1
- import{f as e,n as t}from"./platform-wF65ZFgV.js";import{C as n,D as r,I as i,L as a,M as o,O as s,P as c,S as l,T as u,_ as d,a as f,b as p,c as m,j as h,n as g,o as _,r as v,s as y,t as ee,v as b,w as x,y as S}from"./vendor-opencode-client-BM2r1f0o.js";import{a as te}from"./vendor-tanstack-query-core-BSjXNgF_.js";import{b as ne,v as C}from"./runtime-file-resource-DnhWnndu.js";import{o as w}from"./path-utils-jGozTg9d.js";import{a as T,n as re}from"./vendor-aparajita-capacitor-secure-storage-xol_6BsB.js";import{Dt as ie,ht as ae,mt as oe,y as se}from"./vendor-effect-X1Hqc7ba.js";import{t as E}from"./native-errors-06if6eu-.js";import{a as ce,i as le,n as ue,o as de,r as fe,s as D}from"./appearance-DFsI3pnP.js";import{i as pe,o as me}from"./fileReferenceParser-1HHDBUum.js";import{a as he,r as O}from"./pages-CYkE04ml.js";import{n as ge,t as _e}from"./vendor-solid-js-BBVUd3Hw.js";import{a as ve,c as ye,d as be,f as k,g as A,h as j,i as M,l as N,m as xe,n as Se,o as P,p as F,r as Ce,s as we,t as Te,u as Ee}from"./vendor-opencode-plugin-ZhpPgHCL.js";var I={"@opencode/plugin/gui":P,"@opencode/plugin/gui/main":P,"@opencode/plugin/gui/file":ve,"@opencode/plugin/gui/review":M,"@opencode/plugin/gui/browser":Ce,"@opencode/plugin/rpc":Te,"@opencode/schema/rpc":Se,"@opencode/client":v,"@opencode/client/effect":g,"@opencode/client/solid":ee,effect:se,"solid-js":c,"solid-js/web":ge,"solid-js/store":y},De=new Set(`assert assert/strict async_hooks buffer child_process cluster console constants crypto dgram diagnostics_channel dns dns/promises domain events fs fs/promises http http2 https inspector inspector/promises module net os path path/posix path/win32 perf_hooks process punycode querystring readline readline/promises repl stream stream/consumers stream/promises stream/web string_decoder sys timers timers/promises tls trace_events tty url util util/types v8 vm wasi worker_threads zlib`.split(` `));function Oe(){let e=new Proxy(function(){},{get:(t,n)=>n===`then`?void 0:n===Symbol.hasInstance?()=>!1:n===Symbol.toPrimitive||n===`toString`?()=>`[main-only module]`:e,apply:()=>e,construct:()=>e,set:()=>!0});return e}function ke(e,t){if(e.length>16777216)throw Error(`GUI bundle exceeds 16 MiB`);let n={exports:{}};Function(`require`,`module`,`exports`,e)(e=>{if(Object.hasOwn(I,e))return I[e];if(e===`electron`||e.startsWith(`node:`)||De.has(e))return Oe();throw Error(`Unsupported GUI shared module: ${e}`)},n,n.exports);let r=n.exports,i=r&&typeof r==`object`&&`default`in r?r.default:r;if(!i||typeof i!=`object`)throw Error(`GUI bundle must default-export Plugin.define`);if((!(`setup`in i)||typeof i.setup!=`function`)&&!(t&&`main`in i&&typeof i.main==`function`))throw new E(`GUI_PLUGIN_UNSUPPORTED`,`This host requires a window setup; main-only plugins are unsupported`);if(`os`in i&&i.os!==void 0){if(!t)throw new E(`GUI_PLUGIN_UNSUPPORTED`,`OS-restricted plugins require the native GUI host`);if(!Array.isArray(i.os)||!i.os.includes(t))throw new E(`GUI_PLUGIN_UNSUPPORTED`,`GUI plugin is unavailable on this OS`)}if(`main`in i&&i.main!==void 0&&typeof i.main!=`function`)throw Error(`Invalid GUI main entry`);if(`stores`in i&&i.stores!==void 0){if(!i.stores||typeof i.stores!=`object`||Array.isArray(i.stores))throw Error(`Invalid GUI stores`);for(let e of Object.values(i.stores))if(!e||typeof e!=`object`||!(`schema`in e)||!ie(e.schema)||!(`scope`in e)||![`global`,`session`].includes(String(e.scope))||!(`initial`in e))throw Error(`Invalid GUI store declaration`)}if(`i18n`in i&&i.i18n!==void 0){if(!i.i18n||typeof i.i18n!=`object`||Array.isArray(i.i18n))throw Error(`Invalid GUI locale catalog`);for(let e of Object.values(i.i18n))if(!e||typeof e!=`object`||Array.isArray(e)||Object.values(e).some(e=>typeof e!=`string`))throw Error(`GUI locales must be inline string dictionaries`)}return i}function L(t){let n=t;if(/^file:/i.test(n)){let e=new URL(n);n=`${e.hostname&&e.hostname!==`localhost`?`//${e.hostname}`:``}${decodeURIComponent(e.pathname)}`,/^\/[a-z]:\//i.test(n)&&(n=n.slice(1))}let r=e(n)??``;return r===`.`?``:r}var R=e=>/^(?:\/|[a-z]:\/)/i.test(e),z=()=>{throw Error(`Unsupported GUI file API: tree`)},B=class extends Error{},V=e=>new TextEncoder().encode(e).byteLength,Ae=class{files;query;transport;root;api;ended=!1;states=new Map;inflight=new Map;watches=new Map;apiLeases=new Map;registeredOwners=new WeakSet;endedOwners=new WeakSet;leaseCount=0;rerun=new Set;selections=new Map;scrolls=new Map;subscriptions=new Map;constructor(e,t,n,r){this.files=e,this.query=t,this.transport=n,this.root=r,this.root=L(r),this.api={root:this.root,ready:()=>!this.ended,resolve:e=>this.resolve(e),absolute:R,get:e=>{let t=this.track(e,`file`);return this.states.get(t)},missing:e=>{let t=this.track(e,`missing`);return this.states.get(t)?.notFound===!0},sync:(e,t)=>{let n=s();return this.ended||n&&this.endedOwners.has(n)?Promise.resolve():(this.acquireApiLease(e),this.sync(e,t?.force))},unwatch:e=>this.releaseApiLease(s(),this.resolve(e)),exists:async e=>{try{if(this.files.statFile)return(await this.query.fetchQuery(this.statOptions(e))).isFile;let t=this.full(e);return(await this.files.listDirectory(t.slice(0,t.lastIndexOf(`/`)))).entries.some(e=>!e.isDirectory&&L(e.path)===t)}catch{return!1}},search:async(e,t)=>{if(t?.kind===`any`)throw Error(`Unsupported GUI file search: directories`);t?.signal?.throwIfAborted();let r=await this.query.fetchQuery({queryKey:[`gui-plugin-files`,n,this.root,`search`,e,t?.limit],gcTime:3e4,queryFn:async({signal:n})=>(n.throwIfAborted(),this.files.search({directory:this.root,query:e,maxResults:t?.limit??100}))});if(t?.signal?.throwIfAborted(),this.ended)throw new DOMException(`GUI file model was disposed`,`AbortError`);return r.map(e=>this.resolve(e.path))},selection:{get:e=>this.selections.get(this.track(e,`selection`)),set:(e,t)=>{let n=this.resolve(e),r=this.selections.get(n);r===t||r&&t&&r.start===t.start&&r.end===t.end&&r.side===t.side&&r.endSide===t.endSide||(this.selections.set(n,t),this.trim(this.selections,`selection`),this.changed(n,`selection`))}},scroll:{get:e=>this.scrolls.get(this.track(e,`scroll`))??{},set:(e,t)=>{let n=this.resolve(e),r=this.scrolls.get(n),i={...r,...t};(r?.top!==i.top||r?.left!==i.left)&&(this.scrolls.set(n,i),this.trim(this.scrolls,`scroll`),this.changed(n,`scroll`))}},tree:{list:z,state:z,sync:z,expand:z,collapse:z}}}resolve(e){let t=L(e);if(!R(t))return t;if(t===this.root)return``;let n=this.root.endsWith(`/`)?this.root:`${this.root}/`;return t.startsWith(n)?t.slice(n.length):t}full(e){let t=this.resolve(e);return R(t)?t:L(`${this.root}/${t}`)}input(e){return{scopeDirectory:this.root,path:this.full(e),options:{directory:this.root}}}statOptions(e){return{...ne(this.files,this.input(e),this.transport),gcTime:3e4}}track(e,t){let n=this.resolve(e),i=r();if(!i||this.ended)return n;let a=`${t}:${n}`,s=this.subscriptions.get(a);s||(s={revision:u(0),listeners:new Set},this.subscriptions.set(a,s));let c=s;return c.listeners.has(i)||(c.listeners.add(i),o(i,()=>h(()=>{c.listeners.delete(i),!c.listeners.size&&this.subscriptions.get(a)===c&&this.subscriptions.delete(a)}))),c.revision[0](),n}changed(e,t){this.ended||this.subscriptions.get(`${t}:${e}`)?.revision[1](e=>e+1)}trim(e,t){for(;e.size>64;){let n=e.keys().next().value;e.delete(n),this.changed(n,t)}}setState(e,t){let n=this.states.get(e);n?.content?.content===t.content?.content&&n?.content?.type===t.content?.type&&(t.content=n?.content),!(n&&n.loaded===t.loaded&&n.loading===t.loading&&n.error===t.error&&n.notFound===t.notFound&&n.content===t.content)&&(this.states.set(e,t),d(()=>{this.changed(e,`file`),n?.notFound===!0!=(t.notFound===!0)&&this.changed(e,`missing`)}))}acquireApiLease(e){let t=s();if(this.ended||t&&this.endedOwners.has(t)||!this.files.statFile)return;let n=this.resolve(e),r=this.apiLeases.get(t);if(r?.has(n))return;if(this.leaseCount>=256)throw Error(`GUI file consumer limit exceeded`);let i=this.watch(n);r||(r=new Map,this.apiLeases.set(t,r)),r.set(n,i),this.leaseCount++,t&&!this.registeredOwners.has(t)&&(this.registeredOwners.add(t),h(()=>{`fn`in t||this.endedOwners.add(t),this.registeredOwners.delete(t);for(let e of[...this.apiLeases.get(t)?.keys()??[]])this.releaseApiLease(t,e)}))}releaseApiLease(e,t){let n=this.apiLeases.get(e),r=n?.get(t);r&&(n.delete(t),this.leaseCount--,n.size||this.apiLeases.delete(e),r())}reserve(e){if(!this.states.has(e)){if(this.states.size>=64){let e=[...this.states.keys()].find(e=>!this.watches.has(e)&&!this.inflight.has(e));if(!e)throw Error(`GUI file cache limit exceeded`);let t=this.states.get(e)?.notFound===!0;this.states.delete(e),d(()=>{this.changed(e,`file`),t&&this.changed(e,`missing`)})}this.states.set(e,{path:e,name:e.split(`/`).at(-1)??e})}}async sync(e,t=!1){if(this.ended)return;let n=this.resolve(e);if(this.inflight.has(n))return t&&this.rerun.add(n),this.inflight.get(n);if(!t&&this.states.get(n)?.loaded&&!this.states.get(n)?.error)return;this.reserve(n);let r=this.states.get(n);this.setState(n,{...r,path:n,name:n.split(`/`).at(-1)??n,loading:!r?.loaded&&!this.watches.get(n)?.failed});let i=(async()=>{try{do{this.rerun.delete(n);let e=this.watches.get(n),r=e?.epoch;try{let i=C(this.files,this.input(n),this.transport),a=await this.query.fetchQuery({...i,gcTime:3e4,staleTime:t?0:3e4,queryFn:async()=>{if(!this.files.readFile)throw Error(`File content reads are unavailable in this runtime`);let e=await this.files.readFile(this.full(n),{directory:this.root});if(e.exists===!1)throw new B(`File does not exist`);let t=e.content;if(V(t)>131072)throw Error(`GUI file preview exceeds 128 KiB`);return t}});if(this.ended)return;if(V(a)>131072)throw Error(`GUI file preview exceeds 128 KiB`);(!e||e.epoch===r&&!e.failed)&&this.setState(n,{path:n,name:n.split(`/`).at(-1)??n,loaded:!0,loading:!1,content:{type:`text`,content:a}})}catch(t){if(this.ended)return;if((!e||e.epoch===r&&!e.failed)&&this.setState(n,{...this.states.get(n),loading:!1,...t instanceof B?{notFound:!0}:{},error:String(t)}),!this.rerun.has(n))throw t}t=!0}while(!this.ended&&this.rerun.has(n))}finally{this.inflight.delete(n),this.rerun.delete(n)}})();return this.inflight.set(n,i),i}watch(e){if(this.ended||!this.files.statFile)return()=>{};let t=this.resolve(e),n=this.watches.get(t);if(!n){if(this.watches.size>=64)throw Error(`GUI file watch limit exceeded`);this.reserve(t),n={count:0,epoch:0,failed:!1,stop:()=>{}};let e=n;this.watches.set(t,e);let r,i=new te(this.query,{...this.statOptions(t),refetchInterval:2e3,refetchIntervalInBackground:!1}),a=i.subscribe(n=>{if(this.ended||this.watches.get(t)!==e||n.isFetching)return;if(n.isError||n.isSuccess&&!n.data.isFile){e.failed=!0,e.epoch++,this.setState(t,{...this.states.get(t),loading:!1,notFound:n.isSuccess?!0:this.states.get(t)?.notFound,error:n.isError?String(n.error):`File does not exist`});return}if(!n.data||!n.isSuccess)return;let i=`${n.data.size}:${n.data.mtimeMs??``}`,a=e.failed||r!==void 0&&i!==r;e.failed=!1,r=i,a&&(e.epoch++,this.sync(t,!0).catch(()=>{}))});e.stop=()=>{a(),i.destroy()},this.states.get(t)?.loaded&&this.sync(t,!0).catch(()=>{})}n.count++;let r=!0;return()=>{r&&(r=!1,--n.count===0&&this.watches.get(t)===n&&this.stopWatch(t))}}stopWatch(e){this.watches.get(e)?.stop(),this.watches.delete(e)}dispose(){this.ended=!0;for(let e of this.watches.values())e.stop();this.watches.clear(),this.apiLeases.clear(),this.leaseCount=0,this.rerun.clear(),this.states.clear(),this.inflight.clear(),this.selections.clear(),this.scrolls.clear(),this.subscriptions.clear()}},H=256,U=2097152,W=e=>structuredClone(m(e)),je=class{backend;transport;memory=new Map;resets=new Map;constructor(e,t){this.backend=e,this.transport=t}forPlugin(e,t){let n=(t,n=`global`)=>{if(typeof n==`object`&&`session`in n&&!n.session.location)throw Error(`Unsupported GUI storage: session location is unknown`);let r=n===`global`?n:`session`in n?[n.session.server.id,n.session.id,n.session.location]:[n.server,n.directory];return`yuri.gui-plugin.${JSON.stringify([this.transport,e,r,t])}`},r=e=>{if(t.aborted)throw Error(`GUI plugin has been disposed`);if(e!==void 0)throw Error(`Unsupported GUI storage migration: from`)},i=new Map;return{store:(e,a)=>{r(a.from);let o=n(e,a.scope),s=i.get(o);if(s)return s;if(i.size>=H)throw Error(`GUI plugin store limit exceeded`);let c=oe(a.schema),l=ae(a.schema),d=c(l(W(a.initial)));if(JSON.stringify(l(d)).length>U)throw Error(`GUI plugin store exceeds 2 MiB`);let f=d,p=this.backend.getItem(o);if(p!==null&&p.length<=U)try{f=c(JSON.parse(p))}catch{f=d}let[m,h]=u(f),g=e=>{r();let t=JSON.stringify(l(W(e)));if(t.length>U)throw Error(`GUI plugin store exceeds 2 MiB`);let n=c(JSON.parse(t));this.backend.setItem(o,t),h(()=>n)},_={get value(){return m()},ready:()=>!0,set:g,update:e=>{let t=W(m());if(e(t)!==void 0)throw Error(`Store update must not return a replacement`);g(t)}},v=()=>h(()=>W(d)),y=this.resets.get(o)??new Set;return y.add(v),this.resets.set(o,y),t.addEventListener(`abort`,()=>{y.delete(v),y.size||this.resets.delete(o),i.clear()},{once:!0}),i.set(o,_),_},memory:(e,t)=>{r();let i=n(e),a=this.memory.get(i);if(a)return[a[0],e=>{r(),a[1](e)}];if(this.memory.size>=H)throw Error(`GUI plugin memory store limit exceeded`);if(JSON.stringify(t.initial).length>U)throw Error(`GUI plugin memory exceeds 2 MiB`);let[o,s]=f(W(t.initial)),c=[o,e=>{r();let t=W(m(o));if(e(t)!==void 0)throw Error(`Memory update must not return a replacement`);if(JSON.stringify(t).length>U)throw Error(`GUI plugin memory exceeds 2 MiB`);s(_(t))}];return this.memory.set(i,[o,e=>{let t=W(m(o));if(e(t)!==void 0)throw Error(`Memory update must not return a replacement`);if(JSON.stringify(t).length>U)throw Error(`GUI plugin memory exceeds 2 MiB`);s(_(t))}]),c},remove:(e,t)=>{r(t?.from);let i=n(e,t?.scope);this.backend.removeItem(i);for(let e of this.resets.get(i)??[])e()}}}dispose(){this.memory.clear(),this.resets.clear()}};function Me(e){if(typeof e!=`string`||e.length>2097152)return;let t=e.trim();if(t)try{if(t.startsWith(`<`))return D(t);if(!/^data:/i.test(t))return t;let e=/^data:image\/(svg\+xml|png|jpeg|gif|webp|avif|x-icon|vnd\.microsoft\.icon)(?:;charset=utf-8)?(;base64)?,([\s\S]+)$/i.exec(t);if(!e)return;let[,n,r,i]=e;if(r&&!/^[A-Za-z0-9+/]+={0,2}$/.test(i))return;if(n.toLowerCase()===`svg+xml`){let e=r?new TextDecoder(`utf-8`,{fatal:!0}).decode(Uint8Array.from(atob(i),e=>e.charCodeAt(0))):decodeURIComponent(i);return D(e)}return!r||!atob(i).length?void 0:`data:image/${n.toLowerCase()};base64,${i}`}catch{return}}var G=e=>e===`yuri.exportPDF`||e===`yuri.exportLongImage`,Ne=class{api;probe;clients=new Map;ended=!1;constructor(e){this.api=e}use(e,t){let n=this.clients.get(t),r=n?.get(e);if(r)return r.live;let[i,a]=u(this.api&&!t.aborted&&!this.ended?{status:`pending`}:{status:`inactive`,reason:`disabled`}),o=()=>{a({status:`inactive`,reason:`disabled`}),t.removeEventListener(`abort`,o),this.clients.delete(t)},s={live:A(i),stop:o};if(this.ended||t.aborted||(n||(n=new Map,this.clients.set(t,n)),n.set(e,s),t.addEventListener(`abort`,o,{once:!0}),!this.api))return s.live;let c=this.api;return this.probe??=Promise.resolve().then(()=>c.capabilities()),this.probe.then(n=>{if(this.ended||t.aborted)return;let r=e===`yuri.exportPDF`?`exportPDF`:`exportLongImage`;if(n.version!==1||!n[r]){a({status:`inactive`,reason:`disabled`});return}let o=async(e,n={})=>{if(this.ended||t.aborted||i().status!==`active`)return{status:`cancelled`};let o=AbortSignal.any([t,...n.signal?[n.signal]:[]]);try{return await c[r](e,{...n,signal:o})}catch(e){throw e&&typeof e==`object`&&`code`in e&&e.code===`EXPORT_UNSUPPORTED`&&a({status:`inactive`,reason:`failed`}),e}},s=Object.freeze(e===`yuri.exportPDF`?{version:1,limits:n.limits,exportPDF:o}:{version:1,limits:n.limits,exportLongImage:o});a({status:`active`,generation:1,value:s})}).catch(()=>{!this.ended&&!t.aborted&&a({status:`inactive`,reason:`failed`})}),s.live}dispose(){this.ended=!0;for(let e of this.clients.values())for(let t of e.values())t.stop();this.clients.clear()}};function Pe(e,t){let n=new Map,r=Object.freeze({dismiss(){}});return e.addEventListener(`abort`,()=>{for(let e of[...n.values()])e.handle.dismiss()},{once:!0}),Object.freeze({show(i){if(e.aborted)return r;if(!t)throw new E(`GUI_PLUGIN_UNSUPPORTED`,`GUI toast is unavailable`);if(!i||typeof i!=`object`)throw new E(`GUI_PLUGIN_INVALID_INPUT`,`Expected toast options`);let{title:a,description:o,variant:s=`default`,duration:c=5e3,persistent:l=!1,icon:u,actions:d}=i;if(typeof a!=`string`||o!==void 0&&typeof o!=`string`||![`default`,`success`,`error`,`loading`].includes(s)||typeof l!=`boolean`||typeof c!=`number`||!Number.isFinite(c)||c<0)throw new E(`GUI_PLUGIN_INVALID_INPUT`,`Invalid toast options`);if(u!==void 0||d!==void 0)throw new E(`GUI_PLUGIN_UNSUPPORTED`,`GUI toast icon/actions are unsupported`);if(e.aborted)return r;let f=JSON.stringify([a,o??null,s,c,l]),p=n.get(f),m=()=>{let e=n.get(f);!e||e.id!==h||(clearTimeout(e.timer),n.delete(f))},h=(s==="default"?t:t[s])(a,{id:p?.id,description:o,duration:l?1/0:c,onDismiss:m,onAutoClose:m}),g=p?.handle??Object.freeze({dismiss(){m(),t.dismiss(h)}});clearTimeout(p?.timer);let _=s===`loading`&&!l?setTimeout(()=>g.dismiss(),c):void 0;return n.set(f,{id:h,handle:g,timer:_}),g}})}var Fe=T(`YuriMedia`);async function Ie(e){let n=/\.html?$/i.test(e.name)?`text/html`:`text/plain`,r=new Blob([e.content],{type:n});if(t()){if(!re.isPluginAvailable(`YuriMedia`))throw new E(`GUI_PLUGIN_UNSUPPORTED`,`Native file saving is unavailable`);if(r.size>33554432)throw new E(`GUI_PLUGIN_INVALID_INPUT`,`File exceeds maximum size`);let t=await new Promise((e,t)=>{let n=new FileReader;n.onload=()=>{if(typeof n.result!=`string`){t(Error(`Failed to encode file`));return}e(n.result.slice(n.result.indexOf(`,`)+1))},n.onerror=()=>t(n.error??Error(`Failed to encode file`)),n.readAsDataURL(r)});return!(await Fe.saveFile({dataBase64:t,mimeType:n,filename:e.name})).cancelled}let i=URL.createObjectURL(r),a=document.createElement(`a`);try{return a.href=i,a.download=e.name,document.body.append(a),a.click(),!0}finally{a.remove(),setTimeout(()=>URL.revokeObjectURL(i),1e3)}}var K=p();function Le(e){return{version:1,register(t){let n=a(K);if(!n||n.plugin!==e||n.signal.aborted||e.aborted)throw Error(`Preview actions require the owning mounted panel`);let r=new AbortController,i=AbortSignal.any([e,n.signal,r.signal]),o,s=()=>{i.removeEventListener(`abort`,s),r.abort(),o?.remove()};h(s),i.addEventListener(`abort`,s,{once:!0});try{o=t.render({element:t.element,signal:i,async snapshot(e={}){let r=AbortSignal.any([i,...e.signal?[e.signal]:[]]);if(r.throwIfAborted(),!n.content.contains(t.element)||n.target.contains(t.element))throw Error(`Preview capture region is no longer in its owning panel`);let a=await t.capture({...e,signal:r});if(r.throwIfAborted(),!n.content.contains(t.element))throw Error(`Preview capture region was replaced`);return a}}),i.throwIfAborted(),n.target.append(o)}catch(e){throw s(),e}return s}}}var Re=`yuri.work-status`;function q(e,t){return e===t||!!(e&&t&&Object.keys(e).length===Object.keys(t).length&&Object.keys(e).every(n=>e[n]===t[n]))}var J=e=>e&&Object.freeze({...e});function Y(e,t,n){let r=new AbortController,[i,a]=u(!0),[o,s]=u(J(e.project),{equals:q}),[c,l]=u(J(e.worktree),{equals:q}),[f,p]=u(Object.freeze({...e.git}),{equals:q}),[m,h]=u(e.placement);return{props:Object.freeze({session:t,directory:e.directory,runtimeId:n,signal:r.signal,get active(){return i()},get project(){return o()},get worktree(){return c()},get git(){return f()},get placement(){return m()}}),matches:t=>t.sessionId===e.sessionId&&t.directory===e.directory&&t.scope===e.scope,update(e){r.signal.aborted||d(()=>{s(J(e.project)),l(J(e.worktree)),p(Object.freeze({...e.git})),h(e.placement)})},dispose(){r.signal.aborted||(a(!1),r.abort())}}}var ze=class{plugins=new Map;order=new Map;snapshot=Object.freeze([]);generation=0;listeners=new Set;subscribe=e=>(this.listeners.add(e),()=>{this.listeners.delete(e)});getSnapshot=()=>this.snapshot;setOrder(e){e.length===this.order.size&&e.every((e,t)=>this.order.get(e)===t)||(this.order=new Map(e.map((e,t)=>[e,t])),this.publish())}replace(e,t,n){let r=this.plugins.get(e)??[],i=new Set,a=n.map(n=>{if(!n||typeof n!=`object`||!(`id`in n)||typeof n.id!=`string`||!n.id.trim()||n.id.length>128||i.has(n.id)||!(`render`in n)||typeof n.render!=`function`||`order`in n&&n.order!==void 0&&(typeof n.order!=`number`||!Number.isFinite(n.order)))throw Error(`Invalid or duplicate yuri.work-status contribution`);i.add(n.id);let a=JSON.stringify([e,n.id]),o=`order`in n&&typeof n.order==`number`?n.order:0,s=n.render,c=r.find(e=>e.key===a),l=c&&c.revision===t&&c.render===s?c.generation:++this.generation;return c&&c.revision===t&&c.render===s&&c.order===o?c:Object.freeze({key:a,pluginId:e,revision:t,generation:l,order:o,render:s})});a.length?this.plugins.set(e,a):this.plugins.delete(e),this.publish()}contains(e){return this.plugins.get(e.pluginId)?.some(t=>t.key===e.key&&t.generation===e.generation)??!1}remove(e){this.plugins.delete(e)&&this.publish()}dispose(){this.plugins.clear(),this.publish(),this.listeners.clear()}publish(){let e=[...this.plugins.values()].flat().sort((e,t)=>e.order-t.order||(this.order.get(e.pluginId)??2**53-1)-(this.order.get(t.pluginId)??2**53-1));if(!(e.length===this.snapshot.length&&e.every((e,t)=>e===this.snapshot[t]))){this.snapshot=Object.freeze(e);for(let e of this.listeners)i(e)}}},X=e=>{throw new E(`GUI_PLUGIN_UNSUPPORTED`,`Unsupported GUI host API: ${e}`)};function Z(e,t){return new Proxy(t,{get:(t,n)=>n in t?Reflect.get(t,n):X(`${e}.${String(n)}`)})}var Q=e=>Object.freeze(e.map(e=>Object.freeze(e)));function Be(e,t){if(!e.fields||!t.fields)return!1;let n=Reflect.ownKeys(e.fields);return n.length===Reflect.ownKeys(t.fields).length&&n.every(n=>{let r=e.fields[n],i=t.fields[n];return i!==void 0&&`value`in r&&`value`in i&&Object.is(r.value,i.value)&&r.enumerable===i.enumerable&&r.configurable===i.configurable&&r.writable===i.writable})}function $(e,t){if(e){for(let n of e.owned??[])$(n,t);e.cleanups&&=e.cleanups.map(e=>()=>{try{Promise.resolve(e()).catch(t)}catch(e){t(e)}})}}var Ve=class{options;fileIcons=new de;appearanceCatalog=new le;workStatus=new ze;instances=new Map;listeners=new Set;panelMounts=new Set;fileViews=new Map;changes=u(0);views=u(0);session=u();currentPage=u();mobilePageNetworkReady=u(!1);appearance;layouts=new Map;files;storage;ended=!1;contracts=new Map;snapshot=Object.freeze({plugins:Object.freeze([]),commands:Object.freeze([]),titlebarItems:Object.freeze([]),panels:Object.freeze([]),pages:Object.freeze([]),settings:Object.freeze([]),menuItems:Object.freeze([]),activePanel:null});#e;viewExports;constructor(e){this.options=e,this.viewExports=new Ne(e.viewExport),this.appearance=u({locale:e.locale,mode:e.mode,narrow:e.narrow}),this.storage=new je(e.storage,e.transport);let t=()=>(this.session[0](),this.files?.api??X(`screen.file without a session`));this.#e=Z(`screen`,{get file(){return t()}})}subscribe=e=>(this.listeners.add(e),()=>{this.listeners.delete(e)});getSnapshot=()=>this.snapshot;changed(e=!1){let t=this.snapshot;this.changes[1](e=>e+1),e&&t===this.snapshot&&this.publish()}setSession(e){if(this.ended)return;let t=this.session[0]();if(t?.id===e?.id&&t?.directory===e?.directory)return;if(!e)for(let e of[...this.panelMounts])e();this.files?.dispose(),this.files=e?new Ae(this.options.files,this.options.queryClient,this.options.transport,e.directory):void 0;let n=e?this.sessionReference(e):void 0,r=this.snapshot;this.session[1](n),r===this.snapshot&&this.publish()}sessionReference(e,t){let n=t?JSON.stringify(t.queryScope):this.options.transport,r=Z(`session.server`,{id:n,name:t?.location.hostId??this.options.transport,...t?{}:{client:this.options.client}});return Object.freeze(Z(`session`,{id:e.id,directory:e.directory,key:t?JSON.stringify([n,e.id]):`${this.options.transport}\n${e.id}`,tab:e.id,server:r,pending:!1,visit:{},location:t?Object.freeze({...t.location}):{directory:e.directory}}))}setAppearance(e){if(this.ended)return;let t=this.appearance[0]();(t.locale!==e.locale||t.mode!==e.mode||t.narrow!==e.narrow)&&this.appearance[1]({...e})}setPage(e){this.ended||this.currentPage[1](e)}setMobilePageNetworkReady(e){this.mobilePageNetworkReady[1](!this.ended&&e)}install(e,t,r){if(this.options.mobileNetworkRequired&&!this.mobilePageNetworkReady[0]()&&!this.ended)throw new E(`GUI_PLUGIN_UNAVAILABLE`,`Mobile plugin Relay is not ready`);let a=this.instances.get(e);if(this.ended||a?.status===`active`&&a.revision===t.revision&&a.native?.active!==!1){r?.dispose();return}a&&(this.instances.delete(e),this.release(a));let c={id:e,native:r,revision:t.revision,controller:new AbortController,status:`active`,cleanups:new Set,contributions:new Set,iconChanges:u(0),appearanceChanges:u(0),workStatusChanges:u(0),commands:[],titlebarItems:[],panels:[],pages:[],settings:[],menus:[]};this.instances.set(e,c);try{if(e===`yuri`||e.startsWith(`yuri.`))throw Error(`The yuri namespace is reserved to the host`);let a=ke(t.code,r?.activation.os);x(e=>{c.dispose=e,c.root=s(),b(()=>S(j.Provider,{value:c.context=this.context(c,a,t.options),get children(){c.owner=s();let e=i(()=>a.setup?.(c.context));if(typeof e==`function`)c.cleanups.add(()=>{Promise.resolve(e()).catch(e=>{c.error=String(e)})});else if(e!==void 0)throw e&&typeof e==`object`&&`then`in e&&Promise.resolve(e).catch(()=>{}),Error(`GUI setup must be synchronous and return only cleanup`);return null}}),e=>this.fail(c,e)),c.controller.signal.aborted||o(c.owner,()=>n(()=>{if(c.iconChanges[0](),!c.controller.signal.aborted)try{let e=[...c.contributions].filter(e=>e.registry===ce).map(e=>e.read()).filter(e=>e!==void 0);this.fileIcons.replace(c.id,e),c.iconError!==void 0&&i(()=>{c.iconError=void 0,this.publish()})}catch(e){i(()=>{this.fileIcons.remove(c.id),c.iconError=e instanceof Error?e.message:String(e),this.publish()})}})),c.controller.signal.aborted||o(c.owner,()=>n(()=>{if(c.appearanceChanges[0](),!c.controller.signal.aborted)try{let e=e=>[...c.contributions].filter(t=>t.registry===e).map(e=>e.read()).filter(e=>e!==void 0);this.appearanceCatalog.replace(c.id,e(fe),e(ue),c.native?.activation.capabilities?.dockIcon===!0)}catch(e){i(()=>this.fail(c,e))}})),c.controller.signal.aborted||o(c.owner,()=>n(()=>{if(c.workStatusChanges[0](),!c.controller.signal.aborted)try{let e=[...c.contributions].filter(e=>e.registry===Re).map(e=>e.read()).filter(e=>e!==void 0);this.workStatus.replace(c.id,c.revision,e)}catch(e){i(()=>this.fail(c,e))}})),c.controller.signal.aborted||o(c.owner,()=>n(()=>{this.changes[0](),this.session[0](),this.appearance[0]();try{this.derive(c)}catch(e){i(()=>this.fail(c,e))}i(()=>this.publish())}))})}catch(e){this.fail(c,e)}this.changed(!0)}release(e){e.controller.abort(),e.native?.dispose();for(let t of[...e.cleanups])try{t()}catch(t){e.error??=String(t)}e.cleanups.clear(),$(e.root,t=>{e.error??=String(t)});try{e.dispose?.()}catch(t){e.error??=String(t)}e.contributions.clear(),e.commands=[],e.titlebarItems=[],e.panels=[],e.pages=[],e.settings=[],e.menus=[],this.fileIcons.remove(e.id),this.appearanceCatalog.remove(e.id),this.workStatus.remove(e.id);for(let t of this.contracts.values())t.provider===e&&(t.provider=void 0,t.live[1]({status:`inactive`,reason:e.status===`failed`?`failed`:`disabled`}))}fail(e,t){e.status!==`failed`&&this.instances.get(e.id)===e&&(e.status=`failed`,e.error=t instanceof Error?t.message:String(t),t instanceof E&&(e.errorCode=t.code),this.release(e),this.publish())}uninstall(e){let t=this.instances.get(e);if(t){this.instances.delete(e),this.release(t);for(let t of this.layouts.values())t.open=t.open.filter(t=>!t.startsWith(`${e}:`)),t.active?.startsWith(`${e}:`)&&(t.active=null);this.changed(!0)}}dispose(){this.ended||(this.ended=!0,d(()=>{for(let e of[...this.instances.keys()])this.uninstall(e)}),this.viewExports.dispose(),this.files?.dispose(),this.fileIcons.dispose(),this.appearanceCatalog.dispose(),this.workStatus.dispose(),this.storage.dispose(),this.layouts.clear(),this.fileViews.clear(),this.contracts.clear(),this.listeners.clear())}async setDockIcon(e,t){let n=this.instances.get(e),r=n?.native;if(!r?.active||!r.activation.capabilities?.dockIcon)return X(`Dock icon`);try{await r.setDockIcon(t)}catch(e){throw t!==null&&n&&this.fail(n,e),e}}own(e,t){let n=!0,r=()=>{n&&(n=!1,e.cleanups.delete(r),t())};return e.controller.signal.aborted||a(F)?.ended?(r(),r):(e.cleanups.add(r),s()&&h(r),r)}list(e){this.changes[0]();let t=[];for(let n of this.instances.values())if(n.status===`active`){for(let r of n.contributions)if(r.registry===e.id){let e=r.read();e!==void 0&&t.push(e)}}return t}context(e,t,r){let o=this.storage.forPlugin(e.id,e.controller.signal),c=Object.fromEntries(Object.entries(t.stores??{}).map(([e,t])=>[e,t.scope===`global`?o.store(e,{...t,scope:`global`}):n=>o.store(e,{...t,scope:{session:n}})])),u=(e,n)=>{let r=this.appearance[0]().locale;return(t.i18n?.[r]?.[e]??t.i18n?.[r.split(`-`)[0]]?.[e]??t.i18n?.en?.[e]??e).replace(/\{\{(\w+)\}\}/g,(e,t)=>String(n?.[t]??e))},d=Z(`layout`,{narrow:()=>this.appearance[0]().narrow,ready:()=>!!this.session[0](),open:(t,n,r)=>{e.controller.signal.aborted||this.openPanel(t,n,r)},close:(t,n)=>{e.controller.signal.aborted||this.closeFor(t,n)},toggle:(e,t)=>d.state(e,t)===`visible`?d.close(e,t):d.open(e,t),hide:(t,n)=>{if(e.controller.signal.aborted)return;let r=this.layout(n);r.active===t&&r.shown&&(r.shown=!1,this.changed())},state:(e,t)=>{this.changes[0]();let n=this.layout(t);return n.active===e?n.shown?`visible`:`active`:n.open.includes(e)?`open`:`closed`},stored:t=>(this.changes[0](),this.layout(t).open.filter(t=>t.startsWith(`${e.id}:`)).map(t=>t.slice(e.id.length+1))),side:{opened:e=>(this.changes[0](),this.layout(e).shown),toggle:t=>{if(e.controller.signal.aborted)return;let n=this.layout(t);n.shown=!n.shown,this.changed()},menu:()=>this.list(N).filter(e=>e.menu===`session.panel`).sort((e,t)=>(e.order??0)-(t.order??0))},scroll:{get:(e,t)=>(this.changes[0](),this.layout(e).scroll.get(t)),set:(t,n,r)=>{if(e.controller.signal.aborted)return;let i=this.layout(t).scroll;if(!i.has(n)&&i.size>=128)throw Error(`GUI layout scroll limit exceeded`);i.set(n,{...r}),this.changed()}}}),f=Le(e.controller.signal),p=A(()=>e.controller.signal.aborted?{status:`inactive`,reason:`disabled`}:{status:`active`,generation:1,value:f}),m={open:t=>e.controller.signal.aborted||this.appearance[0]().narrow&&!this.mobilePageNetworkReady[0]()||!e.pages.some(e=>e.id===t)?!1:this.options.openPage?.(O(e.id,t))??!1,current:()=>{let t=this.currentPage[0]();return e.pages.find(n=>O(e.id,n.id)===t)?.id}},g=A(()=>e.controller.signal.aborted||!this.options.openPage||this.appearance[0]().narrow&&!this.mobilePageNetworkReady[0]()?{status:`inactive`,reason:`disabled`}:{status:`active`,generation:1,value:m});return Z(`ctx`,{id:e.id,options:r,signal:e.controller.signal,client:this.options.client,storage:o,stores:c,toast:Pe(e.controller.signal,this.options.toast),app:{name:`yuri`,version:e.native?.activation.app.version??``,channel:e.native?.activation.app.packaged?`prod`:`local`,platform:e.native?`desktop`:`web`,packaged:e.native?.activation.app.packaged??!1},desktop:e.native?Z(`desktop`,{os:e.native.activation.os}):void 0,t:u,plural:(e,t,n)=>{let r=`${e}.${new Intl.PluralRules(this.appearance[0]().locale).select(t)}`;return u(r,{...n,count:t})===r?u(`${e}.other`,{...n,count:t}):u(r,{...n,count:t})},add:(t,r)=>{if(e.controller.signal.aborted||a(F)?.ended)return()=>{};if([`server`,`composer-pill`,`slot`,`file.viewer`,`menubar-item`].includes(t.id)&&X(`registry.${t.id}`),e.contributions.size>=256)throw Error(`GUI contribution limit exceeded`);let o=()=>{},c,u=x(i=>{o=i,c=s();let a=()=>typeof r==`function`?r():r,u;if(t.id===`yuri.file-icon`){let e=l(()=>{try{return{ok:!0,value:a()}}catch(e){return{ok:!1,error:e}}});u=()=>{let t=e();if(!t.ok)throw t.error;return t.value}}else u=l(a);if(t.id===`style`){let t=document.createElement(`style`);t.dataset.yuriPluginStyle=e.id,document.head.append(t),h(()=>t.remove()),n(()=>{let e=u();t.textContent=e===void 0?``:String(e)})}return{registry:t.id,read:u}},s()??e.owner);e.contributions.add(u);let d=()=>{t.id===`yuri.file-icon`&&e.iconChanges[1](e=>e+1)},f=()=>{(t.id===`yuri.theme`||t.id===`yuri.branding`)&&e.appearanceChanges[1](e=>e+1)},p=()=>{t.id===`yuri.work-status`&&e.workStatusChanges[1](e=>e+1)};return i(d),i(f),i(p),i(()=>this.changed()),this.own(e,()=>{$(c,t=>{e.error??=String(t)}),o(),e.contributions.delete(u),i(d),i(f),i(p),i(()=>this.changed())})},list:e=>this.list(e),provide:(t,n)=>{if(e.controller.signal.aborted||a(F)?.ended)return()=>{};if(G(t.id)||t.id===`yuri.previewActions`||t.id===`yuri.pages`)throw Error(`Preview/export/page contracts are provided only by the Yuri host`);if(t.kind!==`contract`||!(t.id===e.id||t.id.startsWith(`${e.id}.`)))throw Error(`Contract must belong to the providing plugin`);let r=this.contract(t.id);if(r.provider)throw Error(`Contract already provided: ${t.id}`);return r.provider=e,r.live[1]({status:`active`,value:n,generation:++r.generation}),this.own(e,()=>{r.provider===e&&(r.provider=void 0,r.live[1]({status:`inactive`,reason:e.status===`failed`?`failed`:`disabled`}))})},use:t=>t.id===`yuri.pages`?t.kind===`contract`?g:X(`pages token must be a Contract`):t.id===`yuri.previewActions`?t.kind===`contract`?p:X(`preview actions token must be a Contract`):G(t.id)?t.kind===`contract`?this.viewExports.use(t.id,e.controller.signal):X(`export token must be a Contract`):t.kind===`ipc`&&e.native?e.native.token(t).live:this.contract(t.id,t.kind===`ipc`).live[0],main:t=>{if(!(t.id===e.id||t.id.startsWith(`${e.id}.`)))throw new E(`GUI_PLUGIN_FORBIDDEN`,`IPC must belong to the plugin`);return e.native?e.native.token(t).value:new Proxy({state:()=>void 0},{get:(e,t)=>t===`state`?e.state:t===`on`?()=>{throw new E(`GUI_PLUGIN_UNSUPPORTED`)}:()=>Promise.reject(new E(`GUI_PLUGIN_UNSUPPORTED`))})},sessions:{current:this.session[0],list:()=>{let e=this.session[0]();return e?[e]:[]}},screen:{current:()=>this.session[0]()?this.#e:void 0},layout:d,appearance:{mode:()=>this.appearance[0]().mode,font:()=>getComputedStyle(document.documentElement).getPropertyValue(`--font-mono`).trim()||`monospace`},locale:{locale:()=>this.appearance[0]().locale,direction:()=>/^(ar|fa|he|ur)(-|$)/i.test(this.appearance[0]().locale)?`rtl`:`ltr`},system:{copy:e=>navigator.clipboard.writeText(e),openExternal:e=>{let t=new URL(e);[`https:`,`http:`,`mailto:`].includes(t.protocol)||X(`system.openExternal protocol`),window.open(e,`_blank`,`noopener,noreferrer`)},save:Ie},commands:{run:t=>e.controller.signal.aborted||!this.command(t)?!1:(this.runCommand(t),!0)},links:{open:t=>!e.controller.signal.aborted&&this.navigateLink(e,t),exists:t=>i(()=>{if(e.controller.signal.aborted)return!1;let n=this.linkHandler(t);try{return Promise.resolve(n?.value.exists?.(t)??!1).catch(()=>!1)}catch{return!1}})}})}contract(e,t=!1){let n=this.contracts.get(e);if(!n){if(this.contracts.size>=256)throw Error(`GUI contract limit exceeded`);let t=u({status:`inactive`,reason:`disabled`});n={live:[A(t[0]),t[1]],generation:0},this.contracts.set(e,n)}return t&&n.provider&&X(`IPC contract collision`),n}derive(e){if(e.status!==`active`)return;let t=[],n=[],r=[],a=[],o=[],s=[],c=this.session[0]();for(let i of e.contributions){if([`yuri.file-icon`,`yuri.theme`,`yuri.branding`,`yuri.work-status`].includes(i.registry))continue;let l=i.read();if(l!==void 0){if(i.registry===`yuri.page`){let e=he(l);if(s.some(t=>t.id===e.id))throw Error(`Duplicate yuri.page id`);s.push(e)}else if(i.registry===we.id){let n=l;n.enabled!==!1&&t.push({key:`${e.id}.${n.id}`,pluginId:e.id,title:n.title,description:n.description,bind:n.bind,hidden:n.hidden,run:()=>this.invoke(e,()=>n.run())})}else if(i.registry===k.id){let t=l;o.push({key:JSON.stringify([e.id,t.id]),pluginId:e.id,label:t.label,title:t.title,icon:Me(t.icon),busy:t.busy,pressed:t.pressed,actionable:!!t.run,run:t.run})}else if(i.registry===Ee.id&&c){let t=l,r=`${e.id}:`,i=this.layout(c).open.filter(e=>e.startsWith(r)).map(e=>e.slice(r.length));for(let r of t.list({session:c,screen:this.#e,open:i}))n.push({plugin:e,panel:t,tab:r})}else if(i.registry===be.id){let e=l;(e.page||e.section)&&X(`SettingsPage host sections`),e.title,r.push(e)}else if(i.registry===N.id){let e=l;e.menu===`session.panel`?(e.title,a.push(e)):X(`MenuItem.${e.menu}`)}}}for(let e of n)e.tab.title;e.commands=t,e.titlebarItems=o,e.panels=n,e.pages=s,e.settings=r,e.menus=a,i(()=>this.views[1](e=>e+1))}publish(){let e=i(this.session[0]),t=e?this.layouts.get(e.key):void 0,n=[...this.instances.values()],r=n.filter(e=>e.status===`active`),a=r.flatMap(e=>e.panels.map(({tab:n})=>{let r=n.file?this.filePath(n.file):void 0;return{key:`${e.id}:${n.id}`,pluginId:e.id,title:n.title,file:r,inline:!!(r&&this.fileViews.has(r)),active:t?.shown===!0&&t.active===`${e.id}:${n.id}`}}));this.snapshot=Object.freeze({plugins:Q(n.map(({id:e,revision:t,status:n,error:r,errorCode:i,iconError:a})=>({id:e,revision:t,status:n,error:r??a,...i?{errorCode:i}:{}}))),commands:Q(r.flatMap(e=>e.commands.filter(e=>!e.hidden))),panels:Q(a),titlebarItems:Q(r.flatMap(e=>e.titlebarItems.map(({run:e,...t})=>t))),pages:Q(r.flatMap(e=>e.pages.map(t=>({key:O(e.id,t.id),pluginId:e.id,title:t.title,icon:t.icon})))),settings:Q(r.flatMap(e=>e.settings.map(t=>({key:`${e.id}:${t.id}`,pluginId:e.id,title:t.title})))),menuItems:Q(r.flatMap(e=>e.menus.map(t=>({key:`${e.id}:${t.id}`,pluginId:e.id,title:t.title,description:t.description,run:()=>{this.invoke(e,()=>t.run())}})))),activePanel:t?.shown&&a.some(e=>e.key===t.active)?t.active:null,sessionKey:e?.key});for(let e of this.listeners)e()}invoke(e,t){if(!e.controller.signal.aborted)try{let n=o(e.owner??null,t);if(n instanceof Promise)return n.catch(t=>this.fail(e,t))}catch(t){this.fail(e,t)}}command(e){return[...this.instances.values()].flatMap(e=>e.commands).find(t=>t.key===e)}runCommand(e){return this.command(e)?.run()}runTitlebarItem(e){for(let t of this.instances.values()){let n=t.titlebarItems.find(t=>t.key===e);if(n?.run&&!n.busy)return this.invoke(t,n.run)}}linkHandler(e){let t=[];for(let e of this.instances.values())for(let n of e.contributions)if(n.registry===ye.id){let r=n.read();r&&t.push({instance:e,value:r})}for(let n of t.sort((e,t)=>(t.value.priority??0)-(e.value.priority??0)))try{if(n.value.match(e))return n}catch(e){this.fail(n.instance,e)}}navigateLink(e,t){if(this.ended)return!1;let n=me(t.href);if(!n||!pe(n.path))return this.openLink(t);let r=this.session[0]();if(!r||t.session&&(t.session.key!==r.key||t.session.server.id!==r.server.id))return!1;if(!this.options.focusFile)return this.openLink(t);let i=w(t.base??r.directory,n.path),a=n.line===void 0?``:`:${n.line}${n.column===void 0?``:`:${n.column}`}`;return this.invoke(e,()=>this.options.focusFile(i+a,r.directory)),!0}openLink(e){if(this.ended)return!1;let t={...e,session:e.session??this.session[0]()},n=this.linkHandler(t);return n?(this.invoke(n.instance,()=>n.value.open(t)),!0):!1}filePath(e,t=this.session[0]()?.directory){let n=L(e);return/^(?:\/|[a-z]:\/)/i.test(n)||!t?n:L(`${t}/${n}`)}registerFileView(e,t){if(this.ended)return()=>{};let n=this.filePath(e,t),r=this.fileViews.get(n)??0;this.fileViews.set(n,r+1),r===0&&this.changed(!0);let i=!1;return()=>{if(i||this.ended)return;i=!0;let e=(this.fileViews.get(n)??1)-1;if(e){this.fileViews.set(n,e);return}{let e=this.session[0](),t=e&&this.layouts.get(e.key);t?.active&&this.snapshot.panels.some(e=>e.key===t.active&&e.file===n)&&(t.shown=!1),this.fileViews.delete(n)}this.changed(!0)}}filePanel(e,t){let n=this.filePath(e,t);return this.snapshot.panels.find(e=>e.file===n&&e.inline)}panelVisible(e){let t=this.session[0]();if(!t)return!1;let n=this.panel(e)?.tab.file;if(n&&this.fileViews.has(this.filePath(n)))return!0;let r=this.layouts.get(t.key);return!!(r?.shown&&r.active===e)}layout(e){let t=this.layouts.get(e.key);if(!t){if(this.layouts.size>=128)throw Error(`GUI session layout limit exceeded`);t={open:[],active:null,shown:!1,scroll:new Map},this.layouts.set(e.key,t)}return t}openPanel(e,t,n){if(this.ended)return;let r=this.layout(t),i=r.active,a=r.shown,o=r.open.length;if(!r.open.includes(e)){if(r.open.length>=64)throw Error(`GUI panel tab limit exceeded`);r.open=[...r.open,e]}n?.tab!==`append`&&(r.active=e,r.shown=!(this.appearance[0]().narrow&&n?.background)),(i!==r.active||a!==r.shown||o!==r.open.length)&&this.changed(!0);let s=this.panel(e);t.key===this.session[0]()?.key&&s&&n?.tab!==`append`&&this.invoke(s.plugin,()=>s.panel.focus?.({...this.props(e),restored:!1}))}selectPanel(e){let t=this.session[0]();t&&this.openPanel(e,t)}closeFor(e,t){let n=this.layout(t),r=t.key===this.session[0]()?.key?this.panel(e):void 0;if(!n.open.includes(e)||r?.tab.pinned||r?.tab.closable===!1)return;let i=this.session[0](),a=r&&i?{tab:r.tab,session:i,screen:this.#e}:void 0;n.open=n.open.filter(t=>t!==e),n.active===e&&(n.active=n.open.at(-1)??null),this.changed(!0),r&&a&&this.invoke(r.plugin,()=>r.panel.close?.(a))}closePanel(e){let t=this.session[0]();t&&this.closeFor(e,t)}hidePanel(){let e=this.session[0]();if(!e)return;let t=this.layout(e);t.shown&&(t.shown=!1,this.changed(!0))}panel(e){return[...this.instances.values()].flatMap(e=>e.panels).find(t=>`${t.plugin.id}:${t.tab.id}`===e)}props(e,t=!1){let n=this.panel(e)?.tab,r=()=>(this.views[0](),this.panel(e)?.tab??n??X(`panel no longer listed`)),i=t?l(()=>{let e=r();return{tab:e,fields:Object.getPrototypeOf(e)===Object.prototype?Object.getOwnPropertyDescriptors(e):void 0}},void 0,{equals:Be}):void 0,a=i?()=>i().tab:r,o=()=>this.session[0]()??X(`panel without session`);return{get tab(){return a()},get session(){return o()},screen:this.#e}}mountPanel(e,t,r){let a=this.panel(e);if(!a)return()=>{};let o=new AbortController,s=()=>{let s=l(()=>{this.session[0](),this.changes[0](),this.views[0]();let t=this.panel(e)?.tab.file;return t&&this.files&&this.panelVisible(e)?{model:this.files,file:t}:void 0},void 0,{equals:(e,t)=>e?.model===t?.model&&e?.file===t?.file});n(()=>{let e=s();e&&(h(e.model.watch(e.file)),e.model.sync(e.file).catch(()=>{}))});let c=()=>i(()=>a.panel.render(this.props(e,!0)));return S(K.Provider,{value:r?{plugin:a.plugin.controller.signal,signal:o.signal,content:t,target:r}:void 0,get children(){return c()}})},c=this.mount(a.plugin,t,()=>S(xe.Provider,{value:{visible:()=>(this.changes[0](),this.panelVisible(e)),present:()=>(this.changes[0](),this.panelVisible(e)),placement:()=>this.appearance[0]().narrow?`mobile`:`side`,reserve:()=>!1,animate:()=>!1,sidebar:Z(`panel.sidebar`,{}),open:()=>{let e=this.session[0]();return e?a.plugin.context.layout.stored(e):[]}},get children(){return s()}})),u=()=>{this.panelMounts.delete(u),o.abort(),c()};return this.panelMounts.add(u),this.own(a.plugin,u)}mountSettings(e,t){for(let n of this.instances.values()){let r=n.settings.find(t=>`${n.id}:${t.id}`===e);if(r)return this.mount(n,t,()=>r.render({}))}return()=>{}}mountPage(e,t){if(this.appearance[0]().narrow&&!this.mobilePageNetworkReady[0]())throw new E(`GUI_PLUGIN_UNAVAILABLE`,`Mobile page Relay is not ready`);for(let n of this.instances.values()){let r=n.pages.find(t=>O(n.id,t.id)===e);if(r)return this.mount(n,t,()=>r.render())}return()=>{}}mountWorkStatus(e,t,n){let r=this.instances.get(e.pluginId);if(!r||!this.workStatus.contains(e)||this.ended)return{update(){},dispose(){}};let i=Y(n,n.sessionId&&n.directory?this.sessionReference({id:n.sessionId,directory:n.directory},n.scope):void 0,n.scope?JSON.stringify(n.scope.queryScope):this.options.transport),a=()=>{},o=()=>{},s=this.own(r,()=>{i.dispose(),o(),a()});return o=this.workStatus.subscribe(()=>{this.workStatus.contains(e)||s()}),a=this.mount(r,t,()=>e.render(i.props)),i.props.signal.aborted&&(o(),a()),{update:e=>{if(!i.matches(e)){s();return}i.update(e)},dispose:s}}mount(e,t,n){if(e.controller.signal.aborted)return()=>{};let r=()=>{},a,o=t=>{queueMicrotask(()=>this.fail(e,t))};try{r=_e(()=>S(j.Provider,{value:e.context,get children(){return a=s(),b(()=>i(n),o)}}),t)}catch(t){this.fail(e,t)}return this.own(e,()=>{$(a,t=>{e.error??=String(t)}),r(),t.replaceChildren()})}};export{Ve as GuiPluginHost};
1
+ import{f as e,n as t}from"./platform-CiUKDeXd.js";import{C as n,D as r,I as i,L as a,M as o,O as s,P as c,S as l,T as u,_ as d,a as f,b as p,c as m,j as h,n as g,o as _,r as v,s as y,t as ee,v as b,w as x,y as S}from"./vendor-opencode-client-BM2r1f0o.js";import{a as te}from"./vendor-tanstack-query-core-BSjXNgF_.js";import{b as ne,v as C}from"./runtime-file-resource-CKQQEwNv.js";import{o as w}from"./path-utils-jGozTg9d.js";import{a as T,n as re}from"./vendor-aparajita-capacitor-secure-storage-xol_6BsB.js";import{Dt as ie,ht as ae,mt as oe,y as se}from"./vendor-effect-X1Hqc7ba.js";import{t as E}from"./native-errors-06if6eu-.js";import{a as ce,i as le,n as ue,o as de,r as fe,s as D}from"./appearance-DFsI3pnP.js";import{i as pe,o as me}from"./fileReferenceParser-1HHDBUum.js";import{a as he,r as O}from"./pages-CYkE04ml.js";import{n as ge,t as _e}from"./vendor-solid-js-BBVUd3Hw.js";import{a as ve,c as ye,d as be,f as k,g as A,h as j,i as M,l as N,m as xe,n as Se,o as P,p as F,r as Ce,s as we,t as Te,u as Ee}from"./vendor-opencode-plugin-ZhpPgHCL.js";var I={"@opencode/plugin/gui":P,"@opencode/plugin/gui/main":P,"@opencode/plugin/gui/file":ve,"@opencode/plugin/gui/review":M,"@opencode/plugin/gui/browser":Ce,"@opencode/plugin/rpc":Te,"@opencode/schema/rpc":Se,"@opencode/client":v,"@opencode/client/effect":g,"@opencode/client/solid":ee,effect:se,"solid-js":c,"solid-js/web":ge,"solid-js/store":y},De=new Set(`assert assert/strict async_hooks buffer child_process cluster console constants crypto dgram diagnostics_channel dns dns/promises domain events fs fs/promises http http2 https inspector inspector/promises module net os path path/posix path/win32 perf_hooks process punycode querystring readline readline/promises repl stream stream/consumers stream/promises stream/web string_decoder sys timers timers/promises tls trace_events tty url util util/types v8 vm wasi worker_threads zlib`.split(` `));function Oe(){let e=new Proxy(function(){},{get:(t,n)=>n===`then`?void 0:n===Symbol.hasInstance?()=>!1:n===Symbol.toPrimitive||n===`toString`?()=>`[main-only module]`:e,apply:()=>e,construct:()=>e,set:()=>!0});return e}function ke(e,t){if(e.length>16777216)throw Error(`GUI bundle exceeds 16 MiB`);let n={exports:{}};Function(`require`,`module`,`exports`,e)(e=>{if(Object.hasOwn(I,e))return I[e];if(e===`electron`||e.startsWith(`node:`)||De.has(e))return Oe();throw Error(`Unsupported GUI shared module: ${e}`)},n,n.exports);let r=n.exports,i=r&&typeof r==`object`&&`default`in r?r.default:r;if(!i||typeof i!=`object`)throw Error(`GUI bundle must default-export Plugin.define`);if((!(`setup`in i)||typeof i.setup!=`function`)&&!(t&&`main`in i&&typeof i.main==`function`))throw new E(`GUI_PLUGIN_UNSUPPORTED`,`This host requires a window setup; main-only plugins are unsupported`);if(`os`in i&&i.os!==void 0){if(!t)throw new E(`GUI_PLUGIN_UNSUPPORTED`,`OS-restricted plugins require the native GUI host`);if(!Array.isArray(i.os)||!i.os.includes(t))throw new E(`GUI_PLUGIN_UNSUPPORTED`,`GUI plugin is unavailable on this OS`)}if(`main`in i&&i.main!==void 0&&typeof i.main!=`function`)throw Error(`Invalid GUI main entry`);if(`stores`in i&&i.stores!==void 0){if(!i.stores||typeof i.stores!=`object`||Array.isArray(i.stores))throw Error(`Invalid GUI stores`);for(let e of Object.values(i.stores))if(!e||typeof e!=`object`||!(`schema`in e)||!ie(e.schema)||!(`scope`in e)||![`global`,`session`].includes(String(e.scope))||!(`initial`in e))throw Error(`Invalid GUI store declaration`)}if(`i18n`in i&&i.i18n!==void 0){if(!i.i18n||typeof i.i18n!=`object`||Array.isArray(i.i18n))throw Error(`Invalid GUI locale catalog`);for(let e of Object.values(i.i18n))if(!e||typeof e!=`object`||Array.isArray(e)||Object.values(e).some(e=>typeof e!=`string`))throw Error(`GUI locales must be inline string dictionaries`)}return i}function L(t){let n=t;if(/^file:/i.test(n)){let e=new URL(n);n=`${e.hostname&&e.hostname!==`localhost`?`//${e.hostname}`:``}${decodeURIComponent(e.pathname)}`,/^\/[a-z]:\//i.test(n)&&(n=n.slice(1))}let r=e(n)??``;return r===`.`?``:r}var R=e=>/^(?:\/|[a-z]:\/)/i.test(e),z=()=>{throw Error(`Unsupported GUI file API: tree`)},B=class extends Error{},V=e=>new TextEncoder().encode(e).byteLength,Ae=class{files;query;transport;root;api;ended=!1;states=new Map;inflight=new Map;watches=new Map;apiLeases=new Map;registeredOwners=new WeakSet;endedOwners=new WeakSet;leaseCount=0;rerun=new Set;selections=new Map;scrolls=new Map;subscriptions=new Map;constructor(e,t,n,r){this.files=e,this.query=t,this.transport=n,this.root=r,this.root=L(r),this.api={root:this.root,ready:()=>!this.ended,resolve:e=>this.resolve(e),absolute:R,get:e=>{let t=this.track(e,`file`);return this.states.get(t)},missing:e=>{let t=this.track(e,`missing`);return this.states.get(t)?.notFound===!0},sync:(e,t)=>{let n=s();return this.ended||n&&this.endedOwners.has(n)?Promise.resolve():(this.acquireApiLease(e),this.sync(e,t?.force))},unwatch:e=>this.releaseApiLease(s(),this.resolve(e)),exists:async e=>{try{if(this.files.statFile)return(await this.query.fetchQuery(this.statOptions(e))).isFile;let t=this.full(e);return(await this.files.listDirectory(t.slice(0,t.lastIndexOf(`/`)))).entries.some(e=>!e.isDirectory&&L(e.path)===t)}catch{return!1}},search:async(e,t)=>{if(t?.kind===`any`)throw Error(`Unsupported GUI file search: directories`);t?.signal?.throwIfAborted();let r=await this.query.fetchQuery({queryKey:[`gui-plugin-files`,n,this.root,`search`,e,t?.limit],gcTime:3e4,queryFn:async({signal:n})=>(n.throwIfAborted(),this.files.search({directory:this.root,query:e,maxResults:t?.limit??100}))});if(t?.signal?.throwIfAborted(),this.ended)throw new DOMException(`GUI file model was disposed`,`AbortError`);return r.map(e=>this.resolve(e.path))},selection:{get:e=>this.selections.get(this.track(e,`selection`)),set:(e,t)=>{let n=this.resolve(e),r=this.selections.get(n);r===t||r&&t&&r.start===t.start&&r.end===t.end&&r.side===t.side&&r.endSide===t.endSide||(this.selections.set(n,t),this.trim(this.selections,`selection`),this.changed(n,`selection`))}},scroll:{get:e=>this.scrolls.get(this.track(e,`scroll`))??{},set:(e,t)=>{let n=this.resolve(e),r=this.scrolls.get(n),i={...r,...t};(r?.top!==i.top||r?.left!==i.left)&&(this.scrolls.set(n,i),this.trim(this.scrolls,`scroll`),this.changed(n,`scroll`))}},tree:{list:z,state:z,sync:z,expand:z,collapse:z}}}resolve(e){let t=L(e);if(!R(t))return t;if(t===this.root)return``;let n=this.root.endsWith(`/`)?this.root:`${this.root}/`;return t.startsWith(n)?t.slice(n.length):t}full(e){let t=this.resolve(e);return R(t)?t:L(`${this.root}/${t}`)}input(e){return{scopeDirectory:this.root,path:this.full(e),options:{directory:this.root}}}statOptions(e){return{...ne(this.files,this.input(e),this.transport),gcTime:3e4}}track(e,t){let n=this.resolve(e),i=r();if(!i||this.ended)return n;let a=`${t}:${n}`,s=this.subscriptions.get(a);s||(s={revision:u(0),listeners:new Set},this.subscriptions.set(a,s));let c=s;return c.listeners.has(i)||(c.listeners.add(i),o(i,()=>h(()=>{c.listeners.delete(i),!c.listeners.size&&this.subscriptions.get(a)===c&&this.subscriptions.delete(a)}))),c.revision[0](),n}changed(e,t){this.ended||this.subscriptions.get(`${t}:${e}`)?.revision[1](e=>e+1)}trim(e,t){for(;e.size>64;){let n=e.keys().next().value;e.delete(n),this.changed(n,t)}}setState(e,t){let n=this.states.get(e);n?.content?.content===t.content?.content&&n?.content?.type===t.content?.type&&(t.content=n?.content),!(n&&n.loaded===t.loaded&&n.loading===t.loading&&n.error===t.error&&n.notFound===t.notFound&&n.content===t.content)&&(this.states.set(e,t),d(()=>{this.changed(e,`file`),n?.notFound===!0!=(t.notFound===!0)&&this.changed(e,`missing`)}))}acquireApiLease(e){let t=s();if(this.ended||t&&this.endedOwners.has(t)||!this.files.statFile)return;let n=this.resolve(e),r=this.apiLeases.get(t);if(r?.has(n))return;if(this.leaseCount>=256)throw Error(`GUI file consumer limit exceeded`);let i=this.watch(n);r||(r=new Map,this.apiLeases.set(t,r)),r.set(n,i),this.leaseCount++,t&&!this.registeredOwners.has(t)&&(this.registeredOwners.add(t),h(()=>{`fn`in t||this.endedOwners.add(t),this.registeredOwners.delete(t);for(let e of[...this.apiLeases.get(t)?.keys()??[]])this.releaseApiLease(t,e)}))}releaseApiLease(e,t){let n=this.apiLeases.get(e),r=n?.get(t);r&&(n.delete(t),this.leaseCount--,n.size||this.apiLeases.delete(e),r())}reserve(e){if(!this.states.has(e)){if(this.states.size>=64){let e=[...this.states.keys()].find(e=>!this.watches.has(e)&&!this.inflight.has(e));if(!e)throw Error(`GUI file cache limit exceeded`);let t=this.states.get(e)?.notFound===!0;this.states.delete(e),d(()=>{this.changed(e,`file`),t&&this.changed(e,`missing`)})}this.states.set(e,{path:e,name:e.split(`/`).at(-1)??e})}}async sync(e,t=!1){if(this.ended)return;let n=this.resolve(e);if(this.inflight.has(n))return t&&this.rerun.add(n),this.inflight.get(n);if(!t&&this.states.get(n)?.loaded&&!this.states.get(n)?.error)return;this.reserve(n);let r=this.states.get(n);this.setState(n,{...r,path:n,name:n.split(`/`).at(-1)??n,loading:!r?.loaded&&!this.watches.get(n)?.failed});let i=(async()=>{try{do{this.rerun.delete(n);let e=this.watches.get(n),r=e?.epoch;try{let i=C(this.files,this.input(n),this.transport),a=await this.query.fetchQuery({...i,gcTime:3e4,staleTime:t?0:3e4,queryFn:async()=>{if(!this.files.readFile)throw Error(`File content reads are unavailable in this runtime`);let e=await this.files.readFile(this.full(n),{directory:this.root});if(e.exists===!1)throw new B(`File does not exist`);let t=e.content;if(V(t)>131072)throw Error(`GUI file preview exceeds 128 KiB`);return t}});if(this.ended)return;if(V(a)>131072)throw Error(`GUI file preview exceeds 128 KiB`);(!e||e.epoch===r&&!e.failed)&&this.setState(n,{path:n,name:n.split(`/`).at(-1)??n,loaded:!0,loading:!1,content:{type:`text`,content:a}})}catch(t){if(this.ended)return;if((!e||e.epoch===r&&!e.failed)&&this.setState(n,{...this.states.get(n),loading:!1,...t instanceof B?{notFound:!0}:{},error:String(t)}),!this.rerun.has(n))throw t}t=!0}while(!this.ended&&this.rerun.has(n))}finally{this.inflight.delete(n),this.rerun.delete(n)}})();return this.inflight.set(n,i),i}watch(e){if(this.ended||!this.files.statFile)return()=>{};let t=this.resolve(e),n=this.watches.get(t);if(!n){if(this.watches.size>=64)throw Error(`GUI file watch limit exceeded`);this.reserve(t),n={count:0,epoch:0,failed:!1,stop:()=>{}};let e=n;this.watches.set(t,e);let r,i=new te(this.query,{...this.statOptions(t),refetchInterval:2e3,refetchIntervalInBackground:!1}),a=i.subscribe(n=>{if(this.ended||this.watches.get(t)!==e||n.isFetching)return;if(n.isError||n.isSuccess&&!n.data.isFile){e.failed=!0,e.epoch++,this.setState(t,{...this.states.get(t),loading:!1,notFound:n.isSuccess?!0:this.states.get(t)?.notFound,error:n.isError?String(n.error):`File does not exist`});return}if(!n.data||!n.isSuccess)return;let i=`${n.data.size}:${n.data.mtimeMs??``}`,a=e.failed||r!==void 0&&i!==r;e.failed=!1,r=i,a&&(e.epoch++,this.sync(t,!0).catch(()=>{}))});e.stop=()=>{a(),i.destroy()},this.states.get(t)?.loaded&&this.sync(t,!0).catch(()=>{})}n.count++;let r=!0;return()=>{r&&(r=!1,--n.count===0&&this.watches.get(t)===n&&this.stopWatch(t))}}stopWatch(e){this.watches.get(e)?.stop(),this.watches.delete(e)}dispose(){this.ended=!0;for(let e of this.watches.values())e.stop();this.watches.clear(),this.apiLeases.clear(),this.leaseCount=0,this.rerun.clear(),this.states.clear(),this.inflight.clear(),this.selections.clear(),this.scrolls.clear(),this.subscriptions.clear()}},H=256,U=2097152,W=e=>structuredClone(m(e)),je=class{backend;transport;memory=new Map;resets=new Map;constructor(e,t){this.backend=e,this.transport=t}forPlugin(e,t){let n=(t,n=`global`)=>{if(typeof n==`object`&&`session`in n&&!n.session.location)throw Error(`Unsupported GUI storage: session location is unknown`);let r=n===`global`?n:`session`in n?[n.session.server.id,n.session.id,n.session.location]:[n.server,n.directory];return`yuri.gui-plugin.${JSON.stringify([this.transport,e,r,t])}`},r=e=>{if(t.aborted)throw Error(`GUI plugin has been disposed`);if(e!==void 0)throw Error(`Unsupported GUI storage migration: from`)},i=new Map;return{store:(e,a)=>{r(a.from);let o=n(e,a.scope),s=i.get(o);if(s)return s;if(i.size>=H)throw Error(`GUI plugin store limit exceeded`);let c=oe(a.schema),l=ae(a.schema),d=c(l(W(a.initial)));if(JSON.stringify(l(d)).length>U)throw Error(`GUI plugin store exceeds 2 MiB`);let f=d,p=this.backend.getItem(o);if(p!==null&&p.length<=U)try{f=c(JSON.parse(p))}catch{f=d}let[m,h]=u(f),g=e=>{r();let t=JSON.stringify(l(W(e)));if(t.length>U)throw Error(`GUI plugin store exceeds 2 MiB`);let n=c(JSON.parse(t));this.backend.setItem(o,t),h(()=>n)},_={get value(){return m()},ready:()=>!0,set:g,update:e=>{let t=W(m());if(e(t)!==void 0)throw Error(`Store update must not return a replacement`);g(t)}},v=()=>h(()=>W(d)),y=this.resets.get(o)??new Set;return y.add(v),this.resets.set(o,y),t.addEventListener(`abort`,()=>{y.delete(v),y.size||this.resets.delete(o),i.clear()},{once:!0}),i.set(o,_),_},memory:(e,t)=>{r();let i=n(e),a=this.memory.get(i);if(a)return[a[0],e=>{r(),a[1](e)}];if(this.memory.size>=H)throw Error(`GUI plugin memory store limit exceeded`);if(JSON.stringify(t.initial).length>U)throw Error(`GUI plugin memory exceeds 2 MiB`);let[o,s]=f(W(t.initial)),c=[o,e=>{r();let t=W(m(o));if(e(t)!==void 0)throw Error(`Memory update must not return a replacement`);if(JSON.stringify(t).length>U)throw Error(`GUI plugin memory exceeds 2 MiB`);s(_(t))}];return this.memory.set(i,[o,e=>{let t=W(m(o));if(e(t)!==void 0)throw Error(`Memory update must not return a replacement`);if(JSON.stringify(t).length>U)throw Error(`GUI plugin memory exceeds 2 MiB`);s(_(t))}]),c},remove:(e,t)=>{r(t?.from);let i=n(e,t?.scope);this.backend.removeItem(i);for(let e of this.resets.get(i)??[])e()}}}dispose(){this.memory.clear(),this.resets.clear()}};function Me(e){if(typeof e!=`string`||e.length>2097152)return;let t=e.trim();if(t)try{if(t.startsWith(`<`))return D(t);if(!/^data:/i.test(t))return t;let e=/^data:image\/(svg\+xml|png|jpeg|gif|webp|avif|x-icon|vnd\.microsoft\.icon)(?:;charset=utf-8)?(;base64)?,([\s\S]+)$/i.exec(t);if(!e)return;let[,n,r,i]=e;if(r&&!/^[A-Za-z0-9+/]+={0,2}$/.test(i))return;if(n.toLowerCase()===`svg+xml`){let e=r?new TextDecoder(`utf-8`,{fatal:!0}).decode(Uint8Array.from(atob(i),e=>e.charCodeAt(0))):decodeURIComponent(i);return D(e)}return!r||!atob(i).length?void 0:`data:image/${n.toLowerCase()};base64,${i}`}catch{return}}var G=e=>e===`yuri.exportPDF`||e===`yuri.exportLongImage`,Ne=class{api;probe;clients=new Map;ended=!1;constructor(e){this.api=e}use(e,t){let n=this.clients.get(t),r=n?.get(e);if(r)return r.live;let[i,a]=u(this.api&&!t.aborted&&!this.ended?{status:`pending`}:{status:`inactive`,reason:`disabled`}),o=()=>{a({status:`inactive`,reason:`disabled`}),t.removeEventListener(`abort`,o),this.clients.delete(t)},s={live:A(i),stop:o};if(this.ended||t.aborted||(n||(n=new Map,this.clients.set(t,n)),n.set(e,s),t.addEventListener(`abort`,o,{once:!0}),!this.api))return s.live;let c=this.api;return this.probe??=Promise.resolve().then(()=>c.capabilities()),this.probe.then(n=>{if(this.ended||t.aborted)return;let r=e===`yuri.exportPDF`?`exportPDF`:`exportLongImage`;if(n.version!==1||!n[r]){a({status:`inactive`,reason:`disabled`});return}let o=async(e,n={})=>{if(this.ended||t.aborted||i().status!==`active`)return{status:`cancelled`};let o=AbortSignal.any([t,...n.signal?[n.signal]:[]]);try{return await c[r](e,{...n,signal:o})}catch(e){throw e&&typeof e==`object`&&`code`in e&&e.code===`EXPORT_UNSUPPORTED`&&a({status:`inactive`,reason:`failed`}),e}},s=Object.freeze(e===`yuri.exportPDF`?{version:1,limits:n.limits,exportPDF:o}:{version:1,limits:n.limits,exportLongImage:o});a({status:`active`,generation:1,value:s})}).catch(()=>{!this.ended&&!t.aborted&&a({status:`inactive`,reason:`failed`})}),s.live}dispose(){this.ended=!0;for(let e of this.clients.values())for(let t of e.values())t.stop();this.clients.clear()}};function Pe(e,t){let n=new Map,r=Object.freeze({dismiss(){}});return e.addEventListener(`abort`,()=>{for(let e of[...n.values()])e.handle.dismiss()},{once:!0}),Object.freeze({show(i){if(e.aborted)return r;if(!t)throw new E(`GUI_PLUGIN_UNSUPPORTED`,`GUI toast is unavailable`);if(!i||typeof i!=`object`)throw new E(`GUI_PLUGIN_INVALID_INPUT`,`Expected toast options`);let{title:a,description:o,variant:s=`default`,duration:c=5e3,persistent:l=!1,icon:u,actions:d}=i;if(typeof a!=`string`||o!==void 0&&typeof o!=`string`||![`default`,`success`,`error`,`loading`].includes(s)||typeof l!=`boolean`||typeof c!=`number`||!Number.isFinite(c)||c<0)throw new E(`GUI_PLUGIN_INVALID_INPUT`,`Invalid toast options`);if(u!==void 0||d!==void 0)throw new E(`GUI_PLUGIN_UNSUPPORTED`,`GUI toast icon/actions are unsupported`);if(e.aborted)return r;let f=JSON.stringify([a,o??null,s,c,l]),p=n.get(f),m=()=>{let e=n.get(f);!e||e.id!==h||(clearTimeout(e.timer),n.delete(f))},h=(s==="default"?t:t[s])(a,{id:p?.id,description:o,duration:l?1/0:c,onDismiss:m,onAutoClose:m}),g=p?.handle??Object.freeze({dismiss(){m(),t.dismiss(h)}});clearTimeout(p?.timer);let _=s===`loading`&&!l?setTimeout(()=>g.dismiss(),c):void 0;return n.set(f,{id:h,handle:g,timer:_}),g}})}var Fe=T(`YuriMedia`);async function Ie(e){let n=/\.html?$/i.test(e.name)?`text/html`:`text/plain`,r=new Blob([e.content],{type:n});if(t()){if(!re.isPluginAvailable(`YuriMedia`))throw new E(`GUI_PLUGIN_UNSUPPORTED`,`Native file saving is unavailable`);if(r.size>33554432)throw new E(`GUI_PLUGIN_INVALID_INPUT`,`File exceeds maximum size`);let t=await new Promise((e,t)=>{let n=new FileReader;n.onload=()=>{if(typeof n.result!=`string`){t(Error(`Failed to encode file`));return}e(n.result.slice(n.result.indexOf(`,`)+1))},n.onerror=()=>t(n.error??Error(`Failed to encode file`)),n.readAsDataURL(r)});return!(await Fe.saveFile({dataBase64:t,mimeType:n,filename:e.name})).cancelled}let i=URL.createObjectURL(r),a=document.createElement(`a`);try{return a.href=i,a.download=e.name,document.body.append(a),a.click(),!0}finally{a.remove(),setTimeout(()=>URL.revokeObjectURL(i),1e3)}}var K=p();function Le(e){return{version:1,register(t){let n=a(K);if(!n||n.plugin!==e||n.signal.aborted||e.aborted)throw Error(`Preview actions require the owning mounted panel`);let r=new AbortController,i=AbortSignal.any([e,n.signal,r.signal]),o,s=()=>{i.removeEventListener(`abort`,s),r.abort(),o?.remove()};h(s),i.addEventListener(`abort`,s,{once:!0});try{o=t.render({element:t.element,signal:i,async snapshot(e={}){let r=AbortSignal.any([i,...e.signal?[e.signal]:[]]);if(r.throwIfAborted(),!n.content.contains(t.element)||n.target.contains(t.element))throw Error(`Preview capture region is no longer in its owning panel`);let a=await t.capture({...e,signal:r});if(r.throwIfAborted(),!n.content.contains(t.element))throw Error(`Preview capture region was replaced`);return a}}),i.throwIfAborted(),n.target.append(o)}catch(e){throw s(),e}return s}}}var Re=`yuri.work-status`;function q(e,t){return e===t||!!(e&&t&&Object.keys(e).length===Object.keys(t).length&&Object.keys(e).every(n=>e[n]===t[n]))}var J=e=>e&&Object.freeze({...e});function Y(e,t,n){let r=new AbortController,[i,a]=u(!0),[o,s]=u(J(e.project),{equals:q}),[c,l]=u(J(e.worktree),{equals:q}),[f,p]=u(Object.freeze({...e.git}),{equals:q}),[m,h]=u(e.placement);return{props:Object.freeze({session:t,directory:e.directory,runtimeId:n,signal:r.signal,get active(){return i()},get project(){return o()},get worktree(){return c()},get git(){return f()},get placement(){return m()}}),matches:t=>t.sessionId===e.sessionId&&t.directory===e.directory&&t.scope===e.scope,update(e){r.signal.aborted||d(()=>{s(J(e.project)),l(J(e.worktree)),p(Object.freeze({...e.git})),h(e.placement)})},dispose(){r.signal.aborted||(a(!1),r.abort())}}}var ze=class{plugins=new Map;order=new Map;snapshot=Object.freeze([]);generation=0;listeners=new Set;subscribe=e=>(this.listeners.add(e),()=>{this.listeners.delete(e)});getSnapshot=()=>this.snapshot;setOrder(e){e.length===this.order.size&&e.every((e,t)=>this.order.get(e)===t)||(this.order=new Map(e.map((e,t)=>[e,t])),this.publish())}replace(e,t,n){let r=this.plugins.get(e)??[],i=new Set,a=n.map(n=>{if(!n||typeof n!=`object`||!(`id`in n)||typeof n.id!=`string`||!n.id.trim()||n.id.length>128||i.has(n.id)||!(`render`in n)||typeof n.render!=`function`||`order`in n&&n.order!==void 0&&(typeof n.order!=`number`||!Number.isFinite(n.order)))throw Error(`Invalid or duplicate yuri.work-status contribution`);i.add(n.id);let a=JSON.stringify([e,n.id]),o=`order`in n&&typeof n.order==`number`?n.order:0,s=n.render,c=r.find(e=>e.key===a),l=c&&c.revision===t&&c.render===s?c.generation:++this.generation;return c&&c.revision===t&&c.render===s&&c.order===o?c:Object.freeze({key:a,pluginId:e,revision:t,generation:l,order:o,render:s})});a.length?this.plugins.set(e,a):this.plugins.delete(e),this.publish()}contains(e){return this.plugins.get(e.pluginId)?.some(t=>t.key===e.key&&t.generation===e.generation)??!1}remove(e){this.plugins.delete(e)&&this.publish()}dispose(){this.plugins.clear(),this.publish(),this.listeners.clear()}publish(){let e=[...this.plugins.values()].flat().sort((e,t)=>e.order-t.order||(this.order.get(e.pluginId)??2**53-1)-(this.order.get(t.pluginId)??2**53-1));if(!(e.length===this.snapshot.length&&e.every((e,t)=>e===this.snapshot[t]))){this.snapshot=Object.freeze(e);for(let e of this.listeners)i(e)}}},X=e=>{throw new E(`GUI_PLUGIN_UNSUPPORTED`,`Unsupported GUI host API: ${e}`)};function Z(e,t){return new Proxy(t,{get:(t,n)=>n in t?Reflect.get(t,n):X(`${e}.${String(n)}`)})}var Q=e=>Object.freeze(e.map(e=>Object.freeze(e)));function Be(e,t){if(!e.fields||!t.fields)return!1;let n=Reflect.ownKeys(e.fields);return n.length===Reflect.ownKeys(t.fields).length&&n.every(n=>{let r=e.fields[n],i=t.fields[n];return i!==void 0&&`value`in r&&`value`in i&&Object.is(r.value,i.value)&&r.enumerable===i.enumerable&&r.configurable===i.configurable&&r.writable===i.writable})}function $(e,t){if(e){for(let n of e.owned??[])$(n,t);e.cleanups&&=e.cleanups.map(e=>()=>{try{Promise.resolve(e()).catch(t)}catch(e){t(e)}})}}var Ve=class{options;fileIcons=new de;appearanceCatalog=new le;workStatus=new ze;instances=new Map;listeners=new Set;panelMounts=new Set;fileViews=new Map;changes=u(0);views=u(0);session=u();currentPage=u();mobilePageNetworkReady=u(!1);appearance;layouts=new Map;files;storage;ended=!1;contracts=new Map;snapshot=Object.freeze({plugins:Object.freeze([]),commands:Object.freeze([]),titlebarItems:Object.freeze([]),panels:Object.freeze([]),pages:Object.freeze([]),settings:Object.freeze([]),menuItems:Object.freeze([]),activePanel:null});#e;viewExports;constructor(e){this.options=e,this.viewExports=new Ne(e.viewExport),this.appearance=u({locale:e.locale,mode:e.mode,narrow:e.narrow}),this.storage=new je(e.storage,e.transport);let t=()=>(this.session[0](),this.files?.api??X(`screen.file without a session`));this.#e=Z(`screen`,{get file(){return t()}})}subscribe=e=>(this.listeners.add(e),()=>{this.listeners.delete(e)});getSnapshot=()=>this.snapshot;changed(e=!1){let t=this.snapshot;this.changes[1](e=>e+1),e&&t===this.snapshot&&this.publish()}setSession(e){if(this.ended)return;let t=this.session[0]();if(t?.id===e?.id&&t?.directory===e?.directory)return;if(!e)for(let e of[...this.panelMounts])e();this.files?.dispose(),this.files=e?new Ae(this.options.files,this.options.queryClient,this.options.transport,e.directory):void 0;let n=e?this.sessionReference(e):void 0,r=this.snapshot;this.session[1](n),r===this.snapshot&&this.publish()}sessionReference(e,t){let n=t?JSON.stringify(t.queryScope):this.options.transport,r=Z(`session.server`,{id:n,name:t?.location.hostId??this.options.transport,...t?{}:{client:this.options.client}});return Object.freeze(Z(`session`,{id:e.id,directory:e.directory,key:t?JSON.stringify([n,e.id]):`${this.options.transport}\n${e.id}`,tab:e.id,server:r,pending:!1,visit:{},location:t?Object.freeze({...t.location}):{directory:e.directory}}))}setAppearance(e){if(this.ended)return;let t=this.appearance[0]();(t.locale!==e.locale||t.mode!==e.mode||t.narrow!==e.narrow)&&this.appearance[1]({...e})}setPage(e){this.ended||this.currentPage[1](e)}setMobilePageNetworkReady(e){this.mobilePageNetworkReady[1](!this.ended&&e)}install(e,t,r){if(this.options.mobileNetworkRequired&&!this.mobilePageNetworkReady[0]()&&!this.ended)throw new E(`GUI_PLUGIN_UNAVAILABLE`,`Mobile plugin Relay is not ready`);let a=this.instances.get(e);if(this.ended||a?.status===`active`&&a.revision===t.revision&&a.native?.active!==!1){r?.dispose();return}a&&(this.instances.delete(e),this.release(a));let c={id:e,native:r,revision:t.revision,controller:new AbortController,status:`active`,cleanups:new Set,contributions:new Set,iconChanges:u(0),appearanceChanges:u(0),workStatusChanges:u(0),commands:[],titlebarItems:[],panels:[],pages:[],settings:[],menus:[]};this.instances.set(e,c);try{if(e===`yuri`||e.startsWith(`yuri.`))throw Error(`The yuri namespace is reserved to the host`);let a=ke(t.code,r?.activation.os);x(e=>{c.dispose=e,c.root=s(),b(()=>S(j.Provider,{value:c.context=this.context(c,a,t.options),get children(){c.owner=s();let e=i(()=>a.setup?.(c.context));if(typeof e==`function`)c.cleanups.add(()=>{Promise.resolve(e()).catch(e=>{c.error=String(e)})});else if(e!==void 0)throw e&&typeof e==`object`&&`then`in e&&Promise.resolve(e).catch(()=>{}),Error(`GUI setup must be synchronous and return only cleanup`);return null}}),e=>this.fail(c,e)),c.controller.signal.aborted||o(c.owner,()=>n(()=>{if(c.iconChanges[0](),!c.controller.signal.aborted)try{let e=[...c.contributions].filter(e=>e.registry===ce).map(e=>e.read()).filter(e=>e!==void 0);this.fileIcons.replace(c.id,e),c.iconError!==void 0&&i(()=>{c.iconError=void 0,this.publish()})}catch(e){i(()=>{this.fileIcons.remove(c.id),c.iconError=e instanceof Error?e.message:String(e),this.publish()})}})),c.controller.signal.aborted||o(c.owner,()=>n(()=>{if(c.appearanceChanges[0](),!c.controller.signal.aborted)try{let e=e=>[...c.contributions].filter(t=>t.registry===e).map(e=>e.read()).filter(e=>e!==void 0);this.appearanceCatalog.replace(c.id,e(fe),e(ue),c.native?.activation.capabilities?.dockIcon===!0)}catch(e){i(()=>this.fail(c,e))}})),c.controller.signal.aborted||o(c.owner,()=>n(()=>{if(c.workStatusChanges[0](),!c.controller.signal.aborted)try{let e=[...c.contributions].filter(e=>e.registry===Re).map(e=>e.read()).filter(e=>e!==void 0);this.workStatus.replace(c.id,c.revision,e)}catch(e){i(()=>this.fail(c,e))}})),c.controller.signal.aborted||o(c.owner,()=>n(()=>{this.changes[0](),this.session[0](),this.appearance[0]();try{this.derive(c)}catch(e){i(()=>this.fail(c,e))}i(()=>this.publish())}))})}catch(e){this.fail(c,e)}this.changed(!0)}release(e){e.controller.abort(),e.native?.dispose();for(let t of[...e.cleanups])try{t()}catch(t){e.error??=String(t)}e.cleanups.clear(),$(e.root,t=>{e.error??=String(t)});try{e.dispose?.()}catch(t){e.error??=String(t)}e.contributions.clear(),e.commands=[],e.titlebarItems=[],e.panels=[],e.pages=[],e.settings=[],e.menus=[],this.fileIcons.remove(e.id),this.appearanceCatalog.remove(e.id),this.workStatus.remove(e.id);for(let t of this.contracts.values())t.provider===e&&(t.provider=void 0,t.live[1]({status:`inactive`,reason:e.status===`failed`?`failed`:`disabled`}))}fail(e,t){e.status!==`failed`&&this.instances.get(e.id)===e&&(e.status=`failed`,e.error=t instanceof Error?t.message:String(t),t instanceof E&&(e.errorCode=t.code),this.release(e),this.publish())}uninstall(e){let t=this.instances.get(e);if(t){this.instances.delete(e),this.release(t);for(let t of this.layouts.values())t.open=t.open.filter(t=>!t.startsWith(`${e}:`)),t.active?.startsWith(`${e}:`)&&(t.active=null);this.changed(!0)}}dispose(){this.ended||(this.ended=!0,d(()=>{for(let e of[...this.instances.keys()])this.uninstall(e)}),this.viewExports.dispose(),this.files?.dispose(),this.fileIcons.dispose(),this.appearanceCatalog.dispose(),this.workStatus.dispose(),this.storage.dispose(),this.layouts.clear(),this.fileViews.clear(),this.contracts.clear(),this.listeners.clear())}async setDockIcon(e,t){let n=this.instances.get(e),r=n?.native;if(!r?.active||!r.activation.capabilities?.dockIcon)return X(`Dock icon`);try{await r.setDockIcon(t)}catch(e){throw t!==null&&n&&this.fail(n,e),e}}own(e,t){let n=!0,r=()=>{n&&(n=!1,e.cleanups.delete(r),t())};return e.controller.signal.aborted||a(F)?.ended?(r(),r):(e.cleanups.add(r),s()&&h(r),r)}list(e){this.changes[0]();let t=[];for(let n of this.instances.values())if(n.status===`active`){for(let r of n.contributions)if(r.registry===e.id){let e=r.read();e!==void 0&&t.push(e)}}return t}context(e,t,r){let o=this.storage.forPlugin(e.id,e.controller.signal),c=Object.fromEntries(Object.entries(t.stores??{}).map(([e,t])=>[e,t.scope===`global`?o.store(e,{...t,scope:`global`}):n=>o.store(e,{...t,scope:{session:n}})])),u=(e,n)=>{let r=this.appearance[0]().locale;return(t.i18n?.[r]?.[e]??t.i18n?.[r.split(`-`)[0]]?.[e]??t.i18n?.en?.[e]??e).replace(/\{\{(\w+)\}\}/g,(e,t)=>String(n?.[t]??e))},d=Z(`layout`,{narrow:()=>this.appearance[0]().narrow,ready:()=>!!this.session[0](),open:(t,n,r)=>{e.controller.signal.aborted||this.openPanel(t,n,r)},close:(t,n)=>{e.controller.signal.aborted||this.closeFor(t,n)},toggle:(e,t)=>d.state(e,t)===`visible`?d.close(e,t):d.open(e,t),hide:(t,n)=>{if(e.controller.signal.aborted)return;let r=this.layout(n);r.active===t&&r.shown&&(r.shown=!1,this.changed())},state:(e,t)=>{this.changes[0]();let n=this.layout(t);return n.active===e?n.shown?`visible`:`active`:n.open.includes(e)?`open`:`closed`},stored:t=>(this.changes[0](),this.layout(t).open.filter(t=>t.startsWith(`${e.id}:`)).map(t=>t.slice(e.id.length+1))),side:{opened:e=>(this.changes[0](),this.layout(e).shown),toggle:t=>{if(e.controller.signal.aborted)return;let n=this.layout(t);n.shown=!n.shown,this.changed()},menu:()=>this.list(N).filter(e=>e.menu===`session.panel`).sort((e,t)=>(e.order??0)-(t.order??0))},scroll:{get:(e,t)=>(this.changes[0](),this.layout(e).scroll.get(t)),set:(t,n,r)=>{if(e.controller.signal.aborted)return;let i=this.layout(t).scroll;if(!i.has(n)&&i.size>=128)throw Error(`GUI layout scroll limit exceeded`);i.set(n,{...r}),this.changed()}}}),f=Le(e.controller.signal),p=A(()=>e.controller.signal.aborted?{status:`inactive`,reason:`disabled`}:{status:`active`,generation:1,value:f}),m={open:t=>e.controller.signal.aborted||this.appearance[0]().narrow&&!this.mobilePageNetworkReady[0]()||!e.pages.some(e=>e.id===t)?!1:this.options.openPage?.(O(e.id,t))??!1,current:()=>{let t=this.currentPage[0]();return e.pages.find(n=>O(e.id,n.id)===t)?.id}},g=A(()=>e.controller.signal.aborted||!this.options.openPage||this.appearance[0]().narrow&&!this.mobilePageNetworkReady[0]()?{status:`inactive`,reason:`disabled`}:{status:`active`,generation:1,value:m});return Z(`ctx`,{id:e.id,options:r,signal:e.controller.signal,client:this.options.client,storage:o,stores:c,toast:Pe(e.controller.signal,this.options.toast),app:{name:`yuri`,version:e.native?.activation.app.version??``,channel:e.native?.activation.app.packaged?`prod`:`local`,platform:e.native?`desktop`:`web`,packaged:e.native?.activation.app.packaged??!1},desktop:e.native?Z(`desktop`,{os:e.native.activation.os}):void 0,t:u,plural:(e,t,n)=>{let r=`${e}.${new Intl.PluralRules(this.appearance[0]().locale).select(t)}`;return u(r,{...n,count:t})===r?u(`${e}.other`,{...n,count:t}):u(r,{...n,count:t})},add:(t,r)=>{if(e.controller.signal.aborted||a(F)?.ended)return()=>{};if([`server`,`composer-pill`,`slot`,`file.viewer`,`menubar-item`].includes(t.id)&&X(`registry.${t.id}`),e.contributions.size>=256)throw Error(`GUI contribution limit exceeded`);let o=()=>{},c,u=x(i=>{o=i,c=s();let a=()=>typeof r==`function`?r():r,u;if(t.id===`yuri.file-icon`){let e=l(()=>{try{return{ok:!0,value:a()}}catch(e){return{ok:!1,error:e}}});u=()=>{let t=e();if(!t.ok)throw t.error;return t.value}}else u=l(a);if(t.id===`style`){let t=document.createElement(`style`);t.dataset.yuriPluginStyle=e.id,document.head.append(t),h(()=>t.remove()),n(()=>{let e=u();t.textContent=e===void 0?``:String(e)})}return{registry:t.id,read:u}},s()??e.owner);e.contributions.add(u);let d=()=>{t.id===`yuri.file-icon`&&e.iconChanges[1](e=>e+1)},f=()=>{(t.id===`yuri.theme`||t.id===`yuri.branding`)&&e.appearanceChanges[1](e=>e+1)},p=()=>{t.id===`yuri.work-status`&&e.workStatusChanges[1](e=>e+1)};return i(d),i(f),i(p),i(()=>this.changed()),this.own(e,()=>{$(c,t=>{e.error??=String(t)}),o(),e.contributions.delete(u),i(d),i(f),i(p),i(()=>this.changed())})},list:e=>this.list(e),provide:(t,n)=>{if(e.controller.signal.aborted||a(F)?.ended)return()=>{};if(G(t.id)||t.id===`yuri.previewActions`||t.id===`yuri.pages`)throw Error(`Preview/export/page contracts are provided only by the Yuri host`);if(t.kind!==`contract`||!(t.id===e.id||t.id.startsWith(`${e.id}.`)))throw Error(`Contract must belong to the providing plugin`);let r=this.contract(t.id);if(r.provider)throw Error(`Contract already provided: ${t.id}`);return r.provider=e,r.live[1]({status:`active`,value:n,generation:++r.generation}),this.own(e,()=>{r.provider===e&&(r.provider=void 0,r.live[1]({status:`inactive`,reason:e.status===`failed`?`failed`:`disabled`}))})},use:t=>t.id===`yuri.pages`?t.kind===`contract`?g:X(`pages token must be a Contract`):t.id===`yuri.previewActions`?t.kind===`contract`?p:X(`preview actions token must be a Contract`):G(t.id)?t.kind===`contract`?this.viewExports.use(t.id,e.controller.signal):X(`export token must be a Contract`):t.kind===`ipc`&&e.native?e.native.token(t).live:this.contract(t.id,t.kind===`ipc`).live[0],main:t=>{if(!(t.id===e.id||t.id.startsWith(`${e.id}.`)))throw new E(`GUI_PLUGIN_FORBIDDEN`,`IPC must belong to the plugin`);return e.native?e.native.token(t).value:new Proxy({state:()=>void 0},{get:(e,t)=>t===`state`?e.state:t===`on`?()=>{throw new E(`GUI_PLUGIN_UNSUPPORTED`)}:()=>Promise.reject(new E(`GUI_PLUGIN_UNSUPPORTED`))})},sessions:{current:this.session[0],list:()=>{let e=this.session[0]();return e?[e]:[]}},screen:{current:()=>this.session[0]()?this.#e:void 0},layout:d,appearance:{mode:()=>this.appearance[0]().mode,font:()=>getComputedStyle(document.documentElement).getPropertyValue(`--font-mono`).trim()||`monospace`},locale:{locale:()=>this.appearance[0]().locale,direction:()=>/^(ar|fa|he|ur)(-|$)/i.test(this.appearance[0]().locale)?`rtl`:`ltr`},system:{copy:e=>navigator.clipboard.writeText(e),openExternal:e=>{let t=new URL(e);[`https:`,`http:`,`mailto:`].includes(t.protocol)||X(`system.openExternal protocol`),window.open(e,`_blank`,`noopener,noreferrer`)},save:Ie},commands:{run:t=>e.controller.signal.aborted||!this.command(t)?!1:(this.runCommand(t),!0)},links:{open:t=>!e.controller.signal.aborted&&this.navigateLink(e,t),exists:t=>i(()=>{if(e.controller.signal.aborted)return!1;let n=this.linkHandler(t);try{return Promise.resolve(n?.value.exists?.(t)??!1).catch(()=>!1)}catch{return!1}})}})}contract(e,t=!1){let n=this.contracts.get(e);if(!n){if(this.contracts.size>=256)throw Error(`GUI contract limit exceeded`);let t=u({status:`inactive`,reason:`disabled`});n={live:[A(t[0]),t[1]],generation:0},this.contracts.set(e,n)}return t&&n.provider&&X(`IPC contract collision`),n}derive(e){if(e.status!==`active`)return;let t=[],n=[],r=[],a=[],o=[],s=[],c=this.session[0]();for(let i of e.contributions){if([`yuri.file-icon`,`yuri.theme`,`yuri.branding`,`yuri.work-status`].includes(i.registry))continue;let l=i.read();if(l!==void 0){if(i.registry===`yuri.page`){let e=he(l);if(s.some(t=>t.id===e.id))throw Error(`Duplicate yuri.page id`);s.push(e)}else if(i.registry===we.id){let n=l;n.enabled!==!1&&t.push({key:`${e.id}.${n.id}`,pluginId:e.id,title:n.title,description:n.description,bind:n.bind,hidden:n.hidden,run:()=>this.invoke(e,()=>n.run())})}else if(i.registry===k.id){let t=l;o.push({key:JSON.stringify([e.id,t.id]),pluginId:e.id,label:t.label,title:t.title,icon:Me(t.icon),busy:t.busy,pressed:t.pressed,actionable:!!t.run,run:t.run})}else if(i.registry===Ee.id&&c){let t=l,r=`${e.id}:`,i=this.layout(c).open.filter(e=>e.startsWith(r)).map(e=>e.slice(r.length));for(let r of t.list({session:c,screen:this.#e,open:i}))n.push({plugin:e,panel:t,tab:r})}else if(i.registry===be.id){let e=l;(e.page||e.section)&&X(`SettingsPage host sections`),e.title,r.push(e)}else if(i.registry===N.id){let e=l;e.menu===`session.panel`?(e.title,a.push(e)):X(`MenuItem.${e.menu}`)}}}for(let e of n)e.tab.title;e.commands=t,e.titlebarItems=o,e.panels=n,e.pages=s,e.settings=r,e.menus=a,i(()=>this.views[1](e=>e+1))}publish(){let e=i(this.session[0]),t=e?this.layouts.get(e.key):void 0,n=[...this.instances.values()],r=n.filter(e=>e.status===`active`),a=r.flatMap(e=>e.panels.map(({tab:n})=>{let r=n.file?this.filePath(n.file):void 0;return{key:`${e.id}:${n.id}`,pluginId:e.id,title:n.title,file:r,inline:!!(r&&this.fileViews.has(r)),active:t?.shown===!0&&t.active===`${e.id}:${n.id}`}}));this.snapshot=Object.freeze({plugins:Q(n.map(({id:e,revision:t,status:n,error:r,errorCode:i,iconError:a})=>({id:e,revision:t,status:n,error:r??a,...i?{errorCode:i}:{}}))),commands:Q(r.flatMap(e=>e.commands.filter(e=>!e.hidden))),panels:Q(a),titlebarItems:Q(r.flatMap(e=>e.titlebarItems.map(({run:e,...t})=>t))),pages:Q(r.flatMap(e=>e.pages.map(t=>({key:O(e.id,t.id),pluginId:e.id,title:t.title,icon:t.icon})))),settings:Q(r.flatMap(e=>e.settings.map(t=>({key:`${e.id}:${t.id}`,pluginId:e.id,title:t.title})))),menuItems:Q(r.flatMap(e=>e.menus.map(t=>({key:`${e.id}:${t.id}`,pluginId:e.id,title:t.title,description:t.description,run:()=>{this.invoke(e,()=>t.run())}})))),activePanel:t?.shown&&a.some(e=>e.key===t.active)?t.active:null,sessionKey:e?.key});for(let e of this.listeners)e()}invoke(e,t){if(!e.controller.signal.aborted)try{let n=o(e.owner??null,t);if(n instanceof Promise)return n.catch(t=>this.fail(e,t))}catch(t){this.fail(e,t)}}command(e){return[...this.instances.values()].flatMap(e=>e.commands).find(t=>t.key===e)}runCommand(e){return this.command(e)?.run()}runTitlebarItem(e){for(let t of this.instances.values()){let n=t.titlebarItems.find(t=>t.key===e);if(n?.run&&!n.busy)return this.invoke(t,n.run)}}linkHandler(e){let t=[];for(let e of this.instances.values())for(let n of e.contributions)if(n.registry===ye.id){let r=n.read();r&&t.push({instance:e,value:r})}for(let n of t.sort((e,t)=>(t.value.priority??0)-(e.value.priority??0)))try{if(n.value.match(e))return n}catch(e){this.fail(n.instance,e)}}navigateLink(e,t){if(this.ended)return!1;let n=me(t.href);if(!n||!pe(n.path))return this.openLink(t);let r=this.session[0]();if(!r||t.session&&(t.session.key!==r.key||t.session.server.id!==r.server.id))return!1;if(!this.options.focusFile)return this.openLink(t);let i=w(t.base??r.directory,n.path),a=n.line===void 0?``:`:${n.line}${n.column===void 0?``:`:${n.column}`}`;return this.invoke(e,()=>this.options.focusFile(i+a,r.directory)),!0}openLink(e){if(this.ended)return!1;let t={...e,session:e.session??this.session[0]()},n=this.linkHandler(t);return n?(this.invoke(n.instance,()=>n.value.open(t)),!0):!1}filePath(e,t=this.session[0]()?.directory){let n=L(e);return/^(?:\/|[a-z]:\/)/i.test(n)||!t?n:L(`${t}/${n}`)}registerFileView(e,t){if(this.ended)return()=>{};let n=this.filePath(e,t),r=this.fileViews.get(n)??0;this.fileViews.set(n,r+1),r===0&&this.changed(!0);let i=!1;return()=>{if(i||this.ended)return;i=!0;let e=(this.fileViews.get(n)??1)-1;if(e){this.fileViews.set(n,e);return}{let e=this.session[0](),t=e&&this.layouts.get(e.key);t?.active&&this.snapshot.panels.some(e=>e.key===t.active&&e.file===n)&&(t.shown=!1),this.fileViews.delete(n)}this.changed(!0)}}filePanel(e,t){let n=this.filePath(e,t);return this.snapshot.panels.find(e=>e.file===n&&e.inline)}panelVisible(e){let t=this.session[0]();if(!t)return!1;let n=this.panel(e)?.tab.file;if(n&&this.fileViews.has(this.filePath(n)))return!0;let r=this.layouts.get(t.key);return!!(r?.shown&&r.active===e)}layout(e){let t=this.layouts.get(e.key);if(!t){if(this.layouts.size>=128)throw Error(`GUI session layout limit exceeded`);t={open:[],active:null,shown:!1,scroll:new Map},this.layouts.set(e.key,t)}return t}openPanel(e,t,n){if(this.ended)return;let r=this.layout(t),i=r.active,a=r.shown,o=r.open.length;if(!r.open.includes(e)){if(r.open.length>=64)throw Error(`GUI panel tab limit exceeded`);r.open=[...r.open,e]}n?.tab!==`append`&&(r.active=e,r.shown=!(this.appearance[0]().narrow&&n?.background)),(i!==r.active||a!==r.shown||o!==r.open.length)&&this.changed(!0);let s=this.panel(e);t.key===this.session[0]()?.key&&s&&n?.tab!==`append`&&this.invoke(s.plugin,()=>s.panel.focus?.({...this.props(e),restored:!1}))}selectPanel(e){let t=this.session[0]();t&&this.openPanel(e,t)}closeFor(e,t){let n=this.layout(t),r=t.key===this.session[0]()?.key?this.panel(e):void 0;if(!n.open.includes(e)||r?.tab.pinned||r?.tab.closable===!1)return;let i=this.session[0](),a=r&&i?{tab:r.tab,session:i,screen:this.#e}:void 0;n.open=n.open.filter(t=>t!==e),n.active===e&&(n.active=n.open.at(-1)??null),this.changed(!0),r&&a&&this.invoke(r.plugin,()=>r.panel.close?.(a))}closePanel(e){let t=this.session[0]();t&&this.closeFor(e,t)}hidePanel(){let e=this.session[0]();if(!e)return;let t=this.layout(e);t.shown&&(t.shown=!1,this.changed(!0))}panel(e){return[...this.instances.values()].flatMap(e=>e.panels).find(t=>`${t.plugin.id}:${t.tab.id}`===e)}props(e,t=!1){let n=this.panel(e)?.tab,r=()=>(this.views[0](),this.panel(e)?.tab??n??X(`panel no longer listed`)),i=t?l(()=>{let e=r();return{tab:e,fields:Object.getPrototypeOf(e)===Object.prototype?Object.getOwnPropertyDescriptors(e):void 0}},void 0,{equals:Be}):void 0,a=i?()=>i().tab:r,o=()=>this.session[0]()??X(`panel without session`);return{get tab(){return a()},get session(){return o()},screen:this.#e}}mountPanel(e,t,r){let a=this.panel(e);if(!a)return()=>{};let o=new AbortController,s=()=>{let s=l(()=>{this.session[0](),this.changes[0](),this.views[0]();let t=this.panel(e)?.tab.file;return t&&this.files&&this.panelVisible(e)?{model:this.files,file:t}:void 0},void 0,{equals:(e,t)=>e?.model===t?.model&&e?.file===t?.file});n(()=>{let e=s();e&&(h(e.model.watch(e.file)),e.model.sync(e.file).catch(()=>{}))});let c=()=>i(()=>a.panel.render(this.props(e,!0)));return S(K.Provider,{value:r?{plugin:a.plugin.controller.signal,signal:o.signal,content:t,target:r}:void 0,get children(){return c()}})},c=this.mount(a.plugin,t,()=>S(xe.Provider,{value:{visible:()=>(this.changes[0](),this.panelVisible(e)),present:()=>(this.changes[0](),this.panelVisible(e)),placement:()=>this.appearance[0]().narrow?`mobile`:`side`,reserve:()=>!1,animate:()=>!1,sidebar:Z(`panel.sidebar`,{}),open:()=>{let e=this.session[0]();return e?a.plugin.context.layout.stored(e):[]}},get children(){return s()}})),u=()=>{this.panelMounts.delete(u),o.abort(),c()};return this.panelMounts.add(u),this.own(a.plugin,u)}mountSettings(e,t){for(let n of this.instances.values()){let r=n.settings.find(t=>`${n.id}:${t.id}`===e);if(r)return this.mount(n,t,()=>r.render({}))}return()=>{}}mountPage(e,t){if(this.appearance[0]().narrow&&!this.mobilePageNetworkReady[0]())throw new E(`GUI_PLUGIN_UNAVAILABLE`,`Mobile page Relay is not ready`);for(let n of this.instances.values()){let r=n.pages.find(t=>O(n.id,t.id)===e);if(r)return this.mount(n,t,()=>r.render())}return()=>{}}mountWorkStatus(e,t,n){let r=this.instances.get(e.pluginId);if(!r||!this.workStatus.contains(e)||this.ended)return{update(){},dispose(){}};let i=Y(n,n.sessionId&&n.directory?this.sessionReference({id:n.sessionId,directory:n.directory},n.scope):void 0,n.scope?JSON.stringify(n.scope.queryScope):this.options.transport),a=()=>{},o=()=>{},s=this.own(r,()=>{i.dispose(),o(),a()});return o=this.workStatus.subscribe(()=>{this.workStatus.contains(e)||s()}),a=this.mount(r,t,()=>e.render(i.props)),i.props.signal.aborted&&(o(),a()),{update:e=>{if(!i.matches(e)){s();return}i.update(e)},dispose:s}}mount(e,t,n){if(e.controller.signal.aborted)return()=>{};let r=()=>{},a,o=t=>{queueMicrotask(()=>this.fail(e,t))};try{r=_e(()=>S(j.Provider,{value:e.context,get children(){return a=s(),b(()=>i(n),o)}}),t)}catch(t){this.fail(e,t)}return this.own(e,()=>{$(a,t=>{e.error??=String(t)}),r(),t.replaceChildren()})}};export{Ve as GuiPluginHost};
@@ -1 +1 @@
1
- import{r as e}from"./rolldown-runtime-hePW80VL.js";import{A as t,F as n,j as r}from"./platform-wF65ZFgV.js";import{ot as i,st as a}from"./vendor-base-ui-fom6orB6.js";import{n as o}from"./vendor-react-D5BntRmA.js";import{n as s,t as c}from"./runtime-ead7P81A.js";import"./bootstrap-eLlfzqAI.js";import{i as l,t as u}from"./store-Dj5cSf8B.js";var d=e(a(),1),f=o(),p=async(e,n)=>{if(!t())throw Error(`Desktop runtime is not available`);return r(e,n)},m=async()=>{if(n())try{await p(`desktop_start_window_drag`)}catch{}},h=async e=>{if(n())try{await p(`desktop_set_window_title`,{title:e})}catch{}},g=async(e,t)=>{if(n())try{await p(`desktop_set_window_theme`,{themeMode:e,themeVariant:t})}catch{}},_=async e=>{if(n())try{await p(`desktop_set_menu_locale`,{locale:e})}catch{}},v=async()=>{if(!n())return null;try{let e=await p(`desktop_get_app_version`);return typeof e==`string`&&e.trim().length>0?e:null}catch{return null}},y=d.createContext(null),b=i(),x=e=>{let t=(0,f.c)(19),{children:n}=e,r=l(S),i=l(C),a=l(w),o=l(T),p,m;t[0]===r?(p=t[1],m=t[2]):(p=()=>{typeof document>`u`||(document.documentElement.lang=r)},m=[r],t[0]=r,t[1]=p,t[2]=m),d.useEffect(p,m);let h,g;t[3]!==a||t[4]!==r?(h=()=>{a===null&&_(r)},g=[r,a],t[3]=a,t[4]=r,t[5]=h,t[6]=g):(h=t[5],g=t[6]),d.useEffect(h,g);let v;t[7]===i?v=t[8]:(v=(e,t)=>u(i,e,t),t[7]=i,t[8]=v);let x=v,E;t[9]===x?E=t[10]:(E=e=>x(s[e]),t[9]=x,t[10]=E);let D;t[11]!==r||t[12]!==o||t[13]!==x||t[14]!==E?(D={locale:r,locales:c,setLocale:o,label:E,t:x},t[11]=r,t[12]=o,t[13]=x,t[14]=E,t[15]=D):D=t[15];let O=D,k;return t[16]!==n||t[17]!==O?(k=(0,b.jsx)(y.Provider,{value:O,children:n}),t[16]=n,t[17]=O,t[18]=k):k=t[18],k};function S(e){return e.locale}function C(e){return e.dictionary}function w(e){return e.loadingLocale}function T(e){return e.setLocale}var E={en:`en-US`,fr:`fr-FR`,"zh-CN":`zh-CN`,"zh-TW":`zh-TW`,uk:`uk-UA`,es:`es-ES`,"pt-BR":`pt-BR`,ko:`ko-KR`,pl:`pl-PL`,ja:`ja-JP`},D=e=>E[e]??`en-US`,O=()=>D(l.getState().locale);function k(){let e=d.useContext(y);if(!e)throw Error(`useI18n must be used within I18nProvider`);return e}export{p as a,m as c,v as i,O as n,g as o,x as r,h as s,k as t};
1
+ import{r as e}from"./rolldown-runtime-hePW80VL.js";import{A as t,F as n,j as r}from"./platform-CiUKDeXd.js";import{ot as i,st as a}from"./vendor-base-ui-fom6orB6.js";import{n as o}from"./vendor-react-D5BntRmA.js";import{n as s,t as c}from"./runtime-ead7P81A.js";import"./bootstrap-eLlfzqAI.js";import{i as l,t as u}from"./store-Dj5cSf8B.js";var d=e(a(),1),f=o(),p=async(e,n)=>{if(!t())throw Error(`Desktop runtime is not available`);return r(e,n)},m=async()=>{if(n())try{await p(`desktop_start_window_drag`)}catch{}},h=async e=>{if(n())try{await p(`desktop_set_window_title`,{title:e})}catch{}},g=async(e,t)=>{if(n())try{await p(`desktop_set_window_theme`,{themeMode:e,themeVariant:t})}catch{}},_=async e=>{if(n())try{await p(`desktop_set_menu_locale`,{locale:e})}catch{}},v=async()=>{if(!n())return null;try{let e=await p(`desktop_get_app_version`);return typeof e==`string`&&e.trim().length>0?e:null}catch{return null}},y=d.createContext(null),b=i(),x=e=>{let t=(0,f.c)(19),{children:n}=e,r=l(S),i=l(C),a=l(w),o=l(T),p,m;t[0]===r?(p=t[1],m=t[2]):(p=()=>{typeof document>`u`||(document.documentElement.lang=r)},m=[r],t[0]=r,t[1]=p,t[2]=m),d.useEffect(p,m);let h,g;t[3]!==a||t[4]!==r?(h=()=>{a===null&&_(r)},g=[r,a],t[3]=a,t[4]=r,t[5]=h,t[6]=g):(h=t[5],g=t[6]),d.useEffect(h,g);let v;t[7]===i?v=t[8]:(v=(e,t)=>u(i,e,t),t[7]=i,t[8]=v);let x=v,E;t[9]===x?E=t[10]:(E=e=>x(s[e]),t[9]=x,t[10]=E);let D;t[11]!==r||t[12]!==o||t[13]!==x||t[14]!==E?(D={locale:r,locales:c,setLocale:o,label:E,t:x},t[11]=r,t[12]=o,t[13]=x,t[14]=E,t[15]=D):D=t[15];let O=D,k;return t[16]!==n||t[17]!==O?(k=(0,b.jsx)(y.Provider,{value:O,children:n}),t[16]=n,t[17]=O,t[18]=k):k=t[18],k};function S(e){return e.locale}function C(e){return e.dictionary}function w(e){return e.loadingLocale}function T(e){return e.setLocale}var E={en:`en-US`,fr:`fr-FR`,"zh-CN":`zh-CN`,"zh-TW":`zh-TW`,uk:`uk-UA`,es:`es-ES`,"pt-BR":`pt-BR`,ko:`ko-KR`,pl:`pl-PL`,ja:`ja-JP`},D=e=>E[e]??`en-US`,O=()=>D(l.getState().locale);function k(){let e=d.useContext(y);if(!e)throw Error(`useI18n must be used within I18nProvider`);return e}export{p as a,m as c,v as i,O as n,g as o,x as r,h as s,k as t};
@@ -1 +1 @@
1
- import{r as e}from"./rolldown-runtime-hePW80VL.js";import{_ as t,s as n}from"./runtime-auth-mjIpsk3N.js";import{c as r,i}from"./runtime-switch-BMjl5Y5W.js";import{st as a}from"./vendor-base-ui-fom6orB6.js";import"./brand-storage-bootstrap-D4BW3w-M.js";import{n as o}from"./vendor-react-D5BntRmA.js";import{E as s,t as c}from"./runtime-file-resource-DnhWnndu.js";import{a as l,o as u,r as d}from"./path-utils-jGozTg9d.js";var f=e(a(),1),p=o(),m=[0,250,750],h=e=>{try{return decodeURIComponent(e)}catch{return e}},g=e=>{try{let t=new URL(e),n=h(t.hostname),r=h(t.pathname);return/^[A-Za-z]$/.test(n)?r=`${n.toUpperCase()}:${r}`:n&&n.toLowerCase()!==`localhost`&&(r=`//${n}${r}`),/^\/[A-Za-z]:[\\/]/.test(r)&&(r=r.slice(1)),l(r)}catch{let t=h(e.replace(/^file:\/\//i,``));return/^\/[A-Za-z]:[\\/]/.test(t)&&(t=t.slice(1)),l(t)}},_=(e,t)=>{let n=e.trim();if(!n||/^https?:/i.test(n)||/^(?:data|blob):/i.test(n)||/^\/api(?=\/|[?#]|$)/.test(n))return{kind:`direct`,source:n};if(/^file:\/\//i.test(n))return{kind:`runtime-file`,source:n,path:g(n)};if(/^[a-z][a-z\d+.-]*:/i.test(n)&&!/^[A-Za-z]:[\\/]/.test(n))return{kind:`direct`,source:n};let r=h(n);return{kind:`runtime-file`,source:n,path:d(r)?l(r):u(t,r)}},v=(e,t,n)=>y(()=>c(e,t,void 0,n),t),y=async(e,t)=>{let r=i(),a=n(),o;for(let s of m){t.throwIfAborted(),s>0&&await new Promise((e,n)=>{let r=window.setTimeout(()=>{t.removeEventListener(`abort`,i),e()},s),i=()=>{window.clearTimeout(r),n(t.reason)};t.addEventListener(`abort`,i,{once:!0})});try{if(t.throwIfAborted(),r!==i()||a!==n())throw new DOMException(`Image request superseded`,`AbortError`);return await e()}catch(e){if(t.aborted||r!==i()||a!==n())throw e;o=e}}throw o instanceof Error?o:Error(`Image source request failed`)},b=()=>!1,x=e=>e.startsWith(`relay:`)||b(),S=(e,t)=>typeof t==`number`&&Number.isFinite(t)&&t>1048576&&x(e),C=()=>f.useSyncExternalStore(T,i,i),w=e=>e.kind===`runtime-file`&&!!e.path,T=e=>r(()=>e()),E=e=>t(()=>e()),D=(e,t,r)=>{let a=(0,p.c)(22),o=r===void 0?`inline`:r,l=s(),u=l?.entry.location.hostId?l.entry:void 0,d=f.useSyncExternalStore(E,n,n),m=f.useSyncExternalStore(T,i,i),h;a[0]!==t||a[1]!==e?(h=_(e,t),a[0]=t,a[1]=e,a[2]=h):h=a[2];let g=h,v;a[3]===g?v=a[4]:(v=w(g),a[3]=g,a[4]=v);let y=v,b=`${m}\n${u?.key??``}\n${u?.connectionGeneration??``}\n${d}\n${t}\n${e}\n${o}`,x=y?``:g.source,S=y,C;a[5]!==S||a[6]!==x||a[7]!==b?(C={key:b,source:x,loading:S,error:null},a[5]=S,a[6]=x,a[7]=b,a[8]=C):C=a[8];let[D,O]=f.useState(C),k,A;a[9]!==o||a[10]!==b||a[11]!==g||a[12]!==u||a[13]!==m||a[14]!==y?(k=()=>{if(!y||!w(g)){O({key:b,source:g.source,loading:!1,error:null});return}O({key:b,source:``,loading:!0,error:null});let e=new AbortController,t;return c(g.path,e.signal,o,u).then(n=>{if(e.signal.aborted||i()!==m){n.release();return}t=n.release,O({key:b,source:n.url,loading:!1,error:null})}).catch(t=>{e.signal.aborted||O({key:b,source:``,loading:!1,error:t instanceof Error?t.message:`Image source request failed`})}),()=>{e.abort(),t?.()}},A=[b,g,m,y,o,u],a[9]=o,a[10]=b,a[11]=g,a[12]=u,a[13]=m,a[14]=y,a[15]=k,a[16]=A):(k=a[15],A=a[16]),f.useEffect(k,A);let j;return a[17]!==D||a[18]!==S||a[19]!==x||a[20]!==b?(j=D.key===b?D:{key:b,source:x,loading:S,error:null},a[17]=D,a[18]=S,a[19]=x,a[20]=b,a[21]=j):j=a[21],j},O=(e,t,n)=>D(e,t,n===void 0?`inline`:n).source;export{_ as a,C as c,w as i,S as n,D as o,x as r,O as s,v as t};
1
+ import{r as e}from"./rolldown-runtime-hePW80VL.js";import{_ as t,s as n}from"./runtime-auth-DA-qfGHk.js";import{c as r,i}from"./runtime-switch-DEPKHgdL.js";import{st as a}from"./vendor-base-ui-fom6orB6.js";import"./brand-storage-bootstrap-D4BW3w-M.js";import{n as o}from"./vendor-react-D5BntRmA.js";import{E as s,t as c}from"./runtime-file-resource-CKQQEwNv.js";import{a as l,o as u,r as d}from"./path-utils-jGozTg9d.js";var f=e(a(),1),p=o(),m=[0,250,750],h=e=>{try{return decodeURIComponent(e)}catch{return e}},g=e=>{try{let t=new URL(e),n=h(t.hostname),r=h(t.pathname);return/^[A-Za-z]$/.test(n)?r=`${n.toUpperCase()}:${r}`:n&&n.toLowerCase()!==`localhost`&&(r=`//${n}${r}`),/^\/[A-Za-z]:[\\/]/.test(r)&&(r=r.slice(1)),l(r)}catch{let t=h(e.replace(/^file:\/\//i,``));return/^\/[A-Za-z]:[\\/]/.test(t)&&(t=t.slice(1)),l(t)}},_=(e,t)=>{let n=e.trim();if(!n||/^https?:/i.test(n)||/^(?:data|blob):/i.test(n)||/^\/api(?=\/|[?#]|$)/.test(n))return{kind:`direct`,source:n};if(/^file:\/\//i.test(n))return{kind:`runtime-file`,source:n,path:g(n)};if(/^[a-z][a-z\d+.-]*:/i.test(n)&&!/^[A-Za-z]:[\\/]/.test(n))return{kind:`direct`,source:n};let r=h(n);return{kind:`runtime-file`,source:n,path:d(r)?l(r):u(t,r)}},v=(e,t,n)=>y(()=>c(e,t,void 0,n),t),y=async(e,t)=>{let r=i(),a=n(),o;for(let s of m){t.throwIfAborted(),s>0&&await new Promise((e,n)=>{let r=window.setTimeout(()=>{t.removeEventListener(`abort`,i),e()},s),i=()=>{window.clearTimeout(r),n(t.reason)};t.addEventListener(`abort`,i,{once:!0})});try{if(t.throwIfAborted(),r!==i()||a!==n())throw new DOMException(`Image request superseded`,`AbortError`);return await e()}catch(e){if(t.aborted||r!==i()||a!==n())throw e;o=e}}throw o instanceof Error?o:Error(`Image source request failed`)},b=()=>!1,x=e=>e.startsWith(`relay:`)||b(),S=(e,t)=>typeof t==`number`&&Number.isFinite(t)&&t>1048576&&x(e),C=()=>f.useSyncExternalStore(T,i,i),w=e=>e.kind===`runtime-file`&&!!e.path,T=e=>r(()=>e()),E=e=>t(()=>e()),D=(e,t,r)=>{let a=(0,p.c)(22),o=r===void 0?`inline`:r,l=s(),u=l?.entry.location.hostId?l.entry:void 0,d=f.useSyncExternalStore(E,n,n),m=f.useSyncExternalStore(T,i,i),h;a[0]!==t||a[1]!==e?(h=_(e,t),a[0]=t,a[1]=e,a[2]=h):h=a[2];let g=h,v;a[3]===g?v=a[4]:(v=w(g),a[3]=g,a[4]=v);let y=v,b=`${m}\n${u?.key??``}\n${u?.connectionGeneration??``}\n${d}\n${t}\n${e}\n${o}`,x=y?``:g.source,S=y,C;a[5]!==S||a[6]!==x||a[7]!==b?(C={key:b,source:x,loading:S,error:null},a[5]=S,a[6]=x,a[7]=b,a[8]=C):C=a[8];let[D,O]=f.useState(C),k,A;a[9]!==o||a[10]!==b||a[11]!==g||a[12]!==u||a[13]!==m||a[14]!==y?(k=()=>{if(!y||!w(g)){O({key:b,source:g.source,loading:!1,error:null});return}O({key:b,source:``,loading:!0,error:null});let e=new AbortController,t;return c(g.path,e.signal,o,u).then(n=>{if(e.signal.aborted||i()!==m){n.release();return}t=n.release,O({key:b,source:n.url,loading:!1,error:null})}).catch(t=>{e.signal.aborted||O({key:b,source:``,loading:!1,error:t instanceof Error?t.message:`Image source request failed`})}),()=>{e.abort(),t?.()}},A=[b,g,m,y,o,u],a[9]=o,a[10]=b,a[11]=g,a[12]=u,a[13]=m,a[14]=y,a[15]=k,a[16]=A):(k=a[15],A=a[16]),f.useEffect(k,A);let j;return a[17]!==D||a[18]!==S||a[19]!==x||a[20]!==b?(j=D.key===b?D:{key:b,source:x,loading:S,error:null},a[17]=D,a[18]=S,a[19]=x,a[20]=b,a[21]=j):j=a[21],j},O=(e,t,n)=>D(e,t,n===void 0?`inline`:n).source;export{_ as a,C as c,w as i,S as n,D as o,x as r,O as s,v as t};
@@ -1 +1 @@
1
- import"./rolldown-runtime-hePW80VL.js";import{ot as e,st as t}from"./vendor-base-ui-fom6orB6.js";import{n}from"./vendor-react-D5BntRmA.js";import{Rn as r}from"./useMobileNavigationStore-BkVbj6Lg.js";var i=n();t();var a=e();function o(e){let t=(0,i.c)(23),n,o,s,c,l,u;t[0]===e?(n=t[1],o=t[2],s=t[3],c=t[4],l=t[5],u=t[6]):({className:o,type:u,bordered:n,placeholder:c,endAdornment:s,...l}=e,t[0]=e,t[1]=n,t[2]=o,t[3]=s,t[4]=c,t[5]=l,t[6]=u);let d=c||` `,f=n!==void 0&&`border border-transparent ring-0 focus:ring-0 aria-invalid:ring-1 aria-invalid:focus:ring-1`,p=n&&`border-[var(--form-surface-border)]`,m=s&&`pe-11`,h;t[7]!==o||t[8]!==f||t[9]!==p||t[10]!==m?(h=r(`text-foreground file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground bg-[var(--surface-elevated)] appearance-none flex h-9 w-full min-w-0 rounded-lg px-3 py-1 typography-markdown outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:typography-ui-label file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:typography-ui-label`,`ring-1 ring-inset ring-border/60 transition duration-200 ease-out`,`hover:[&:not(:focus)]:bg-[var(--surface-subtle)] hover:[&:not(:focus)]:ring-transparent`,`focus:ring-2 focus:ring-[var(--interactive-focus-ring)] focus-visible:outline-none`,`aria-invalid:ring-[var(--status-error)] aria-invalid:focus:ring-[var(--status-error)]`,f,p,o,m),t[7]=o,t[8]=f,t[9]=p,t[10]=m,t[11]=h):h=t[11];let g;t[12]!==n||t[13]!==l||t[14]!==d||t[15]!==h||t[16]!==u?(g=(0,a.jsx)(`input`,{type:u,"data-slot":`input`,"data-bordered":n,placeholder:d,className:h,spellCheck:!1,autoComplete:`off`,autoCorrect:`off`,autoCapitalize:`off`,...l}),t[12]=n,t[13]=l,t[14]=d,t[15]=h,t[16]=u,t[17]=g):g=t[17];let _=g;if(!s)return _;let v;t[18]===s?v=t[19]:(v=(0,a.jsx)(`div`,{"data-slot":`input-end-adornment`,className:`absolute inset-y-0 end-0 flex items-center`,children:s}),t[18]=s,t[19]=v);let y;return t[20]!==_||t[21]!==v?(y=(0,a.jsxs)(`div`,{"data-slot":`input-wrapper`,className:`relative min-w-0 w-full flex-1`,children:[_,v]}),t[20]=_,t[21]=v,t[22]=y):y=t[22],y}export{o as t};
1
+ import"./rolldown-runtime-hePW80VL.js";import{ot as e,st as t}from"./vendor-base-ui-fom6orB6.js";import{n}from"./vendor-react-D5BntRmA.js";import{Rn as r}from"./useMobileNavigationStore-oveTY29a.js";var i=n();t();var a=e();function o(e){let t=(0,i.c)(23),n,o,s,c,l,u;t[0]===e?(n=t[1],o=t[2],s=t[3],c=t[4],l=t[5],u=t[6]):({className:o,type:u,bordered:n,placeholder:c,endAdornment:s,...l}=e,t[0]=e,t[1]=n,t[2]=o,t[3]=s,t[4]=c,t[5]=l,t[6]=u);let d=c||` `,f=n!==void 0&&`border border-transparent ring-0 focus:ring-0 aria-invalid:ring-1 aria-invalid:focus:ring-1`,p=n&&`border-[var(--form-surface-border)]`,m=s&&`pe-11`,h;t[7]!==o||t[8]!==f||t[9]!==p||t[10]!==m?(h=r(`text-foreground file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground bg-[var(--surface-elevated)] appearance-none flex h-9 w-full min-w-0 rounded-lg px-3 py-1 typography-markdown outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:typography-ui-label file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:typography-ui-label`,`ring-1 ring-inset ring-border/60 transition duration-200 ease-out`,`hover:[&:not(:focus)]:bg-[var(--surface-subtle)] hover:[&:not(:focus)]:ring-transparent`,`focus:ring-2 focus:ring-[var(--interactive-focus-ring)] focus-visible:outline-none`,`aria-invalid:ring-[var(--status-error)] aria-invalid:focus:ring-[var(--status-error)]`,f,p,o,m),t[7]=o,t[8]=f,t[9]=p,t[10]=m,t[11]=h):h=t[11];let g;t[12]!==n||t[13]!==l||t[14]!==d||t[15]!==h||t[16]!==u?(g=(0,a.jsx)(`input`,{type:u,"data-slot":`input`,"data-bordered":n,placeholder:d,className:h,spellCheck:!1,autoComplete:`off`,autoCorrect:`off`,autoCapitalize:`off`,...l}),t[12]=n,t[13]=l,t[14]=d,t[15]=h,t[16]=u,t[17]=g):g=t[17];let _=g;if(!s)return _;let v;t[18]===s?v=t[19]:(v=(0,a.jsx)(`div`,{"data-slot":`input-end-adornment`,className:`absolute inset-y-0 end-0 flex items-center`,children:s}),t[18]=s,t[19]=v);let y;return t[20]!==_||t[21]!==v?(y=(0,a.jsxs)(`div`,{"data-slot":`input-wrapper`,className:`relative min-w-0 w-full flex-1`,children:[_,v]}),t[20]=_,t[21]=v,t[22]=y):y=t[22],y}export{o as t};
@@ -1 +1 @@
1
- import{i as e,n as t}from"./runtime-switch-BMjl5Y5W.js";import{a as n}from"./vendor-zustand-CNn3HHhT.js";import{t as r}from"./brand-storage-migration-Bhz6UOBJ.js";import"./brand-storage-bootstrap-D4BW3w-M.js";import{D as i,E as a,F as o,O as s,R as c,S as l,k as u,o as d,s as f,w as p,x as m}from"./prompt-attachment-upload-8bssUUT3.js";import{t as h}from"./uuid-D-SDZijH.js";var g=`yuri_input_draft_metadata_v1`,_=`yuri_input_draft_metadata_migration_v1`,v=`yuri_chat_input_draft_`,y=`yuri_chat_confirmed_mentions_`,b=()=>({ok:!1,error:{code:`unavailable`}}),x=()=>({ok:!1,error:{code:`cancelled`}}),S=e=>({ok:!1,error:{code:e instanceof DOMException&&e.name===`QuotaExceededError`?`quota`:`unavailable`}}),C=e=>typeof e==`object`&&!!e&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null),w=(e,t)=>Object.keys(e).every(e=>t.includes(e)),T=e=>typeof e==`number`&&Number.isSafeInteger(e)&&e>0,E=e=>typeof e==`string`&&e.length>0,D=e=>({read:async t=>{if(!e)return b();try{return{ok:!0,value:e.getItem(t)}}catch(e){return S(e)}},write:async(t,n)=>{if(!e)return b();try{return e.setItem(t,n),{ok:!0,value:void 0}}catch(e){return S(e)}},remove:async t=>{if(!e)return b();try{return e.removeItem(t),{ok:!0,value:void 0}}catch(e){return S(e)}},keys:async()=>{if(!e)return b();try{let t=[];for(let n=0;n<e.length;n+=1){let r=e.key(n);r!==null&&t.push(r)}return{ok:!0,value:t}}catch(e){return S(e)}}}),O=()=>{try{return D(typeof window>`u`?null:window.localStorage)}catch{return D(null)}},k=(e,t,n,r)=>{let i=[];try{let e=n===null?[]:JSON.parse(n);Array.isArray(e)&&(i=e.filter(e=>typeof e==`string`))}catch{}return{suffix:e,text:t??``,mentions:i,keys:r}},ee=async e=>{let t=await e.keys();if(!t.ok)return t;let n=new Set;for(let e of t.value)e.startsWith(v)&&n.add(e.slice(22)),e.startsWith(y)&&n.add(e.slice(29));let r=[];for(let i of n){let n=`${v}${i}`,a=`${y}${i}`,[o,s]=await Promise.all([e.read(n),e.read(a)]);if(!o.ok)return o;if(!s.ok)return s;r.push(k(i,o.value,s.value,[n,a].filter(e=>t.value.includes(e))))}return{ok:!0,value:r}},te=e=>{if(!(!C(e)||!w(e,[`suffix`,`text`,`mentions`,`keys`])||typeof e.suffix!=`string`||typeof e.text!=`string`||!Array.isArray(e.mentions)||!e.mentions.every(e=>typeof e==`string`)||!Array.isArray(e.keys)||!e.keys.every(e=>typeof e==`string`)))return{suffix:e.suffix,text:e.text,mentions:[...e.mentions],keys:[...e.keys]}},ne=e=>{try{let t=JSON.parse(e);return Array.isArray(t)&&t.length===3&&E(t[0])&&(t[1]===`session`||t[1]===`draft`)&&E(t[2])&&e===JSON.stringify(t)}catch{return!1}},A=e=>{if(!C(e)||!w(e,[`complete`,`claimedTransportIdentity`,`captured`,`markerCommitted`,`cleanupComplete`])||typeof e.complete!=`boolean`||typeof e.claimedTransportIdentity!=`string`||e.captured!==void 0&&typeof e.captured!=`boolean`||e.markerCommitted!==void 0&&typeof e.markerCommitted!=`boolean`||e.cleanupComplete!==void 0&&typeof e.cleanupComplete!=`boolean`)return;let t=e.cleanupComplete??e.complete,n=e.captured??e.complete,r=e.markerCommitted??e.complete;if(!((n||r||t)&&!E(e.claimedTransportIdentity))&&!(r&&!n)&&!(t&&(!n||!r)))return{complete:t,claimedTransportIdentity:e.claimedTransportIdentity,captured:n,markerCommitted:r,cleanupComplete:t}},j=e=>{if(!C(e)||!w(e,[`version`,`drafts`,`tombstones`,`migration`,`legacy`])||e.version!==1||!C(e.drafts)||!C(e.tombstones)||!C(e.legacy)||!w(e.legacy,[`new`,`entries`])||!C(e.legacy.entries))return;let t=A(e.migration);if(!t)return;let n={};for(let[t,r]of Object.entries(e.drafts)){let e=c(r);if(!e||t!==a(e.key))return;n[t]=e}let r={};for(let[t,n]of Object.entries(e.tombstones)){if(!ne(t)||!T(n))return;r[t]=n}let i={};for(let[t,n]of Object.entries(e.legacy.entries)){let e=te(n);if(!e||t!==e.suffix||t===`new`)return;i[t]=e}let o=e.legacy.new===void 0?void 0:te(e.legacy.new);if(!(e.legacy.new!==void 0&&(!o||o.suffix!==`new`)))return{version:1,drafts:n,tombstones:r,migration:t,legacy:{...o?{new:o}:{},entries:i}}},M=(e=``)=>({version:1,drafts:{},tombstones:{},migration:{complete:!1,claimedTransportIdentity:e,captured:!1,markerCommitted:!1,cleanupComplete:!1},legacy:{entries:{}}}),N=e=>{try{return{ok:!0,value:JSON.stringify(e)}}catch{return{ok:!1,error:{code:`serialization`}}}},P=async e=>{let t=await e.read(g);if(!t.ok)return t;if(t.value===null)return{ok:!0,value:null};try{let e=j(JSON.parse(t.value));return e?{ok:!0,value:e}:{ok:!1,error:{code:`corrupt`}}}catch{return{ok:!1,error:{code:`corrupt`}}}},F=async(e,t)=>{let n=j(t);if(!n)return{ok:!1,error:{code:`corrupt`}};let r=N(n);return r.ok?e.write(g,r.value):r},I=e=>C(e)&&w(e,[`version`,`claimedTransportIdentity`])&&e.version===1&&E(e.claimedTransportIdentity)?{version:1,claimedTransportIdentity:e.claimedTransportIdentity}:void 0,re=e=>N({version:1,claimedTransportIdentity:e}),ie=(e,t,n)=>{let r={},i;for(let e of t)e.suffix===`new`?i=e:r[e.suffix]=e;return{...e,migration:{complete:!1,claimedTransportIdentity:n,captured:!0,markerCommitted:!1,cleanupComplete:!1},legacy:{...i?{new:i}:{},entries:r}}},L=e=>[...new Set([e.legacy.new,...Object.values(e.legacy.entries)].flatMap(e=>e?.keys??[]))],ae=new WeakMap,R=e=>{let t=ae.get(e);if(t)return t;let n=Promise.resolve(),r,i=!0,a=e=>{let t=n.then(e,e);return n=t.then(()=>void 0,()=>void 0),t},o={persist:t=>{let n=j(t);return n?i?a(async()=>i?F(e,n):b()):Promise.resolve(b()):Promise.resolve({ok:!1,error:{code:`corrupt`}})},migrate:(t,n={})=>{if(r)return r;let o=a(async()=>{let r=await P(e);if(!r.ok)return r;let a=r.value??M(),o=i&&(n.persistenceEnabled??!0);if(!a.migration.captured){let n=await ee(e);if(!n.ok)return n;if(!o)return{ok:!0,value:ie(a,n.value,``)};if(a=ie(a,n.value,t),!i)return{ok:!0,value:a};let r=await F(e,a);if(!r.ok)return r}if(!i||!(n.persistenceEnabled??!0)){let t=await ee(e);return t.ok?{ok:!0,value:a}:t}let s=await e.read(_);if(!s.ok)return s;if(s.value!==null)try{let t=I(JSON.parse(s.value));if(!t)return{ok:!1,error:{code:`corrupt`}};if(t.claimedTransportIdentity!==a.migration.claimedTransportIdentity){let t=re(a.migration.claimedTransportIdentity);if(!t.ok)return t;if(!i)return{ok:!0,value:a};let n=await e.write(_,t.value);if(!n.ok)return n}}catch{return{ok:!1,error:{code:`corrupt`}}}else{let t=re(a.migration.claimedTransportIdentity);if(!t.ok)return t;if(!i)return{ok:!0,value:a};let n=await e.write(_,t.value);if(!n.ok)return n}if(a.migration.cleanupComplete)return{ok:!0,value:a};for(let t of L(a)){if(!i)return{ok:!0,value:a};let n=await e.remove(t);if(!n.ok)return n}if(a={...a,migration:{complete:!0,claimedTransportIdentity:a.migration.claimedTransportIdentity,captured:!0,markerCommitted:!0,cleanupComplete:!0}},!i)return{ok:!0,value:a};let c=await F(e,a);return c.ok?{ok:!0,value:a}:c}).finally(()=>{r=void 0});return r=o,o},flush:()=>n,setEnabled:async e=>{i=e,i||await n}};return ae.set(e,o),o},z=e=>{let t=R(e),n=!0,r=!1,i=[],a=[],o=()=>{if(r||i.length>0)return;let e=a;a=[],e.forEach(e=>e())},s=()=>{if(r)return;let e=i.shift();if(!e){o();return}r=!0,t.persist(e.snapshot).then(e.resolve).finally(()=>{r=!1,s()})};return{persist:e=>{let t=j(e);return t?n?new Promise(e=>{i.push({snapshot:t,resolve:e}),s()}):Promise.resolve(b()):Promise.resolve({ok:!1,error:{code:`corrupt`}})},cancelPending:()=>{let e=i;i=[],e.forEach(({resolve:e})=>e(x())),o()},flush:()=>r||i.length>0?new Promise(e=>a.push(e)):Promise.resolve(),setEnabled:async e=>{if(n=e,!n){let e=i;i=[],e.forEach(({resolve:e})=>e(x()))}await(r||i.length>0?new Promise(e=>a.push(e)):Promise.resolve()),await t.setEnabled(e),await t.flush()}}},oe=`yuri-input-drafts`,se=1,ce=`blobs`,le=`blobRefs`,B=class extends Error{code;constructor(e){super(e),this.code=e}},V=e=>({ok:!1,error:{code:e instanceof B?e.code:e instanceof DOMException&&e.name===`QuotaExceededError`?`quota-exceeded`:e instanceof DOMException&&e.name===`AbortError`?`transaction-aborted`:`transaction-failed`}}),H=e=>{if(!(e instanceof Blob)&&!u(e))throw new B(`invalid-value`)},U=e=>{if(!e)throw new B(`invalid-value`)},W=(e,t)=>({id:p(e),blobID:t,transportIdentity:e.transportIdentity,ownerKind:e.owner.kind,ownerID:e.owner.ownerID}),G=async e=>{if(typeof e==`string`)return`url:${e}`;let t=await crypto.subtle.digest(`SHA-256`,await e.arrayBuffer()),n=[...new Uint8Array(t)].map(e=>e.toString(16).padStart(2,`0`)).join(``);return`blob:${e.type}:${e.size}:${n}`},K=async(e,t)=>(e.fingerprint??await G(e.value))===t,q=async(e,t=!1)=>{let n=await e.getAllBlobRefs(),r=await e.getAllBlobs(),i=new Map;for(let t of n)await e.getBlob(t.blobID)?i.set(t.blobID,(i.get(t.blobID)??0)+1):await e.deleteBlobRef(t.id);for(let n of r){let r=i.get(n.id)??0;r||!t?await e.putBlob({...n,refCount:r}):await e.deleteBlob(n.id)}},ue=e=>{try{let t=JSON.parse(e);return!Array.isArray(t)||t.length!==4||typeof t[0]!=`string`||typeof t[2]!=`string`||t[1]!==`session`&&t[1]!==`draft`&&t[1]!==`surface`&&t[1]!==`queue`&&t[1]!==`send`?void 0:{transportIdentity:t[0],ownerKind:t[1],ownerID:t[2]}}catch{return}},J=(e,t)=>{let n=ue(e.id),r=e.ownerKind??n?.ownerKind,i=e.transportIdentity??n?.transportIdentity;return r!==void 0&&t.ownerKinds.includes(r)&&(t.transportIdentities===void 0||i!==void 0&&t.transportIdentities.includes(i))},Y=(e=de())=>{let t=async(t,n)=>{try{return{ok:!0,value:await e.transaction(async e=>{let r=await e.getBlobRef(p(t));return!r||n!==void 0&&r.blobID!==n?!1:(await e.deleteBlobRef(r.id),await q(e),(await e.getAllBlobRefs()).some(e=>e.blobID===r.blobID)||await e.deleteBlob(r.blobID),!0)})}}catch(e){return V(e)}};return{put:async(t,n)=>{try{U(t),H(n);let r=await G(n);return await e.transaction(async e=>{let i=await e.getBlob(t);if(i&&!await K(i,r))throw new B(`blob-id-conflict`);i||await e.putBlob({id:t,value:n,refCount:0,fingerprint:r})}),{ok:!0,value:void 0}}catch(e){return V(e)}},putAndRetain:async(t,n,r)=>{try{U(n),H(r);let i=await G(r);return await e.transaction(async e=>{let a=p(t),o=await e.getBlobRef(a);if(o&&o.blobID!==n)throw new B(`blob-id-conflict`);let s=await e.getBlob(n);if(s&&!await K(s,i))throw new B(`blob-id-conflict`);s||await e.putBlob({id:n,value:r,refCount:0,fingerprint:i}),o||await e.putBlobRef(W(t,n)),await q(e)}),{ok:!0,value:void 0}}catch(e){return V(e)}},read:async t=>{try{let n=await e.transaction(e=>e.getBlob(t));return n?{ok:!0,value:n.value}:{ok:!1,error:{code:`missing-blob`}}}catch(e){return V(e)}},readReference:async t=>{try{return{ok:!0,value:(await e.transaction(e=>e.getBlobRef(p(t))))?.blobID}}catch(e){return V(e)}},retain:async(t,n)=>{try{return U(n),await e.transaction(async e=>{let r=await e.getBlobRef(p(t));if(r&&r.blobID!==n)throw new B(`blob-id-conflict`);if(!await e.getBlob(n))throw new B(`missing-blob`);r||await e.putBlobRef(W(t,n)),await q(e)}),{ok:!0,value:void 0}}catch(e){return V(e)}},release:e=>t(e),releaseIfMatches:(e,n)=>t(e,n),reconcileReferences:async(t,n={ownerKinds:[`session`,`draft`]})=>{try{return{ok:!0,value:await e.transaction(async e=>{let r=[],i=[],a=[],o=new Map((await e.getAllBlobRefs()).map(e=>[e.id,e]));for(let[i,a]of o)J(a,n)&&t.get(i)!==a.blobID&&(await e.deleteBlobRef(i),r.push(i));for(let[r,s]of t){let t=ue(r);if(!t||!n.ownerKinds.includes(t.ownerKind)||n.transportIdentities!==void 0&&!n.transportIdentities.includes(t.transportIdentity)){a.push(r);continue}let c=o.get(r);if(!await e.getBlob(s)){a.push(r);continue}(!c||c.blobID!==s)&&(await e.putBlobRef({id:r,blobID:s,...t}),i.push(r))}return await q(e,!0),{released:r,repaired:i,missing:a}})}}catch(e){return V(e)}},reconcileOwnerReferences:async(t,n)=>{let r=new Map;for(let[e,i]of n)r.set(p({transportIdentity:t.transportIdentity,owner:t.owner,attachmentOccurrenceRefID:e}),i);try{return{ok:!0,value:await e.transaction(async e=>{let n=0,i=new Set;for(let a of await e.getAllBlobRefs())a.transportIdentity===t.transportIdentity&&a.ownerKind===t.owner.kind&&a.ownerID===t.owner.ownerID&&r.get(a.id)!==a.blobID&&(await e.deleteBlobRef(a.id),i.add(a.blobID),n++);await q(e);let a=await e.getAllBlobRefs();for(let t of i)a.some(e=>e.blobID===t)||await e.deleteBlob(t);return n})}}catch(e){return V(e)}},discardUnreferenced:async t=>{try{return{ok:!0,value:await e.transaction(async e=>!await e.getBlob(t)||(await e.getAllBlobRefs()).some(e=>e.blobID===t)?!1:(await e.deleteBlob(t),!0))}}catch(e){return V(e)}}}},de=(e=oe)=>({transaction:async t=>{let n=await X(e),r=n.transaction([ce,le],`readwrite`),i=r.objectStore(ce),a=r.objectStore(le),o=e=>new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error??r.error??Error(`IndexedDB request failed`))}),s=new Promise((e,t)=>{r.oncomplete=()=>e(),r.onabort=()=>t(r.error??new DOMException(`aborted`,`AbortError`)),r.onerror=()=>{console.error(`Input draft IndexedDB transaction error`,r.error)}}),c;try{let e=await t({getBlob:e=>o(i.get(e)),getAllBlobs:()=>o(i.getAll()),putBlob:async e=>{await o(i.put(e))},deleteBlob:async e=>{await o(i.delete(e))},getBlobRef:e=>o(a.get(e)),getAllBlobRefs:()=>o(a.getAll()),putBlobRef:async e=>{await o(a.put(e))},deleteBlobRef:async e=>{await o(a.delete(e))}});return await s,e}catch(e){c=e;try{r.abort()}catch{}try{await s}catch(e){c===void 0&&(c=e)}throw c}finally{n.close()}}}),X=e=>(e===oe?r(oe):Promise.resolve()).then(()=>new Promise((t,n)=>{if(!globalThis.indexedDB){n(new B(`database-unavailable`));return}let r=indexedDB.open(e,se),i=!1,a=()=>{i||(i=!0,n(new B(`database-unavailable`)))};r.onupgradeneeded=()=>{let e=r.result;e.objectStoreNames.contains(ce)||e.createObjectStore(ce,{keyPath:`id`}),e.objectStoreNames.contains(le)||e.createObjectStore(le,{keyPath:`id`})},r.onsuccess=()=>{let e=r.result;if(e.onversionchange=()=>e.close(),i){e.close();return}i=!0,t(e)},r.onerror=a,r.onblocked=a})),fe=()=>({drafts:{},tombstones:{},migration:{complete:!1,claimedTransportIdentity:``,captured:!1,markerCommitted:!1,cleanupComplete:!1},legacy:{entries:{}}}),pe=e=>({version:1,drafts:e.drafts,tombstones:e.tombstones,migration:e.migration,legacy:e.legacy}),me=e=>{let t=pe(e),n=he(JSON.parse(JSON.stringify(t)));return{drafts:n.drafts,tombstones:n.tombstones,migration:n.migration,legacy:n.legacy}},he=e=>{let t=j(e);if(!t)throw Error(`invalid draft snapshot`);return t},ge=e=>e instanceof Map?[...e.entries()]:Object.entries(e??{}),_e=e=>typeof e==`string`?e:a(e),ve=[`session`,`draft`,`surface`],Z=e=>({transportIdentity:e.transportIdentity,owner:{kind:e.owner.kind,ownerID:e.owner.ownerID},attachmentOccurrenceRefID:e.attachmentOccurrenceRefID}),ye=e=>JSON.parse(JSON.stringify(e)),be=e=>e.phase===`metadata`?{phase:`metadata`,error:{code:e.error.code}}:{phase:`blob`,error:{...e.error},...e.reference?{reference:Z(e.reference)}:{}},xe=e=>({status:e.status,keys:[...e.keys],errors:e.errors.map(be),cleanupErrors:e.cleanupErrors.map(be)}),Se=e=>typeof e==`number`&&Number.isSafeInteger(e)&&e>0,Ce=e=>{try{let t=JSON.parse(e);return Array.isArray(t)&&t.length===3&&typeof t[0]==`string`&&ve.includes(t[1])&&typeof t[2]==`string`&&t[0].length>0&&t[2].length>0}catch{return!1}},we=e=>[...e.attachments,...e.syntheticParts.flatMap(e=>e.attachments)].flatMap(t=>t.locator.kind===`blob`?[{reference:{transportIdentity:e.key.transportIdentity,owner:{kind:e.key.owner.kind,ownerID:e.key.owner.ownerID},attachmentOccurrenceRefID:t.attachmentRefID},attachment:ye(t)}]:[]),Te=e=>{let t=new Map;for(let n of Object.values(e))for(let e of we(n))t.set(p(e.reference),e);return t},Q=(e,t)=>({phase:`blob`,error:{...e},...t?{reference:Z(t)}:{}}),$=(e,t=[])=>({status:e,keys:t,errors:[],cleanupErrors:[]}),Ee=e=>e?.attachment.locator.kind===`blob`?e.attachment.locator.blobID:``,De=(e,t,n={})=>{let r=fe(),i=n.enabled??!0,o=0,s=!1,l=Promise.resolve(),u=new Map,d=e=>{let t=l.then(e,e);return l=t.then(()=>void 0,()=>void 0),t.then(e=>e&&typeof e==`object`&&`status`in e&&`keys`in e&&`errors`in e&&`cleanupErrors`in e?xe(e):e)},f=async(t=r.drafts)=>{let n=[],i=new Map([...Te(t)].map(([e,t])=>[e,t.attachment.locator.kind===`blob`?t.attachment.locator.blobID:``]));for(let[t,r]of u){if(i.get(t)===r.expectedBlobID){u.delete(t);continue}let a=await e.releaseIfMatches(Z(r.reference),r.expectedBlobID);a.ok?u.delete(t):n.push(Q(a.error,r.reference))}return n},m=async(t,n,r,i)=>{let a=Z(t),s=await e.releaseIfMatches(a,n);s.ok||(u.set(p(a),{reference:Z(a),expectedBlobID:n,generation:o,reason:i}),r.push(Q(s.error,a)))},h=async(t,n)=>{let r=t.attachment.locator.kind===`blob`?t.attachment.locator.blobID:``,i=Z(t.reference),a=ye(t.attachment),o=await e.readReference(i);if(!o.ok)return{acquired:!1,error:Q(o.error,i)};if(o.value&&o.value!==r)return{acquired:!1,error:Q({code:`reference-conflict`},i)};if(o.value===r){let t=await e.read(r);if(t.ok)return{acquired:!1};if(t.error.code!==`missing-blob`)return{acquired:!1,error:Q(t.error,i)};let o=await n?.(Z(i),ye(a));if(o===void 0)return{acquired:!1,error:Q({code:`runtime-value-missing`},i)};let s=await e.putAndRetain(i,r,o);return s.ok?{acquired:!0}:{acquired:!1,error:Q(s.error,i)}}let s=await e.read(r);if(s.ok){let t=await e.retain(i,r);return t.ok?{acquired:!0}:{acquired:!1,error:Q(t.error,i)}}if(s.error.code!==`missing-blob`)return{acquired:!1,error:Q(s.error,i)};let c=await n?.(Z(i),ye(a));if(c===void 0)return{acquired:!1,error:Q({code:`runtime-value-missing`},i)};let l=await e.putAndRetain(i,r,c);return l.ok?{acquired:!0}:{acquired:!1,error:Q(l.error,i)}};return{seed:t=>d(async()=>{if(!i)return $(`disabled`);if(s)return{...$(`failed`),errors:[Q({code:`invalid-record`})]};let n;try{if(!t)n=fe();else{let e=he(JSON.parse(JSON.stringify(t)));n={drafts:e.drafts,tombstones:e.tombstones,migration:e.migration,legacy:e.legacy}}}catch{return{...$(`failed`),errors:[Q({code:`invalid-record`})]}}let a=Te(n.drafts),o=await e.reconcileReferences(new Map([...a].map(([e,t])=>[e,Ee(t)])),{ownerKinds:ve});return o.ok?(r=n,s=!0,{...$(`committed`),errors:o.value.missing.map(e=>Q({code:`missing-blob`},a.get(e)?.reference))}):{...$(`failed`),errors:[Q(o.error)]}}),commit:e=>{let n=[...ge(e.drafts).map(([e])=>e),...(e.delete??[]).map(_e)];return i?d(async()=>{if(!s)return $(`unseeded`,n);if(!i)return $(`disabled`,n);let l=o,u=[],d=me(r),g=ge(e.drafts),_=ge(e.tombstones),v=(e.delete??[]).map(_e);if(g.some(([e,t])=>!Ce(e)||!Se(t.revision))||_.some(([e,t])=>!Ce(e)||!Se(t))||v.some(e=>!Ce(e))||new Set(g.map(([e])=>e)).size!==g.length||_.some(([e])=>g.some(([t])=>t===e)))return{...$(`failed`,n),errors:[Q({code:`invalid-record`})]};try{for(let[e,t]of g){let n=c(t);if(!n||e!==a(n.key))throw Error(`invalid draft record`);d.drafts[e]=n,delete d.tombstones[e]}for(let e of v)delete d.drafts[e];for(let[e,t]of _)d.tombstones[e]=t;e.migration&&(d.migration=e.migration),e.legacy&&(d.legacy=e.legacy);let t=he(pe(d));d.drafts=t.drafts,d.tombstones=t.tombstones,d.migration=t.migration,d.legacy=t.legacy}catch{return{...$(`failed`,n),errors:[Q({code:`invalid-record`})],cleanupErrors:u}}if(!await e.isCurrent())return $(`stale`,n);let y=Te(r.drafts),b=Te(d.drafts);u=await f(d.drafts);let x=[];for(let[t,r]of b){let i=y.get(t);if((i?.attachment.locator.kind===`blob`?i.attachment.locator.blobID:void 0)===(r.attachment.locator.kind===`blob`?r.attachment.locator.blobID:void 0))continue;let a=await h(r,e.resolveBlobValue);if(a.error){for(let e of x.reverse())await m(e,Ee(b.get(p(e))),u,`acquire-failed`);return{...$(`failed`,n),errors:[a.error],cleanupErrors:u}}a.acquired&&x.push(r.reference)}if(!await e.isCurrent()){for(let e of x.reverse())await m(e,Ee(b.get(p(e))),u,`stale`);return{...$(`stale`,n),cleanupErrors:u}}if(!i||l!==o){for(let e of x.reverse())await m(e,Ee(b.get(p(e))),u,`disabled`);return{...$(`disabled`,n),cleanupErrors:u}}let S=await t.persist(pe(d));if(!S.ok){for(let e of x.reverse())await m(e,Ee(b.get(p(e))),u,`metadata-failed`);return{...$(`failed`,n),errors:[{phase:`metadata`,error:S.error}],cleanupErrors:u}}r=d;for(let[e,t]of y)b.has(e)||await m(t.reference,t.attachment.locator.kind===`blob`?t.attachment.locator.blobID:``,u,`metadata-committed`);return{...$(`committed`,n),cleanupErrors:u}}):Promise.resolve(xe($(`disabled`,n)))},reconcile:()=>d(async()=>{if(!s)return $(`unseeded`);if(!i)return $(`disabled`);let t=await f(),n=new Map([...Te(r.drafts)].map(([e,t])=>[e,t.attachment.locator.kind===`blob`?t.attachment.locator.blobID:``])),a=await e.reconcileReferences(n,{ownerKinds:ve}),o=a.ok?a.value.missing.map(e=>Q({code:`missing-blob`},Te(r.drafts).get(e)?.reference)):[Q(a.error)];return{status:a.ok?`committed`:`failed`,keys:[],errors:o,cleanupErrors:t}}),retryCleanup:()=>d(async()=>({...$(`committed`),cleanupErrors:await f()})),flush:()=>l,setEnabled:async e=>{if(!e){i=!1,o+=1,t.cancelPending?.(),await t.setEnabled?.(!1),await l,await t.flush?.();return}await t.setEnabled?.(!0),i=!0,o+=1}}},Oe=`yuri-composer-reference-draft`,ke=`yuri-pasted-text-draft`,Ae=e=>Array.from(e).length,je=e=>typeof e==`object`&&!!e&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null),Me=(e,t)=>typeof e==`string`&&e.length>0&&e.length<=t,Ne=(e,t)=>{let n=[],r=[],i=0;for(let a=0;a<Math.min(t.length,m.referenceCount);a+=1){let o=t[a];if(!(!je(o)||!Me(o.id,m.idLength)||!Me(o.token,m.displayLength)||typeof o.text!=`string`||o.text.length>m.pastePayloadLength||typeof o.characterCount!=`number`||!Number.isSafeInteger(o.characterCount)||o.characterCount!==Ae(o.text)||typeof o.index!=`number`||!Number.isSafeInteger(o.index)||o.index<1))for(let t=e.indexOf(o.token);t>=0&&n.length<m.referenceCount;t=e.indexOf(o.token,t+o.token.length)){let e=t+o.token.length;if(r.some(n=>n.start<e&&n.end>t)||i+o.text.length>m.totalPastePayloadLength)continue;let a=n.filter(e=>e.id.startsWith(`${o.id}:`)).length;n.push({id:`${o.id}:${a}`,kind:`paste`,start:t,end:e,display:o.token,text:o.text,characterCount:o.characterCount,index:o.index}),r.push({start:t,end:e}),i+=o.text.length}}return n.sort((e,t)=>e.start-t.start)},Pe=e=>{try{let t=JSON.parse(e);if(!je(t)||typeof t.text!=`string`)return{text:e,references:[]};if(t.type===Oe||t.type===`openchamber-composer-reference-draft`)return(t.version===2?o(t.text,t.references):void 0)??{text:t.text,references:[]};if(t.type===ke||t.type===`openchamber-pasted-text-draft`){let e=t.version===1&&Array.isArray(t.references)?Ne(t.text,t.references):[];return o(t.text,e)??{text:t.text,references:[]}}}catch{}return{text:e,references:[]}},Fe=`file://`,Ie=e=>{let t=e.replace(/\\/g,`/`);return/^[A-Za-z]:/.test(t)&&(t=`/${t}`),t.split(`/`).map((e,t)=>t===1&&/^[A-Za-z]:$/.test(e)?e:encodeURIComponent(e)).join(`/`)},Le=e=>{let t=e.replace(/\\/g,`/`).trim();return t.toLowerCase().startsWith(Fe)?t:`${Fe}${Ie(t)}`},Re=(e,t)=>`${e}\u0000${t}`,ze=e=>new Promise((t,n)=>{let r=new FileReader;r.onload=()=>t(r.result),r.onerror=()=>n(r.error??Error(`Failed to read file`)),r.onabort=()=>n(Error(`File read aborted`)),r.readAsDataURL(e)}),Be=e=>{if(!e.startsWith(`data:`))return 0;let t=e.indexOf(`,`);if(t<0)return 0;let n=e.slice(0,t).toLowerCase(),r=e.slice(t+1);if(!n.endsWith(`;base64`))return 0;let i=0;return r.endsWith(`==`)?i=2:r.endsWith(`=`)&&(i=1),Math.max(0,Math.floor(r.length*3/4)-i)},Ve=(e,t)=>e===t?!0:!e||!t?!1:e.filePath===t.filePath&&e.fileName===t.fileName&&e.relativePath===t.relativePath&&e.fileSize===t.fileSize&&e.selection?.startLine===t.selection?.startLine&&e.selection?.endLine===t.selection?.endLine&&e.selection?.text===t.selection?.text,He=e=>({version:1,key:e,revision:1,text:``,attachments:[],syntheticParts:[],mentions:[]}),Ue=(e,t)=>t.flatMap(t=>{let n=`@${t}`,r=[],i=e.indexOf(n);for(;i>=0;)r.push({kind:`file`,value:t,path:t,label:t,range:{start:i,end:i+n.length}}),i=e.indexOf(n,i+n.length);return r}),We=(r={})=>{let o=r.sink??O(),p=r.repository??R(o),m=r.coordinator??z(o),g=r.blobStore??Y(),_=r.durability??De(g,m,{enabled:r.persistenceEnabled??!0}),v=new Map,y=new Map,b=new Map,x=new Map,S=new Map,C=new Set,w=new Set,T,E,D=0,k=0,ee=!1,te=!1,ne,A=new Set,j=new Map,M=new Set;return n()((n,o)=>{let m=e=>v.set(e,(v.get(e)??0)+1),O=(...e)=>{for(let t of e)b.set(t,(b.get(t)??0)+1),x.delete(t)},N=e=>c(e),P=()=>r.runtimeCapture?.()??{transportIdentity:e(),generation:t()},F=e=>{let t=P();return t.transportIdentity===e.transportIdentity&&t.generation===e.generation},I=e=>[...e.attachments,...e.syntheticParts.flatMap(e=>e.attachments)],re=e=>new Set(I(e).map(e=>e.attachmentRefID)),ie=(e,t,n)=>{let r=re(n);return{draftAttachmentViews:{...e.draftAttachmentViews,[t]:Object.fromEntries(Object.entries(e.draftAttachmentViews[t]??{}).filter(([e])=>r.has(e)))},draftMissingAttachmentRefIDs:{...e.draftMissingAttachmentRefIDs,[t]:(e.draftMissingAttachmentRefIDs[t]??[]).filter(e=>r.has(e))}}},L=()=>r.createID?.()??h(),ae=async(e,t)=>{let n=t instanceof File?t:new File([t],e.filename,{type:e.mimeType});return{id:e.attachmentID,file:n,dataUrl:typeof t==`string`?t:await ze(n),mimeType:e.mimeType,filename:e.filename,size:e.size,source:e.source,...e.serverPath?{serverPath:e.serverPath}:{},...e.vscodePath?{vscodePath:e.vscodePath}:{},...e.vscodeSource?{vscodeSource:e.vscodeSource}:{}}},R=e=>{let t=e.errors[0]??e.cleanupErrors[0];return t?.phase===`metadata`||t?.phase===`blob`&&[`blob-id-conflict`,`database-unavailable`,`invalid-value`,`missing-blob`,`quota-exceeded`,`transaction-aborted`,`transaction-failed`].includes(t.error.code)?t.error.code:`unavailable`},z=(e,t)=>{let r=o(),i=D,a=t??P(),s=[...new Set(e)];if(s.forEach(e=>w.delete(e)),T&&w.size===0&&(clearTimeout(T),T=void 0,E=void 0),!r.persistenceEnabled)return s.forEach(e=>A.add(e)),Promise.resolve({status:`disabled`,keys:s,errors:[],cleanupErrors:[]});let c=new Map(s.map(e=>[e,v.get(e)??0])),l=new Map(s.map(e=>[e,r.drafts[e]?.revision??r.tombstones[e]??0])),u=s.filter(e=>r.drafts[e]),d=Object.fromEntries(u.map(e=>[e,r.draftPersistence[e]?.status===`error`?r.draftPersistence[e]:{status:`saving`,revision:l.get(e)}])),f=Object.fromEntries(u.map(e=>[e,r.draftAttachmentPersistence[e]?.status===`error`?r.draftAttachmentPersistence[e]:{status:`saving`,revision:l.get(e)}]));n(e=>({draftPersistence:{...e.draftPersistence,...d},draftAttachmentPersistence:{...e.draftAttachmentPersistence,...f}})),te||s.forEach(e=>A.add(e));let p=(async()=>{let e=o(),t=await _.commit({drafts:Object.fromEntries(s.flatMap(t=>e.drafts[t]?[[t,e.drafts[t]]]:[])),tombstones:Object.fromEntries(s.flatMap(t=>e.tombstones[t]?[[t,e.tombstones[t]]]:[])),delete:s.filter(t=>!e.drafts[t]),migration:e.migration,legacy:{...e.legacyNewDraft?{new:e.legacyNewDraft}:{},entries:e.legacyDraftEntries},resolveBlobValue:t=>{for(let[n,r]of Object.entries(e.drafts))if(r.key.transportIdentity===t.transportIdentity&&r.key.owner.kind===t.owner.kind&&r.key.owner.ownerID===t.owner.ownerID)return e.draftAttachmentViews[n]?.[t.attachmentOccurrenceRefID]?.file},isCurrent:()=>D===i&&o().persistenceEnabled&&F(a)&&s.every(e=>(v.get(e)??0)===c.get(e)&&(o().drafts[e]?.revision??o().tombstones[e]??0)===l.get(e))}),r=D===i&&o().persistenceEnabled&&F(a);return(!r||t.status===`unseeded`||t.status===`stale`||t.status===`disabled`)&&s.forEach(e=>A.add(e)),r&&n(e=>{let n={...e.draftPersistence};for(let e of u){if((v.get(e)??0)!==c.get(e))continue;let r=l.get(e);if(t.status===`committed`)n[e]={status:`saved`,revision:r};else if(t.status===`unseeded`||t.status===`stale`||t.status===`disabled`)continue;else n[e]={status:`error`,revision:r,errorCode:R(t)}}let r={...e.draftAttachmentPersistence};for(let e of u){if((v.get(e)??0)!==c.get(e))continue;let n=l.get(e);r[e]=t.status===`committed`&&t.cleanupErrors.length===0?{status:`saved`,revision:n}:t.status===`failed`||t.cleanupErrors.length>0?{status:`error`,revision:n,errorCode:R(t)}:r[e]??{status:`idle`,revision:n}}return{draftPersistence:n,draftAttachmentPersistence:r}}),t})();return C.add(p),p.then(()=>C.delete(p),()=>C.delete(p)),p},oe=e=>{let t=o(),r=Object.fromEntries(e.flatMap(e=>{let n=t.drafts[e];return n?[[e,{status:`saving`,revision:n.revision}]]:[]}));Object.keys(r).length&&n(e=>({draftPersistence:{...e.draftPersistence,...r}}))},se=()=>{T&&clearTimeout(T),T=void 0;let e=[...w];w.clear();let t=E;return E=void 0,e.length?z(e,t).then(()=>void 0):Promise.resolve()},ce=e=>{if(!o().persistenceEnabled){A.add(e);return}w.add(e),oe([e]),!T&&(E=P(),T=setTimeout(()=>{se()},40))},le=e=>{let t=[...e];return t.forEach(e=>w.delete(e)),T&&w.size===0&&(clearTimeout(T),T=void 0,E=void 0),z(t)},B=(e,t,r,i=`immediate`)=>{let s=a(e),c=o().drafts[s];if(!c||r!==void 0&&c.revision!==r)return;let l=N(t(c));if(!(!l||a(l.key)!==s))return m(s),n(e=>({drafts:{...e.drafts,[s]:l},...ie(e,s,l)})),i===`deferred`?ce(s):le([s]),l},V=e=>e?l(e):void 0,H=(e=[])=>JSON.parse(JSON.stringify(e)),U=(e,t,n,r=!1,i=!1)=>({status:e,...V(n)?{record:V(n)}:{},errors:H(t?.errors),cleanupErrors:H(t?.cleanupErrors),current:r,durable:i}),W=(e,t,n,r,i=!1,a=!1)=>({status:e,errors:H(t?.errors),cleanupErrors:H(t?.cleanupErrors),current:i,durable:a,source:V(n),destination:V(r)}),G=e=>e.status,K=e=>typeof e==`number`&&Number.isSafeInteger(e)&&e>0,q=(e,...t)=>{let n={...e};for(let e of t)delete n[e];return n},ue=async(e,t)=>{let n={},r=o().draftAttachmentViews[a(e.key)]??{};for(let i of I(e)){let e;if(i.locator.kind===`url`){let n=t?.get(i.attachmentRefID);e=n===void 0?i.locator.url:n}else e=t?.get(i.attachmentRefID)??r[i.attachmentRefID]?.file??(typeof r[i.attachmentRefID]?.dataUrl==`string`&&u(r[i.attachmentRefID].dataUrl)?r[i.attachmentRefID].dataUrl:void 0);if(i.locator.kind===`url`&&e!==void 0&&(e!==i.locator.url||!u(e))||i.locator.kind===`blob`&&e!==void 0&&!(e instanceof Blob)&&!(typeof e==`string`&&u(e)))return;e!==void 0&&(n[i.attachmentRefID]=await ae(i,e))}return n},J=e=>e?a(e):`legacy-unowned`,Y=e=>j.get(e)??0,de=e=>{j.set(e,Y(e)+1)},X=(e,t,r=!1)=>{r&&de(e),n(n=>{let r=t(n.attachmentBuckets[e]??[]);return{attachmentBuckets:{...n.attachmentBuckets,[e]:r},...J(n.activeAttachmentDraft)===e?{attachedFiles:r}:{}}})};return{drafts:{},tombstones:{},draftHydration:{},draftPersistence:{},draftAttachmentViews:{},draftMissingAttachmentRefIDs:{},draftAttachmentPersistence:{},persistenceEnabled:r.persistenceEnabled??!0,legacyDraftEntries:{},migration:{complete:!1,claimedTransportIdentity:``},captureDraftRuntime:()=>P(),commitDraftSnapshot:async e=>{let t=a(e.key),r=e.runtime;if(r.transportIdentity!==e.key.transportIdentity||!F(r))return U(`stale`,void 0);let i=o(),s=i.drafts[t],c=i.tombstones[t]??0;if(e.expectedRevision!==`absent`&&!K(e.expectedRevision)||!Number.isSafeInteger(c)||c<0)return U(`failed`,void 0);if(e.expectedRevision===`absent`?s:s?.revision!==e.expectedRevision)return U(`conflict`,void 0,s);let u=e.expectedRevision===`absent`?c+1:e.expectedRevision+1;if(!K(u))return U(`failed`,void 0);let d=N({version:1,key:e.key,revision:u,...e.snapshot});if(!d)return U(`failed`,void 0);let f=await ue(d,e.values);if(!f)return U(`failed`,void 0);let p=v.get(t)??0,h=s?.revision??c,g=await _.commit({drafts:{[t]:d},isCurrent:()=>F(r)&&(v.get(t)??0)===p&&(o().drafts[t]?.revision??o().tombstones[t]??0)===h,resolveBlobValue:t=>e.values?.get(t.attachmentOccurrenceRefID)});if(g.status!==`committed`)return U(G(g),g,s);let y=(v.get(t)??0)===p&&(o().drafts[t]?.revision??o().tombstones[t]??0)===h,b=F(r);if(!y)return b||n(e=>({draftAttachmentViews:q(e.draftAttachmentViews,t),draftMissingAttachmentRefIDs:q(e.draftMissingAttachmentRefIDs,t),draftHydration:q(e.draftHydration,t),draftPersistence:q(e.draftPersistence,t),draftAttachmentPersistence:q(e.draftAttachmentPersistence,t)})),U(`stale`,g,d,!1,!0);let x=l(d);return x?(m(t),O(t),n(e=>({drafts:{...e.drafts,[t]:x},tombstones:(()=>{let n={...e.tombstones};return delete n[t],n})(),draftAttachmentViews:b?{...e.draftAttachmentViews,[t]:f}:q(e.draftAttachmentViews,t),draftMissingAttachmentRefIDs:b?{...e.draftMissingAttachmentRefIDs,[t]:[]}:q(e.draftMissingAttachmentRefIDs,t),draftHydration:b?e.draftHydration:q(e.draftHydration,t),draftPersistence:b?{...e.draftPersistence,[t]:{status:`saved`,revision:x.revision}}:q(e.draftPersistence,t),draftAttachmentPersistence:b?{...e.draftAttachmentPersistence,[t]:g.cleanupErrors.length?{status:`error`,revision:x.revision,errorCode:R(g)}:{status:`saved`,revision:x.revision}}:q(e.draftAttachmentPersistence,t)})),U(b?`committed`:`stale`,g,x,b,!0)):U(`failed`,g)},deleteDraftSnapshot:async e=>{let t=a(e.key),r=e.runtime;if(r.transportIdentity!==e.key.transportIdentity||!F(r))return U(`stale`,void 0);let i=o(),s=i.drafts[t],c=i.tombstones[t]??0;if(!K(e.expectedRevision)||!Number.isSafeInteger(c)||c<0)return U(`failed`,void 0);if(!s||s.revision!==e.expectedRevision)return U(`conflict`,void 0);let l=e.expectedRevision+1;if(!K(l))return U(`failed`,void 0);let u=v.get(t)??0,d=s.revision,f=Math.max(c,l),p=await _.commit({tombstones:{[t]:f},delete:[t],isCurrent:()=>F(r)&&(v.get(t)??0)===u&&o().drafts[t]?.revision===d&&(o().tombstones[t]??0)===c});if(p.status!==`committed`)return U(G(p),p);let h=(v.get(t)??0)===u&&o().drafts[t]?.revision===d&&(o().tombstones[t]??0)===c,g=F(r);return h?(m(t),O(t),n(e=>{let n={...e.drafts};return delete n[t],{drafts:n,tombstones:{...e.tombstones,[t]:Math.max(e.tombstones[t]??0,f)},draftAttachmentViews:q(e.draftAttachmentViews,t),draftMissingAttachmentRefIDs:q(e.draftMissingAttachmentRefIDs,t),draftHydration:q(e.draftHydration,t),draftPersistence:q(e.draftPersistence,t),draftAttachmentPersistence:q(e.draftAttachmentPersistence,t)}}),U(g?`committed`:`stale`,p,void 0,g,!0)):(g||n(e=>({draftAttachmentViews:q(e.draftAttachmentViews,t),draftMissingAttachmentRefIDs:q(e.draftMissingAttachmentRefIDs,t),draftHydration:q(e.draftHydration,t),draftPersistence:q(e.draftPersistence,t),draftAttachmentPersistence:q(e.draftAttachmentPersistence,t)})),U(`stale`,p,void 0,!1,!0))},finalizeDraftOwnership:async e=>{let t=a(e.source),r=a(e.destination),i=e.runtime,s=o(),c=s.drafts[t],u=s.drafts[r];if(t===r||e.destination.owner.kind!==`session`||e.source.transportIdentity!==i.transportIdentity||e.destination.transportIdentity!==i.transportIdentity||!F(i))return W(`stale`,void 0,c,u);if(!K(e.expectedSourceRevision))return W(`failed`,void 0,c,u);if(!c||c.revision!==e.expectedSourceRevision||u)return W(`conflict`,void 0,c,u);let d=v.get(t)??0,f=v.get(r)??0,p=s.tombstones[t]??0,h=s.tombstones[r]??0;if(!Number.isSafeInteger(p)||p<0||!Number.isSafeInteger(h)||h<0)return W(`failed`,void 0,c,u);let g=Math.max(c.revision+1,h+1);if(!K(g))return W(`failed`,void 0,c,u);let y=N(e.disposition===`preserve`?{...c,key:e.destination,revision:g}:{...He(e.destination),revision:g});if(!y)return W(`failed`,void 0,c,u);let b=await _.commit({drafts:{[r]:y},tombstones:{[t]:Math.max(p,g)},delete:[t],isCurrent:()=>F(i)&&(v.get(t)??0)===d&&(v.get(r)??0)===f&&o().drafts[t]?.revision===c.revision&&!o().drafts[r]&&(o().tombstones[t]??0)===p&&(o().tombstones[r]??0)===h,resolveBlobValue:e=>s.draftAttachmentViews[t]?.[e.attachmentOccurrenceRefID]?.file});if(b.status!==`committed`)return W(G(b),b,c,u);let x=(v.get(t)??0)===d&&o().drafts[t]?.revision===c.revision&&(o().tombstones[t]??0)===p,S=(v.get(r)??0)===f&&!o().drafts[r]&&(o().tombstones[r]??0)===h,C=F(i),w=l(y);if(!w)return W(`failed`,b,c,u);if(C&&!x&&!S)return W(`stale`,b,c,y,!1,!0);x&&(m(t),O(t)),S&&(m(r),O(r)),n(n=>{let i=n.drafts,a=n.tombstones;(x||S)&&(i={...i}),(x||S)&&(a={...a}),x&&(delete i[t],a[t]=Math.max(a[t]??0,g)),S&&(i[r]=w,delete a[r]);let o=n.draftHydration,s=n.draftPersistence,c=n.draftAttachmentViews,l=n.draftMissingAttachmentRefIDs,u=n.draftAttachmentPersistence;return C?(x&&(o=q(o,t),s=q(s,t),c=q(c,t),l=q(l,t),u=q(u,t)),S&&(o=q(o,r),s={...q(s,r),[r]:{status:`saved`,revision:w.revision}},c=q(c,r),l=q(l,r),u={...q(u,r),[r]:b.cleanupErrors.length?{status:`error`,revision:w.revision,errorCode:R(b)}:{status:`saved`,revision:w.revision}},C&&x&&e.disposition===`preserve`&&(c={...c,[r]:n.draftAttachmentViews[t]??{}},l={...l,[r]:n.draftMissingAttachmentRefIDs[t]??[]}))):(o=q(o,t,r),s=q(s,t,r),c=q(c,t,r),l=q(l,t,r),u=q(u,t,r)),{drafts:i,tombstones:a,draftHydration:o,draftPersistence:s,draftAttachmentViews:c,draftMissingAttachmentRefIDs:l,draftAttachmentPersistence:u}});let T=x&&S&&C;return W(T?`committed`:`stale`,b,c,y,T,!0)},flushDraftPersistence:async()=>{for(await se();C.size;)await Promise.all([...C]);await _.flush()},ensureDraft:e=>{let t=a(e),r=o().drafts[t];if(r)return r;let i=N({...He(e),revision:(o().tombstones[t]??0)+1});if(!i)throw Error(`Invalid empty draft`);return m(t),n(e=>({drafts:{...e.drafts,[t]:i}})),le([t]),i},getDraft:e=>o().drafts[a(e)],setDraftText:(e,t)=>{let n=o().getDraft(e)??o().ensureDraft(e);return B(e,e=>({...e,revision:e.revision+1,text:t,mentions:e.mentions.filter(e=>e.range.end<=t.length&&t.slice(e.range.start,e.range.end)===`@${e.value}`),composerReferences:[]}),n.revision,`deferred`)??n},setDraftComposerDocument:(e,t)=>{let n=o().getDraft(e)??o().ensureDraft(e);return o().setDraftComposerState(e,{document:t,mentions:n.mentions})},setDraftComposerState:(e,t)=>{let n=o().getDraft(e)??o().ensureDraft(e);return B(e,e=>({...e,revision:e.revision+1,text:t.document.text,composerReferences:t.document.references,mentions:t.mentions}),n.revision,`deferred`)},replaceDraft:(e,t,n)=>B(e,e=>({version:1,key:e.key,revision:e.revision+1,text:n.text,attachments:n.attachments,syntheticParts:n.syntheticParts,mentions:n.mentions,...n.composerReferences===void 0?{}:{composerReferences:n.composerReferences}}),t),setDraftMentions:(e,t)=>B(e,e=>({...e,revision:e.revision+1,mentions:t})),addDraftMention:(e,t)=>B(e,e=>({...e,revision:e.revision+1,mentions:[...e.mentions,t]})),removeDraftMention:(e,t)=>B(e,e=>({...e,revision:e.revision+1,mentions:e.mentions.filter(e=>e.value!==t)})),setDraftSyntheticParts:(e,t)=>B(e,e=>({...e,revision:e.revision+1,syntheticParts:t})),consumeDraftSyntheticParts:(e,t)=>{let n=o().getDraft(e);if(!n)return null;let r=n.syntheticParts.filter(e=>!t?.(e)),i=n.syntheticParts.filter(e=>t?.(e));return B(e,e=>({...e,revision:e.revision+1,syntheticParts:i}),n.revision)?r:null},setDraftAttachments:(e,t)=>B(e,e=>({...e,revision:e.revision+1,attachments:t})),addDraftLocalAttachment:async(e,t,r={})=>{let c=o().getDraft(e);if(r.partID&&!c?.syntheticParts.some(e=>e.partID===r.partID))return;let l=a(e),u=v.get(l)??0,d=o().tombstones[l]??0,f=P(),p=t instanceof File?t:new File([t],r.filename??`attachment`,{type:t.type}),h;try{h=await ze(p)}catch{let e=o().drafts[l];if(F(f)&&(o().tombstones[l]??0)===d&&(e?a(e.key)===l:(v.get(l)??0)===u)&&(!r.partID||e?.syntheticParts.some(e=>e.partID===r.partID))){let t=e?.revision??o().tombstones[l]??0;n(e=>({draftAttachmentPersistence:{...e.draftAttachmentPersistence,[l]:{status:`error`,revision:t,errorCode:`transaction-failed`}}}))}return}if(!F(f)||(o().tombstones[l]??0)!==d)return;let g=o().drafts[l];if(!g&&(v.get(l)??0)!==u)return;let _=g??o().ensureDraft(e);if(a(_.key)!==l||r.partID&&!_.syntheticParts.some(e=>e.partID===r.partID))return;let y=r.attachmentID??L(),b=r.partID?s(r.partID,y):i(y),x=L(),S={attachmentID:y,attachmentRefID:b,filename:r.filename??(t instanceof File?t.name:`attachment`),mimeType:t.type,size:t.size,locator:{kind:`blob`,blobID:x},source:r.source??`local`,...r.vscodePath?{vscodePath:r.vscodePath}:{},...r.vscodeSource?{vscodeSource:r.vscodeSource}:{}},C=r.partID?{..._,revision:_.revision+1,syntheticParts:_.syntheticParts.map(e=>e.partID===r.partID?{...e,attachments:[...e.attachments,S]}:e)}:{..._,revision:_.revision+1,attachments:[..._.attachments,S]},w=N(C);if(!w)return;m(l);let T={id:y,file:p,dataUrl:h,mimeType:S.mimeType,filename:S.filename,size:S.size,source:S.source,...r.vscodePath?{vscodePath:r.vscodePath}:{},...r.vscodeSource?{vscodeSource:r.vscodeSource}:{}};return n(e=>({drafts:{...e.drafts,[l]:w},draftAttachmentViews:{...e.draftAttachmentViews,[l]:{...e.draftAttachmentViews[l],[b]:T}}})),await z([l]),S},addDraftDurableAttachment:(e,t)=>{let r=o().getDraft(e)??o().ensureDraft(e);if(t.partID&&!r.syntheticParts.some(e=>e.partID===t.partID))return;let c=t.attachmentID??L(),l=t.partID?s(t.partID,c):i(c),u={attachmentID:c,attachmentRefID:l,filename:t.filename,mimeType:t.mimeType,size:t.size,source:t.source,locator:{kind:`url`,url:t.url},...t.serverPath?{serverPath:t.serverPath}:{},...t.vscodePath?{vscodePath:t.vscodePath}:{},...t.vscodeSource?{vscodeSource:t.vscodeSource}:{}},d=t.partID?{...r,revision:r.revision+1,syntheticParts:r.syntheticParts.map(e=>e.partID===t.partID?{...e,attachments:[...e.attachments,u]}:e)}:{...r,revision:r.revision+1,attachments:[...r.attachments,u]},f=N(d);if(!f)return;let p=a(e);m(p);let h={id:c,file:new File([],u.filename,{type:u.mimeType}),dataUrl:t.url,mimeType:u.mimeType,filename:u.filename,size:u.size,source:u.source,...u.serverPath?{serverPath:u.serverPath}:{},...u.vscodePath?{vscodePath:u.vscodePath}:{},...u.vscodeSource?{vscodeSource:u.vscodeSource}:{}};return n(e=>({drafts:{...e.drafts,[p]:f},draftAttachmentViews:{...e.draftAttachmentViews,[p]:{...e.draftAttachmentViews[p],[l]:h}}})),z([p]),u},getDraftAttachmentViews:e=>{let t=a(e),n=o().drafts[t],r=o().draftAttachmentViews[t]??{};return n?I(n).flatMap(e=>r[e.attachmentRefID]?[r[e.attachmentRefID]]:[]):[]},retryDraftAttachmentPersistence:async e=>{let t=a(e);if(!o().persistenceEnabled||!o().drafts[t]&&!o().tombstones[t])return;let r=await _.retryCleanup();r.cleanupErrors.length&&n(e=>({draftAttachmentPersistence:{...e.draftAttachmentPersistence,[t]:{status:`error`,revision:e.drafts[t]?.revision??e.tombstones[t],errorCode:R(r)}}})),await z([t])},hydrateDraftAttachments:async e=>{let t=a(e),r=x.get(t);if(r)return r;let i=o().drafts[t];if(!i)return;let s=(b.get(t)??0)+1;b.set(t,s);let c=P(),l=D,u=(async()=>{n(e=>({draftHydration:{...e.draftHydration,[t]:`loading`}}));let e=()=>{if(b.get(t)!==s)return;let e=o(),r=e.draftAttachmentViews[t],i=e.draftMissingAttachmentRefIDs[t]??[];n(e=>({draftHydration:{...e.draftHydration,[t]:i.length?`degraded`:Object.keys(r??{}).length?`ready`:`idle`}}))},r={},a=[];for(let u of I(i)){let d=u.locator.kind===`url`?{ok:!0,value:u.locator.url}:await g.read(u.locator.blobID);if(!d.ok){if(d.error.code===`missing-blob`)a.push(u.attachmentRefID);else{b.get(t)===s&&D===l&&F(c)&&o().drafts[t]===i?n(e=>({draftHydration:{...e.draftHydration,[t]:`error`}})):e();return}continue}try{r[u.attachmentRefID]=await ae(u,d.value)}catch{b.get(t)===s&&D===l&&F(c)&&o().drafts[t]===i?n(e=>({draftHydration:{...e.draftHydration,[t]:`error`}})):e();return}}let u=o(),d=u.drafts[t],f=b.get(t);if(f===s&&D===l&&F(c)&&d===i)n(e=>({draftAttachmentViews:{...e.draftAttachmentViews,[t]:r},draftMissingAttachmentRefIDs:{...e.draftMissingAttachmentRefIDs,[t]:a},draftHydration:{...e.draftHydration,[t]:a.length?`degraded`:`ready`}}));else if(f===s){let e=u.draftAttachmentViews[t],r=u.draftMissingAttachmentRefIDs[t]??[];n(n=>({draftHydration:{...n.draftHydration,[t]:r.length?`degraded`:Object.keys(e??{}).length?`ready`:`idle`}}))}})();x.set(t,u);try{await u}finally{x.get(t)===u&&x.delete(t)}},removeDraftAttachment:async(e,t)=>{let r=a(e),i=o().drafts[r],s=i&&I(i).find(e=>e.attachmentRefID===t);if(!i||!s)return!1;let c=d(s)?f(i.text,[s.filename],i.mentions,i.composerReferences):void 0,l=N({...i,revision:i.revision+1,...c?.changed?{text:c.text,mentions:c.mentions,...c.composerReferences===void 0?{}:{composerReferences:c.composerReferences}}:{},attachments:i.attachments.filter(e=>e.attachmentRefID!==t),syntheticParts:i.syntheticParts.map(e=>({...e,attachments:e.attachments.filter(e=>e.attachmentRefID!==t)}))});return l?(m(r),n(e=>{let n={...e.draftAttachmentViews[r]};return delete n[t],{drafts:{...e.drafts,[r]:l},draftAttachmentViews:{...e.draftAttachmentViews,[r]:n},draftMissingAttachmentRefIDs:{...e.draftMissingAttachmentRefIDs,[r]:(e.draftMissingAttachmentRefIDs[r]??[]).filter(e=>e!==t)}}}),(await z([r])).status===`committed`):!1},replaceDraftAttachment:async(e,t,r,c)=>{let l=a(e),u=o().drafts[l],d=u&&I(u).find(e=>e.attachmentRefID===t);if(!u||!d)return;let f=P(),p=o().tombstones[l]??0,h=r instanceof File?r:new File([r],c?.filename??`attachment`,{type:r.type}),g;try{g=await ze(h)}catch{let e=o().drafts[l],r=e&&I(e).find(e=>e.attachmentRefID===t);F(f)&&(o().tombstones[l]??0)===p&&e&&r?.attachmentID===d.attachmentID&&r.attachmentRefID===d.attachmentRefID&&a(e.key)===l&&n(t=>({draftAttachmentPersistence:{...t.draftAttachmentPersistence,[l]:{status:`error`,revision:e.revision,errorCode:`transaction-failed`}}}));return}let _=o().drafts[l],v=_&&I(_).find(e=>e.attachmentRefID===t);if(!F(f)||(o().tombstones[l]??0)!==p||!_||v?.attachmentID!==d.attachmentID||v.attachmentRefID!==d.attachmentRefID||a(_.key)!==l)return;let y=_.syntheticParts.find(e=>e.attachments.some(e=>e.attachmentRefID===t)),b=L(),x={attachmentID:b,attachmentRefID:y?s(y.partID,b):i(b),filename:c?.filename??h.name,mimeType:h.type,size:h.size,locator:{kind:`blob`,blobID:L()},source:c?.source??`local`,...c?.vscodePath?{vscodePath:c.vscodePath}:{},...c?.vscodeSource?{vscodeSource:c.vscodeSource}:{}},S=N({..._,revision:_.revision+1,attachments:y?_.attachments:_.attachments.map(e=>e.attachmentRefID===t?x:e),syntheticParts:_.syntheticParts.map(e=>e.partID===y?.partID?{...e,attachments:e.attachments.map(e=>e.attachmentRefID===t?x:e)}:e)});if(!S)return;m(l);let C={id:b,file:h,dataUrl:g,mimeType:x.mimeType,filename:x.filename,size:x.size,source:x.source,...x.vscodePath?{vscodePath:x.vscodePath}:{},...x.vscodeSource?{vscodeSource:x.vscodeSource}:{}};return n(e=>{let n={...e.draftAttachmentViews[l]};return delete n[t],{drafts:{...e.drafts,[l]:S},draftAttachmentViews:{...e.draftAttachmentViews,[l]:{...n,[x.attachmentRefID]:C}},draftMissingAttachmentRefIDs:{...e.draftMissingAttachmentRefIDs,[l]:(e.draftMissingAttachmentRefIDs[l]??[]).filter(e=>e!==t)}}}),(await z([l])).status===`committed`?x:void 0},replaceDraftRootAttachments:async(e,t)=>{let n=a(e),r=P();if(r.transportIdentity!==e.transportIdentity||!F(r))return U(`stale`,void 0);let s=o().drafts[n],c=s?s.revision:`absent`,l=[],d=new Map;for(let e of t){let t=e.id,n=i(t);if(e.source===`server`&&e.dataUrl&&u(e.dataUrl))l.push({attachmentID:t,attachmentRefID:n,filename:e.filename,mimeType:e.mimeType,size:e.size,source:`server`,locator:{kind:`url`,url:e.dataUrl},...e.serverPath?{serverPath:e.serverPath}:{}}),d.set(n,e.dataUrl);else if(e.source===`vscode`&&e.vscodeSource===`file`&&e.dataUrl&&u(e.dataUrl))l.push({attachmentID:t,attachmentRefID:n,filename:e.filename,mimeType:e.mimeType,size:e.size,source:`vscode`,locator:{kind:`url`,url:e.dataUrl},...e.vscodePath?{vscodePath:e.vscodePath}:{},vscodeSource:`file`}),d.set(n,e.dataUrl);else{let r=e.file instanceof File?e.file:new File([e.file],e.filename,{type:e.mimeType}),i=L();l.push({attachmentID:t,attachmentRefID:n,filename:e.filename,mimeType:e.mimeType,size:e.size,source:e.source===`vscode`?`vscode`:`local`,locator:{kind:`blob`,blobID:i},...e.vscodePath?{vscodePath:e.vscodePath}:{},...e.vscodeSource===`selection`?{vscodeSource:`selection`}:{}}),d.set(n,r)}}let f=s?.syntheticParts??[];for(let e of f)for(let t of e.attachments)t.locator.kind===`url`&&!d.has(t.attachmentRefID)&&d.set(t.attachmentRefID,t.locator.url);let p={text:s?.text??``,attachments:l,syntheticParts:f,mentions:s?.mentions??[],...s?.composerReferences===void 0?{}:{composerReferences:s.composerReferences}};return o().commitDraftSnapshot({key:e,expectedRevision:c,snapshot:p,values:d,runtime:r})},restoreDraftRootAttachments:async(e,t)=>{let n=a(e),r=P();if(r.transportIdentity!==e.transportIdentity||!F(r))return U(`stale`,void 0);let s=o().drafts[n],c=s?s.revision:`absent`,l=new Set(t.map(e=>e.id)),d=[],f=new Map;for(let e of t){let t=e.id,n=i(t);if(e.source===`server`&&e.dataUrl&&u(e.dataUrl))d.push({attachmentID:t,attachmentRefID:n,filename:e.filename,mimeType:e.mimeType,size:e.size,source:`server`,locator:{kind:`url`,url:e.dataUrl},...e.serverPath?{serverPath:e.serverPath}:{}}),f.set(n,e.dataUrl);else if(e.source===`vscode`&&e.vscodeSource===`file`&&e.dataUrl&&u(e.dataUrl))d.push({attachmentID:t,attachmentRefID:n,filename:e.filename,mimeType:e.mimeType,size:e.size,source:`vscode`,locator:{kind:`url`,url:e.dataUrl},...e.vscodePath?{vscodePath:e.vscodePath}:{},vscodeSource:`file`}),f.set(n,e.dataUrl);else{let r=e.file instanceof File?e.file:new File([e.file],e.filename,{type:e.mimeType}),i=L();d.push({attachmentID:t,attachmentRefID:n,filename:e.filename,mimeType:e.mimeType,size:e.size,source:e.source===`vscode`?`vscode`:`local`,locator:{kind:`blob`,blobID:i},...e.vscodePath?{vscodePath:e.vscodePath}:{},...e.vscodeSource===`selection`?{vscodeSource:`selection`}:{}}),f.set(n,r)}}let p=o().draftAttachmentViews[n]??{};for(let e of s?.attachments??[])if(!l.has(e.attachmentID))if(d.push(JSON.parse(JSON.stringify(e))),e.locator.kind===`url`)f.set(e.attachmentRefID,e.locator.url);else{let t=p[e.attachmentRefID];t?.file instanceof Blob?f.set(e.attachmentRefID,t.file):typeof t?.dataUrl==`string`&&u(t.dataUrl)&&f.set(e.attachmentRefID,t.dataUrl)}let m=s?.syntheticParts??[];for(let e of m)for(let t of e.attachments)t.locator.kind===`url`&&!f.has(t.attachmentRefID)&&f.set(t.attachmentRefID,t.locator.url);let h={text:s?.text??``,attachments:d,syntheticParts:m,mentions:s?.mentions??[],...s?.composerReferences===void 0?{}:{composerReferences:s.composerReferences}};return o().commitDraftSnapshot({key:e,expectedRevision:c,snapshot:h,values:f,runtime:r})},deleteDraft:(e,t)=>{let r=a(e),i=o().drafts[r];if(!i||t!==void 0&&i.revision!==t)return!1;let s=i.revision+1;return K(s)?(m(r),O(r),n(e=>{let t={...e.drafts};delete t[r];let n={...e.draftHydration},i={...e.draftPersistence},a={...e.draftAttachmentViews},o={...e.draftMissingAttachmentRefIDs},c={...e.draftAttachmentPersistence};return delete n[r],delete i[r],delete a[r],delete o[r],delete c[r],{drafts:t,tombstones:{...e.tombstones,[r]:Math.max(e.tombstones[r]??0,s)},draftHydration:n,draftPersistence:i,draftAttachmentViews:a,draftMissingAttachmentRefIDs:o,draftAttachmentPersistence:c}}),z([r]),!0):!1},moveDraft:(e,t,r)=>{let i=a(e),s=a(t),c=o().drafts[i];if(!c||i===s||r!==void 0&&c.revision!==r||o().drafts[s]||(o().tombstones[s]??0)>=c.revision+1||[...c.attachments,...c.syntheticParts.flatMap(e=>e.attachments)].some(e=>e.locator.kind===`blob`))return;let l=N({...c,key:t,revision:c.revision+1});if(l)return m(i),m(s),O(i,s),n(e=>{let t={...e.drafts};delete t[i];let n={...e.tombstones,[i]:Math.max(e.tombstones[i]??0,l.revision)};(n[s]??0)<l.revision&&delete n[s];let r=e=>{let t={...e},n=t[i];return delete t[i],delete t[s],n===void 0?t:{...t,[s]:n}};return{drafts:{...t,[s]:l},tombstones:n,draftHydration:r(e.draftHydration),draftPersistence:r(e.draftPersistence),draftAttachmentViews:r(e.draftAttachmentViews),draftMissingAttachmentRefIDs:r(e.draftMissingAttachmentRefIDs),draftAttachmentPersistence:r(e.draftAttachmentPersistence)}}),z([i,s]),l},moveDraftWithAttachments:async(e,t,r)=>{let i=a(e),s=a(t),c=o().drafts[i];if(!c||i===s||r!==void 0&&c.revision!==r||o().drafts[s]||(o().tombstones[s]??0)>=c.revision+1)return;let l=N({...c,key:t,revision:c.revision+1});if(l)return m(i),m(s),O(i,s),n(e=>{let t={...e.drafts};delete t[i];let n={...e.tombstones,[i]:Math.max(e.tombstones[i]??0,l.revision)};(n[s]??0)<l.revision&&delete n[s];let r=e=>{let t={...e},n=t[i];return delete t[i],delete t[s],n===void 0?t:{...t,[s]:n}};return{drafts:{...t,[s]:l},tombstones:n,draftHydration:r(e.draftHydration),draftPersistence:r(e.draftPersistence),draftAttachmentViews:r(e.draftAttachmentViews),draftMissingAttachmentRefIDs:r(e.draftMissingAttachmentRefIDs),draftAttachmentPersistence:r(e.draftAttachmentPersistence)}}),(await z([i,s])).status===`committed`?l:void 0},setDraftPersistenceEnabled:async e=>{if(D+=1,!e){T&&clearTimeout(T),T=void 0,w.clear(),E=void 0,n({persistenceEnabled:!1,draftPersistence:{}}),await _.setEnabled(!1),await _.flush();return}n({persistenceEnabled:!0}),await _.setEnabled(!0);let t=P();te||await o().hydrateDraftMetadata(t.transportIdentity);let r=new Set([...Object.keys(o().drafts),...Object.keys(o().tombstones),...A]);A.clear(),await z(r),await _.flush()},hydrateDraftMetadata:e=>{let t=S.get(e);if(t)return t;let r=(async()=>{let t=(y.get(e)??0)+1;y.set(e,t);let r=P();if(r.transportIdentity!==e)return!1;let i=D,s=new Map(v),c=k,l=Object.entries(o().drafts).filter(([,t])=>t.key.transportIdentity===e).map(([e])=>e);n(e=>({draftHydration:{...e.draftHydration,...Object.fromEntries(l.map(e=>[e,`loading`]))}}));let u=o().persistenceEnabled,d;try{d=await p.migrate(e,{persistenceEnabled:u})}catch{return!1}if(y.get(e)!==t||D!==i||!F(r))return!1;if(!d.ok)return n(e=>({draftHydration:{...e.draftHydration,...Object.fromEntries(l.map(t=>[t,e.drafts[t]?`degraded`:`error`]))}})),!1;let f=d.value;if(!te){ne??=_.seed(f).finally(()=>{ne=void 0});let a;try{a=await ne}catch{return!1}if(y.get(e)!==t||D!==i||!F(r))return!1;if(a.status!==`committed`&&a.status!==`disabled`)return n(e=>({draftHydration:{...e.draftHydration,...Object.fromEntries(l.map(e=>[e,`degraded`]))}})),!1;a.status===`committed`&&(te=!0)}let m=o(),h={...m.drafts},g={...m.tombstones},b=new Set;for(let[e,t]of Object.entries(f.tombstones))(v.get(e)??0)===(s.get(e)??0)&&(t>=(g[e]??0)&&(g[e]=t,(h[e]?.revision??0)<=t&&delete h[e]),b.add(e));for(let[t,n]of Object.entries(f.drafts)){if(n.key.transportIdentity!==e||(v.get(t)??0)!==(s.get(t)??0))continue;let r=h[t],i=N(n);i&&(!r||r.revision<i.revision)&&(g[t]??0)<i.revision&&(h[t]=i),b.add(t)}let x=k===c?{...f.legacy.entries}:{...m.legacyDraftEntries};if(f.migration.claimedTransportIdentity===e&&k===c)for(let[t,n]of Object.entries(x)){let r={transportIdentity:e,owner:{kind:`session`,ownerID:t}},i=a(r),o=Pe(n.text),c=N({...He(r),text:o.text,composerReferences:o.references,mentions:Ue(o.text,n.mentions)});c&&!h[i]&&!g[i]&&(v.get(i)??0)===(s.get(i)??0)&&(h[i]=c),delete x[t],b.add(i)}n(e=>({drafts:h,tombstones:g,legacyNewDraft:k===c&&!ee?f.legacy.new:e.legacyNewDraft,legacyDraftEntries:x,migration:k===c?f.migration:e.migration,draftHydration:{...e.draftHydration,...Object.fromEntries([...b].map(e=>[e,`ready`]))}}));let S=[...A];for(let e of S)b.add(e);A.clear();try{await z(b),await _.flush()}catch{return!1}return y.get(e)===t&&D===i&&F(r)})();return S.set(e,r),r.finally(()=>{S.get(e)===r&&S.delete(e)}).catch(()=>void 0),r},claimLegacyNewDraft:async e=>{let t=o().legacyNewDraft;if(!t)return o().getDraft(e);let r=a(e),i=o().drafts[r];if(k+=1,ee=!0,i||o().tombstones[r])return n({legacyNewDraft:void 0}),z([r]),i;let s=Pe(t.text),c=N({...He(e),text:s.text,composerReferences:s.references,mentions:Ue(s.text,t.mentions)});if(c)return m(r),n(e=>({drafts:{...e.drafts,[r]:c},legacyNewDraft:void 0})),z([r]),c},pendingInputText:null,pendingInputMode:`replace`,pendingSyntheticParts:null,pendingPresetSubmit:null,attachedFiles:[],attachmentBuckets:{"legacy-unowned":[]},activeAttachmentDraft:null,activeEditorFile:null,setPendingInputText:(e,t=`replace`)=>n({pendingInputText:e,pendingInputMode:t}),consumePendingInputText:()=>{let{pendingInputText:e,pendingInputMode:t}=o();return e===null?null:(n({pendingInputText:null,pendingInputMode:`replace`}),{text:e,mode:t})},requestPresetSubmit:e=>n({pendingPresetSubmit:e}),consumePendingPresetSubmit:()=>{let{pendingPresetSubmit:e}=o();return e===null?null:(n({pendingPresetSubmit:null}),e)},setPendingSyntheticParts:e=>n({pendingSyntheticParts:e}),consumePendingSyntheticParts:()=>{let{pendingSyntheticParts:e}=o();return e!==null&&n({pendingSyntheticParts:null}),e},setActiveAttachmentDraft:e=>{let t=J(e);n(n=>({activeAttachmentDraft:e,attachedFiles:n.attachmentBuckets[t]??[],attachmentBuckets:n.attachmentBuckets[t]?n.attachmentBuckets:{...n.attachmentBuckets,[t]:[]}}))},addAttachedFile:async e=>{let t=o().activeAttachmentDraft;if(t){let n=J(t),r=Y(n),i=await o().addDraftLocalAttachment(t,e);r!==Y(n)&&i&&o().removeDraftAttachment(t,i.attachmentRefID);return}let n=`${Date.now()}-${Math.random().toString(36).slice(2)}`,r=J(null),i=Y(r),a;try{a=await ze(e)}catch{return}if(i!==Y(r))return;let s={id:n,file:e,dataUrl:a,mimeType:e.type,filename:e.name,size:e.size,source:`local`};X(r,e=>[...e,s])},removeAttachedFile:e=>{let t=o().activeAttachmentDraft;if(t){let n=o().getDraft(t),r=n?[...n.attachments,...n.syntheticParts.flatMap(e=>e.attachments)].find(t=>t.attachmentID===e):void 0;r&&o().removeDraftAttachment(t,r.attachmentRefID);return}X(J(null),t=>t.filter(t=>t.id!==e))},setAttachedFiles:e=>{X(J(o().activeAttachmentDraft),()=>e,!0)},clearAttachedFiles:()=>{let e=o().activeAttachmentDraft;if(e){de(J(e)),o().getDraft(e)||o().ensureDraft(e),o().setDraftAttachments(e,[]);return}X(J(null),()=>[],!0)},addDraftVSCodeFileAttachment:(e,t,n,r)=>{if(o().getDraftAttachmentViews(e).some(e=>e.source===`vscode`&&e.vscodeSource===`file`&&(e.vscodePath||``)===t)||(o().getDraft(e)?.attachments.some(e=>e.source===`vscode`&&e.vscodeSource===`file`&&(e.vscodePath||``)===t)??!1))return;let i=Le(t);o().addDraftDurableAttachment(e,{filename:n,mimeType:`text/plain`,size:r||0,source:`vscode`,vscodePath:t,vscodeSource:`file`,url:i})},addDraftVSCodeSelectionAttachment:async(e,t,n)=>{let r=a(e),i=Y(r),s=`${r}\u0000${Re(t,n.name)}`;if(!(o().getDraftAttachmentViews(e).some(e=>e.source===`vscode`&&e.vscodeSource===`selection`&&e.filename===n.name&&e.vscodePath===t)||(o().getDraft(e)?.attachments.some(e=>e.source===`vscode`&&e.vscodeSource===`selection`&&e.filename===n.name&&e.vscodePath===t)??!1)||M.has(s))){M.add(s);try{let a=await o().addDraftLocalAttachment(e,n,{source:`vscode`,vscodePath:t,vscodeSource:`selection`});i!==Y(r)&&a&&o().removeDraftAttachment(e,a.attachmentRefID)}finally{M.delete(s)}}},addVSCodeFileAttachment:(e,t,n)=>{let r=o().activeAttachmentDraft;if(r){o().addDraftVSCodeFileAttachment(r,e,t,n);return}let i=`${Date.now()}-${Math.random().toString(36).slice(2)}`,a=J(null);if((o().attachmentBuckets[a]??[]).some(t=>t.source===`vscode`&&t.vscodeSource===`file`&&(t.vscodePath||``)===e))return;let s=Le(e),c={id:i,file:new File([],t,{type:`text/plain`}),dataUrl:s,mimeType:`text/plain`,filename:t,size:n||0,source:`vscode`,vscodePath:e,vscodeSource:`file`};X(a,e=>[...e,c])},addVSCodeSelectionAttachment:async(e,t)=>{let n=o().activeAttachmentDraft;if(n){await o().addDraftVSCodeSelectionAttachment(n,e,t);return}let r=`${Date.now()}-${Math.random().toString(36).slice(2)}`,i=J(null),a=Y(i),s=`${i}\u0000${Re(e,t.name)}`;if((o().attachmentBuckets[i]??[]).some(n=>n.source===`vscode`&&n.vscodeSource===`selection`&&n.filename===t.name&&n.vscodePath===e)||M.has(s))return;M.add(s);let c;try{c=await ze(t)}catch{return}finally{M.delete(s)}if(a!==Y(i))return;let l={id:r,file:t,dataUrl:c,mimeType:t.type,filename:t.name,size:t.size,source:`vscode`,vscodePath:e,vscodeSource:`selection`};X(i,e=>[...e,l])},addCodeSelectionAttachment:async(e,t,n)=>{let r=new File([n],t,{type:`text/plain`});await o().addVSCodeSelectionAttachment(e,r)},setActiveEditorFile:e=>{Ve(o().activeEditorFile,e)||n({activeEditorFile:e})},addRestoredAttachment:({url:e,mimeType:t,filename:n})=>{let r=o().activeAttachmentDraft;if(r){if(e.startsWith(`data:`)){let i=a(r);(async()=>{try{let s=await(await fetch(e)).blob(),c=new File([s],n,{type:t||s.type||`application/octet-stream`}),l=o().activeAttachmentDraft;if(!l||a(l)!==i)return;await o().addDraftLocalAttachment(r,c)}catch{}})();return}if(!u(e))return;o().addDraftDurableAttachment(r,{filename:n,mimeType:t,size:Be(e),source:`local`,serverPath:e,url:e});return}let i={id:`restored-${Date.now()}-${Math.random().toString(36).slice(2)}`,file:new File([],n,{type:t}),dataUrl:e,mimeType:t,filename:n,size:Be(e),source:`local`,serverPath:e};X(J(null),e=>[...e,i])}}})},Ge=We();export{O as a,Y as i,Ge as n,de as r,We as t};
1
+ import{i as e,n as t}from"./runtime-switch-DEPKHgdL.js";import{a as n}from"./vendor-zustand-CNn3HHhT.js";import{t as r}from"./brand-storage-migration-Bhz6UOBJ.js";import"./brand-storage-bootstrap-D4BW3w-M.js";import{D as i,E as a,F as o,O as s,R as c,S as l,k as u,o as d,s as f,w as p,x as m}from"./prompt-attachment-upload-Bem87nmm.js";import{t as h}from"./uuid-D-SDZijH.js";var g=`yuri_input_draft_metadata_v1`,_=`yuri_input_draft_metadata_migration_v1`,v=`yuri_chat_input_draft_`,y=`yuri_chat_confirmed_mentions_`,b=()=>({ok:!1,error:{code:`unavailable`}}),x=()=>({ok:!1,error:{code:`cancelled`}}),S=e=>({ok:!1,error:{code:e instanceof DOMException&&e.name===`QuotaExceededError`?`quota`:`unavailable`}}),C=e=>typeof e==`object`&&!!e&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null),w=(e,t)=>Object.keys(e).every(e=>t.includes(e)),T=e=>typeof e==`number`&&Number.isSafeInteger(e)&&e>0,E=e=>typeof e==`string`&&e.length>0,D=e=>({read:async t=>{if(!e)return b();try{return{ok:!0,value:e.getItem(t)}}catch(e){return S(e)}},write:async(t,n)=>{if(!e)return b();try{return e.setItem(t,n),{ok:!0,value:void 0}}catch(e){return S(e)}},remove:async t=>{if(!e)return b();try{return e.removeItem(t),{ok:!0,value:void 0}}catch(e){return S(e)}},keys:async()=>{if(!e)return b();try{let t=[];for(let n=0;n<e.length;n+=1){let r=e.key(n);r!==null&&t.push(r)}return{ok:!0,value:t}}catch(e){return S(e)}}}),O=()=>{try{return D(typeof window>`u`?null:window.localStorage)}catch{return D(null)}},k=(e,t,n,r)=>{let i=[];try{let e=n===null?[]:JSON.parse(n);Array.isArray(e)&&(i=e.filter(e=>typeof e==`string`))}catch{}return{suffix:e,text:t??``,mentions:i,keys:r}},ee=async e=>{let t=await e.keys();if(!t.ok)return t;let n=new Set;for(let e of t.value)e.startsWith(v)&&n.add(e.slice(22)),e.startsWith(y)&&n.add(e.slice(29));let r=[];for(let i of n){let n=`${v}${i}`,a=`${y}${i}`,[o,s]=await Promise.all([e.read(n),e.read(a)]);if(!o.ok)return o;if(!s.ok)return s;r.push(k(i,o.value,s.value,[n,a].filter(e=>t.value.includes(e))))}return{ok:!0,value:r}},te=e=>{if(!(!C(e)||!w(e,[`suffix`,`text`,`mentions`,`keys`])||typeof e.suffix!=`string`||typeof e.text!=`string`||!Array.isArray(e.mentions)||!e.mentions.every(e=>typeof e==`string`)||!Array.isArray(e.keys)||!e.keys.every(e=>typeof e==`string`)))return{suffix:e.suffix,text:e.text,mentions:[...e.mentions],keys:[...e.keys]}},ne=e=>{try{let t=JSON.parse(e);return Array.isArray(t)&&t.length===3&&E(t[0])&&(t[1]===`session`||t[1]===`draft`)&&E(t[2])&&e===JSON.stringify(t)}catch{return!1}},A=e=>{if(!C(e)||!w(e,[`complete`,`claimedTransportIdentity`,`captured`,`markerCommitted`,`cleanupComplete`])||typeof e.complete!=`boolean`||typeof e.claimedTransportIdentity!=`string`||e.captured!==void 0&&typeof e.captured!=`boolean`||e.markerCommitted!==void 0&&typeof e.markerCommitted!=`boolean`||e.cleanupComplete!==void 0&&typeof e.cleanupComplete!=`boolean`)return;let t=e.cleanupComplete??e.complete,n=e.captured??e.complete,r=e.markerCommitted??e.complete;if(!((n||r||t)&&!E(e.claimedTransportIdentity))&&!(r&&!n)&&!(t&&(!n||!r)))return{complete:t,claimedTransportIdentity:e.claimedTransportIdentity,captured:n,markerCommitted:r,cleanupComplete:t}},j=e=>{if(!C(e)||!w(e,[`version`,`drafts`,`tombstones`,`migration`,`legacy`])||e.version!==1||!C(e.drafts)||!C(e.tombstones)||!C(e.legacy)||!w(e.legacy,[`new`,`entries`])||!C(e.legacy.entries))return;let t=A(e.migration);if(!t)return;let n={};for(let[t,r]of Object.entries(e.drafts)){let e=c(r);if(!e||t!==a(e.key))return;n[t]=e}let r={};for(let[t,n]of Object.entries(e.tombstones)){if(!ne(t)||!T(n))return;r[t]=n}let i={};for(let[t,n]of Object.entries(e.legacy.entries)){let e=te(n);if(!e||t!==e.suffix||t===`new`)return;i[t]=e}let o=e.legacy.new===void 0?void 0:te(e.legacy.new);if(!(e.legacy.new!==void 0&&(!o||o.suffix!==`new`)))return{version:1,drafts:n,tombstones:r,migration:t,legacy:{...o?{new:o}:{},entries:i}}},M=(e=``)=>({version:1,drafts:{},tombstones:{},migration:{complete:!1,claimedTransportIdentity:e,captured:!1,markerCommitted:!1,cleanupComplete:!1},legacy:{entries:{}}}),N=e=>{try{return{ok:!0,value:JSON.stringify(e)}}catch{return{ok:!1,error:{code:`serialization`}}}},P=async e=>{let t=await e.read(g);if(!t.ok)return t;if(t.value===null)return{ok:!0,value:null};try{let e=j(JSON.parse(t.value));return e?{ok:!0,value:e}:{ok:!1,error:{code:`corrupt`}}}catch{return{ok:!1,error:{code:`corrupt`}}}},F=async(e,t)=>{let n=j(t);if(!n)return{ok:!1,error:{code:`corrupt`}};let r=N(n);return r.ok?e.write(g,r.value):r},I=e=>C(e)&&w(e,[`version`,`claimedTransportIdentity`])&&e.version===1&&E(e.claimedTransportIdentity)?{version:1,claimedTransportIdentity:e.claimedTransportIdentity}:void 0,re=e=>N({version:1,claimedTransportIdentity:e}),ie=(e,t,n)=>{let r={},i;for(let e of t)e.suffix===`new`?i=e:r[e.suffix]=e;return{...e,migration:{complete:!1,claimedTransportIdentity:n,captured:!0,markerCommitted:!1,cleanupComplete:!1},legacy:{...i?{new:i}:{},entries:r}}},L=e=>[...new Set([e.legacy.new,...Object.values(e.legacy.entries)].flatMap(e=>e?.keys??[]))],ae=new WeakMap,R=e=>{let t=ae.get(e);if(t)return t;let n=Promise.resolve(),r,i=!0,a=e=>{let t=n.then(e,e);return n=t.then(()=>void 0,()=>void 0),t},o={persist:t=>{let n=j(t);return n?i?a(async()=>i?F(e,n):b()):Promise.resolve(b()):Promise.resolve({ok:!1,error:{code:`corrupt`}})},migrate:(t,n={})=>{if(r)return r;let o=a(async()=>{let r=await P(e);if(!r.ok)return r;let a=r.value??M(),o=i&&(n.persistenceEnabled??!0);if(!a.migration.captured){let n=await ee(e);if(!n.ok)return n;if(!o)return{ok:!0,value:ie(a,n.value,``)};if(a=ie(a,n.value,t),!i)return{ok:!0,value:a};let r=await F(e,a);if(!r.ok)return r}if(!i||!(n.persistenceEnabled??!0)){let t=await ee(e);return t.ok?{ok:!0,value:a}:t}let s=await e.read(_);if(!s.ok)return s;if(s.value!==null)try{let t=I(JSON.parse(s.value));if(!t)return{ok:!1,error:{code:`corrupt`}};if(t.claimedTransportIdentity!==a.migration.claimedTransportIdentity){let t=re(a.migration.claimedTransportIdentity);if(!t.ok)return t;if(!i)return{ok:!0,value:a};let n=await e.write(_,t.value);if(!n.ok)return n}}catch{return{ok:!1,error:{code:`corrupt`}}}else{let t=re(a.migration.claimedTransportIdentity);if(!t.ok)return t;if(!i)return{ok:!0,value:a};let n=await e.write(_,t.value);if(!n.ok)return n}if(a.migration.cleanupComplete)return{ok:!0,value:a};for(let t of L(a)){if(!i)return{ok:!0,value:a};let n=await e.remove(t);if(!n.ok)return n}if(a={...a,migration:{complete:!0,claimedTransportIdentity:a.migration.claimedTransportIdentity,captured:!0,markerCommitted:!0,cleanupComplete:!0}},!i)return{ok:!0,value:a};let c=await F(e,a);return c.ok?{ok:!0,value:a}:c}).finally(()=>{r=void 0});return r=o,o},flush:()=>n,setEnabled:async e=>{i=e,i||await n}};return ae.set(e,o),o},z=e=>{let t=R(e),n=!0,r=!1,i=[],a=[],o=()=>{if(r||i.length>0)return;let e=a;a=[],e.forEach(e=>e())},s=()=>{if(r)return;let e=i.shift();if(!e){o();return}r=!0,t.persist(e.snapshot).then(e.resolve).finally(()=>{r=!1,s()})};return{persist:e=>{let t=j(e);return t?n?new Promise(e=>{i.push({snapshot:t,resolve:e}),s()}):Promise.resolve(b()):Promise.resolve({ok:!1,error:{code:`corrupt`}})},cancelPending:()=>{let e=i;i=[],e.forEach(({resolve:e})=>e(x())),o()},flush:()=>r||i.length>0?new Promise(e=>a.push(e)):Promise.resolve(),setEnabled:async e=>{if(n=e,!n){let e=i;i=[],e.forEach(({resolve:e})=>e(x()))}await(r||i.length>0?new Promise(e=>a.push(e)):Promise.resolve()),await t.setEnabled(e),await t.flush()}}},oe=`yuri-input-drafts`,se=1,ce=`blobs`,le=`blobRefs`,B=class extends Error{code;constructor(e){super(e),this.code=e}},V=e=>({ok:!1,error:{code:e instanceof B?e.code:e instanceof DOMException&&e.name===`QuotaExceededError`?`quota-exceeded`:e instanceof DOMException&&e.name===`AbortError`?`transaction-aborted`:`transaction-failed`}}),H=e=>{if(!(e instanceof Blob)&&!u(e))throw new B(`invalid-value`)},U=e=>{if(!e)throw new B(`invalid-value`)},W=(e,t)=>({id:p(e),blobID:t,transportIdentity:e.transportIdentity,ownerKind:e.owner.kind,ownerID:e.owner.ownerID}),G=async e=>{if(typeof e==`string`)return`url:${e}`;let t=await crypto.subtle.digest(`SHA-256`,await e.arrayBuffer()),n=[...new Uint8Array(t)].map(e=>e.toString(16).padStart(2,`0`)).join(``);return`blob:${e.type}:${e.size}:${n}`},K=async(e,t)=>(e.fingerprint??await G(e.value))===t,q=async(e,t=!1)=>{let n=await e.getAllBlobRefs(),r=await e.getAllBlobs(),i=new Map;for(let t of n)await e.getBlob(t.blobID)?i.set(t.blobID,(i.get(t.blobID)??0)+1):await e.deleteBlobRef(t.id);for(let n of r){let r=i.get(n.id)??0;r||!t?await e.putBlob({...n,refCount:r}):await e.deleteBlob(n.id)}},ue=e=>{try{let t=JSON.parse(e);return!Array.isArray(t)||t.length!==4||typeof t[0]!=`string`||typeof t[2]!=`string`||t[1]!==`session`&&t[1]!==`draft`&&t[1]!==`surface`&&t[1]!==`queue`&&t[1]!==`send`?void 0:{transportIdentity:t[0],ownerKind:t[1],ownerID:t[2]}}catch{return}},J=(e,t)=>{let n=ue(e.id),r=e.ownerKind??n?.ownerKind,i=e.transportIdentity??n?.transportIdentity;return r!==void 0&&t.ownerKinds.includes(r)&&(t.transportIdentities===void 0||i!==void 0&&t.transportIdentities.includes(i))},Y=(e=de())=>{let t=async(t,n)=>{try{return{ok:!0,value:await e.transaction(async e=>{let r=await e.getBlobRef(p(t));return!r||n!==void 0&&r.blobID!==n?!1:(await e.deleteBlobRef(r.id),await q(e),(await e.getAllBlobRefs()).some(e=>e.blobID===r.blobID)||await e.deleteBlob(r.blobID),!0)})}}catch(e){return V(e)}};return{put:async(t,n)=>{try{U(t),H(n);let r=await G(n);return await e.transaction(async e=>{let i=await e.getBlob(t);if(i&&!await K(i,r))throw new B(`blob-id-conflict`);i||await e.putBlob({id:t,value:n,refCount:0,fingerprint:r})}),{ok:!0,value:void 0}}catch(e){return V(e)}},putAndRetain:async(t,n,r)=>{try{U(n),H(r);let i=await G(r);return await e.transaction(async e=>{let a=p(t),o=await e.getBlobRef(a);if(o&&o.blobID!==n)throw new B(`blob-id-conflict`);let s=await e.getBlob(n);if(s&&!await K(s,i))throw new B(`blob-id-conflict`);s||await e.putBlob({id:n,value:r,refCount:0,fingerprint:i}),o||await e.putBlobRef(W(t,n)),await q(e)}),{ok:!0,value:void 0}}catch(e){return V(e)}},read:async t=>{try{let n=await e.transaction(e=>e.getBlob(t));return n?{ok:!0,value:n.value}:{ok:!1,error:{code:`missing-blob`}}}catch(e){return V(e)}},readReference:async t=>{try{return{ok:!0,value:(await e.transaction(e=>e.getBlobRef(p(t))))?.blobID}}catch(e){return V(e)}},retain:async(t,n)=>{try{return U(n),await e.transaction(async e=>{let r=await e.getBlobRef(p(t));if(r&&r.blobID!==n)throw new B(`blob-id-conflict`);if(!await e.getBlob(n))throw new B(`missing-blob`);r||await e.putBlobRef(W(t,n)),await q(e)}),{ok:!0,value:void 0}}catch(e){return V(e)}},release:e=>t(e),releaseIfMatches:(e,n)=>t(e,n),reconcileReferences:async(t,n={ownerKinds:[`session`,`draft`]})=>{try{return{ok:!0,value:await e.transaction(async e=>{let r=[],i=[],a=[],o=new Map((await e.getAllBlobRefs()).map(e=>[e.id,e]));for(let[i,a]of o)J(a,n)&&t.get(i)!==a.blobID&&(await e.deleteBlobRef(i),r.push(i));for(let[r,s]of t){let t=ue(r);if(!t||!n.ownerKinds.includes(t.ownerKind)||n.transportIdentities!==void 0&&!n.transportIdentities.includes(t.transportIdentity)){a.push(r);continue}let c=o.get(r);if(!await e.getBlob(s)){a.push(r);continue}(!c||c.blobID!==s)&&(await e.putBlobRef({id:r,blobID:s,...t}),i.push(r))}return await q(e,!0),{released:r,repaired:i,missing:a}})}}catch(e){return V(e)}},reconcileOwnerReferences:async(t,n)=>{let r=new Map;for(let[e,i]of n)r.set(p({transportIdentity:t.transportIdentity,owner:t.owner,attachmentOccurrenceRefID:e}),i);try{return{ok:!0,value:await e.transaction(async e=>{let n=0,i=new Set;for(let a of await e.getAllBlobRefs())a.transportIdentity===t.transportIdentity&&a.ownerKind===t.owner.kind&&a.ownerID===t.owner.ownerID&&r.get(a.id)!==a.blobID&&(await e.deleteBlobRef(a.id),i.add(a.blobID),n++);await q(e);let a=await e.getAllBlobRefs();for(let t of i)a.some(e=>e.blobID===t)||await e.deleteBlob(t);return n})}}catch(e){return V(e)}},discardUnreferenced:async t=>{try{return{ok:!0,value:await e.transaction(async e=>!await e.getBlob(t)||(await e.getAllBlobRefs()).some(e=>e.blobID===t)?!1:(await e.deleteBlob(t),!0))}}catch(e){return V(e)}}}},de=(e=oe)=>({transaction:async t=>{let n=await X(e),r=n.transaction([ce,le],`readwrite`),i=r.objectStore(ce),a=r.objectStore(le),o=e=>new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error??r.error??Error(`IndexedDB request failed`))}),s=new Promise((e,t)=>{r.oncomplete=()=>e(),r.onabort=()=>t(r.error??new DOMException(`aborted`,`AbortError`)),r.onerror=()=>{console.error(`Input draft IndexedDB transaction error`,r.error)}}),c;try{let e=await t({getBlob:e=>o(i.get(e)),getAllBlobs:()=>o(i.getAll()),putBlob:async e=>{await o(i.put(e))},deleteBlob:async e=>{await o(i.delete(e))},getBlobRef:e=>o(a.get(e)),getAllBlobRefs:()=>o(a.getAll()),putBlobRef:async e=>{await o(a.put(e))},deleteBlobRef:async e=>{await o(a.delete(e))}});return await s,e}catch(e){c=e;try{r.abort()}catch{}try{await s}catch(e){c===void 0&&(c=e)}throw c}finally{n.close()}}}),X=e=>(e===oe?r(oe):Promise.resolve()).then(()=>new Promise((t,n)=>{if(!globalThis.indexedDB){n(new B(`database-unavailable`));return}let r=indexedDB.open(e,se),i=!1,a=()=>{i||(i=!0,n(new B(`database-unavailable`)))};r.onupgradeneeded=()=>{let e=r.result;e.objectStoreNames.contains(ce)||e.createObjectStore(ce,{keyPath:`id`}),e.objectStoreNames.contains(le)||e.createObjectStore(le,{keyPath:`id`})},r.onsuccess=()=>{let e=r.result;if(e.onversionchange=()=>e.close(),i){e.close();return}i=!0,t(e)},r.onerror=a,r.onblocked=a})),fe=()=>({drafts:{},tombstones:{},migration:{complete:!1,claimedTransportIdentity:``,captured:!1,markerCommitted:!1,cleanupComplete:!1},legacy:{entries:{}}}),pe=e=>({version:1,drafts:e.drafts,tombstones:e.tombstones,migration:e.migration,legacy:e.legacy}),me=e=>{let t=pe(e),n=he(JSON.parse(JSON.stringify(t)));return{drafts:n.drafts,tombstones:n.tombstones,migration:n.migration,legacy:n.legacy}},he=e=>{let t=j(e);if(!t)throw Error(`invalid draft snapshot`);return t},ge=e=>e instanceof Map?[...e.entries()]:Object.entries(e??{}),_e=e=>typeof e==`string`?e:a(e),ve=[`session`,`draft`,`surface`],Z=e=>({transportIdentity:e.transportIdentity,owner:{kind:e.owner.kind,ownerID:e.owner.ownerID},attachmentOccurrenceRefID:e.attachmentOccurrenceRefID}),ye=e=>JSON.parse(JSON.stringify(e)),be=e=>e.phase===`metadata`?{phase:`metadata`,error:{code:e.error.code}}:{phase:`blob`,error:{...e.error},...e.reference?{reference:Z(e.reference)}:{}},xe=e=>({status:e.status,keys:[...e.keys],errors:e.errors.map(be),cleanupErrors:e.cleanupErrors.map(be)}),Se=e=>typeof e==`number`&&Number.isSafeInteger(e)&&e>0,Ce=e=>{try{let t=JSON.parse(e);return Array.isArray(t)&&t.length===3&&typeof t[0]==`string`&&ve.includes(t[1])&&typeof t[2]==`string`&&t[0].length>0&&t[2].length>0}catch{return!1}},we=e=>[...e.attachments,...e.syntheticParts.flatMap(e=>e.attachments)].flatMap(t=>t.locator.kind===`blob`?[{reference:{transportIdentity:e.key.transportIdentity,owner:{kind:e.key.owner.kind,ownerID:e.key.owner.ownerID},attachmentOccurrenceRefID:t.attachmentRefID},attachment:ye(t)}]:[]),Te=e=>{let t=new Map;for(let n of Object.values(e))for(let e of we(n))t.set(p(e.reference),e);return t},Q=(e,t)=>({phase:`blob`,error:{...e},...t?{reference:Z(t)}:{}}),$=(e,t=[])=>({status:e,keys:t,errors:[],cleanupErrors:[]}),Ee=e=>e?.attachment.locator.kind===`blob`?e.attachment.locator.blobID:``,De=(e,t,n={})=>{let r=fe(),i=n.enabled??!0,o=0,s=!1,l=Promise.resolve(),u=new Map,d=e=>{let t=l.then(e,e);return l=t.then(()=>void 0,()=>void 0),t.then(e=>e&&typeof e==`object`&&`status`in e&&`keys`in e&&`errors`in e&&`cleanupErrors`in e?xe(e):e)},f=async(t=r.drafts)=>{let n=[],i=new Map([...Te(t)].map(([e,t])=>[e,t.attachment.locator.kind===`blob`?t.attachment.locator.blobID:``]));for(let[t,r]of u){if(i.get(t)===r.expectedBlobID){u.delete(t);continue}let a=await e.releaseIfMatches(Z(r.reference),r.expectedBlobID);a.ok?u.delete(t):n.push(Q(a.error,r.reference))}return n},m=async(t,n,r,i)=>{let a=Z(t),s=await e.releaseIfMatches(a,n);s.ok||(u.set(p(a),{reference:Z(a),expectedBlobID:n,generation:o,reason:i}),r.push(Q(s.error,a)))},h=async(t,n)=>{let r=t.attachment.locator.kind===`blob`?t.attachment.locator.blobID:``,i=Z(t.reference),a=ye(t.attachment),o=await e.readReference(i);if(!o.ok)return{acquired:!1,error:Q(o.error,i)};if(o.value&&o.value!==r)return{acquired:!1,error:Q({code:`reference-conflict`},i)};if(o.value===r){let t=await e.read(r);if(t.ok)return{acquired:!1};if(t.error.code!==`missing-blob`)return{acquired:!1,error:Q(t.error,i)};let o=await n?.(Z(i),ye(a));if(o===void 0)return{acquired:!1,error:Q({code:`runtime-value-missing`},i)};let s=await e.putAndRetain(i,r,o);return s.ok?{acquired:!0}:{acquired:!1,error:Q(s.error,i)}}let s=await e.read(r);if(s.ok){let t=await e.retain(i,r);return t.ok?{acquired:!0}:{acquired:!1,error:Q(t.error,i)}}if(s.error.code!==`missing-blob`)return{acquired:!1,error:Q(s.error,i)};let c=await n?.(Z(i),ye(a));if(c===void 0)return{acquired:!1,error:Q({code:`runtime-value-missing`},i)};let l=await e.putAndRetain(i,r,c);return l.ok?{acquired:!0}:{acquired:!1,error:Q(l.error,i)}};return{seed:t=>d(async()=>{if(!i)return $(`disabled`);if(s)return{...$(`failed`),errors:[Q({code:`invalid-record`})]};let n;try{if(!t)n=fe();else{let e=he(JSON.parse(JSON.stringify(t)));n={drafts:e.drafts,tombstones:e.tombstones,migration:e.migration,legacy:e.legacy}}}catch{return{...$(`failed`),errors:[Q({code:`invalid-record`})]}}let a=Te(n.drafts),o=await e.reconcileReferences(new Map([...a].map(([e,t])=>[e,Ee(t)])),{ownerKinds:ve});return o.ok?(r=n,s=!0,{...$(`committed`),errors:o.value.missing.map(e=>Q({code:`missing-blob`},a.get(e)?.reference))}):{...$(`failed`),errors:[Q(o.error)]}}),commit:e=>{let n=[...ge(e.drafts).map(([e])=>e),...(e.delete??[]).map(_e)];return i?d(async()=>{if(!s)return $(`unseeded`,n);if(!i)return $(`disabled`,n);let l=o,u=[],d=me(r),g=ge(e.drafts),_=ge(e.tombstones),v=(e.delete??[]).map(_e);if(g.some(([e,t])=>!Ce(e)||!Se(t.revision))||_.some(([e,t])=>!Ce(e)||!Se(t))||v.some(e=>!Ce(e))||new Set(g.map(([e])=>e)).size!==g.length||_.some(([e])=>g.some(([t])=>t===e)))return{...$(`failed`,n),errors:[Q({code:`invalid-record`})]};try{for(let[e,t]of g){let n=c(t);if(!n||e!==a(n.key))throw Error(`invalid draft record`);d.drafts[e]=n,delete d.tombstones[e]}for(let e of v)delete d.drafts[e];for(let[e,t]of _)d.tombstones[e]=t;e.migration&&(d.migration=e.migration),e.legacy&&(d.legacy=e.legacy);let t=he(pe(d));d.drafts=t.drafts,d.tombstones=t.tombstones,d.migration=t.migration,d.legacy=t.legacy}catch{return{...$(`failed`,n),errors:[Q({code:`invalid-record`})],cleanupErrors:u}}if(!await e.isCurrent())return $(`stale`,n);let y=Te(r.drafts),b=Te(d.drafts);u=await f(d.drafts);let x=[];for(let[t,r]of b){let i=y.get(t);if((i?.attachment.locator.kind===`blob`?i.attachment.locator.blobID:void 0)===(r.attachment.locator.kind===`blob`?r.attachment.locator.blobID:void 0))continue;let a=await h(r,e.resolveBlobValue);if(a.error){for(let e of x.reverse())await m(e,Ee(b.get(p(e))),u,`acquire-failed`);return{...$(`failed`,n),errors:[a.error],cleanupErrors:u}}a.acquired&&x.push(r.reference)}if(!await e.isCurrent()){for(let e of x.reverse())await m(e,Ee(b.get(p(e))),u,`stale`);return{...$(`stale`,n),cleanupErrors:u}}if(!i||l!==o){for(let e of x.reverse())await m(e,Ee(b.get(p(e))),u,`disabled`);return{...$(`disabled`,n),cleanupErrors:u}}let S=await t.persist(pe(d));if(!S.ok){for(let e of x.reverse())await m(e,Ee(b.get(p(e))),u,`metadata-failed`);return{...$(`failed`,n),errors:[{phase:`metadata`,error:S.error}],cleanupErrors:u}}r=d;for(let[e,t]of y)b.has(e)||await m(t.reference,t.attachment.locator.kind===`blob`?t.attachment.locator.blobID:``,u,`metadata-committed`);return{...$(`committed`,n),cleanupErrors:u}}):Promise.resolve(xe($(`disabled`,n)))},reconcile:()=>d(async()=>{if(!s)return $(`unseeded`);if(!i)return $(`disabled`);let t=await f(),n=new Map([...Te(r.drafts)].map(([e,t])=>[e,t.attachment.locator.kind===`blob`?t.attachment.locator.blobID:``])),a=await e.reconcileReferences(n,{ownerKinds:ve}),o=a.ok?a.value.missing.map(e=>Q({code:`missing-blob`},Te(r.drafts).get(e)?.reference)):[Q(a.error)];return{status:a.ok?`committed`:`failed`,keys:[],errors:o,cleanupErrors:t}}),retryCleanup:()=>d(async()=>({...$(`committed`),cleanupErrors:await f()})),flush:()=>l,setEnabled:async e=>{if(!e){i=!1,o+=1,t.cancelPending?.(),await t.setEnabled?.(!1),await l,await t.flush?.();return}await t.setEnabled?.(!0),i=!0,o+=1}}},Oe=`yuri-composer-reference-draft`,ke=`yuri-pasted-text-draft`,Ae=e=>Array.from(e).length,je=e=>typeof e==`object`&&!!e&&(Object.getPrototypeOf(e)===Object.prototype||Object.getPrototypeOf(e)===null),Me=(e,t)=>typeof e==`string`&&e.length>0&&e.length<=t,Ne=(e,t)=>{let n=[],r=[],i=0;for(let a=0;a<Math.min(t.length,m.referenceCount);a+=1){let o=t[a];if(!(!je(o)||!Me(o.id,m.idLength)||!Me(o.token,m.displayLength)||typeof o.text!=`string`||o.text.length>m.pastePayloadLength||typeof o.characterCount!=`number`||!Number.isSafeInteger(o.characterCount)||o.characterCount!==Ae(o.text)||typeof o.index!=`number`||!Number.isSafeInteger(o.index)||o.index<1))for(let t=e.indexOf(o.token);t>=0&&n.length<m.referenceCount;t=e.indexOf(o.token,t+o.token.length)){let e=t+o.token.length;if(r.some(n=>n.start<e&&n.end>t)||i+o.text.length>m.totalPastePayloadLength)continue;let a=n.filter(e=>e.id.startsWith(`${o.id}:`)).length;n.push({id:`${o.id}:${a}`,kind:`paste`,start:t,end:e,display:o.token,text:o.text,characterCount:o.characterCount,index:o.index}),r.push({start:t,end:e}),i+=o.text.length}}return n.sort((e,t)=>e.start-t.start)},Pe=e=>{try{let t=JSON.parse(e);if(!je(t)||typeof t.text!=`string`)return{text:e,references:[]};if(t.type===Oe||t.type===`openchamber-composer-reference-draft`)return(t.version===2?o(t.text,t.references):void 0)??{text:t.text,references:[]};if(t.type===ke||t.type===`openchamber-pasted-text-draft`){let e=t.version===1&&Array.isArray(t.references)?Ne(t.text,t.references):[];return o(t.text,e)??{text:t.text,references:[]}}}catch{}return{text:e,references:[]}},Fe=`file://`,Ie=e=>{let t=e.replace(/\\/g,`/`);return/^[A-Za-z]:/.test(t)&&(t=`/${t}`),t.split(`/`).map((e,t)=>t===1&&/^[A-Za-z]:$/.test(e)?e:encodeURIComponent(e)).join(`/`)},Le=e=>{let t=e.replace(/\\/g,`/`).trim();return t.toLowerCase().startsWith(Fe)?t:`${Fe}${Ie(t)}`},Re=(e,t)=>`${e}\u0000${t}`,ze=e=>new Promise((t,n)=>{let r=new FileReader;r.onload=()=>t(r.result),r.onerror=()=>n(r.error??Error(`Failed to read file`)),r.onabort=()=>n(Error(`File read aborted`)),r.readAsDataURL(e)}),Be=e=>{if(!e.startsWith(`data:`))return 0;let t=e.indexOf(`,`);if(t<0)return 0;let n=e.slice(0,t).toLowerCase(),r=e.slice(t+1);if(!n.endsWith(`;base64`))return 0;let i=0;return r.endsWith(`==`)?i=2:r.endsWith(`=`)&&(i=1),Math.max(0,Math.floor(r.length*3/4)-i)},Ve=(e,t)=>e===t?!0:!e||!t?!1:e.filePath===t.filePath&&e.fileName===t.fileName&&e.relativePath===t.relativePath&&e.fileSize===t.fileSize&&e.selection?.startLine===t.selection?.startLine&&e.selection?.endLine===t.selection?.endLine&&e.selection?.text===t.selection?.text,He=e=>({version:1,key:e,revision:1,text:``,attachments:[],syntheticParts:[],mentions:[]}),Ue=(e,t)=>t.flatMap(t=>{let n=`@${t}`,r=[],i=e.indexOf(n);for(;i>=0;)r.push({kind:`file`,value:t,path:t,label:t,range:{start:i,end:i+n.length}}),i=e.indexOf(n,i+n.length);return r}),We=(r={})=>{let o=r.sink??O(),p=r.repository??R(o),m=r.coordinator??z(o),g=r.blobStore??Y(),_=r.durability??De(g,m,{enabled:r.persistenceEnabled??!0}),v=new Map,y=new Map,b=new Map,x=new Map,S=new Map,C=new Set,w=new Set,T,E,D=0,k=0,ee=!1,te=!1,ne,A=new Set,j=new Map,M=new Set;return n()((n,o)=>{let m=e=>v.set(e,(v.get(e)??0)+1),O=(...e)=>{for(let t of e)b.set(t,(b.get(t)??0)+1),x.delete(t)},N=e=>c(e),P=()=>r.runtimeCapture?.()??{transportIdentity:e(),generation:t()},F=e=>{let t=P();return t.transportIdentity===e.transportIdentity&&t.generation===e.generation},I=e=>[...e.attachments,...e.syntheticParts.flatMap(e=>e.attachments)],re=e=>new Set(I(e).map(e=>e.attachmentRefID)),ie=(e,t,n)=>{let r=re(n);return{draftAttachmentViews:{...e.draftAttachmentViews,[t]:Object.fromEntries(Object.entries(e.draftAttachmentViews[t]??{}).filter(([e])=>r.has(e)))},draftMissingAttachmentRefIDs:{...e.draftMissingAttachmentRefIDs,[t]:(e.draftMissingAttachmentRefIDs[t]??[]).filter(e=>r.has(e))}}},L=()=>r.createID?.()??h(),ae=async(e,t)=>{let n=t instanceof File?t:new File([t],e.filename,{type:e.mimeType});return{id:e.attachmentID,file:n,dataUrl:typeof t==`string`?t:await ze(n),mimeType:e.mimeType,filename:e.filename,size:e.size,source:e.source,...e.serverPath?{serverPath:e.serverPath}:{},...e.vscodePath?{vscodePath:e.vscodePath}:{},...e.vscodeSource?{vscodeSource:e.vscodeSource}:{}}},R=e=>{let t=e.errors[0]??e.cleanupErrors[0];return t?.phase===`metadata`||t?.phase===`blob`&&[`blob-id-conflict`,`database-unavailable`,`invalid-value`,`missing-blob`,`quota-exceeded`,`transaction-aborted`,`transaction-failed`].includes(t.error.code)?t.error.code:`unavailable`},z=(e,t)=>{let r=o(),i=D,a=t??P(),s=[...new Set(e)];if(s.forEach(e=>w.delete(e)),T&&w.size===0&&(clearTimeout(T),T=void 0,E=void 0),!r.persistenceEnabled)return s.forEach(e=>A.add(e)),Promise.resolve({status:`disabled`,keys:s,errors:[],cleanupErrors:[]});let c=new Map(s.map(e=>[e,v.get(e)??0])),l=new Map(s.map(e=>[e,r.drafts[e]?.revision??r.tombstones[e]??0])),u=s.filter(e=>r.drafts[e]),d=Object.fromEntries(u.map(e=>[e,r.draftPersistence[e]?.status===`error`?r.draftPersistence[e]:{status:`saving`,revision:l.get(e)}])),f=Object.fromEntries(u.map(e=>[e,r.draftAttachmentPersistence[e]?.status===`error`?r.draftAttachmentPersistence[e]:{status:`saving`,revision:l.get(e)}]));n(e=>({draftPersistence:{...e.draftPersistence,...d},draftAttachmentPersistence:{...e.draftAttachmentPersistence,...f}})),te||s.forEach(e=>A.add(e));let p=(async()=>{let e=o(),t=await _.commit({drafts:Object.fromEntries(s.flatMap(t=>e.drafts[t]?[[t,e.drafts[t]]]:[])),tombstones:Object.fromEntries(s.flatMap(t=>e.tombstones[t]?[[t,e.tombstones[t]]]:[])),delete:s.filter(t=>!e.drafts[t]),migration:e.migration,legacy:{...e.legacyNewDraft?{new:e.legacyNewDraft}:{},entries:e.legacyDraftEntries},resolveBlobValue:t=>{for(let[n,r]of Object.entries(e.drafts))if(r.key.transportIdentity===t.transportIdentity&&r.key.owner.kind===t.owner.kind&&r.key.owner.ownerID===t.owner.ownerID)return e.draftAttachmentViews[n]?.[t.attachmentOccurrenceRefID]?.file},isCurrent:()=>D===i&&o().persistenceEnabled&&F(a)&&s.every(e=>(v.get(e)??0)===c.get(e)&&(o().drafts[e]?.revision??o().tombstones[e]??0)===l.get(e))}),r=D===i&&o().persistenceEnabled&&F(a);return(!r||t.status===`unseeded`||t.status===`stale`||t.status===`disabled`)&&s.forEach(e=>A.add(e)),r&&n(e=>{let n={...e.draftPersistence};for(let e of u){if((v.get(e)??0)!==c.get(e))continue;let r=l.get(e);if(t.status===`committed`)n[e]={status:`saved`,revision:r};else if(t.status===`unseeded`||t.status===`stale`||t.status===`disabled`)continue;else n[e]={status:`error`,revision:r,errorCode:R(t)}}let r={...e.draftAttachmentPersistence};for(let e of u){if((v.get(e)??0)!==c.get(e))continue;let n=l.get(e);r[e]=t.status===`committed`&&t.cleanupErrors.length===0?{status:`saved`,revision:n}:t.status===`failed`||t.cleanupErrors.length>0?{status:`error`,revision:n,errorCode:R(t)}:r[e]??{status:`idle`,revision:n}}return{draftPersistence:n,draftAttachmentPersistence:r}}),t})();return C.add(p),p.then(()=>C.delete(p),()=>C.delete(p)),p},oe=e=>{let t=o(),r=Object.fromEntries(e.flatMap(e=>{let n=t.drafts[e];return n?[[e,{status:`saving`,revision:n.revision}]]:[]}));Object.keys(r).length&&n(e=>({draftPersistence:{...e.draftPersistence,...r}}))},se=()=>{T&&clearTimeout(T),T=void 0;let e=[...w];w.clear();let t=E;return E=void 0,e.length?z(e,t).then(()=>void 0):Promise.resolve()},ce=e=>{if(!o().persistenceEnabled){A.add(e);return}w.add(e),oe([e]),!T&&(E=P(),T=setTimeout(()=>{se()},40))},le=e=>{let t=[...e];return t.forEach(e=>w.delete(e)),T&&w.size===0&&(clearTimeout(T),T=void 0,E=void 0),z(t)},B=(e,t,r,i=`immediate`)=>{let s=a(e),c=o().drafts[s];if(!c||r!==void 0&&c.revision!==r)return;let l=N(t(c));if(!(!l||a(l.key)!==s))return m(s),n(e=>({drafts:{...e.drafts,[s]:l},...ie(e,s,l)})),i===`deferred`?ce(s):le([s]),l},V=e=>e?l(e):void 0,H=(e=[])=>JSON.parse(JSON.stringify(e)),U=(e,t,n,r=!1,i=!1)=>({status:e,...V(n)?{record:V(n)}:{},errors:H(t?.errors),cleanupErrors:H(t?.cleanupErrors),current:r,durable:i}),W=(e,t,n,r,i=!1,a=!1)=>({status:e,errors:H(t?.errors),cleanupErrors:H(t?.cleanupErrors),current:i,durable:a,source:V(n),destination:V(r)}),G=e=>e.status,K=e=>typeof e==`number`&&Number.isSafeInteger(e)&&e>0,q=(e,...t)=>{let n={...e};for(let e of t)delete n[e];return n},ue=async(e,t)=>{let n={},r=o().draftAttachmentViews[a(e.key)]??{};for(let i of I(e)){let e;if(i.locator.kind===`url`){let n=t?.get(i.attachmentRefID);e=n===void 0?i.locator.url:n}else e=t?.get(i.attachmentRefID)??r[i.attachmentRefID]?.file??(typeof r[i.attachmentRefID]?.dataUrl==`string`&&u(r[i.attachmentRefID].dataUrl)?r[i.attachmentRefID].dataUrl:void 0);if(i.locator.kind===`url`&&e!==void 0&&(e!==i.locator.url||!u(e))||i.locator.kind===`blob`&&e!==void 0&&!(e instanceof Blob)&&!(typeof e==`string`&&u(e)))return;e!==void 0&&(n[i.attachmentRefID]=await ae(i,e))}return n},J=e=>e?a(e):`legacy-unowned`,Y=e=>j.get(e)??0,de=e=>{j.set(e,Y(e)+1)},X=(e,t,r=!1)=>{r&&de(e),n(n=>{let r=t(n.attachmentBuckets[e]??[]);return{attachmentBuckets:{...n.attachmentBuckets,[e]:r},...J(n.activeAttachmentDraft)===e?{attachedFiles:r}:{}}})};return{drafts:{},tombstones:{},draftHydration:{},draftPersistence:{},draftAttachmentViews:{},draftMissingAttachmentRefIDs:{},draftAttachmentPersistence:{},persistenceEnabled:r.persistenceEnabled??!0,legacyDraftEntries:{},migration:{complete:!1,claimedTransportIdentity:``},captureDraftRuntime:()=>P(),commitDraftSnapshot:async e=>{let t=a(e.key),r=e.runtime;if(r.transportIdentity!==e.key.transportIdentity||!F(r))return U(`stale`,void 0);let i=o(),s=i.drafts[t],c=i.tombstones[t]??0;if(e.expectedRevision!==`absent`&&!K(e.expectedRevision)||!Number.isSafeInteger(c)||c<0)return U(`failed`,void 0);if(e.expectedRevision===`absent`?s:s?.revision!==e.expectedRevision)return U(`conflict`,void 0,s);let u=e.expectedRevision===`absent`?c+1:e.expectedRevision+1;if(!K(u))return U(`failed`,void 0);let d=N({version:1,key:e.key,revision:u,...e.snapshot});if(!d)return U(`failed`,void 0);let f=await ue(d,e.values);if(!f)return U(`failed`,void 0);let p=v.get(t)??0,h=s?.revision??c,g=await _.commit({drafts:{[t]:d},isCurrent:()=>F(r)&&(v.get(t)??0)===p&&(o().drafts[t]?.revision??o().tombstones[t]??0)===h,resolveBlobValue:t=>e.values?.get(t.attachmentOccurrenceRefID)});if(g.status!==`committed`)return U(G(g),g,s);let y=(v.get(t)??0)===p&&(o().drafts[t]?.revision??o().tombstones[t]??0)===h,b=F(r);if(!y)return b||n(e=>({draftAttachmentViews:q(e.draftAttachmentViews,t),draftMissingAttachmentRefIDs:q(e.draftMissingAttachmentRefIDs,t),draftHydration:q(e.draftHydration,t),draftPersistence:q(e.draftPersistence,t),draftAttachmentPersistence:q(e.draftAttachmentPersistence,t)})),U(`stale`,g,d,!1,!0);let x=l(d);return x?(m(t),O(t),n(e=>({drafts:{...e.drafts,[t]:x},tombstones:(()=>{let n={...e.tombstones};return delete n[t],n})(),draftAttachmentViews:b?{...e.draftAttachmentViews,[t]:f}:q(e.draftAttachmentViews,t),draftMissingAttachmentRefIDs:b?{...e.draftMissingAttachmentRefIDs,[t]:[]}:q(e.draftMissingAttachmentRefIDs,t),draftHydration:b?e.draftHydration:q(e.draftHydration,t),draftPersistence:b?{...e.draftPersistence,[t]:{status:`saved`,revision:x.revision}}:q(e.draftPersistence,t),draftAttachmentPersistence:b?{...e.draftAttachmentPersistence,[t]:g.cleanupErrors.length?{status:`error`,revision:x.revision,errorCode:R(g)}:{status:`saved`,revision:x.revision}}:q(e.draftAttachmentPersistence,t)})),U(b?`committed`:`stale`,g,x,b,!0)):U(`failed`,g)},deleteDraftSnapshot:async e=>{let t=a(e.key),r=e.runtime;if(r.transportIdentity!==e.key.transportIdentity||!F(r))return U(`stale`,void 0);let i=o(),s=i.drafts[t],c=i.tombstones[t]??0;if(!K(e.expectedRevision)||!Number.isSafeInteger(c)||c<0)return U(`failed`,void 0);if(!s||s.revision!==e.expectedRevision)return U(`conflict`,void 0);let l=e.expectedRevision+1;if(!K(l))return U(`failed`,void 0);let u=v.get(t)??0,d=s.revision,f=Math.max(c,l),p=await _.commit({tombstones:{[t]:f},delete:[t],isCurrent:()=>F(r)&&(v.get(t)??0)===u&&o().drafts[t]?.revision===d&&(o().tombstones[t]??0)===c});if(p.status!==`committed`)return U(G(p),p);let h=(v.get(t)??0)===u&&o().drafts[t]?.revision===d&&(o().tombstones[t]??0)===c,g=F(r);return h?(m(t),O(t),n(e=>{let n={...e.drafts};return delete n[t],{drafts:n,tombstones:{...e.tombstones,[t]:Math.max(e.tombstones[t]??0,f)},draftAttachmentViews:q(e.draftAttachmentViews,t),draftMissingAttachmentRefIDs:q(e.draftMissingAttachmentRefIDs,t),draftHydration:q(e.draftHydration,t),draftPersistence:q(e.draftPersistence,t),draftAttachmentPersistence:q(e.draftAttachmentPersistence,t)}}),U(g?`committed`:`stale`,p,void 0,g,!0)):(g||n(e=>({draftAttachmentViews:q(e.draftAttachmentViews,t),draftMissingAttachmentRefIDs:q(e.draftMissingAttachmentRefIDs,t),draftHydration:q(e.draftHydration,t),draftPersistence:q(e.draftPersistence,t),draftAttachmentPersistence:q(e.draftAttachmentPersistence,t)})),U(`stale`,p,void 0,!1,!0))},finalizeDraftOwnership:async e=>{let t=a(e.source),r=a(e.destination),i=e.runtime,s=o(),c=s.drafts[t],u=s.drafts[r];if(t===r||e.destination.owner.kind!==`session`||e.source.transportIdentity!==i.transportIdentity||e.destination.transportIdentity!==i.transportIdentity||!F(i))return W(`stale`,void 0,c,u);if(!K(e.expectedSourceRevision))return W(`failed`,void 0,c,u);if(!c||c.revision!==e.expectedSourceRevision||u)return W(`conflict`,void 0,c,u);let d=v.get(t)??0,f=v.get(r)??0,p=s.tombstones[t]??0,h=s.tombstones[r]??0;if(!Number.isSafeInteger(p)||p<0||!Number.isSafeInteger(h)||h<0)return W(`failed`,void 0,c,u);let g=Math.max(c.revision+1,h+1);if(!K(g))return W(`failed`,void 0,c,u);let y=N(e.disposition===`preserve`?{...c,key:e.destination,revision:g}:{...He(e.destination),revision:g});if(!y)return W(`failed`,void 0,c,u);let b=await _.commit({drafts:{[r]:y},tombstones:{[t]:Math.max(p,g)},delete:[t],isCurrent:()=>F(i)&&(v.get(t)??0)===d&&(v.get(r)??0)===f&&o().drafts[t]?.revision===c.revision&&!o().drafts[r]&&(o().tombstones[t]??0)===p&&(o().tombstones[r]??0)===h,resolveBlobValue:e=>s.draftAttachmentViews[t]?.[e.attachmentOccurrenceRefID]?.file});if(b.status!==`committed`)return W(G(b),b,c,u);let x=(v.get(t)??0)===d&&o().drafts[t]?.revision===c.revision&&(o().tombstones[t]??0)===p,S=(v.get(r)??0)===f&&!o().drafts[r]&&(o().tombstones[r]??0)===h,C=F(i),w=l(y);if(!w)return W(`failed`,b,c,u);if(C&&!x&&!S)return W(`stale`,b,c,y,!1,!0);x&&(m(t),O(t)),S&&(m(r),O(r)),n(n=>{let i=n.drafts,a=n.tombstones;(x||S)&&(i={...i}),(x||S)&&(a={...a}),x&&(delete i[t],a[t]=Math.max(a[t]??0,g)),S&&(i[r]=w,delete a[r]);let o=n.draftHydration,s=n.draftPersistence,c=n.draftAttachmentViews,l=n.draftMissingAttachmentRefIDs,u=n.draftAttachmentPersistence;return C?(x&&(o=q(o,t),s=q(s,t),c=q(c,t),l=q(l,t),u=q(u,t)),S&&(o=q(o,r),s={...q(s,r),[r]:{status:`saved`,revision:w.revision}},c=q(c,r),l=q(l,r),u={...q(u,r),[r]:b.cleanupErrors.length?{status:`error`,revision:w.revision,errorCode:R(b)}:{status:`saved`,revision:w.revision}},C&&x&&e.disposition===`preserve`&&(c={...c,[r]:n.draftAttachmentViews[t]??{}},l={...l,[r]:n.draftMissingAttachmentRefIDs[t]??[]}))):(o=q(o,t,r),s=q(s,t,r),c=q(c,t,r),l=q(l,t,r),u=q(u,t,r)),{drafts:i,tombstones:a,draftHydration:o,draftPersistence:s,draftAttachmentViews:c,draftMissingAttachmentRefIDs:l,draftAttachmentPersistence:u}});let T=x&&S&&C;return W(T?`committed`:`stale`,b,c,y,T,!0)},flushDraftPersistence:async()=>{for(await se();C.size;)await Promise.all([...C]);await _.flush()},ensureDraft:e=>{let t=a(e),r=o().drafts[t];if(r)return r;let i=N({...He(e),revision:(o().tombstones[t]??0)+1});if(!i)throw Error(`Invalid empty draft`);return m(t),n(e=>({drafts:{...e.drafts,[t]:i}})),le([t]),i},getDraft:e=>o().drafts[a(e)],setDraftText:(e,t)=>{let n=o().getDraft(e)??o().ensureDraft(e);return B(e,e=>({...e,revision:e.revision+1,text:t,mentions:e.mentions.filter(e=>e.range.end<=t.length&&t.slice(e.range.start,e.range.end)===`@${e.value}`),composerReferences:[]}),n.revision,`deferred`)??n},setDraftComposerDocument:(e,t)=>{let n=o().getDraft(e)??o().ensureDraft(e);return o().setDraftComposerState(e,{document:t,mentions:n.mentions})},setDraftComposerState:(e,t)=>{let n=o().getDraft(e)??o().ensureDraft(e);return B(e,e=>({...e,revision:e.revision+1,text:t.document.text,composerReferences:t.document.references,mentions:t.mentions}),n.revision,`deferred`)},replaceDraft:(e,t,n)=>B(e,e=>({version:1,key:e.key,revision:e.revision+1,text:n.text,attachments:n.attachments,syntheticParts:n.syntheticParts,mentions:n.mentions,...n.composerReferences===void 0?{}:{composerReferences:n.composerReferences}}),t),setDraftMentions:(e,t)=>B(e,e=>({...e,revision:e.revision+1,mentions:t})),addDraftMention:(e,t)=>B(e,e=>({...e,revision:e.revision+1,mentions:[...e.mentions,t]})),removeDraftMention:(e,t)=>B(e,e=>({...e,revision:e.revision+1,mentions:e.mentions.filter(e=>e.value!==t)})),setDraftSyntheticParts:(e,t)=>B(e,e=>({...e,revision:e.revision+1,syntheticParts:t})),consumeDraftSyntheticParts:(e,t)=>{let n=o().getDraft(e);if(!n)return null;let r=n.syntheticParts.filter(e=>!t?.(e)),i=n.syntheticParts.filter(e=>t?.(e));return B(e,e=>({...e,revision:e.revision+1,syntheticParts:i}),n.revision)?r:null},setDraftAttachments:(e,t)=>B(e,e=>({...e,revision:e.revision+1,attachments:t})),addDraftLocalAttachment:async(e,t,r={})=>{let c=o().getDraft(e);if(r.partID&&!c?.syntheticParts.some(e=>e.partID===r.partID))return;let l=a(e),u=v.get(l)??0,d=o().tombstones[l]??0,f=P(),p=t instanceof File?t:new File([t],r.filename??`attachment`,{type:t.type}),h;try{h=await ze(p)}catch{let e=o().drafts[l];if(F(f)&&(o().tombstones[l]??0)===d&&(e?a(e.key)===l:(v.get(l)??0)===u)&&(!r.partID||e?.syntheticParts.some(e=>e.partID===r.partID))){let t=e?.revision??o().tombstones[l]??0;n(e=>({draftAttachmentPersistence:{...e.draftAttachmentPersistence,[l]:{status:`error`,revision:t,errorCode:`transaction-failed`}}}))}return}if(!F(f)||(o().tombstones[l]??0)!==d)return;let g=o().drafts[l];if(!g&&(v.get(l)??0)!==u)return;let _=g??o().ensureDraft(e);if(a(_.key)!==l||r.partID&&!_.syntheticParts.some(e=>e.partID===r.partID))return;let y=r.attachmentID??L(),b=r.partID?s(r.partID,y):i(y),x=L(),S={attachmentID:y,attachmentRefID:b,filename:r.filename??(t instanceof File?t.name:`attachment`),mimeType:t.type,size:t.size,locator:{kind:`blob`,blobID:x},source:r.source??`local`,...r.vscodePath?{vscodePath:r.vscodePath}:{},...r.vscodeSource?{vscodeSource:r.vscodeSource}:{}},C=r.partID?{..._,revision:_.revision+1,syntheticParts:_.syntheticParts.map(e=>e.partID===r.partID?{...e,attachments:[...e.attachments,S]}:e)}:{..._,revision:_.revision+1,attachments:[..._.attachments,S]},w=N(C);if(!w)return;m(l);let T={id:y,file:p,dataUrl:h,mimeType:S.mimeType,filename:S.filename,size:S.size,source:S.source,...r.vscodePath?{vscodePath:r.vscodePath}:{},...r.vscodeSource?{vscodeSource:r.vscodeSource}:{}};return n(e=>({drafts:{...e.drafts,[l]:w},draftAttachmentViews:{...e.draftAttachmentViews,[l]:{...e.draftAttachmentViews[l],[b]:T}}})),await z([l]),S},addDraftDurableAttachment:(e,t)=>{let r=o().getDraft(e)??o().ensureDraft(e);if(t.partID&&!r.syntheticParts.some(e=>e.partID===t.partID))return;let c=t.attachmentID??L(),l=t.partID?s(t.partID,c):i(c),u={attachmentID:c,attachmentRefID:l,filename:t.filename,mimeType:t.mimeType,size:t.size,source:t.source,locator:{kind:`url`,url:t.url},...t.serverPath?{serverPath:t.serverPath}:{},...t.vscodePath?{vscodePath:t.vscodePath}:{},...t.vscodeSource?{vscodeSource:t.vscodeSource}:{}},d=t.partID?{...r,revision:r.revision+1,syntheticParts:r.syntheticParts.map(e=>e.partID===t.partID?{...e,attachments:[...e.attachments,u]}:e)}:{...r,revision:r.revision+1,attachments:[...r.attachments,u]},f=N(d);if(!f)return;let p=a(e);m(p);let h={id:c,file:new File([],u.filename,{type:u.mimeType}),dataUrl:t.url,mimeType:u.mimeType,filename:u.filename,size:u.size,source:u.source,...u.serverPath?{serverPath:u.serverPath}:{},...u.vscodePath?{vscodePath:u.vscodePath}:{},...u.vscodeSource?{vscodeSource:u.vscodeSource}:{}};return n(e=>({drafts:{...e.drafts,[p]:f},draftAttachmentViews:{...e.draftAttachmentViews,[p]:{...e.draftAttachmentViews[p],[l]:h}}})),z([p]),u},getDraftAttachmentViews:e=>{let t=a(e),n=o().drafts[t],r=o().draftAttachmentViews[t]??{};return n?I(n).flatMap(e=>r[e.attachmentRefID]?[r[e.attachmentRefID]]:[]):[]},retryDraftAttachmentPersistence:async e=>{let t=a(e);if(!o().persistenceEnabled||!o().drafts[t]&&!o().tombstones[t])return;let r=await _.retryCleanup();r.cleanupErrors.length&&n(e=>({draftAttachmentPersistence:{...e.draftAttachmentPersistence,[t]:{status:`error`,revision:e.drafts[t]?.revision??e.tombstones[t],errorCode:R(r)}}})),await z([t])},hydrateDraftAttachments:async e=>{let t=a(e),r=x.get(t);if(r)return r;let i=o().drafts[t];if(!i)return;let s=(b.get(t)??0)+1;b.set(t,s);let c=P(),l=D,u=(async()=>{n(e=>({draftHydration:{...e.draftHydration,[t]:`loading`}}));let e=()=>{if(b.get(t)!==s)return;let e=o(),r=e.draftAttachmentViews[t],i=e.draftMissingAttachmentRefIDs[t]??[];n(e=>({draftHydration:{...e.draftHydration,[t]:i.length?`degraded`:Object.keys(r??{}).length?`ready`:`idle`}}))},r={},a=[];for(let u of I(i)){let d=u.locator.kind===`url`?{ok:!0,value:u.locator.url}:await g.read(u.locator.blobID);if(!d.ok){if(d.error.code===`missing-blob`)a.push(u.attachmentRefID);else{b.get(t)===s&&D===l&&F(c)&&o().drafts[t]===i?n(e=>({draftHydration:{...e.draftHydration,[t]:`error`}})):e();return}continue}try{r[u.attachmentRefID]=await ae(u,d.value)}catch{b.get(t)===s&&D===l&&F(c)&&o().drafts[t]===i?n(e=>({draftHydration:{...e.draftHydration,[t]:`error`}})):e();return}}let u=o(),d=u.drafts[t],f=b.get(t);if(f===s&&D===l&&F(c)&&d===i)n(e=>({draftAttachmentViews:{...e.draftAttachmentViews,[t]:r},draftMissingAttachmentRefIDs:{...e.draftMissingAttachmentRefIDs,[t]:a},draftHydration:{...e.draftHydration,[t]:a.length?`degraded`:`ready`}}));else if(f===s){let e=u.draftAttachmentViews[t],r=u.draftMissingAttachmentRefIDs[t]??[];n(n=>({draftHydration:{...n.draftHydration,[t]:r.length?`degraded`:Object.keys(e??{}).length?`ready`:`idle`}}))}})();x.set(t,u);try{await u}finally{x.get(t)===u&&x.delete(t)}},removeDraftAttachment:async(e,t)=>{let r=a(e),i=o().drafts[r],s=i&&I(i).find(e=>e.attachmentRefID===t);if(!i||!s)return!1;let c=d(s)?f(i.text,[s.filename],i.mentions,i.composerReferences):void 0,l=N({...i,revision:i.revision+1,...c?.changed?{text:c.text,mentions:c.mentions,...c.composerReferences===void 0?{}:{composerReferences:c.composerReferences}}:{},attachments:i.attachments.filter(e=>e.attachmentRefID!==t),syntheticParts:i.syntheticParts.map(e=>({...e,attachments:e.attachments.filter(e=>e.attachmentRefID!==t)}))});return l?(m(r),n(e=>{let n={...e.draftAttachmentViews[r]};return delete n[t],{drafts:{...e.drafts,[r]:l},draftAttachmentViews:{...e.draftAttachmentViews,[r]:n},draftMissingAttachmentRefIDs:{...e.draftMissingAttachmentRefIDs,[r]:(e.draftMissingAttachmentRefIDs[r]??[]).filter(e=>e!==t)}}}),(await z([r])).status===`committed`):!1},replaceDraftAttachment:async(e,t,r,c)=>{let l=a(e),u=o().drafts[l],d=u&&I(u).find(e=>e.attachmentRefID===t);if(!u||!d)return;let f=P(),p=o().tombstones[l]??0,h=r instanceof File?r:new File([r],c?.filename??`attachment`,{type:r.type}),g;try{g=await ze(h)}catch{let e=o().drafts[l],r=e&&I(e).find(e=>e.attachmentRefID===t);F(f)&&(o().tombstones[l]??0)===p&&e&&r?.attachmentID===d.attachmentID&&r.attachmentRefID===d.attachmentRefID&&a(e.key)===l&&n(t=>({draftAttachmentPersistence:{...t.draftAttachmentPersistence,[l]:{status:`error`,revision:e.revision,errorCode:`transaction-failed`}}}));return}let _=o().drafts[l],v=_&&I(_).find(e=>e.attachmentRefID===t);if(!F(f)||(o().tombstones[l]??0)!==p||!_||v?.attachmentID!==d.attachmentID||v.attachmentRefID!==d.attachmentRefID||a(_.key)!==l)return;let y=_.syntheticParts.find(e=>e.attachments.some(e=>e.attachmentRefID===t)),b=L(),x={attachmentID:b,attachmentRefID:y?s(y.partID,b):i(b),filename:c?.filename??h.name,mimeType:h.type,size:h.size,locator:{kind:`blob`,blobID:L()},source:c?.source??`local`,...c?.vscodePath?{vscodePath:c.vscodePath}:{},...c?.vscodeSource?{vscodeSource:c.vscodeSource}:{}},S=N({..._,revision:_.revision+1,attachments:y?_.attachments:_.attachments.map(e=>e.attachmentRefID===t?x:e),syntheticParts:_.syntheticParts.map(e=>e.partID===y?.partID?{...e,attachments:e.attachments.map(e=>e.attachmentRefID===t?x:e)}:e)});if(!S)return;m(l);let C={id:b,file:h,dataUrl:g,mimeType:x.mimeType,filename:x.filename,size:x.size,source:x.source,...x.vscodePath?{vscodePath:x.vscodePath}:{},...x.vscodeSource?{vscodeSource:x.vscodeSource}:{}};return n(e=>{let n={...e.draftAttachmentViews[l]};return delete n[t],{drafts:{...e.drafts,[l]:S},draftAttachmentViews:{...e.draftAttachmentViews,[l]:{...n,[x.attachmentRefID]:C}},draftMissingAttachmentRefIDs:{...e.draftMissingAttachmentRefIDs,[l]:(e.draftMissingAttachmentRefIDs[l]??[]).filter(e=>e!==t)}}}),(await z([l])).status===`committed`?x:void 0},replaceDraftRootAttachments:async(e,t)=>{let n=a(e),r=P();if(r.transportIdentity!==e.transportIdentity||!F(r))return U(`stale`,void 0);let s=o().drafts[n],c=s?s.revision:`absent`,l=[],d=new Map;for(let e of t){let t=e.id,n=i(t);if(e.source===`server`&&e.dataUrl&&u(e.dataUrl))l.push({attachmentID:t,attachmentRefID:n,filename:e.filename,mimeType:e.mimeType,size:e.size,source:`server`,locator:{kind:`url`,url:e.dataUrl},...e.serverPath?{serverPath:e.serverPath}:{}}),d.set(n,e.dataUrl);else if(e.source===`vscode`&&e.vscodeSource===`file`&&e.dataUrl&&u(e.dataUrl))l.push({attachmentID:t,attachmentRefID:n,filename:e.filename,mimeType:e.mimeType,size:e.size,source:`vscode`,locator:{kind:`url`,url:e.dataUrl},...e.vscodePath?{vscodePath:e.vscodePath}:{},vscodeSource:`file`}),d.set(n,e.dataUrl);else{let r=e.file instanceof File?e.file:new File([e.file],e.filename,{type:e.mimeType}),i=L();l.push({attachmentID:t,attachmentRefID:n,filename:e.filename,mimeType:e.mimeType,size:e.size,source:e.source===`vscode`?`vscode`:`local`,locator:{kind:`blob`,blobID:i},...e.vscodePath?{vscodePath:e.vscodePath}:{},...e.vscodeSource===`selection`?{vscodeSource:`selection`}:{}}),d.set(n,r)}}let f=s?.syntheticParts??[];for(let e of f)for(let t of e.attachments)t.locator.kind===`url`&&!d.has(t.attachmentRefID)&&d.set(t.attachmentRefID,t.locator.url);let p={text:s?.text??``,attachments:l,syntheticParts:f,mentions:s?.mentions??[],...s?.composerReferences===void 0?{}:{composerReferences:s.composerReferences}};return o().commitDraftSnapshot({key:e,expectedRevision:c,snapshot:p,values:d,runtime:r})},restoreDraftRootAttachments:async(e,t)=>{let n=a(e),r=P();if(r.transportIdentity!==e.transportIdentity||!F(r))return U(`stale`,void 0);let s=o().drafts[n],c=s?s.revision:`absent`,l=new Set(t.map(e=>e.id)),d=[],f=new Map;for(let e of t){let t=e.id,n=i(t);if(e.source===`server`&&e.dataUrl&&u(e.dataUrl))d.push({attachmentID:t,attachmentRefID:n,filename:e.filename,mimeType:e.mimeType,size:e.size,source:`server`,locator:{kind:`url`,url:e.dataUrl},...e.serverPath?{serverPath:e.serverPath}:{}}),f.set(n,e.dataUrl);else if(e.source===`vscode`&&e.vscodeSource===`file`&&e.dataUrl&&u(e.dataUrl))d.push({attachmentID:t,attachmentRefID:n,filename:e.filename,mimeType:e.mimeType,size:e.size,source:`vscode`,locator:{kind:`url`,url:e.dataUrl},...e.vscodePath?{vscodePath:e.vscodePath}:{},vscodeSource:`file`}),f.set(n,e.dataUrl);else{let r=e.file instanceof File?e.file:new File([e.file],e.filename,{type:e.mimeType}),i=L();d.push({attachmentID:t,attachmentRefID:n,filename:e.filename,mimeType:e.mimeType,size:e.size,source:e.source===`vscode`?`vscode`:`local`,locator:{kind:`blob`,blobID:i},...e.vscodePath?{vscodePath:e.vscodePath}:{},...e.vscodeSource===`selection`?{vscodeSource:`selection`}:{}}),f.set(n,r)}}let p=o().draftAttachmentViews[n]??{};for(let e of s?.attachments??[])if(!l.has(e.attachmentID))if(d.push(JSON.parse(JSON.stringify(e))),e.locator.kind===`url`)f.set(e.attachmentRefID,e.locator.url);else{let t=p[e.attachmentRefID];t?.file instanceof Blob?f.set(e.attachmentRefID,t.file):typeof t?.dataUrl==`string`&&u(t.dataUrl)&&f.set(e.attachmentRefID,t.dataUrl)}let m=s?.syntheticParts??[];for(let e of m)for(let t of e.attachments)t.locator.kind===`url`&&!f.has(t.attachmentRefID)&&f.set(t.attachmentRefID,t.locator.url);let h={text:s?.text??``,attachments:d,syntheticParts:m,mentions:s?.mentions??[],...s?.composerReferences===void 0?{}:{composerReferences:s.composerReferences}};return o().commitDraftSnapshot({key:e,expectedRevision:c,snapshot:h,values:f,runtime:r})},deleteDraft:(e,t)=>{let r=a(e),i=o().drafts[r];if(!i||t!==void 0&&i.revision!==t)return!1;let s=i.revision+1;return K(s)?(m(r),O(r),n(e=>{let t={...e.drafts};delete t[r];let n={...e.draftHydration},i={...e.draftPersistence},a={...e.draftAttachmentViews},o={...e.draftMissingAttachmentRefIDs},c={...e.draftAttachmentPersistence};return delete n[r],delete i[r],delete a[r],delete o[r],delete c[r],{drafts:t,tombstones:{...e.tombstones,[r]:Math.max(e.tombstones[r]??0,s)},draftHydration:n,draftPersistence:i,draftAttachmentViews:a,draftMissingAttachmentRefIDs:o,draftAttachmentPersistence:c}}),z([r]),!0):!1},moveDraft:(e,t,r)=>{let i=a(e),s=a(t),c=o().drafts[i];if(!c||i===s||r!==void 0&&c.revision!==r||o().drafts[s]||(o().tombstones[s]??0)>=c.revision+1||[...c.attachments,...c.syntheticParts.flatMap(e=>e.attachments)].some(e=>e.locator.kind===`blob`))return;let l=N({...c,key:t,revision:c.revision+1});if(l)return m(i),m(s),O(i,s),n(e=>{let t={...e.drafts};delete t[i];let n={...e.tombstones,[i]:Math.max(e.tombstones[i]??0,l.revision)};(n[s]??0)<l.revision&&delete n[s];let r=e=>{let t={...e},n=t[i];return delete t[i],delete t[s],n===void 0?t:{...t,[s]:n}};return{drafts:{...t,[s]:l},tombstones:n,draftHydration:r(e.draftHydration),draftPersistence:r(e.draftPersistence),draftAttachmentViews:r(e.draftAttachmentViews),draftMissingAttachmentRefIDs:r(e.draftMissingAttachmentRefIDs),draftAttachmentPersistence:r(e.draftAttachmentPersistence)}}),z([i,s]),l},moveDraftWithAttachments:async(e,t,r)=>{let i=a(e),s=a(t),c=o().drafts[i];if(!c||i===s||r!==void 0&&c.revision!==r||o().drafts[s]||(o().tombstones[s]??0)>=c.revision+1)return;let l=N({...c,key:t,revision:c.revision+1});if(l)return m(i),m(s),O(i,s),n(e=>{let t={...e.drafts};delete t[i];let n={...e.tombstones,[i]:Math.max(e.tombstones[i]??0,l.revision)};(n[s]??0)<l.revision&&delete n[s];let r=e=>{let t={...e},n=t[i];return delete t[i],delete t[s],n===void 0?t:{...t,[s]:n}};return{drafts:{...t,[s]:l},tombstones:n,draftHydration:r(e.draftHydration),draftPersistence:r(e.draftPersistence),draftAttachmentViews:r(e.draftAttachmentViews),draftMissingAttachmentRefIDs:r(e.draftMissingAttachmentRefIDs),draftAttachmentPersistence:r(e.draftAttachmentPersistence)}}),(await z([i,s])).status===`committed`?l:void 0},setDraftPersistenceEnabled:async e=>{if(D+=1,!e){T&&clearTimeout(T),T=void 0,w.clear(),E=void 0,n({persistenceEnabled:!1,draftPersistence:{}}),await _.setEnabled(!1),await _.flush();return}n({persistenceEnabled:!0}),await _.setEnabled(!0);let t=P();te||await o().hydrateDraftMetadata(t.transportIdentity);let r=new Set([...Object.keys(o().drafts),...Object.keys(o().tombstones),...A]);A.clear(),await z(r),await _.flush()},hydrateDraftMetadata:e=>{let t=S.get(e);if(t)return t;let r=(async()=>{let t=(y.get(e)??0)+1;y.set(e,t);let r=P();if(r.transportIdentity!==e)return!1;let i=D,s=new Map(v),c=k,l=Object.entries(o().drafts).filter(([,t])=>t.key.transportIdentity===e).map(([e])=>e);n(e=>({draftHydration:{...e.draftHydration,...Object.fromEntries(l.map(e=>[e,`loading`]))}}));let u=o().persistenceEnabled,d;try{d=await p.migrate(e,{persistenceEnabled:u})}catch{return!1}if(y.get(e)!==t||D!==i||!F(r))return!1;if(!d.ok)return n(e=>({draftHydration:{...e.draftHydration,...Object.fromEntries(l.map(t=>[t,e.drafts[t]?`degraded`:`error`]))}})),!1;let f=d.value;if(!te){ne??=_.seed(f).finally(()=>{ne=void 0});let a;try{a=await ne}catch{return!1}if(y.get(e)!==t||D!==i||!F(r))return!1;if(a.status!==`committed`&&a.status!==`disabled`)return n(e=>({draftHydration:{...e.draftHydration,...Object.fromEntries(l.map(e=>[e,`degraded`]))}})),!1;a.status===`committed`&&(te=!0)}let m=o(),h={...m.drafts},g={...m.tombstones},b=new Set;for(let[e,t]of Object.entries(f.tombstones))(v.get(e)??0)===(s.get(e)??0)&&(t>=(g[e]??0)&&(g[e]=t,(h[e]?.revision??0)<=t&&delete h[e]),b.add(e));for(let[t,n]of Object.entries(f.drafts)){if(n.key.transportIdentity!==e||(v.get(t)??0)!==(s.get(t)??0))continue;let r=h[t],i=N(n);i&&(!r||r.revision<i.revision)&&(g[t]??0)<i.revision&&(h[t]=i),b.add(t)}let x=k===c?{...f.legacy.entries}:{...m.legacyDraftEntries};if(f.migration.claimedTransportIdentity===e&&k===c)for(let[t,n]of Object.entries(x)){let r={transportIdentity:e,owner:{kind:`session`,ownerID:t}},i=a(r),o=Pe(n.text),c=N({...He(r),text:o.text,composerReferences:o.references,mentions:Ue(o.text,n.mentions)});c&&!h[i]&&!g[i]&&(v.get(i)??0)===(s.get(i)??0)&&(h[i]=c),delete x[t],b.add(i)}n(e=>({drafts:h,tombstones:g,legacyNewDraft:k===c&&!ee?f.legacy.new:e.legacyNewDraft,legacyDraftEntries:x,migration:k===c?f.migration:e.migration,draftHydration:{...e.draftHydration,...Object.fromEntries([...b].map(e=>[e,`ready`]))}}));let S=[...A];for(let e of S)b.add(e);A.clear();try{await z(b),await _.flush()}catch{return!1}return y.get(e)===t&&D===i&&F(r)})();return S.set(e,r),r.finally(()=>{S.get(e)===r&&S.delete(e)}).catch(()=>void 0),r},claimLegacyNewDraft:async e=>{let t=o().legacyNewDraft;if(!t)return o().getDraft(e);let r=a(e),i=o().drafts[r];if(k+=1,ee=!0,i||o().tombstones[r])return n({legacyNewDraft:void 0}),z([r]),i;let s=Pe(t.text),c=N({...He(e),text:s.text,composerReferences:s.references,mentions:Ue(s.text,t.mentions)});if(c)return m(r),n(e=>({drafts:{...e.drafts,[r]:c},legacyNewDraft:void 0})),z([r]),c},pendingInputText:null,pendingInputMode:`replace`,pendingSyntheticParts:null,pendingPresetSubmit:null,attachedFiles:[],attachmentBuckets:{"legacy-unowned":[]},activeAttachmentDraft:null,activeEditorFile:null,setPendingInputText:(e,t=`replace`)=>n({pendingInputText:e,pendingInputMode:t}),consumePendingInputText:()=>{let{pendingInputText:e,pendingInputMode:t}=o();return e===null?null:(n({pendingInputText:null,pendingInputMode:`replace`}),{text:e,mode:t})},requestPresetSubmit:e=>n({pendingPresetSubmit:e}),consumePendingPresetSubmit:()=>{let{pendingPresetSubmit:e}=o();return e===null?null:(n({pendingPresetSubmit:null}),e)},setPendingSyntheticParts:e=>n({pendingSyntheticParts:e}),consumePendingSyntheticParts:()=>{let{pendingSyntheticParts:e}=o();return e!==null&&n({pendingSyntheticParts:null}),e},setActiveAttachmentDraft:e=>{let t=J(e);n(n=>({activeAttachmentDraft:e,attachedFiles:n.attachmentBuckets[t]??[],attachmentBuckets:n.attachmentBuckets[t]?n.attachmentBuckets:{...n.attachmentBuckets,[t]:[]}}))},addAttachedFile:async e=>{let t=o().activeAttachmentDraft;if(t){let n=J(t),r=Y(n),i=await o().addDraftLocalAttachment(t,e);r!==Y(n)&&i&&o().removeDraftAttachment(t,i.attachmentRefID);return}let n=`${Date.now()}-${Math.random().toString(36).slice(2)}`,r=J(null),i=Y(r),a;try{a=await ze(e)}catch{return}if(i!==Y(r))return;let s={id:n,file:e,dataUrl:a,mimeType:e.type,filename:e.name,size:e.size,source:`local`};X(r,e=>[...e,s])},removeAttachedFile:e=>{let t=o().activeAttachmentDraft;if(t){let n=o().getDraft(t),r=n?[...n.attachments,...n.syntheticParts.flatMap(e=>e.attachments)].find(t=>t.attachmentID===e):void 0;r&&o().removeDraftAttachment(t,r.attachmentRefID);return}X(J(null),t=>t.filter(t=>t.id!==e))},setAttachedFiles:e=>{X(J(o().activeAttachmentDraft),()=>e,!0)},clearAttachedFiles:()=>{let e=o().activeAttachmentDraft;if(e){de(J(e)),o().getDraft(e)||o().ensureDraft(e),o().setDraftAttachments(e,[]);return}X(J(null),()=>[],!0)},addDraftVSCodeFileAttachment:(e,t,n,r)=>{if(o().getDraftAttachmentViews(e).some(e=>e.source===`vscode`&&e.vscodeSource===`file`&&(e.vscodePath||``)===t)||(o().getDraft(e)?.attachments.some(e=>e.source===`vscode`&&e.vscodeSource===`file`&&(e.vscodePath||``)===t)??!1))return;let i=Le(t);o().addDraftDurableAttachment(e,{filename:n,mimeType:`text/plain`,size:r||0,source:`vscode`,vscodePath:t,vscodeSource:`file`,url:i})},addDraftVSCodeSelectionAttachment:async(e,t,n)=>{let r=a(e),i=Y(r),s=`${r}\u0000${Re(t,n.name)}`;if(!(o().getDraftAttachmentViews(e).some(e=>e.source===`vscode`&&e.vscodeSource===`selection`&&e.filename===n.name&&e.vscodePath===t)||(o().getDraft(e)?.attachments.some(e=>e.source===`vscode`&&e.vscodeSource===`selection`&&e.filename===n.name&&e.vscodePath===t)??!1)||M.has(s))){M.add(s);try{let a=await o().addDraftLocalAttachment(e,n,{source:`vscode`,vscodePath:t,vscodeSource:`selection`});i!==Y(r)&&a&&o().removeDraftAttachment(e,a.attachmentRefID)}finally{M.delete(s)}}},addVSCodeFileAttachment:(e,t,n)=>{let r=o().activeAttachmentDraft;if(r){o().addDraftVSCodeFileAttachment(r,e,t,n);return}let i=`${Date.now()}-${Math.random().toString(36).slice(2)}`,a=J(null);if((o().attachmentBuckets[a]??[]).some(t=>t.source===`vscode`&&t.vscodeSource===`file`&&(t.vscodePath||``)===e))return;let s=Le(e),c={id:i,file:new File([],t,{type:`text/plain`}),dataUrl:s,mimeType:`text/plain`,filename:t,size:n||0,source:`vscode`,vscodePath:e,vscodeSource:`file`};X(a,e=>[...e,c])},addVSCodeSelectionAttachment:async(e,t)=>{let n=o().activeAttachmentDraft;if(n){await o().addDraftVSCodeSelectionAttachment(n,e,t);return}let r=`${Date.now()}-${Math.random().toString(36).slice(2)}`,i=J(null),a=Y(i),s=`${i}\u0000${Re(e,t.name)}`;if((o().attachmentBuckets[i]??[]).some(n=>n.source===`vscode`&&n.vscodeSource===`selection`&&n.filename===t.name&&n.vscodePath===e)||M.has(s))return;M.add(s);let c;try{c=await ze(t)}catch{return}finally{M.delete(s)}if(a!==Y(i))return;let l={id:r,file:t,dataUrl:c,mimeType:t.type,filename:t.name,size:t.size,source:`vscode`,vscodePath:e,vscodeSource:`selection`};X(i,e=>[...e,l])},addCodeSelectionAttachment:async(e,t,n)=>{let r=new File([n],t,{type:`text/plain`});await o().addVSCodeSelectionAttachment(e,r)},setActiveEditorFile:e=>{Ve(o().activeEditorFile,e)||n({activeEditorFile:e})},addRestoredAttachment:({url:e,mimeType:t,filename:n})=>{let r=o().activeAttachmentDraft;if(r){if(e.startsWith(`data:`)){let i=a(r);(async()=>{try{let s=await(await fetch(e)).blob(),c=new File([s],n,{type:t||s.type||`application/octet-stream`}),l=o().activeAttachmentDraft;if(!l||a(l)!==i)return;await o().addDraftLocalAttachment(r,c)}catch{}})();return}if(!u(e))return;o().addDraftDurableAttachment(r,{filename:n,mimeType:t,size:Be(e),source:`local`,serverPath:e,url:e});return}let i={id:`restored-${Date.now()}-${Math.random().toString(36).slice(2)}`,file:new File([],n,{type:t}),dataUrl:e,mimeType:t,filename:n,size:Be(e),source:`local`,serverPath:e};X(J(null),e=>[...e,i])}}})},Ge=We();export{O as a,Y as i,Ge as n,de as r,We as t};