@3sln/trove 0.0.7 → 0.0.8

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 (29) hide show
  1. package/package.json +1 -1
  2. package/packages/core/src/collections/index.js +146 -1
  3. package/packages/core/src/encryption/envelope.js +444 -0
  4. package/packages/core/src/encryption/exposure.js +101 -0
  5. package/packages/core/src/encryption/keys.js +88 -0
  6. package/packages/core/src/encryption/policy.js +112 -0
  7. package/packages/core/src/encryption/rotation.js +313 -0
  8. package/packages/core/src/index.js +17 -1
  9. package/packages/core/src/links.js +85 -0
  10. package/packages/core/src/metadata/memory.js +3 -1
  11. package/packages/core/src/metadata/sqlite.js +27 -7
  12. package/packages/core/src/scan.js +35 -1
  13. package/packages/core/src/storage/cost.js +228 -0
  14. package/packages/core/src/uploads.js +197 -15
  15. package/packages/core/src/vfs.js +148 -9
  16. package/packages/server/src/engine/providers/core.js +9 -2
  17. package/packages/server/src/routes.js +29 -1
  18. package/packages/web/dist/assets/main-y778bpte.js +356 -0
  19. package/packages/web/dist/assets/{main-f0f2tfhp.js.map → main-y778bpte.js.map} +10 -8
  20. package/packages/web/dist/assets/styles-nfy8t3n1.css +1 -0
  21. package/packages/web/dist/index.html +9 -3
  22. package/packages/web/dist/sw.js +1 -1
  23. package/packages/web/src/bl/actions.js +20 -4
  24. package/packages/web/src/bl/services.js +64 -4
  25. package/packages/web/src/platform/api.js +134 -11
  26. package/packages/web/src/styles.css +3 -0
  27. package/packages/web/src/ui/components/overlays.js +13 -0
  28. package/packages/web/dist/assets/main-f0f2tfhp.js +0 -356
  29. package/packages/web/dist/assets/styles-d3cyysgp.css +0 -1
@@ -0,0 +1,356 @@
1
+ import{a as sD,c as r8,d as iD}from"./chunk-4xqbzebh.js";var eQ={};r8(eQ,{wbr:()=>LY,video:()=>GY,vdom:()=>IC,ul:()=>hL,u:()=>EY,track:()=>$Y,tr:()=>gY,title:()=>JL,time:()=>KY,thead:()=>xY,th:()=>TY,tfoot:()=>_Y,textarea:()=>oY,template:()=>tY,td:()=>SY,tbody:()=>wY,table:()=>zY,svg:()=>VY,sup:()=>JY,summary:()=>iY,sub:()=>CY,style:()=>LL,strong:()=>BY,special:()=>QL,span:()=>QY,source:()=>MY,small:()=>AY,slot:()=>rY,settings:()=>CL,select:()=>nY,section:()=>PL,script:()=>YL,schedule:()=>eY,samp:()=>eL,s:()=>tL,reconcile:()=>BL,q:()=>rL,progress:()=>dY,pre:()=>yL,portal:()=>RY,picture:()=>FY,param:()=>UY,p:()=>kL,output:()=>lY,option:()=>cY,optgroup:()=>pY,ol:()=>gL,object:()=>WY,noscript:()=>DL,nav:()=>qL,meter:()=>mY,meta:()=>KL,math:()=>qY,mark:()=>iL,map:()=>IY,main:()=>VL,link:()=>EL,li:()=>xL,legend:()=>uY,label:()=>fY,kbd:()=>sL,ins:()=>aL,input:()=>bY,img:()=>XY,iframe:()=>ZY,i:()=>oL,html:()=>VB,hr:()=>TL,header:()=>HL,h6:()=>ML,h5:()=>RL,h4:()=>FL,h3:()=>UL,h2:()=>WL,h1:()=>ZL,h:()=>e8,form:()=>vY,footer:()=>GL,flush:()=>AD,figure:()=>_L,figcaption:()=>SL,fieldset:()=>hY,embed:()=>HY,em:()=>nL,dt:()=>wL,dodo:()=>OJ,dl:()=>zL,div:()=>jL,dialog:()=>sY,dfn:()=>dL,details:()=>aY,del:()=>lL,dd:()=>OL,datalist:()=>yY,data:()=>cL,colgroup:()=>jY,col:()=>OY,code:()=>pL,clear:()=>QD,cite:()=>mL,caption:()=>NY,canvas:()=>PY,button:()=>kY,br:()=>uL,blockquote:()=>NL,b:()=>fL,audio:()=>DY,aside:()=>$L,article:()=>IL,area:()=>YY,alias:()=>AL,address:()=>XL,abbr:()=>bL,a:()=>vL});var $Q=Symbol("ELEMENT_NODE"),MB=Symbol("ALIAS_NODE"),yQ=Symbol("SPECIAL_NODE"),tQ=Symbol("OPAQUE_NODE"),VA=Symbol("NODE_STATE");var m8=new Set(["__proto__","constructor","prototype"]),qJ=(A,Q)=>Object.prototype.hasOwnProperty.call(A,Q);function p8(A,Q){return typeof Q==="string"&&A.toLowerCase()===Q.toLowerCase()}class hQ{constructor(A,Q,B){this.type=A,this.tag=Q,this.args=B}key(A){return this.k=A,this}on(A){return this.hooks=A,this}opaque(){if(this.type!==$Q)throw Error(".opaque() can only be used on element nodes (h).");return this.type=tQ,this}}function c8(A,Q){if(A===Q)return!1;if(A&&Q&&typeof A==="object"&&typeof Q==="object"){if(A.constructor!==Q.constructor)return!0;if(Array.isArray(A)){if(A.length!==Q.length)return!0;for(let B=0;B<A.length;B++)if(A[B]!==Q[B])return!0;return!1}if(A.constructor===Object){let B=Object.keys(A);if(B.length!==Object.keys(Q).length)return!0;for(let C of B)if(!qJ(Q,C)||A[C]!==Q[C])return!0;return!1}}return!0}function l8(A){return Array.isArray(A)||A!=null&&typeof A[Symbol.iterator]==="function"&&typeof A!=="string"}function d8(A){return(...Q)=>new hQ(MB,A,Q)}function n8(A){return(...Q)=>new hQ(yQ,A,Q)}function o8(A,Q){if(A.namespaceURI==="http://www.w3.org/1999/xhtml")switch(Q){case"svg":return"http://www.w3.org/2000/svg";case"math":return"http://www.w3.org/1998/Math/MathML"}return A.namespaceURI??A.host?.namespaceURI??"http://www.w3.org/1999/xhtml"}function PJ(A){return{originalProps:Object.create(null),newVdom:A}}function XC(A,Q,B){let C=A.ownerDocument.createElementNS(o8(A,Q),Q);return C[VA]=PJ(B),C}var NJ=new WeakMap;function a8(A){let Q=[],B=A;while(B)if(Q.push(B),B.parentElement)B=B.parentElement;else B=B.getRootNode()?.host;return Q}function VJ(A,Q){for(let B of Q)A.add(B)}function s8(A,Q){let B=Q??A?.defaultView??globalThis;return B.Node?.prototype??B.Element?.prototype}function i8(A){let Q=new Set;return A.addEventListener("focusin",(B)=>{Q.clear(),VJ(Q,B.composedPath())}),A.addEventListener("focusout",(B)=>{if(!B.relatedTarget)Q.clear()}),VJ(Q,a8(A.activeElement)),NJ.set(A,Q),Q}var IC=(A)=>{let Q=A?.shouldUpdate??c8,B=A?.isMap??((G)=>G?.constructor===Object),C=A?.mapIter??((G)=>Object.entries(G)),J=A?.mapGet??((G,W)=>G[W]),K=A?.mapMerge??((...G)=>Object.assign({},...G)),E=A?.newMap??((G)=>({...G})),L=A?.mapPut??((G,W,H)=>{return G[W]=H,G}),D=A?.isSeq??l8,X=A?.seqIter??((G)=>G),Y=A?.convertName??((G)=>G),I=A?.convertTagName??Y,$=A?.convertPropName??Y,Z=A?.convertStyleName??Y,F=A?.convertDataName??Y,R=A?.convertClassName??Y,P=A?.convertHookName??Y,z=A?.listenerKey??"listener",h=A?.captureKey??"capture",M=A?.passiveKey??"passive",S=E({});function y(G){if(G==null)return[][Symbol.iterator]();if(typeof G[Symbol.iterator]==="function")return G[Symbol.iterator]();if(typeof G.next==="function")return G;return[G][Symbol.iterator]()}function w(G,W,H,N,_){if(G==null)return;for(let O in G)if(qJ(G,O))W(O,G[O],H,N,_)}function v(G,W,H,N,_){if(G==null)return;let O=y(C(G)),p;while(!(p=O.next()).done){let BA=p.value;W(BA[0],BA[1],H,N,_)}}let j=A?.mapEach??(A?.mapIter?v:w);function T(G){return G===null||G===void 0||G===!1}function a(G,W,H){let N=y(X(W)),_;while(!(_=N.next()).done){let O=_.value;if(H&&T(O))continue;if(!D(O))G.push(O);else a(G,O,H)}}function s(G,W){let H=[];return a(H,G,W),H}let i=A?.flattenSeq??s;function vA(G,W){let H=[];for(let N=W;N<G.length;N++){let _=G[N];if(T(_))continue;if(!D(_))H.push(_);else a(H,_,!0)}return H}function XA(G){return T(G)?"":String(G)}function IA(G,W,...H){if(!B(W)){if(W!==null&&W!==void 0)H.unshift(W);W=S}return new hQ($Q,I(G),[W,...H])}function e(G,W,H){H.setProperty(Z(G),W)}function o(G,W,H,N){if(J(N,G)!==void 0)return;H.removeProperty(Z(G))}function YA(G,W,H){let N=G.style;j(H,e,N),j(W,o,N,H)}function AA(G,W,H){H.setAttribute($(G),W)}function XQ(G,W,H,N){if(J(N,G)!==void 0)return;H.removeAttribute($(G))}function UA(G,W,H){j(H,AA,G),j(W,XQ,G,H)}function xA(G,W,H){H.dataset[F(G)]=W}function FA(G,W,H,N){if(J(N,G)!==void 0)return;delete H.dataset[F(G)]}function $A(G,W,H){j(H,xA,G),j(W,FA,G,H)}function n(G,W,H){let N=new Set;for(let _ of i(W,!0)){let O=R(_);if(O)N.add(O)}for(let _ of i(H,!0)){let O=R(_);if(!O)continue;N.delete(O),G.classList.add(O)}for(let _ of N)G.classList.remove(_)}function jA(G,W,H,N){if(m8.has(H)){console.error(`Refusing to assign unsafe prop name '${H}' to a DOM node.`);return}let _=W.originalProps;if(!(H in _))_[H]=G[H];G[H]=N===void 0?_[H]:N}function rA(G,W,H){let N=W.originalProps;if(H in N)G[H]=N[H],delete N[H]}function tA(G,W,H,N,_){let O=$(G),p=J(N,G);if(Object.is(W,p))return;switch(O){case"$styling":{if(!B(W))throw Error("invalid value for styling prop");YA(H,p??S,W??S);break}case"$classes":{if(!D(W))throw Error("invalid value for classes prop");n(H,p??[],W??[]);break}case"$attrs":{if(!B(W))throw Error("invalid value for attrs prop");UA(H,p??S,W??S);break}case"$dataset":{if(!B(W))throw Error("invalid value for dataset prop");$A(H,p??S,W??S);break}default:{if(_)jA(H,H[VA],O,W);else if(W===void 0)H.removeAttribute(O);else H.setAttribute(O,W);break}}}function TQ(G,W,H,N,_){if(J(N,G)!==void 0)return;let O=$(G);switch(O){case"$styling":YA(H,W??S,S);break;case"$classes":n(H,W??[],[]);break;case"$attrs":UA(H,W??S,S);break;case"$dataset":$A(H,W??S,S);break;default:{if(_)rA(H,H[VA],O);else H.removeAttribute(O);break}}}function eA(G,W){let H=G[VA],N=G.namespaceURI==="http://www.w3.org/1999/xhtml",_=H.vdom?.args[0]??S;j(W,tA,G,_,N),j(_,TQ,G,W,N)}function AQ(G,W,H){if(typeof H==="function")G.addEventListener(W,H);else if(H!=null)G.addEventListener(W,J(H,z),{capture:!!J(H,h),passive:!!J(H,M)})}function QQ(G,W,H){if(typeof H==="function")G.removeEventListener(W,H);else if(H!=null)G.removeEventListener(W,J(H,z),!!J(H,h))}function BQ(G,W,H){let N=P(G);if(N[0]==="$")return;AQ(H,N,W)}function iQ(G,W,H,N){let _=P(G);if(_[0]==="$")return;let O=J(N,G);if(W===O)return;QQ(H,_,O),AQ(H,_,W)}function x8(G,W,H,N){let _=P(G);if(_[0]==="$"||J(N,G)!==void 0)return;QQ(H,_,W)}function WJ(G,W){let H=G[VA],N=W??S;if(!H.vdom){j(N,BQ,G);return}let _=H.vdom.hooks??S;j(N,iQ,G,_),j(_,x8,G,N)}function DC(G){let W=G[VA],H=W.newVdom,N=W.vdom,_=H.args;switch(H.type){case $Q:{eA(G,_[0]),rQ(G,vA(_,1));break}case tQ:{eA(G,_[0]);break}case MB:{let O=H.tag.apply(G,H.args);if(T(O))rQ(G,[]);else if(D(O))rQ(G,i(O,!0));else rQ(G,[O]);break}case yQ:{try{H.tag.update?.(G,H.args,N?.args)}catch(O){console.error(O)}break}}if(H.hooks||N?.hooks)WJ(G,H.hooks??S);try{H.hooks?.$update?.(G,H,N)}catch(O){console.error(O)}W.vdom=H,delete W.newVdom}function g8(G,W){if(typeof W!=="object"||W===null)return G.ownerDocument.createTextNode(XA(W));let H;switch(W.type){case $Q:case tQ:H=XC(G,W.tag,W);break;case MB:H=XC(G,"udom-alias",W),H.style.display="contents";break;case yQ:H=XC(G,"udom-special",W),H.style.display="contents";break;default:throw Error("Invalid VDOM node")}return H}function UJ(G){if(G.children)for(let W of G.children)RB(W)}function RB(G){let W=G[VA];if(!W)return;let{vdom:H}=W;if(!H){delete G[VA];return}if(H.hooks)WJ(G,S);if(H.type===$Q||H.type===tQ)eA(G,S);if(H.type===$Q||H.type===MB)UJ(G);delete G[VA];try{if(H.type===yQ)H.tag.detach?.(G);H.hooks?.$detach?.(G)}catch(N){console.error(N)}}function k8(G,W){let H=G[VA];if(Q(H.vdom.args,W.args)||Q(H.vdom.hooks,W.hooks))H.newVdom=W;return G}function y8(G){let W=new Map,H={nodes:[],cursor:0};for(let N of G.childNodes){if(N.nodeType===3){H.nodes.push(N);continue}let _=N[VA],O=_?.vdom;if(O===void 0){if(_?.newVdom)throw Error("Attempt to reconcile against a target while already working on a reconciliation against that same target, this is not allowed");continue}let p=W.get(O.tag);if(!p)p={nodesForKey:null,nodesWithoutKey:{nodes:[],cursor:0}},W.set(O.tag,p);if(O.k!==void 0){if(!p.nodesForKey)p.nodesForKey=new Map;let BA=p.nodesForKey.get(O.k);if(BA)BA.nodes.push(N);else p.nodesForKey.set(O.k,{nodes:[N],cursor:0})}else p.nodesWithoutKey.nodes.push(N)}return{byTag:W,textNodes:H}}function FJ(G){if(!G||G.cursor>=G.nodes.length)return;return G.nodes[G.cursor++]}function h8(G,W,H,N){let _=G.firstChild;for(let O=0;O<W.length;O++){let p=W[O];if(p===_){_=_.nextSibling;continue}(N&&p.isConnected?N:H).call(G,p,_)}}function v8(G,W,H,N){let _=W[N],O=_;for(let BA=N-1;BA>=0;BA--){let lA=W[BA];if(lA!==O.previousSibling)H.call(G,lA,O);O=lA}let p=_.nextSibling;for(let BA=N+1;BA<W.length;BA++){let lA=W[BA];if(lA===p)p=p.nextSibling;else H.call(G,lA,p)}}function b8(G,W){for(let H=0;H<G.length;H++)if(W.has(G[H]))return H;return-1}function f8(G){let W=G[VA];if(!W?.newVdom)return;if(!W.vdom)try{if(W.newVdom.hooks?.$attach?.(G),W.newVdom.type===yQ)W.newVdom.tag.attach?.(G)}catch(H){console.error(H)}DC(G)}function rQ(G,W){let H=G.firstChild?new Set(G.childNodes):null,{byTag:N,textNodes:_}=y8(G),O=[];for(let GA of W){let IQ;if(GA instanceof hQ){let gQ=N.get(GA.tag),kQ=gQ?FJ(GA.k!==void 0?gQ.nodesForKey?.get(GA.k):gQ.nodesWithoutKey):void 0;IQ=kQ?k8(kQ,GA):g8(G,GA)}else{let gQ=FJ(_),kQ=XA(GA);if(gQ){if(IQ=gQ,IQ.nodeValue!==kQ)IQ.nodeValue=kQ}else IQ=G.ownerDocument.createTextNode(kQ)}H?.delete(IQ),O.push(IQ)}if(H)for(let GA of H)RB(GA),G.removeChild(GA);if(O.length===0)return;let p=G.ownerDocument,BA=s8(p,A?.window),lA=BA.insertBefore,RJ=typeof BA.moveBefore==="function"?BA.moveBefore:null,MJ=G.isConnected,xQ=-1;if(MJ&&!RJ){let GA=NJ.get(p)??i8(p);if(xQ=b8(O,GA),xQ!==-1&&O[xQ].parentNode!==G)xQ=-1}if(xQ===-1)h8(G,O,lA,MJ?RJ:null);else v8(G,O,lA,xQ);for(let GA=0;GA<O.length;GA++)f8(O[GA])}function u8(G,W){let H=G[VA];if(W===null||W===void 0){if(H)RB(G);else UJ(G);G.replaceChildren();return}if(D(W)){rQ(G,i(W,!0));return}if(W instanceof hQ){if(H){if(H.vdom.type===W.type&&H.vdom.tag===W.tag){if(Q(H.vdom.args,W.args)||Q(H.vdom.hooks,W.hooks))H.newVdom=W,DC(G);return}RB(G)}switch(W.type){case $Q:case tQ:if(!p8(G.nodeName,I(W.tag)))throw Error("incompatible target for vdom");break}G[VA]=PJ(W);try{if(W.hooks?.$attach?.(G),W.type===yQ)W.tag.attach?.(G)}catch(N){console.error(N)}DC(G);return}throw Error("invalid vdom")}return{h:IA,alias:d8,special:n8,reconcile:u8,settings:{shouldUpdate:Q,isMap:B,mapIter:C,mapEach:j,mapGet:J,mapMerge:K,newMap:E,mapPut:L,isSeq:D,flattenSeq:i,seqIter:X,convertTagName:I,convertPropName:$,convertStyleName:Z,convertDataName:F,convertClassName:R,convertHookName:P,convertName:Y,listenerKey:z,captureKey:h,passiveKey:M}}};function VB({h:A}){return{title:(...Q)=>A("title",...Q),meta:(Q)=>A("meta",Q),link:(Q)=>A("link",Q),style:(...Q)=>A("style",...Q),script:(...Q)=>A("script",...Q),noscript:(...Q)=>A("noscript",...Q),address:(...Q)=>A("address",...Q),article:(...Q)=>A("article",...Q),aside:(...Q)=>A("aside",...Q),footer:(...Q)=>A("footer",...Q),header:(...Q)=>A("header",...Q),h1:(...Q)=>A("h1",...Q),h2:(...Q)=>A("h2",...Q),h3:(...Q)=>A("h3",...Q),h4:(...Q)=>A("h4",...Q),h5:(...Q)=>A("h5",...Q),h6:(...Q)=>A("h6",...Q),main:(...Q)=>A("main",...Q),nav:(...Q)=>A("nav",...Q),section:(...Q)=>A("section",...Q),blockquote:(...Q)=>A("blockquote",...Q),dd:(...Q)=>A("dd",...Q),div:(...Q)=>A("div",...Q),dl:(...Q)=>A("dl",...Q),dt:(...Q)=>A("dt",...Q),figcaption:(...Q)=>A("figcaption",...Q),figure:(...Q)=>A("figure",...Q),hr:()=>A("hr"),li:(...Q)=>A("li",...Q),ol:(...Q)=>A("ol",...Q),p:(...Q)=>A("p",...Q),pre:(...Q)=>A("pre",...Q),ul:(...Q)=>A("ul",...Q),a:(...Q)=>A("a",...Q),abbr:(...Q)=>A("abbr",...Q),b:(...Q)=>A("b",...Q),br:()=>A("br"),cite:(...Q)=>A("cite",...Q),code:(...Q)=>A("code",...Q),data:(...Q)=>A("data",...Q),del:(...Q)=>A("del",...Q),dfn:(...Q)=>A("dfn",...Q),em:(...Q)=>A("em",...Q),i:(...Q)=>A("i",...Q),ins:(...Q)=>A("ins",...Q),kbd:(...Q)=>A("kbd",...Q),mark:(...Q)=>A("mark",...Q),q:(...Q)=>A("q",...Q),s:(...Q)=>A("s",...Q),samp:(...Q)=>A("samp",...Q),small:(...Q)=>A("small",...Q),span:(...Q)=>A("span",...Q),strong:(...Q)=>A("strong",...Q),sub:(...Q)=>A("sub",...Q),sup:(...Q)=>A("sup",...Q),time:(...Q)=>A("time",...Q),u:(...Q)=>A("u",...Q),wbr:()=>A("wbr"),area:(Q)=>A("area",Q),audio:(...Q)=>A("audio",...Q),img:(Q)=>A("img",Q),map:(...Q)=>A("map",...Q),track:(Q)=>A("track",Q),video:(...Q)=>A("video",...Q),embed:(Q)=>A("embed",Q),iframe:(...Q)=>A("iframe",...Q),object:(...Q)=>A("object",...Q),param:(Q)=>A("param",Q),picture:(...Q)=>A("picture",...Q),portal:(...Q)=>A("portal",...Q),source:(Q)=>A("source",Q),svg:(...Q)=>A("svg",...Q),math:(...Q)=>A("math",...Q),canvas:(...Q)=>A("canvas",...Q),caption:(...Q)=>A("caption",...Q),col:(Q)=>A("col",Q),colgroup:(...Q)=>A("colgroup",...Q),table:(...Q)=>A("table",...Q),tbody:(...Q)=>A("tbody",...Q),td:(...Q)=>A("td",...Q),tfoot:(...Q)=>A("tfoot",...Q),th:(...Q)=>A("th",...Q),thead:(...Q)=>A("thead",...Q),tr:(...Q)=>A("tr",...Q),button:(...Q)=>A("button",...Q),datalist:(...Q)=>A("datalist",...Q),fieldset:(...Q)=>A("fieldset",...Q),form:(...Q)=>A("form",...Q),input:(Q)=>A("input",Q),label:(...Q)=>A("label",...Q),legend:(...Q)=>A("legend",...Q),meter:(...Q)=>A("meter",...Q),optgroup:(...Q)=>A("optgroup",...Q),option:(...Q)=>A("option",...Q),output:(...Q)=>A("output",...Q),progress:(...Q)=>A("progress",...Q),select:(...Q)=>A("select",...Q),textarea:(...Q)=>A("textarea",...Q),details:(...Q)=>A("details",...Q),dialog:(...Q)=>A("dialog",...Q),summary:(...Q)=>A("summary",...Q),slot:(...Q)=>A("slot",...Q),template:(...Q)=>A("template",...Q)}}function $C({window:A}={}){let Q=!1,B=0,C=[];function J(){return A??globalThis}function K(Z){let F=J().requestAnimationFrame;return typeof F==="function"?F.call(J(),Z):setTimeout(Z,16)}function E(Z){let F=J().cancelAnimationFrame;if(typeof F==="function")F.call(J(),Z);else clearTimeout(Z)}function L(){return J().performance?.now()??Date.now()}function D(Z){for(let F of Z)try{F()}catch(R){console.error("Error in scheduled function:",R)}}function X(){let Z=L();B=0;while(C.length>0){let F=C.splice(0,100);if(D(F),L()-Z>10&&C.length>0){B=K(X);return}}Q=!1}function Y(Z,{signal:F}={}){if(F?.aborted)return;let R=Z;if(F)R=()=>{if(!F.aborted)Z()};if(C.push(R),!Q)Q=!0,B=K(X)}function I(){if(B)E(B),B=0;Q=!0;while(C.length>0){let Z=C;C=[],D(Z)}Q=!1}function $(){if(B)E(B);C=[],Q=!1,B=0}return{schedule:Y,flush:I,clear:$}}function OJ(A){let Q=IC(A),B=VB(Q),C=A?.scheduler??$C(A);return{...Q,...B,...C}}var t8=OJ();var{h:e8,alias:AL,special:QL,reconcile:BL,settings:CL,title:JL,meta:KL,link:EL,style:LL,script:YL,noscript:DL,address:XL,article:IL,aside:$L,footer:GL,header:HL,h1:ZL,h2:WL,h3:UL,h4:FL,h5:RL,h6:ML,main:VL,nav:qL,section:PL,blockquote:NL,dd:OL,div:jL,dl:zL,dt:wL,figcaption:SL,figure:_L,hr:TL,li:xL,ol:gL,p:kL,pre:yL,ul:hL,a:vL,abbr:bL,b:fL,br:uL,cite:mL,code:pL,data:cL,del:lL,dfn:dL,em:nL,i:oL,ins:aL,kbd:sL,mark:iL,q:rL,s:tL,samp:eL,small:AY,span:QY,strong:BY,sub:CY,sup:JY,time:KY,u:EY,wbr:LY,area:YY,audio:DY,img:XY,map:IY,track:$Y,video:GY,embed:HY,iframe:ZY,object:WY,param:UY,picture:FY,portal:RY,source:MY,svg:VY,math:qY,canvas:PY,caption:NY,col:OY,colgroup:jY,table:zY,tbody:wY,td:SY,tfoot:_Y,th:TY,thead:xY,tr:gY,button:kY,datalist:yY,fieldset:hY,form:vY,input:bY,label:fY,legend:uY,meter:mY,optgroup:pY,option:cY,output:lY,progress:dY,select:nY,textarea:oY,details:aY,dialog:sY,summary:iY,slot:rY,template:tY,schedule:eY,flush:AD,clear:QD}=t8;function BD(A,{signal:Q}={}){queueMicrotask(()=>{if(!Q?.aborted)A()})}function CD(A){return(Q)=>A("pre",{$styling:{"background-color":"#fdd",color:"#330",padding:"1em","white-space":"pre-wrap"}},A("strong",null,`Error: ${Q?.message??String(Q)}`),`
2
+
3
+ `,Q?.stack??"")}function jJ(A){return A!=null&&typeof A.special==="function"&&typeof A.reconcile==="function"}function GC(A){let Q=jJ(A)?{dodo:A}:A,B=Q?.dodo;if(!jJ(B))throw Error("a dodo instance must be provided in settings, e.g. reactive({dodo})");return{schedule:typeof B.schedule==="function"?B.schedule:BD,renderError:CD(B.h),...Q,dodo:B,...B.settings}}var dA=Symbol("dodo.reactive.PENDING"),HA=Symbol("dodo.reactive.NOTHING");function HQ(A){return A!=null&&typeof A.onDirty==="function"&&typeof A.getValue==="function"}function vQ(A){return HQ(A)?A.getValue():A}function JD(A){if(typeof A==="function")return A;if(A&&typeof A.unsubscribe==="function")return()=>A.unsubscribe();return()=>{}}function HC(){let A=new Set;return{listeners:A,notify(){for(let Q of Array.from(A))try{Q()}catch(B){console.error("Error in dodo cell listener:",B)}}}}function qB(A,Q){let{listeners:B,notify:C}=HC(),J=null;return{onDirty(K){if(B.add(K),B.size===1)try{J=JD(A(C))}catch(L){throw B.delete(K),L}let E=!1;return()=>{if(E)return;if(E=!0,B.delete(K),B.size===0&&J){let L=J;J=null,L()}}},getValue(){return Q()}}}function u(A){let Q=A,{listeners:B,notify:C}=HC();return{onDirty(J){return B.add(J),()=>B.delete(J)},getValue(){return Q},setValue(J){if(Object.is(J,Q))return;Q=J,C()},update(J){this.setValue(J(Q))}}}function PB(A){return{onDirty(){return()=>{}},getValue(){return A}}}function ZQ(A,Q){let B=Array.isArray(A)?A:[A],{listeners:C,notify:J}=HC(),K=null,E=HA,L=()=>{E=HA,J()},D=()=>{let X=Array(B.length);for(let Y=0;Y<B.length;Y++){let I=vQ(B[Y]);if(I===dA)return dA;X[Y]=I}return Q(...X)};return{onDirty(X){if(C.add(X),C.size===1)E=HA,K=B.map((I)=>HQ(I)?I.onDirty(L):null);let Y=!1;return()=>{if(Y)return;if(Y=!0,C.delete(X),C.size===0&&K){for(let I of K)I?.();K=null,E=HA}}},getValue(){if(E===HA||!K)E=D();return E}}}function zJ(A,Q){return ZQ([A],Q)}function wJ(A,{initial:Q=dA}={}){return KD(A,{initial:Q},(B,C)=>B.subscribe({next:C.next,error:C.error,complete:C.complete}))}function KD(A,{initial:Q},B){let C=Q,J=HA;return qB((E)=>{return B(A,{next(D){C=D,J=HA,E()},error(D){J=D,E()},complete(){}})},()=>{if(J!==HA)throw J;return C})}function SJ(A){return{subscribe(Q){let B=typeof Q==="function"?{next:Q}:Q??{},C=()=>{let K;try{K=vQ(A)}catch(E){B.error?.(E);return}if(K!==dA)B.next?.(K)},J=HQ(A)?A.onDirty(C):()=>{};return C(),{unsubscribe:J}}}}function gA(A,Q){let B=()=>{let J;try{J=vQ(A)}catch(K){console.error("Error reading cell in effect:",K);return}if(J===dA)return;Q(J)},C=HQ(A)?A.onDirty(B):()=>{};return B(),C}var GQ=Symbol("dodo.reactive.watch");function NB(A){let Q=GC(A),{dodo:B,schedule:C,renderError:J}=Q,{special:K,reconcile:E}=B,L=Q.mapGet??((I,$)=>I[$]),D=(I,$)=>I==null?void 0:L(I,$),X=Q.shouldUpdate??((I,$)=>I!==$);return{watch:K({attach(I){I[GQ]={source:HA,builder:null,placeholder:void 0,errorBuilder:void 0,unsubscribe:null,abortController:null,renderScheduled:!1,lastValue:HA,lastBuilder:HA}},update(I,[$,Z,F]){let R=I[GQ];if(!R)return;if(R.builder=Z,R.placeholder=D(F,"placeholder"),R.errorBuilder=D(F,"error"),R.source!==$){if(R.unsubscribe?.(),R.unsubscribe=null,R.abortController?.abort(),R.abortController=new AbortController,R.source=$,R.lastValue=HA,HQ($))try{R.unsubscribe=$.onDirty(()=>this.invalidate(I))}catch(P){this.renderError(I,P);return}}this.render(I)},invalidate(I){let $=I[GQ];if(!$||$.renderScheduled)return;$.renderScheduled=!0,C(()=>this.render(I),{signal:$.abortController?.signal})},render(I){let $=I[GQ];if(!$)return;$.renderScheduled=!1;let Z;try{Z=vQ($.source===HA?void 0:$.source)}catch(F){this.renderError(I,F);return}if($.builder===$.lastBuilder&&$.lastValue!==HA&&!X($.lastValue,Z))return;$.lastValue=Z,$.lastBuilder=$.builder;try{if(Z===dA)E(I,$.placeholder?[$.placeholder()]:[]);else E(I,[$.builder(Z)])}catch(F){this.renderError(I,F)}},renderError(I,$){let Z=I[GQ];if(!Z)return;Z.lastValue=HA,Z.lastBuilder=HA,console.error("Error in watched cell:",$);try{E(I,[(Z.errorBuilder??J)($)])}catch(F){console.error("Error rendering the error view:",F)}},detach(I){let $=I[GQ];if(!$)return;$.unsubscribe?.(),$.abortController?.abort(),delete I[GQ],E(I,null)}})}}var{watch:OB}=NB({dodo:eQ});var x=eQ;function AB(A){let Q={status:"idle"};return qB((B)=>{if(Q.status==="idle")Q={status:"running"},Promise.resolve().then(A).then((C)=>{Q={status:"done",value:C},B()},(C)=>{Q={status:"failed",error:C},B()});return()=>{}},()=>{if(Q.status==="failed")throw Q.error;return Q.status==="done"?Q.value:dA})}var _J={watch:OB,cell:u,derive:ZQ,constant:PB,mapCell:zJ,connectable:qB,fromObservable:wJ,fromAsync:AB,toObservable:SJ,effect:gA,isCell:HQ,readCell:vQ,PENDING:dA};var f=Object.freeze({NOT_FOUND:"not_found",ALREADY_EXISTS:"already_exists",INVALID:"invalid",CONFLICT:"conflict",UNAUTHORIZED:"unauthorized",FORBIDDEN:"forbidden",UNSUPPORTED:"unsupported",QUOTA:"quota",TOO_LARGE:"too_large",BAD_RANGE:"bad_range",TRANSIENT:"transient",TIMEOUT:"timeout",ABORTED:"aborted",INTERNAL:"internal"}),ED=new Set([f.TRANSIENT,f.TIMEOUT,f.QUOTA]),LD={[f.NOT_FOUND]:404,[f.ALREADY_EXISTS]:409,[f.INVALID]:400,[f.CONFLICT]:412,[f.UNAUTHORIZED]:401,[f.FORBIDDEN]:403,[f.UNSUPPORTED]:501,[f.QUOTA]:429,[f.TOO_LARGE]:413,[f.BAD_RANGE]:416,[f.TRANSIENT]:503,[f.TIMEOUT]:504,[f.ABORTED]:499,[f.INTERNAL]:500};class V extends Error{constructor(A,Q,B={}){super(Q,B.cause!==void 0?{cause:B.cause}:void 0);if(this.name="TroveError",this.code=A||f.INTERNAL,this.retryable=B.retryable??ED.has(this.code),this.details=B.details??null,this.status=LD[this.code]??500,this.code===f.QUOTA&&!this.retryable)this.status=507}toJSON(){return{error:{code:this.code,message:this.message,retryable:this.retryable,...this.details?{details:this.details}:{}}}}static notFound(A,Q){return new V(f.NOT_FOUND,A?`${A} not found`:"Not found",Q)}static alreadyExists(A,Q){return new V(f.ALREADY_EXISTS,`${A} already exists`,Q)}static invalid(A,Q){return new V(f.INVALID,A,Q)}static conflict(A,Q){return new V(f.CONFLICT,A,Q)}static unsupported(A,Q){return new V(f.UNSUPPORTED,A,Q)}static transient(A,Q){return new V(f.TRANSIENT,A,{retryable:!0,...Q})}static timeout(A,Q){return new V(f.TIMEOUT,A,{retryable:!0,...Q})}static aborted(A="Operation aborted",Q){return new V(f.ABORTED,A,{retryable:!1,...Q})}static unauthorized(A="Unauthorized",Q){return new V(f.UNAUTHORIZED,A,Q)}static tooLarge(A="Too large",Q){return new V(f.TOO_LARGE,A,{retryable:!1,...Q})}static badRange(A="Range not satisfiable",Q){return new V(f.BAD_RANGE,A,{retryable:!1,...Q})}static forbidden(A="Forbidden",Q){return new V(f.FORBIDDEN,A,Q)}static internal(A="Internal error",Q){return new V(f.INTERNAL,A,Q)}}function QB(A,Q="Unexpected error"){if(A instanceof V)return A;if(A?.name==="AbortError"||A?.code==="ABORT_ERR")return V.aborted(A.message||"Operation aborted",{cause:A});if(new Set(["ECONNRESET","ECONNREFUSED","ETIMEDOUT","EAI_AGAIN","EPIPE","ENOTFOUND","UND_ERR_SOCKET"]).has(A?.code)||A instanceof TypeError&&/fetch|network/i.test(A.message||""))return V.transient(A.message||"Network error",{cause:A});switch(A?.code){case"ENOENT":return V.notFound(null,{cause:A});case"EEXIST":return V.alreadyExists("Path",{cause:A});case"EACCES":case"EPERM":return new V(f.FORBIDDEN,"Permission denied",{cause:A});case"ENOSPC":return new V(f.QUOTA,"The storage volume is full — free some space and try again",{cause:A,retryable:!1});case"EDQUOT":return new V(f.QUOTA,"The storage quota for this volume has been reached",{cause:A,retryable:!1});case"EFBIG":return new V(f.QUOTA,"That file is larger than this filesystem can store",{cause:A,retryable:!1})}return V.internal(A?.message||Q,{cause:A})}function TJ(A){if(A instanceof V)return A.retryable;return QB(A).retryable}function xJ(A=""){let Q=(globalThis.crypto?.randomUUID?.()??YD()).replace(/-/g,"");return A?`${A}_${Q}`:Q}function YD(){let A="";for(let Q=0;Q<32;Q++)A+=Math.floor(Math.random()*16).toString(16);return A}function gJ(A){let Q=String(A||"").lastIndexOf(".");return Q>0?String(A).slice(Q).toLowerCase():""}function kJ(A,Q){if(!A||!Q)return!1;if(typeof A.match==="function")try{if(A.match(Q))return!0}catch{}let B=gJ(Q.name||"");if(B&&(A.ext||[]).some((K)=>(K.startsWith(".")?K:"."+K).toLowerCase()===B))return!0;let C=Q.contentType||"";return(A.mime||A.contentType||[]).some((K)=>K.endsWith("/*")?C.startsWith(K.slice(0,-1)):C===K)}var bQ="trove+contrib:",yJ="core",DD=/^(?:core|[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)+)$/,XD=/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/;function ID(A){return typeof A==="string"&&DD.test(A)}function jB(A){return typeof A==="string"&&XD.test(A)}function bA(A){return zB(A),`${A.domain}/${A.name}`}function CQ(A,Q){if(!jB(Q))throw V.invalid(`Invalid contribution name "${Q}"`);return`${bQ}${bA(A)}/${Q}`}var $D="workbench";function hJ(A){return`${bQ}${yJ}/${$D}/${A}`}function JQ(A){if(typeof A!=="string"||!A.startsWith(bQ))return null;let Q=A.slice(bQ.length),B=Q.indexOf("/"),C=Q.indexOf("/",B+1);if(B<0||C<0)return null;let J=Q.slice(0,B),K=Q.slice(B+1,C),E=Q.slice(C+1);if(!J||!K||!E)return null;return{domain:J,plugin:K,name:E,pluginId:`${J}/${K}`}}function vJ(A,Q){let B=JQ(Q);return!!B&&B.pluginId===`${A.domain}/${A.name}`}function zB(A){if(!ID(A?.domain))throw V.invalid(`Plugin manifest needs a valid "domain" (got ${JSON.stringify(A?.domain)})`);if(!jB(A?.name))throw V.invalid(`Plugin manifest needs a valid "name" (got ${JSON.stringify(A?.name)})`);if(A.domain===yJ)throw V.invalid('The "core" domain is reserved for built-in contributions')}var fJ={command:{normalize:(A)=>({title:A.title||null,category:A.category||null,icon:A.icon||null,when:A.when||null,palette:A.palette!==!1,offline:!!A.offline})},opener:{needsEntry:!0,normalize:(A)=>({title:A.title||null,match:bJ(A.match),priority:A.priority??50,when:A.when||null,offline:!!A.offline,dock:A.dock||null})},indexer:{needsEntry:!0,normalize:(A)=>({title:A.title||null,match:bJ(A.match)})},statusItem:{normalize:(A)=>{let Q=A.slot==="left"?"left":"right",B=A.render||"html";if(B!=="html")throw V.invalid(`statusItem "render" must be "html" (got ${JSON.stringify(B)})`);return{slot:Q,render:B,order:A.order??0,when:A.when||null,offline:!!A.offline,command:A.command||null}}},register:{normalize:(A)=>({default:A.default??null,description:A.description||null})},keymap:{normalize:(A)=>{if(!A.path||typeof A.path!=="string")throw V.invalid('keymap contribution needs a "path" to a JSON file in the package');return{path:A.path}}}},ZC=Object.keys(fJ);function nA(A){let Q=A?.contributes;if(Q==null)return[];if(typeof Q!=="object"||Array.isArray(Q))throw V.invalid('manifest "contributes" must be a map of name -> contribution');let B=[];for(let[C,J]of Object.entries(Q)){if(!J||typeof J!=="object")throw V.invalid(`Contribution "${C}" must be an object`);if(!jB(C))throw V.invalid(`Invalid contribution name "${C}"`);let K=fJ[J.type];if(!K)throw V.invalid(`Contribution "${C}" has unknown type ${JSON.stringify(J.type)} (expected one of ${ZC.join(", ")})`);let E=J.entry||A.entry;if(K.needsEntry&&!E)throw V.invalid(`Contribution "${C}" (${J.type}) needs an "entry" module`);B.push({name:C,uri:CQ(A,C),pluginId:bA(A),type:J.type,...K.normalize(J),...K.needsEntry?{entry:E}:{}})}return B}function GD(A,Q){return nA(A).filter((B)=>B.type===Q)}function WC(A){return GD(A,"indexer").map((Q)=>({id:Q.uri,name:Q.name,title:Q.title||Q.name,match:Q.match,entry:Q.entry}))}function uJ(A){let Q;try{Q=JSON.parse(A)}catch(C){throw V.invalid("Keymap file is not valid JSON",{cause:C})}let B=Array.isArray(Q)?Q:Array.isArray(Q?.bindings)?Q.bindings:null;if(!B)throw V.invalid("Keymap file must be a JSON array of bindings");return B.filter((C)=>C&&typeof C.key==="string"&&typeof C.command==="string").map((C)=>({key:C.key,command:C.command,when:typeof C.when==="string"?C.when:null,args:Array.isArray(C.args)?C.args:void 0}))}function bJ(A){if(!A||typeof A!=="object"||Array.isArray(A))return{};let Q=(K)=>K==null?void 0:(Array.isArray(K)?K:[K]).filter((E)=>typeof E==="string"),B={},C=Q(A.ext),J=Q(A.mime??A.contentType);if(C)B.ext=C;if(J)B.mime=J;if(typeof A.match==="function")B.match=A.match;return B}var HD=[...ZC,"view"];function wB(A){return String(A).startsWith(bQ)?A:hJ(A)}class UC{constructor(){this.items=new Map,this.cell=u([]),this.byType=new Map}#A(){this.cell.setValue([...this.items.values()])}register(A,Q){let B=Q?.type;if(!HD.includes(B))throw Error(`Unknown contribution type "${B}" for ${A}`);let C=wB(A),J=JQ(C);if(!J)throw Error(`Not a contribution URI: ${C}`);let K=Q.pluginId??(J.domain==="core"?null:J.pluginId),E={...Q,uri:C,type:B,id:J.domain==="core"?J.name:C,name:J.name,pluginId:K};return this.items.set(C,E),this.#A(),()=>this.unregister(C)}update(A,Q){let B=wB(A),C=this.items.get(B);if(!C)return!1;return this.items.set(B,{...C,...Q}),this.#A(),!0}unregister(A){if(this.items.delete(wB(A)))this.#A()}unregisterPlugin(A){let Q=!1;for(let[B,C]of this.items)if(C.pluginId===A)this.items.delete(B),Q=!0;if(Q)this.#A()}get(A){return A?this.items.get(wB(A))||null:null}all(){return[...this.items.values()]}ofType(A){return this.all().filter((Q)=>Q.type===A)}ofPlugin(A,Q){return this.all().filter((B)=>B.pluginId===A&&(!Q||B.type===Q))}observe(){return this.cell}observeType(A){let Q=this.byType.get(A);if(!Q)Q=ZQ([this.cell],(B)=>B.filter((C)=>C.type===A)),this.byType.set(A,Q);return Q}openersFor(A){return this.ofType("opener").filter((Q)=>kJ(Q.match,A)).sort((Q,B)=>(B.priority??0)-(Q.priority??0))}openerFor(A,Q,B){return this.openersFor(A).find((C)=>(!C.when||Q(C.when))&&(!B||B(C)))||null}keybindings(){return this.ofType("keymap").flatMap((A)=>(A.bindings||[]).map((Q)=>({...Q,keymap:A.uri,pluginId:A.pluginId})))}}var FC=new Map;function ZD(A){if(!A)return()=>!0;if(FC.has(A))return FC.get(A);let Q;try{Q=new pJ(A).parseExpression()}catch(B){console.warn(`Invalid when clause: "${A}" — ${B.message}`),Q=()=>!1}return FC.set(A,Q),Q}function mJ(A,Q){return ZD(A)(Q||{})}var SB=/\s*(=~|==|!=|>=|<=|&&|\|\||[()!<>]|trove\+contrib:[A-Za-z0-9_./-]+|\/(?:\\.|[^/])*\/|'(?:\\.|[^'])*'|"(?:\\.|[^"])*"|[A-Za-z0-9_.:-]+)/y;class pJ{constructor(A){this.src=A,this.tokens=this.#A(A),this.pos=0}#A(A){let Q=[],B=0;SB.lastIndex=0;while(B<A.length){SB.lastIndex=B;let C=SB.exec(A);if(!C||C.index==null){if(!A.slice(B).trim())break;throw Error(`Unexpected "${A.slice(B)}"`)}Q.push(C[1]),B=SB.lastIndex}return Q}#Q(){return this.tokens[this.pos]}#B(){return this.tokens[this.pos++]}#C(A){if(this.#Q()!==A)throw Error(`Expected "${A}"`);this.pos++}parseExpression(){let A=this.#J();if(this.pos!==this.tokens.length)throw Error(`Trailing "${this.#Q()}"`);return A}#J(){let A=this.#K();while(this.#Q()==="||"){this.#B();let Q=this.#K(),B=A;A=(C)=>B(C)||Q(C)}return A}#K(){let A=this.#E();while(this.#Q()==="&&"){this.#B();let Q=this.#E(),B=A;A=(C)=>B(C)&&Q(C)}return A}#E(){if(this.#Q()==="!"){this.#B();let A=this.#E();return(Q)=>!A(Q)}return this.#L()}#L(){let A=this.#Y(),Q=this.#Q();if(["==","!=",">=","<=",">","<","=~"].includes(Q)){if(this.#B(),Q==="=~"){let C=this.#B(),J=WD(C);return(K)=>J.test(String(A(K)??""))}let B=this.#Y();return(C)=>FD(Q,A(C),B(C))}return(B)=>UD(A(B))}#Y(){let A=this.#B();if(A===void 0)throw Error("Unexpected end");if(A==="("){let Q=this.#J();return this.#C(")"),Q}if(A==="true")return()=>!0;if(A==="false")return()=>!1;if(/^-?\d+(\.\d+)?$/.test(A)){let Q=Number(A);return()=>Q}if(A[0]==="'"||A[0]==='"'){let Q=A.slice(1,-1).replace(/\\(.)/g,"$1");return()=>Q}return(Q)=>Q[A]}}function WD(A){let Q=/^\/((?:\\.|[^/])*)\/([a-z]*)$/.exec(A);if(!Q)throw Error(`Bad regex ${A}`);return new RegExp(Q[1],Q[2])}function UD(A){return!(A===void 0||A===null||A===!1||A===""||A===0)}function FD(A,Q,B){switch(A){case"==":return Q==B;case"!=":return Q!=B;case">":return Q>B;case"<":return Q<B;case">=":return Q>=B;case"<=":return Q<=B}return!1}class RC{constructor(A={}){this.state={platform:cJ(),isMac:/mac/i.test(cJ()),...A},this.cell=u(this.state)}get(A){return this.state[A]}snapshot(){return this.state}observe(){return this.cell}set(A,Q){if(this.state[A]===Q)return;this.state={...this.state,[A]:Q},this.cell.setValue(this.state)}setMany(A){let Q=!1,B={...this.state};for(let[C,J]of Object.entries(A))if(B[C]!==J)B[C]=J,Q=!0;if(Q)this.state=B,this.cell.setValue(B)}remove(A){if(!(A in this.state))return;let{[A]:Q,...B}=this.state;this.state=B,this.cell.setValue(B)}evaluate(A){return mJ(A,this.state)}scopedFor(A){let Q=`${A}.`;return{set:(B,C)=>this.set(Q+B,C),remove:(B)=>this.remove(Q+B)}}}function cJ(){return typeof navigator<"u"?navigator.platform||navigator.userAgent||"":""}class MC{constructor(A,Q,B){this.contributions=A,this.context=Q,this.notifications=B,this.handlers=new Map}register(A,Q){let B=typeof A==="string"?{id:A,handler:Q}:A;if(B.handler)this.handlers.set(B.id,B.handler);let C=this.contributions.register(B.id,{type:"command",title:B.title??B.id,category:B.category,icon:B.icon,when:B.when,palette:B.palette??!0,pluginId:B.pluginId,offline:B.offline});return()=>{this.handlers.delete(B.id),C()}}has(A){return this.handlers.has(A)}isEnabled(A){let Q=this.contributions.get(A);if(Q?.when&&!this.context.evaluate(Q.when))return!1;return this.isAvailable(Q)}isAvailable(A){if(!A)return!0;return this.availability?this.availability(A):!0}async execute(A,...Q){let B=this.handlers.get(A);if(!B){this.notifications.error(`Command not found: ${A}`);return}let C=this.contributions.get(A);if(!this.isAvailable(C)){this.notifications.warn(`“${C?.title||A}” isn’t available${this.availability?" offline":""} right now.`);return}if(!this.isEnabled(A))return;try{return await B(...Q)}catch(J){throw console.error(`Command ${A} failed`,J),this.notifications.error(J?.message||`Command failed: ${A}`),J}}paletteCommands(){return this.contributions.ofType("command").filter((A)=>A.palette!==!1&&(!A.when||this.context.evaluate(A.when))).sort((A,Q)=>(A.category||"").localeCompare(Q.category||"")||A.title.localeCompare(Q.title))}}function VC(A){let Q=A.trim().toLowerCase().split("+").map((K)=>K.trim()),B=new Set,C="";for(let K of Q)if(["ctrl","control"].includes(K))B.add("ctrl");else if(["cmd","meta","super","win"].includes(K))B.add("meta");else if(K==="alt"||K==="option")B.add("alt");else if(K==="shift")B.add("shift");else if(["ctrlcmd","mod"].includes(K))B.add(lJ()?"meta":"ctrl");else C=K;return[...["ctrl","meta","alt","shift"].filter((K)=>B.has(K)),C].filter(Boolean).join("+")}function qC(A){let Q=[];if(A.ctrlKey)Q.push("ctrl");if(A.metaKey)Q.push("meta");if(A.altKey)Q.push("alt");if(A.shiftKey)Q.push("shift");let B=A.key.toLowerCase();return B={" ":"space",escape:"escape",enter:"enter",arrowup:"up",arrowdown:"down",arrowleft:"left",arrowright:"right"}[B]||B,[...Q.filter((J)=>B!==J),B].join("+")}class fQ{constructor(A,Q,B,C=null){this.contributions=A,this.commands=Q,this.context=B,this.settings=C,this.chordPrefix=null,this.chordTimer=null,this._onKeyDown=this.#B.bind(this)}install(A=window){return A.addEventListener("keydown",this._onKeyDown),()=>A.removeEventListener("keydown",this._onKeyDown)}overrides(){return this.settings?.get("keybindings.overrides")||{}}static bindingId(A){return`${A.command}\x00${VC(A.defaultKey||A.key)}`}rebind(A,Q){if(!this.settings)return;let B=typeof A==="string"?this.#A(A):fQ.bindingId(A);if(!B)return;let C={...this.overrides()};if(Q)C[B]=Q;else delete C[B];this.settings.set("keybindings.overrides",C)}#A(A){let Q=this.contributions.keybindings().find((B)=>B?.command===A&&B.key);return Q?fQ.bindingId({...Q,defaultKey:Q.key}):null}resolved(){let A=this.overrides();return this.contributions.keybindings().filter((Q)=>Q?.key&&Q.command).map((Q)=>{let B=VC(Q.key),C=fQ.bindingId({command:Q.command,defaultKey:B});return{...Q,defaultKey:B,bindingId:C,key:VC(A[C]||Q.key)}})}#Q(A){let Q=this.context.snapshot(),B=this.resolved();for(let C=B.length-1;C>=0;C--){let J=B[C];if(J.key!==A)continue;if(J.when&&!this.context.evaluate(J.when))continue;return J}return null}#B(A){if(A.defaultPrevented)return;let Q=qC(A),B=A.ctrlKey||A.metaKey||A.altKey;if(RD(A.target)&&!B&&A.key!=="Escape"){this.#C();return}let J=this.chordPrefix?`${this.chordPrefix} ${Q}`:Q,K=this.#Q(J);if(K){A.preventDefault(),this.#C(),this.commands.execute(K.command,...K.args||[]);return}if(!this.chordPrefix&&this.resolved().some((E)=>E.key.startsWith(Q+" "))){A.preventDefault(),this.chordPrefix=Q,this.chordTimer=setTimeout(()=>this.#C(),1500);return}this.#C()}#C(){if(this.chordPrefix=null,this.chordTimer)clearTimeout(this.chordTimer);this.chordTimer=null}labelFor(A){let Q=this.resolved().find((B)=>B.command===A);return Q?BB(Q.key):null}}function RD(A){if(!A)return!1;let Q=A.tagName;return Q==="INPUT"||Q==="TEXTAREA"||Q==="SELECT"||A.isContentEditable}function lJ(){return typeof navigator<"u"&&/mac/i.test(navigator.platform||navigator.userAgent||"")}function BB(A){let Q=lJ(),B=Q?{ctrl:"⌃",meta:"⌘",alt:"⌥",shift:"⇧",enter:"↵",escape:"esc",up:"↑",down:"↓",left:"←",right:"→",space:"␣"}:{ctrl:"Ctrl",meta:"Win",alt:"Alt",shift:"Shift",enter:"Enter",escape:"Esc",up:"↑",down:"↓",left:"←",right:"→",space:"Space"};return A.split(" ").map((C)=>C.split("+").map((J)=>B[J]||(J.length===1?J.toUpperCase():J[0].toUpperCase()+J.slice(1))).join(Q?"":"+")).join(" ")}var nJ="trove.settings";class PC{constructor(){this.schema=new Map,this.values=MD(),this.cell=u(this.effective())}register(A){for(let Q of[].concat(A))this.schema.set(Q.key,Q);return this.cell.setValue(this.effective()),()=>{for(let Q of[].concat(A))this.schema.delete(Q.key);this.cell.setValue(this.effective())}}get(A){if(A in this.values)return this.values[A];return this.schema.get(A)?.default}set(A,Q){let B=this.schema.get(A);if(B&&Q===B.default)delete this.values[A];else this.values[A]=Q;dJ(this.values),this.cell.setValue(this.effective())}reset(A){delete this.values[A],dJ(this.values),this.cell.setValue(this.effective())}effective(){let A={};for(let[Q,B]of this.schema)A[Q]=Q in this.values?this.values[Q]:B.default;for(let[Q,B]of Object.entries(this.values))if(!(Q in A))A[Q]=B;return A}observe(){return this.cell}grouped(){let A=new Map;for(let Q of[...this.schema.values()].sort((B,C)=>(B.order??0)-(C.order??0))){if(Q.hidden)continue;let B=Q.category||"General";if(!A.has(B))A.set(B,[]);A.get(B).push({...Q,value:this.get(Q.key)})}return[...A.entries()].map(([Q,B])=>({category:Q,items:B}))}scopedFor(A){let Q=`${A}.`;return{register:(B)=>this.register([].concat(B).map((C)=>({...C,key:Q+C.key,category:C.category||A}))),get:(B)=>this.get(Q+B),set:(B,C)=>this.set(Q+B,C)}}}function MD(){try{return JSON.parse(localStorage.getItem(nJ))||{}}catch{return{}}}function dJ(A){try{localStorage.setItem(nJ,JSON.stringify(A))}catch{}}var VD=0;class NC{constructor(){this.items=[],this.cell=u([])}observe(){return this.cell}#A(A,Q,B={}){let C={id:++VD,level:A,message:Q,actions:B.actions||null,createdAt:Date.now(),sticky:B.sticky||A==="error"};if(this.items=[...this.items,C],this.cell.setValue(this.items),!C.sticky)setTimeout(()=>this.dismiss(C.id),B.timeout??4000);return C.id}info(A,Q){return this.#A("info",A,Q)}success(A,Q){return this.#A("success",A,Q)}warn(A,Q){return this.#A("warn",A,Q)}error(A,Q){return this.#A("error",A,Q)}update(A,Q){this.items=this.items.map((B)=>B.id===A?{...B,...Q}:B),this.cell.setValue(this.items)}dismiss(A){this.items=this.items.filter((Q)=>Q.id!==A),this.cell.setValue(this.items)}}var qD={retries:4,minDelayMs:250,maxDelayMs:8000,factor:2,jitter:!0};function PD(A,Q){return new Promise((B,C)=>{if(Q?.aborted)return C(V.aborted());let J=(L)=>(D)=>{clearTimeout(K),Q?.removeEventListener("abort",E),L(D)},K=setTimeout(()=>J(B)(),A),E=()=>J(C)(V.aborted());Q?.addEventListener("abort",E,{once:!0})})}async function WQ(A,Q={}){let B={...qD,...Q},C=B.shouldRetry??TJ,J=0;for(;;){if(B.signal?.aborted)throw V.aborted();try{return await A(J)}catch(K){let E=QB(K);if(!(J<B.retries&&C(E)&&E.code!=="aborted"))throw E;let D=Math.min(B.maxDelayMs,B.minDelayMs*B.factor**J),X=B.jitter?Math.random()*D:D;B.onRetry?.({attempt:J+1,delayMs:X,error:E}),await PD(X,B.signal),J++}}}var ND=new Uint8Array([84,82,86,49]),OC=1,jC=1,OD=16,zC=8,jD=12,_B=16,wC=44,SC=1048576;function oJ(A,Q=SC){if(_C(Q),!(A>=0))throw V.invalid("plaintextSize must be a non-negative number");let B=A===0?1:Math.ceil(A/Q);return wC+A+B*OD}function _C(A){if(!Number.isInteger(A)||A<=0||A>4294967295)throw V.invalid(`Invalid chunk size ${A}`)}function aJ(A){let Q=new Uint8Array(wC),B=new DataView(Q.buffer);return Q.set(ND,0),Q[4]=A.version??OC,Q[5]=A.algorithm??jC,B.setUint32(8,A.chunkSize,!0),B.setBigUint64(12,BigInt(A.plaintextSize),!0),Q.set(A.noncePrefix,20),Q.set(A.fingerprint,28),Q}function sJ(A,Q){let B=new Uint8Array(jD);return B.set(A,0),new DataView(B.buffer).setUint32(zC,Q,!0),B}async function iJ(A){if(!(A instanceof Uint8Array)||A.length!==32)throw V.invalid("An AES-256 key must be 32 bytes");return crypto.subtle.importKey("raw",A,"AES-GCM",!1,["encrypt","decrypt"])}async function rJ(A,Q,{fingerprint:B,chunkSize:C=SC}={}){if(_C(C),!B||B.length!==_B)throw V.invalid(`A fingerprint must be ${_B} bytes`);let J=await iJ(A),K=crypto.getRandomValues(new Uint8Array(zC)),E=aJ({version:OC,algorithm:jC,chunkSize:C,plaintextSize:Q.length,noncePrefix:K,fingerprint:B}),L=new Uint8Array(oJ(Q.length,C));L.set(E,0);let D=wC,X=Q.length===0?1:Math.ceil(Q.length/C);for(let Y=0;Y<X;Y++){let I=Q.subarray(Y*C,Math.min((Y+1)*C,Q.length)),$=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:sJ(K,Y)},J,I));L.set($,D),D+=$.length}return L}async function tJ(A,Q,{fingerprint:B,plaintextSize:C,chunkSize:J=SC}={}){if(_C(J),!B||B.length!==_B)throw V.invalid(`A fingerprint must be ${_B} bytes`);let K=await iJ(A),E=crypto.getRandomValues(new Uint8Array(zC)),L=aJ({version:OC,algorithm:jC,chunkSize:J,plaintextSize:C,noncePrefix:E,fingerprint:B}),D=Q.getReader(),X=new Uint8Array(0),Y=0,I=!1,$=0,Z=async(F)=>new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:sJ(E,Y++)},K,F));return new ReadableStream({async pull(F){if(!I){I=!0,F.enqueue(L);return}for(;;){if(X.length>=J){let h=X.subarray(0,J);X=X.subarray(J),$+=h.length,F.enqueue(await Z(h));return}let{value:R,done:P}=await D.read();if(P){if(X.length||$===0)$+=X.length,F.enqueue(await Z(X)),X=new Uint8Array(0);if($!==C)throw V.invalid(`Expected ${C} bytes to encrypt and received ${$}`);F.close();return}let z=new Uint8Array(X.length+R.length);z.set(X,0),z.set(R,X.length),X=z}},cancel(F){return D.cancel(F)}})}function CB(A){if(typeof A!=="string"||!A.length||A.length%2||/[^0-9a-f]/i.test(A))throw V.invalid("Not hex");return new Uint8Array(A.match(/../g).map((Q)=>parseInt(Q,16)))}async function eJ(A,Q){let B=new Uint8Array(await A.arrayBuffer()),C=await rJ(CB(Q.key),B,{fingerprint:CB(Q.fingerprint),chunkSize:Q.chunkSize});return new Blob([C],{type:A.type||"application/octet-stream"})}class TC{constructor({baseUrl:A="",fetch:Q=globalThis.fetch.bind(globalThis),token:B=null}={}){this.baseUrl=A.replace(/\/$/,""),this._fetch=Q,this._token=B}token(){return(typeof this._token==="function"?this._token():this._token)||null}authHeaders(){let A=this.token();return A?{authorization:`Bearer ${A}`}:{}}async request(A,Q,{body:B,query:C,signal:J,raw:K}={}){let E=this.baseUrl+Q+(C?"?"+new URLSearchParams(C):"");return WQ(async()=>{let L=await this._fetch(E,{method:A,headers:{...this.authHeaders(),...B?{"content-type":"application/json"}:{}},body:B?JSON.stringify(B):void 0,signal:J});if(L.status===429||L.status>=500){if(!K){let Y;try{let I=await L.text();Y=(I?JSON.parse(I):null)?.error}catch{}if(Y&&Y.retryable===!1)throw new V(Y.code,Y.message,{retryable:!1,details:Y.details});throw V.transient(Y?.message||`Server ${L.status}`)}throw V.transient(`Server ${L.status}`)}if(K)return L;let D=await L.text(),X=D?JSON.parse(D):null;if(!L.ok){let Y=X?.error||{code:"internal",message:`Request failed (${L.status})`};throw new V(Y.code,Y.message,{retryable:Y.retryable,details:Y.details})}return X},{signal:J,retries:3})}capabilities(){return this.request("GET","/api/capabilities")}async reachable(A=4000){try{let Q=AbortSignal.timeout?AbortSignal.timeout(A):void 0;return(await this._fetch(this.baseUrl+"/api/capabilities",{method:"GET",signal:Q,headers:this.authHeaders()})).ok}catch{return!1}}list(A,Q={}){return this.request("GET",`${this.#A(A)}/items`,{query:Q})}stat(A,{collection:Q,...B}={}){let C=String(A).startsWith("trove:")?"uri":"id",J=Q?`${this.#A(Q)}/items/resolve`:"/api/items/resolve";return this.request("GET",J,{query:{[C]:A,...B}})}#A(A){if(!A)throw Error("This call is scoped to a collection — pass one");return`/api/collections/${encodeURIComponent(A)}`}backlinks(A,Q={}){return this.request("GET","/api/items/backlinks",{query:{id:A,...Q}})}rename(A,Q){return this.request("POST","/api/items/rename",{body:{id:A,newName:Q}})}remove(A){return this.request("POST","/api/items/delete",{body:{id:A}})}trash(A){return this.request("GET",`${this.#A(A)}/trash`)}restore(A){return this.request("POST","/api/trash/restore",{body:{id:A}})}purgeTrash({id:A,collection:Q}={}){return A?this.request("POST","/api/trash/purge",{body:{id:A}}):this.request("POST",`${this.#A(Q)}/trash/purge`)}search(A,{collection:Q,...B}={}){let C=Q?`${this.#A(Q)}/search`:"/api/search";return this.request("GET",C,{query:{q:A,...B}})}query(A,{collection:Q,...B}={}){let C=Q?`${this.#A(Q)}/query`:"/api/query";return this.request("POST",C,{body:{q:A,...B}})}tagSearch(A,Q,{collection:B,...C}={}){let J=B?`${this.#A(B)}/tags/search`:"/api/tags/search";return this.request("POST",J,{body:{filters:A,q:Q,...C}})}indexers(){return this.request("GET","/api/indexers")}tasks(){return this.request("GET","/api/tasks")}cancelTask(A){return this.request("POST",`/api/tasks/${encodeURIComponent(A)}/cancel`)}dismissTask(A){return this.request("DELETE",`/api/tasks/${encodeURIComponent(A)}`)}issues(){return this.request("GET","/api/issues")}retryIssue(A){return this.request("POST",`/api/issues/${encodeURIComponent(A)}/retry`)}dismissIssue(A){return this.request("DELETE",`/api/issues/${encodeURIComponent(A)}`)}reindex(){return this.request("POST","/api/reindex")}scanCollection(A){return this.request("POST",`/api/collections/${encodeURIComponent(A)}/scan`)}checkStorage(){return this.request("POST","/api/diagnostics/storage")}async installPlugin(A,Q){let B=Q&&Q.length?"?grants="+encodeURIComponent(Q.join(",")):"",C=await this._fetch(this.baseUrl+"/api/plugins/install"+B,{method:"POST",body:A,headers:this.authHeaders()}),J=await C.json().catch(()=>null);if(!C.ok){let K=J?.error||{code:"internal",message:`Install failed (${C.status})`};throw new V(K.code,K.message,{details:K.details})}return J.install}installedPlugins(){return this.request("GET","/api/plugins/installed")}async pluginPackage(A){let Q=await this._fetch(`${this.baseUrl}/api/plugins/${encodeURIComponent(A)}/package`,{headers:this.authHeaders()});if(!Q.ok)throw new V("not_found",`Package for "${A}" not found`);return new Uint8Array(await Q.arrayBuffer())}uninstallPluginServer(A){return this.request("DELETE",`/api/plugins/${encodeURIComponent(A)}/install`)}pushIndex(A,Q,B){return this.request("POST",`/api/index/${encodeURIComponent(A)}`,{body:{nodeId:Q,...B}})}me(){return this.request("GET","/api/me")}collections(){return this.request("GET","/api/collections")}createCollection(A){return this.request("POST","/api/collections",{body:A})}sidecar(A){return this.request("GET",`/api/items/${encodeURIComponent(A)}/sidecar`)}addComment(A,{body:Q,parentId:B,mentions:C}={}){return this.request("POST",`/api/items/${encodeURIComponent(A)}/comments`,{body:{body:Q,parentId:B,mentions:C}})}editComment(A,Q,B){return this.request("POST",`/api/items/${encodeURIComponent(A)}/comments/${encodeURIComponent(Q)}/edit`,{body:{body:B}})}deleteComment(A,Q){return this.request("DELETE",`/api/items/${encodeURIComponent(A)}/comments/${encodeURIComponent(Q)}`)}reactComment(A,Q,B,C){return this.request("POST",`/api/items/${encodeURIComponent(A)}/comments/${encodeURIComponent(Q)}/react`,{body:{emoji:B,on:C}})}setTag(A,Q,B){return this.request("POST",`/api/items/${encodeURIComponent(A)}/tags`,{body:{name:Q,value:B}})}removeTag(A,Q){return this.request("DELETE",`/api/items/${encodeURIComponent(A)}/tags/${encodeURIComponent(Q)}`)}notifications(){return this.request("GET","/api/notifications")}markNotificationsRead(A){return this.request("POST","/api/notifications/read",{body:{ids:A}})}vapidKey(){return this.request("GET","/api/push/vapid")}apiKeys(){return this.request("GET","/api/keys")}mintApiKey({name:A,scopes:Q,expiresAt:B=null}){return this.request("POST","/api/keys",{body:{name:A,scopes:Q,expiresAt:B}})}revokeApiKey(A){return this.request("DELETE",`/api/keys/${encodeURIComponent(A)}`)}subscribePush(A){return this.request("POST","/api/push/subscribe",{body:{subscription:A}})}downloadUrl(A,{attachment:Q}={}){return`${this.baseUrl}/api/items/download?id=${encodeURIComponent(A)}${Q?"&disposition=attachment":""}`}mintUrls(A,Q="media"){return this.request("POST","/api/items/urls",{body:{ids:A,op:Q}})}async download(A,Q,{attachment:B=!0}={}){let C=this.downloadUrl(A,{attachment:B});if(!this.token())return{url:C,streamed:!0};let J=await this._fetch(C,{headers:this.authHeaders()});if(!J.ok)throw new V("internal",`Download failed (${J.status})`);return{url:URL.createObjectURL(await J.blob()),streamed:!1,revoke:!0}}async readBytes(A,{signal:Q}={}){let B=await this._fetch(this.downloadUrl(A),{signal:Q,headers:this.authHeaders()});if(!B.ok)throw new V("internal",`Download failed (${B.status})`);return new Uint8Array(await B.arrayBuffer())}async readText(A,Q){return new TextDecoder().decode(await this.readBytes(A,Q))}async readTextCapped(A,{maxBytes:Q=524288,size:B=null,signal:C}={}){let J=B==null||B>Q,K=await this._fetch(this.downloadUrl(A),{signal:C,headers:{...this.authHeaders(),...J?{range:`bytes=0-${Q-1}`}:{}}});if(K.status===416)return{text:"",truncated:!1,total:0};if(!K.ok&&K.status!==206)throw new V("internal",`Download failed (${K.status})`);let E=new Uint8Array(await K.arrayBuffer()),L=Number(/\/(\d+)$/.exec(K.headers.get("content-range")||"")?.[1])||null,D=E.length>=Q&&(L==null||L>E.length),X=new TextDecoder("utf-8",{fatal:!1}).decode(E);if(D){let Y=X.lastIndexOf(`
4
+ `);if(Y>0)X=X.slice(0,Y)}return{text:X,truncated:D,total:L}}async upload(A,Q){let B=Q.name||A.name||"untitled",C=A.size,J=(w)=>WQ(w,{signal:Q.signal,retries:4,onRetry:({attempt:v,delayMs:j,error:T})=>Q.onRetry?.({attempt:v,delayMs:j,message:T.message})}),K=await J(()=>this.request("POST",`${this.#A(Q.collection)}/uploads`,{body:{name:B,size:C,contentType:A.type||void 0},signal:Q.signal}));if(K.uploadId)Q.onStart?.(K.uploadId);let E=new AK(K.encryption?.storedSize||C,Q.onProgress),L=K.transfer||{},D=K.endpoints?.complete||`/api/uploads/${K.uploadId}/complete`;if(K.strategy==="single"){let w=K.encryption?await eJ(A,K.encryption):A;return await J(()=>TB(L.url||K.url,w,{headers:L.requiredHeaders,signal:Q.signal,onProgress:(j)=>E.set("single",j)})),(await J(()=>this.request("POST",D,{body:{},signal:Q.signal}))).node}if(K.strategy==="direct-single"){let w=K.encryption?await eJ(A,K.encryption):A;return await J(()=>TB(this.baseUrl+this.#Q(K,1),w,{headers:{...this.authHeaders(),...L.authHeaders},signal:Q.signal,onProgress:(j)=>E.set(1,j)})),(await J(()=>this.request("POST",D,{body:{},signal:Q.signal}))).node}if(K.encryption)return this.#B(A,K,{...Q,progress:E,step:J,completeUrl:D});let X=K.partSize,Y=K.partCount??Math.ceil(C/X),I=new Set;try{let w=K.endpoints?.status||`/api/uploads/${K.uploadId}/status`,v=await this.request("GET",w,{signal:Q.signal});I=new Set(v.received||[])}catch{}let $=[],Z=[];for(let w=1;w<=Y;w++){let v=(w-1)*X,j=A.slice(v,Math.min(v+X,C));Z.push({n:w,blob:j})}let F=Array(Y),R=Math.min(Q.concurrency??4,Z.length),P=0,z=new AbortController,h=()=>z.abort();if(Q.signal)if(Q.signal.aborted)z.abort();else Q.signal.addEventListener("abort",h,{once:!0});let M=async()=>{while(P<Z.length){if(z.signal.aborted)return;let{n:w,blob:v}=Z[P++];if(I.has(w)){E.set(w,v.size);continue}let j=await WQ(()=>this.#C(K,w,v,{signal:z.signal,onProgress:(T)=>E.set(w,T)}),{signal:z.signal,retries:4,onRetry:({attempt:T,delayMs:a,error:s})=>Q.onRetry?.({attempt:T,delayMs:a,part:w,message:s.message})});F[w-1]={partNumber:w,etag:j}}};try{await Promise.all(Array.from({length:R},M))}catch(w){throw z.abort(),w}finally{Q.signal?.removeEventListener("abort",h)}let S=F.filter(Boolean);return(await J(()=>this.request("POST",D,{body:{parts:S},signal:Q.signal}))).node}#Q(A,Q){return(A.transfer?.partUrl||`/api/uploads/${A.uploadId}/parts/{partNumber}`).replace("{partNumber}",String(Q))}async#B(A,Q,{signal:B,progress:C,step:J,completeUrl:K,onRetry:E}){let L=Q.encryption,X=(await tJ(CB(L.key),A.stream(),{fingerprint:CB(L.fingerprint),plaintextSize:A.size,chunkSize:L.chunkSize})).getReader(),Y=[],I=[],$=0,Z=1,F=0,R=async()=>{let z=new Uint8Array($),h=0;for(let w of I)z.set(w,h),h+=w.length;I=[],$=0;let M=Z++,S=F,y=await WQ(()=>this.#C(Q,M,new Blob([z]),{signal:B,onProgress:(w)=>C.set(M,w)}),{signal:B,retries:4,onRetry:({attempt:w,delayMs:v,error:j})=>E?.({attempt:w,delayMs:v,part:M,message:j.message})});F=S+z.length,C.set(M,z.length),Y.push({partNumber:M,etag:y})};for(;;){let{value:z,done:h}=await X.read();if(h)break;if(I.push(z),$+=z.length,$>=Q.partSize)await R()}if($||Y.length===0)await R();return(await J(()=>this.request("POST",K,{body:{parts:Y},signal:B}))).node}async#C(A,Q,B,{signal:C,onProgress:J}){let K=A.transfer||{};if(A.strategy==="presign"){let D=(K.parts||A.parts)?.find(($)=>$.partNumber===Q)?.url;if(!D){let $=A.endpoints?.sign||`/api/uploads/${A.uploadId}/parts/{partNumber}/sign`;D=(await this.request("POST",$.replace("{partNumber}",String(Q)),{signal:C})).url}let Y=(await TB(D,B,{signal:C,onProgress:J,wantEtag:!0})).etag,I=A.endpoints?.report||`/api/uploads/${A.uploadId}/parts/{partNumber}/report`;return await this.request("POST",I.replace("{partNumber}",String(Q)),{body:{etag:Y},signal:C}),Y}return(await TB(this.baseUrl+this.#Q(A,Q),B,{headers:{...this.authHeaders(),...K.authHeaders},signal:C,onProgress:J,wantJson:!0})).json?.etag}async abortUpload(A){return this.request("DELETE",`/api/uploads/${A}`)}}class AK{constructor(A,Q){this.total=A,this.cb=Q,this.parts=new Map}set(A,Q){let B=this.parts.get(A)||0;if(Q<B)return;if(this.parts.set(A,Q),!this.cb)return;let C=0;for(let K of this.parts.values())C+=K;let J=Math.min(C,this.total);this.cb({loaded:J,total:this.total,ratio:this.total?J/this.total:1})}}function TB(A,Q,{signal:B,onProgress:C,wantEtag:J,wantJson:K,headers:E}={}){return new Promise((L,D)=>{let X=new XMLHttpRequest;X.open("PUT",A,!0);for(let[Y,I]of Object.entries(E||{}))try{X.setRequestHeader(Y,I)}catch{}if(B){if(B.aborted)return X.abort(),D(V.aborted());B.addEventListener("abort",()=>X.abort(),{once:!0})}X.upload.onprogress=(Y)=>C?.(Y.loaded),X.onload=()=>{if(X.status>=200&&X.status<300){let Y={status:X.status};if(J)Y.etag=X.getResponseHeader("ETag")||X.getResponseHeader("etag");if(K)try{Y.json=JSON.parse(X.responseText)}catch{}L(Y)}else if(X.status===429||X.status>=500)D(V.transient(`Upload part failed (${X.status})`));else D(new V("internal",`Upload failed (${X.status})`))},X.onerror=()=>D(V.transient("Network error during upload")),X.onabort=()=>D(V.aborted()),X.send(Q)})}var r=Uint8Array,PA=Uint16Array,pC=Int32Array,xB=new r([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),gB=new r([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),hC=new r([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),LK=function(A,Q){var B=new PA(31);for(var C=0;C<31;++C)B[C]=Q+=1<<A[C-1];var J=new pC(B[30]);for(var C=1;C<30;++C)for(var K=B[C];K<B[C+1];++K)J[K]=K-B[C]<<5|C;return{b:B,r:J}},YK=LK(xB,2),DK=YK.b,vC=YK.r;DK[28]=258,vC[258]=28;var XK=LK(gB,0),zD=XK.b,QK=XK.r,bC=new PA(32768);for(b=0;b<32768;++b)fA=(b&43690)>>1|(b&21845)<<1,fA=(fA&52428)>>2|(fA&13107)<<2,fA=(fA&61680)>>4|(fA&3855)<<4,bC[b]=((fA&65280)>>8|(fA&255)<<8)>>1;var fA,b,mA=function(A,Q,B){var C=A.length,J=0,K=new PA(Q);for(;J<C;++J)if(A[J])++K[A[J]-1];var E=new PA(Q);for(J=1;J<Q;++J)E[J]=E[J-1]+K[J-1]<<1;var L;if(B){L=new PA(1<<Q);var D=15-Q;for(J=0;J<C;++J)if(A[J]){var X=J<<4|A[J],Y=Q-A[J],I=E[A[J]-1]++<<Y;for(var $=I|(1<<Y)-1;I<=$;++I)L[bC[I]>>D]=X}}else{L=new PA(C);for(J=0;J<C;++J)if(A[J])L[J]=bC[E[A[J]-1]++]>>15-A[J]}return L},KQ=new r(288);for(b=0;b<144;++b)KQ[b]=8;var b;for(b=144;b<256;++b)KQ[b]=9;var b;for(b=256;b<280;++b)KQ[b]=7;var b;for(b=280;b<288;++b)KQ[b]=8;var b,EB=new r(32);for(b=0;b<32;++b)EB[b]=5;var b,wD=mA(KQ,9,0),SD=mA(KQ,9,1),_D=mA(EB,5,0),TD=mA(EB,5,1),xC=function(A){var Q=A[0];for(var B=1;B<A.length;++B)if(A[B]>Q)Q=A[B];return Q},kA=function(A,Q,B){var C=Q/8|0;return(A[C]|A[C+1]<<8)>>(Q&7)&B},gC=function(A,Q){var B=Q/8|0;return(A[B]|A[B+1]<<8|A[B+2]<<16)>>(Q&7)},cC=function(A){return(A+7)/8|0},LB=function(A,Q,B){if(Q==null||Q<0)Q=0;if(B==null||B>A.length)B=A.length;return new r(A.subarray(Q,B))};var xD=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],ZA=function(A,Q,B){var C=Error(Q||xD[A]);if(C.code=A,Error.captureStackTrace)Error.captureStackTrace(C,ZA);if(!B)throw C;return C},gD=function(A,Q,B,C){var J=A.length,K=C?C.length:0;if(!J||Q.f&&!Q.l)return B||new r(0);var E=!B,L=E||Q.i!=2,D=Q.i;if(E)B=new r(J*3);var X=function(AQ){var QQ=B.length;if(AQ>QQ){var BQ=new r(Math.max(QQ*2,AQ));BQ.set(B),B=BQ}},Y=Q.f||0,I=Q.p||0,$=Q.b||0,Z=Q.l,F=Q.d,R=Q.m,P=Q.n,z=J*8;do{if(!Z){Y=kA(A,I,1);var h=kA(A,I+1,3);if(I+=3,!h){var M=cC(I)+4,S=A[M-4]|A[M-3]<<8,y=M+S;if(y>J){if(D)ZA(0);break}if(L)X($+S);B.set(A.subarray(M,y),$),Q.b=$+=S,Q.p=I=y*8,Q.f=Y;continue}else if(h==1)Z=SD,F=TD,R=9,P=5;else if(h==2){var w=kA(A,I,31)+257,v=kA(A,I+10,15)+4,j=w+kA(A,I+5,31)+1;I+=14;var T=new r(j),a=new r(19);for(var s=0;s<v;++s)a[hC[s]]=kA(A,I+s*3,7);I+=v*3;var i=xC(a),vA=(1<<i)-1,XA=mA(a,i,1);for(var s=0;s<j;){var IA=XA[kA(A,I,vA)];I+=IA&15;var M=IA>>4;if(M<16)T[s++]=M;else{var e=0,o=0;if(M==16)o=3+kA(A,I,3),I+=2,e=T[s-1];else if(M==17)o=3+kA(A,I,7),I+=3;else if(M==18)o=11+kA(A,I,127),I+=7;while(o--)T[s++]=e}}var YA=T.subarray(0,w),AA=T.subarray(w);R=xC(YA),P=xC(AA),Z=mA(YA,R,1),F=mA(AA,P,1)}else ZA(1);if(I>z){if(D)ZA(0);break}}if(L)X($+131072);var XQ=(1<<R)-1,UA=(1<<P)-1,xA=I;for(;;xA=I){var e=Z[gC(A,I)&XQ],FA=e>>4;if(I+=e&15,I>z){if(D)ZA(0);break}if(!e)ZA(2);if(FA<256)B[$++]=FA;else if(FA==256){xA=I,Z=null;break}else{var $A=FA-254;if(FA>264){var s=FA-257,n=xB[s];$A=kA(A,I,(1<<n)-1)+DK[s],I+=n}var jA=F[gC(A,I)&UA],rA=jA>>4;if(!jA)ZA(3);I+=jA&15;var AA=zD[rA];if(rA>3){var n=gB[rA];AA+=gC(A,I)&(1<<n)-1,I+=n}if(I>z){if(D)ZA(0);break}if(L)X($+131072);var tA=$+$A;if($<AA){var TQ=K-AA,eA=Math.min(AA,tA);if(TQ+$<0)ZA(3);for(;$<eA;++$)B[$]=C[TQ+$]}for(;$<tA;++$)B[$]=B[$-AA]}}if(Q.l=Z,Q.p=xA,Q.b=$,Q.f=Y,Z)Y=1,Q.m=R,Q.d=F,Q.n=P}while(!Y);return $!=B.length&&E?LB(B,0,$):B.subarray(0,$)},oA=function(A,Q,B){B<<=Q&7;var C=Q/8|0;A[C]|=B,A[C+1]|=B>>8},JB=function(A,Q,B){B<<=Q&7;var C=Q/8|0;A[C]|=B,A[C+1]|=B>>8,A[C+2]|=B>>16},kC=function(A,Q){var B=[];for(var C=0;C<A.length;++C)if(A[C])B.push({s:C,f:A[C]});var J=B.length,K=B.slice();if(!J)return{t:$K,l:0};if(J==1){var E=new r(B[0].s+1);return E[B[0].s]=1,{t:E,l:1}}B.sort(function(y,w){return y.f-w.f}),B.push({s:-1,f:25001});var L=B[0],D=B[1],X=0,Y=1,I=2;B[0]={s:-1,f:L.f+D.f,l:L,r:D};while(Y!=J-1)L=B[B[X].f<B[I].f?X++:I++],D=B[X!=Y&&B[X].f<B[I].f?X++:I++],B[Y++]={s:-1,f:L.f+D.f,l:L,r:D};var $=K[0].s;for(var C=1;C<J;++C)if(K[C].s>$)$=K[C].s;var Z=new PA($+1),F=fC(B[Y-1],Z,0);if(F>Q){var C=0,R=0,P=F-Q,z=1<<P;K.sort(function(w,v){return Z[v.s]-Z[w.s]||w.f-v.f});for(;C<J;++C){var h=K[C].s;if(Z[h]>Q)R+=z-(1<<F-Z[h]),Z[h]=Q;else break}R>>=P;while(R>0){var M=K[C].s;if(Z[M]<Q)R-=1<<Q-Z[M]++-1;else++C}for(;C>=0&&R;--C){var S=K[C].s;if(Z[S]==Q)--Z[S],++R}F=Q}return{t:new r(Z),l:F}},fC=function(A,Q,B){return A.s==-1?Math.max(fC(A.l,Q,B+1),fC(A.r,Q,B+1)):Q[A.s]=B},BK=function(A){var Q=A.length;while(Q&&!A[--Q]);var B=new PA(++Q),C=0,J=A[0],K=1,E=function(D){B[C++]=D};for(var L=1;L<=Q;++L)if(A[L]==J&&L!=Q)++K;else{if(!J&&K>2){for(;K>138;K-=138)E(32754);if(K>2)E(K>10?K-11<<5|28690:K-3<<5|12305),K=0}else if(K>3){E(J),--K;for(;K>6;K-=6)E(8304);if(K>2)E(K-3<<5|8208),K=0}while(K--)E(J);K=1,J=A[L]}return{c:B.subarray(0,C),n:Q}},KB=function(A,Q){var B=0;for(var C=0;C<Q.length;++C)B+=A[C]*Q[C];return B},IK=function(A,Q,B){var C=B.length,J=cC(Q+2);A[J]=C&255,A[J+1]=C>>8,A[J+2]=A[J]^255,A[J+3]=A[J+1]^255;for(var K=0;K<C;++K)A[J+K+4]=B[K];return(J+4+C)*8},CK=function(A,Q,B,C,J,K,E,L,D,X,Y){oA(Q,Y++,B),++J[256];var I=kC(J,15),$=I.t,Z=I.l,F=kC(K,15),R=F.t,P=F.l,z=BK($),h=z.c,M=z.n,S=BK(R),y=S.c,w=S.n,v=new PA(19);for(var j=0;j<h.length;++j)++v[h[j]&31];for(var j=0;j<y.length;++j)++v[y[j]&31];var T=kC(v,7),a=T.t,s=T.l,i=19;for(;i>4&&!a[hC[i-1]];--i);var vA=X+5<<3,XA=KB(J,KQ)+KB(K,EB)+E,IA=KB(J,$)+KB(K,R)+E+14+3*i+KB(v,a)+2*v[16]+3*v[17]+7*v[18];if(D>=0&&vA<=XA&&vA<=IA)return IK(Q,Y,A.subarray(D,D+X));var e,o,YA,AA;if(oA(Q,Y,1+(IA<XA)),Y+=2,IA<XA){e=mA($,Z,0),o=$,YA=mA(R,P,0),AA=R;var XQ=mA(a,s,0);oA(Q,Y,M-257),oA(Q,Y+5,w-1),oA(Q,Y+10,i-4),Y+=14;for(var j=0;j<i;++j)oA(Q,Y+3*j,a[hC[j]]);Y+=3*i;var UA=[h,y];for(var xA=0;xA<2;++xA){var FA=UA[xA];for(var j=0;j<FA.length;++j){var $A=FA[j]&31;if(oA(Q,Y,XQ[$A]),Y+=a[$A],$A>15)oA(Q,Y,FA[j]>>5&127),Y+=FA[j]>>12}}}else e=wD,o=KQ,YA=_D,AA=EB;for(var j=0;j<L;++j){var n=C[j];if(n>255){var $A=n>>18&31;if(JB(Q,Y,e[$A+257]),Y+=o[$A+257],$A>7)oA(Q,Y,n>>23&31),Y+=xB[$A];var jA=n&31;if(JB(Q,Y,YA[jA]),Y+=AA[jA],jA>3)JB(Q,Y,n>>5&8191),Y+=gB[jA]}else JB(Q,Y,e[n]),Y+=o[n]}return JB(Q,Y,e[256]),Y+o[256]},kD=new pC([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),$K=new r(0),yD=function(A,Q,B,C,J,K){var E=K.z||A.length,L=new r(C+E+5*(1+Math.ceil(E/7000))+J),D=L.subarray(C,L.length-J),X=K.l,Y=(K.r||0)&7;if(Q){if(Y)D[0]=K.r>>3;var I=kD[Q-1],$=I>>13,Z=I&8191,F=(1<<B)-1,R=K.p||new PA(32768),P=K.h||new PA(F+1),z=Math.ceil(B/3),h=2*z,M=function(iQ){return(A[iQ]^A[iQ+1]<<z^A[iQ+2]<<h)&F},S=new pC(25000),y=new PA(288),w=new PA(32),v=0,j=0,T=K.i||0,a=0,s=K.w||0,i=0;for(;T+2<E;++T){var vA=M(T),XA=T&32767,IA=P[vA];if(R[XA]=IA,P[vA]=XA,s<=T){var e=E-T;if((v>7000||a>24576)&&(e>423||!X)){Y=CK(A,D,0,S,y,w,j,a,i,T-i,Y),a=v=j=0,i=T;for(var o=0;o<286;++o)y[o]=0;for(var o=0;o<30;++o)w[o]=0}var YA=2,AA=0,XQ=Z,UA=XA-IA&32767;if(e>2&&vA==M(T-UA)){var xA=Math.min($,e)-1,FA=Math.min(32767,T),$A=Math.min(258,e);while(UA<=FA&&--XQ&&XA!=IA){if(A[T+YA]==A[T+YA-UA]){var n=0;for(;n<$A&&A[T+n]==A[T+n-UA];++n);if(n>YA){if(YA=n,AA=UA,n>xA)break;var jA=Math.min(UA,n-2),rA=0;for(var o=0;o<jA;++o){var tA=T-UA+o&32767,TQ=R[tA],eA=tA-TQ&32767;if(eA>rA)rA=eA,IA=tA}}}XA=IA,IA=R[XA],UA+=XA-IA&32767}}if(AA){S[a++]=268435456|vC[YA]<<18|QK[AA];var AQ=vC[YA]&31,QQ=QK[AA]&31;j+=xB[AQ]+gB[QQ],++y[257+AQ],++w[QQ],s=T+YA,++v}else S[a++]=A[T],++y[A[T]]}}for(T=Math.max(T,s);T<E;++T)S[a++]=A[T],++y[A[T]];if(Y=CK(A,D,X,S,y,w,j,a,i,T-i,Y),!X)K.r=Y&7|D[Y/8|0]<<3,Y-=7,K.h=P,K.p=R,K.i=T,K.w=s}else{for(var T=K.w||0;T<E+X;T+=65535){var BQ=T+65535;if(BQ>=E)D[Y/8|0]=X,BQ=E;Y=IK(D,Y+1,A.subarray(T,BQ))}K.i=E}return LB(L,0,C+cC(Y)+J)},hD=function(){var A=new Int32Array(256);for(var Q=0;Q<256;++Q){var B=Q,C=9;while(--C)B=(B&1&&-306674912)^B>>>1;A[Q]=B}return A}(),vD=function(){var A=-1;return{p:function(Q){var B=A;for(var C=0;C<Q.length;++C)B=hD[B&255^Q[C]]^B>>>8;A=B},d:function(){return~A}}};var bD=function(A,Q,B,C,J){if(!J){if(J={l:1},Q.dictionary){var K=Q.dictionary.subarray(-32768),E=new r(K.length+A.length);E.set(K),E.set(A,K.length),A=E,J.w=K.length}}return yD(A,Q.level==null?6:Q.level,Q.mem==null?J.l?Math.ceil(Math.max(8,Math.min(13,Math.log(A.length)))*1.5):20:12+Q.mem,B,C,J)},GK=function(A,Q){var B={};for(var C in A)B[C]=A[C];for(var C in Q)B[C]=Q[C];return B};var uA=function(A,Q){return A[Q]|A[Q+1]<<8},zA=function(A,Q){return(A[Q]|A[Q+1]<<8|A[Q+2]<<16|A[Q+3]<<24)>>>0},yC=function(A,Q){return zA(A,Q)+zA(A,Q+4)*4294967296},DA=function(A,Q,B){for(;B;++Q)A[Q]=B,B>>>=8};function fD(A,Q){return bD(A,Q||{},0,0)}function uD(A,Q){return gD(A,{i:2},Q&&Q.out,Q&&Q.dictionary)}var HK=function(A,Q,B,C){for(var J in A){var K=A[J],E=Q+J,L=C;if(Array.isArray(K))L=GK(C,K[1]),K=K[0];if(ArrayBuffer.isView(K))B[E]=[K,L];else B[E+="/"]=[new r(0),L],HK(K,E,B,C)}},JK=typeof TextEncoder<"u"&&new TextEncoder,uC=typeof TextDecoder<"u"&&new TextDecoder,mD=0;try{uC.decode($K,{stream:!0}),mD=1}catch(A){}var pD=function(A){for(var Q="",B=0;;){var C=A[B++],J=(C>127)+(C>223)+(C>239);if(B+J>A.length)return{s:Q,r:LB(A,B-1)};if(!J)Q+=String.fromCharCode(C);else if(J==3)C=((C&15)<<18|(A[B++]&63)<<12|(A[B++]&63)<<6|A[B++]&63)-65536,Q+=String.fromCharCode(55296|C>>10,56320|C&1023);else if(J&1)Q+=String.fromCharCode((C&31)<<6|A[B++]&63);else Q+=String.fromCharCode((C&15)<<12|(A[B++]&63)<<6|A[B++]&63)}};function KK(A,Q){if(Q){var B=new r(A.length);for(var C=0;C<A.length;++C)B[C]=A.charCodeAt(C);return B}if(JK)return JK.encode(A);var J=A.length,K=new r(A.length+(A.length>>1)),E=0,L=function(Y){K[E++]=Y};for(var C=0;C<J;++C){if(E+5>K.length){var D=new r(E+8+(J-C<<1));D.set(K),K=D}var X=A.charCodeAt(C);if(X<128||Q)L(X);else if(X<2048)L(192|X>>6),L(128|X&63);else if(X>55295&&X<57344)X=65536+(X&1047552)|A.charCodeAt(++C)&1023,L(240|X>>18),L(128|X>>12&63),L(128|X>>6&63),L(128|X&63);else L(224|X>>12),L(128|X>>6&63),L(128|X&63)}return LB(K,0,E)}function cD(A,Q){if(Q){var B="";for(var C=0;C<A.length;C+=16384)B+=String.fromCharCode.apply(null,A.subarray(C,C+16384));return B}else if(uC)return uC.decode(A);else{var J=pD(A),K=J.s,B=J.r;if(B.length)ZA(8);return K}}var lD=function(A,Q){return Q+30+uA(A,Q+26)+uA(A,Q+28)},dD=function(A,Q,B){var C=uA(A,Q+28),J=uA(A,Q+30),K=cD(A.subarray(Q+46,Q+46+C),!(uA(A,Q+8)&2048)),E=Q+46+C,L=nD(A,E,J,B,zA(A,Q+20),zA(A,Q+24),zA(A,Q+42)),D=L[0],X=L[1],Y=L[2];return[uA(A,Q+10),D,X,K,E+J+uA(A,Q+32),Y]},nD=function(A,Q,B,C,J,K,E){var L=J==4294967295,D=K==4294967295,X=E==4294967295,Y=Q+B,I=L+D+X;if(C&&I){for(;Q+4<Y;Q+=4+uA(A,Q+2))if(uA(A,Q)==1)return[L?yC(A,Q+4+8*D):J,D?yC(A,Q+4):K,X?yC(A,Q+4+8*(D+L)):E,1];if(C<2)ZA(13)}return[J,K,E,0]},mC=function(A){var Q=0;if(A)for(var B in A){var C=A[B].length;if(C>65535)ZA(9);Q+=C+4}return Q},EK=function(A,Q,B,C,J,K,E,L){var D=C.length,X=B.extra,Y=L&&L.length,I=mC(X);if(DA(A,Q,E!=null?33639248:67324752),Q+=4,E!=null)A[Q++]=20,A[Q++]=B.os;A[Q]=20,Q+=2,A[Q++]=B.flag<<1|(K<0&&8),A[Q++]=J&&8,A[Q++]=B.compression&255,A[Q++]=B.compression>>8;var $=new Date(B.mtime==null?Date.now():B.mtime),Z=$.getFullYear()-1980;if(Z<0||Z>119)ZA(10);if(DA(A,Q,Z<<25|$.getMonth()+1<<21|$.getDate()<<16|$.getHours()<<11|$.getMinutes()<<5|$.getSeconds()>>1),Q+=4,K!=-1)DA(A,Q,B.crc),DA(A,Q+4,K<0?-K-2:K),DA(A,Q+8,B.size);if(DA(A,Q+12,D),DA(A,Q+14,I),Q+=16,E!=null)DA(A,Q,Y),DA(A,Q+6,B.attrs),DA(A,Q+10,E),Q+=14;if(A.set(C,Q),Q+=D,I)for(var F in X){var R=X[F],P=R.length;DA(A,Q,+F),DA(A,Q+2,P),A.set(R,Q+4),Q+=4+P}if(Y)A.set(L,Q),Q+=Y;return Q},oD=function(A,Q,B,C,J){DA(A,Q,101010256),DA(A,Q+8,B),DA(A,Q+10,B),DA(A,Q+12,C),DA(A,Q+16,J)};function ZK(A,Q){if(!Q)Q={};var B={},C=[];HK(A,"",B,Q);var J=0,K=0;for(var E in B){var L=B[E],D=L[0],X=L[1],Y=X.level==0?0:8,I=KK(E),$=I.length,Z=X.comment,F=Z&&KK(Z),R=F&&F.length,P=mC(X.extra);if($>65535)ZA(11);var z=Y?fD(D,X):D,h=z.length,M=vD();M.p(D),C.push(GK(X,{size:D.length,crc:M.d(),c:z,f:I,m:F,u:$!=E.length||F&&Z.length!=R,o:J,compression:Y})),J+=30+$+P+h,K+=76+2*($+P)+(R||0)+h}var S=new r(K+22),y=J,w=K-J;for(var v=0;v<C.length;++v){var I=C[v];EK(S,I.o,I,I.f,I.u,I.c.length);var j=30+I.f.length+mC(I.extra);S.set(I.c,I.o+j),EK(S,J,I,I.f,I.u,I.c.length,I.o,I.m),J+=16+j+(I.m?I.m.length:0)}return oD(S,J,C.length,w,y),S}function WK(A,Q){var B={},C=A.length-22;for(;zA(A,C)!=101010256;--C)if(!C||A.length-C>65558)ZA(13);var J=uA(A,C+8);if(!J)return{};var K=zA(A,C+16),E=zA(A,C-20)==117853008;if(E){var L=zA(A,C-12);if(E=zA(A,L)==101075792,E)J=zA(A,L+32),K=zA(A,L+48)}var D=Q&&Q.filter;for(var X=0;X<J;++X){var Y=dD(A,K,E),I=Y[0],$=Y[1],Z=Y[2],F=Y[3],R=Y[4],P=Y[5],z=lD(A,P);if(K=R,!D||D({name:F,size:$,originalSize:Z,compression:I}))if(!I)B[F]=LB(A,z,z+$);else if(I==8)B[F]=uD(A.subarray(z,z+$),{out:new r(Z)});else ZA(14,"unknown compression type "+I)}return B}function aD(){return new Promise((A,Q)=>{let B=indexedDB.open("trove-plugins",1);B.onupgradeneeded=()=>{let C=B.result;if(!C.objectStoreNames.contains("installs"))C.createObjectStore("installs",{keyPath:"id"})},B.onsuccess=()=>A(B.result),B.onerror=()=>Q(B.error)})}function kB(A,Q,B){return new Promise((C,J)=>{let K=A.transaction("installs",Q),E=K.objectStore("installs"),L;Promise.resolve(B(E)).then((D)=>L=D),K.oncomplete=()=>C(L),K.onerror=()=>J(K.error)})}var UK=(A)=>new Promise((Q,B)=>{A.onsuccess=()=>Q(A.result),A.onerror=()=>B(A.error)});class lC{constructor(){this._db=null}async#A(){return this._db??=await aD()}async save(A){let Q=await this.#A();return await kB(Q,"readwrite",(B)=>B.put(A)),A}async get(A){let Q=await this.#A();return kB(Q,"readonly",(B)=>UK(B.get(A)))}async list(){let A=await this.#A();return kB(A,"readonly",(Q)=>UK(Q.getAll()))}async remove(A){let Q=await this.#A();await kB(Q,"readwrite",(B)=>B.delete(A))}async patch(A,Q){let B=await this.get(A);if(!B)return null;let C={...B,...Q};return await this.save(C),C}}var yB=null;function rD(){if(!yB)yB=import("./chunk-h05bxfbs.js").then((m)=>sD(m.default,1)).then((A)=>(A.default||A)({locateFile:()=>"/sql-wasm.wasm"})).catch((A)=>{throw yB=null,A});return yB}var tD="trove-plugin-clientdb",hB="dbs";function eD(){return new Promise((A,Q)=>{let B=indexedDB.open(tD,1);B.onupgradeneeded=()=>{let C=B.result;if(!C.objectStoreNames.contains(hB))C.createObjectStore(hB)},B.onsuccess=()=>A(B.result),B.onerror=()=>Q(B.error)})}function dC(A,Q){return eD().then((B)=>new Promise((C,J)=>{let K=B.transaction(hB,A),E;Promise.resolve(Q(K.objectStore(hB))).then((L)=>E=L),K.oncomplete=()=>{B.close(),C(E)},K.onerror=()=>{B.close(),J(K.error)}}))}var AX=(A)=>new Promise((Q,B)=>{A.onsuccess=()=>Q(A.result),A.onerror=()=>B(A.error)}),QX=(A)=>dC("readonly",(Q)=>AX(Q.get(A))),BX=(A,Q)=>dC("readwrite",(B)=>B.put(Q,A)),CX=(A)=>dC("readwrite",(Q)=>Q.delete(A));class FK{constructor(A,Q){this.key=A,this.db=Q,this._saveTimer=null}#A(){clearTimeout(this._saveTimer),this._saveTimer=setTimeout(()=>{this.flush().catch((A)=>{console.error(`persisting plugin storage "${this.key}" failed`,A),this.onError?.(A,this.key)})},150)}async flush(){clearTimeout(this._saveTimer),this._saveTimer=null,await BX(this.key,this.db.export())}async exec(A){return this.db.exec(A),this.#A(),{ok:!0}}async run(A,...Q){return this.db.run(A,Q),this.#A(),{ok:!0}}async get(A,...Q){let B=this.db.prepare(A);try{return B.bind(Q),B.step()?B.getAsObject():null}finally{B.free()}}async all(A,...Q){let B=this.db.prepare(A),C=[];try{B.bind(Q);while(B.step())C.push(B.getAsObject())}finally{B.free()}return C}async batch(A=[]){this.db.run("BEGIN");try{for(let{sql:Q,params:B=[]}of A)this.db.run(Q,B);this.db.run("COMMIT")}catch(Q){try{this.db.run("ROLLBACK")}catch{}throw Q}return this.#A(),{ok:!0}}close(){clearTimeout(this._saveTimer),this.db.close()}}class nC{constructor({onError:A}={}){this._pool=new Map,this.onError=A||null}async obtain(A){let Q=this._pool.get(A);if(!Q){let B=await rD(),C=await QX(A);Q=new FK(A,new B.Database(C||void 0)),Q.onError=this.onError,this._pool.set(A,Q)}return Q}async drop(A){let Q=this._pool.get(A);if(Q)Q.close(),this._pool.delete(A);await CX(A)}}var RK=new TextEncoder;function oC(A){let Q=atob(A.replace(/-/g,"+").replace(/_/g,"/")),B=new Uint8Array(Q.length);for(let C=0;C<Q.length;C++)B[C]=Q.charCodeAt(C);return B}function MK(A){let Q=new Uint8Array(A),B="";for(let C=0;C<Q.length;C++)B+=Q[C].toString(16).padStart(2,"0");return B}async function VK(A){return new Uint8Array(await crypto.subtle.digest("SHA-256",A))}function JX(A){let Q={...A};return delete Q.signature,JSON.stringify(aC(Q))}function aC(A){if(Array.isArray(A))return A.map(aC);if(A&&typeof A==="object"){let Q={};for(let B of Object.keys(A).sort())Q[B]=aC(A[B]);return Q}return A}async function KX(A){let Q=[...A.keys()].filter((E)=>E!=="manifest.json").sort(),B=[];for(let E of Q){let L=A.get(E),D=RK.encode(E),X=new Uint8Array(4);new DataView(X.buffer).setUint32(0,L.length),B.push(D,new Uint8Array([0]),X,L)}let C=B.reduce((E,L)=>E+L.length,0),J=new Uint8Array(C),K=0;for(let E of B)J.set(E,K),K+=E.length;return MK(await VK(J))}async function EX(A){return MK(await VK(oC(A)))}async function LX({manifest:A,files:Q}){if(!A.signature||!A.publicKey)return{signed:!1,valid:!1};let B=await KX(Q);if(A.contentHash&&A.contentHash!==B)return{signed:!0,valid:!1,reason:"File contents do not match the manifest hash"};try{let C=await crypto.subtle.importKey("spki",oC(A.publicKey),{name:"ECDSA",namedCurve:"P-256"},!1,["verify"]);if(!await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},C,oC(A.signature),RK.encode(JX(A))))return{signed:!0,valid:!1,reason:"Signature does not verify"};return{signed:!0,valid:!0,fingerprint:await EX(A.publicKey)}}catch(C){return{signed:!0,valid:!1,reason:"Bad key/signature: "+C.message}}}function YX(A,Q,B){let C=(E)=>(E||"").toLowerCase().replace(/:/g,""),J=C(Q),K=[B.name,`${B.domain}/${B.name}`];for(let E of A?.keys||[]){if(C(E.fingerprint)!==J)continue;if((E.plugins||[]).some((L)=>L==="*"||K.includes(L)))return!0}return!1}async function qK({manifest:A,files:Q},B){let C=await LX({manifest:A,files:Q});if(!C.signed)return{status:"unverified",reason:"Package is not signed"};if(!C.valid)return{status:"invalid",reason:C.reason||"Invalid signature — the package may have been tampered with"};let J=null;try{J=await B(A.domain)}catch{}if(J&&YX(J,C.fingerprint,A))return{status:"verified",domain:A.domain,fingerprint:C.fingerprint};return{status:"signed",domain:A.domain,fingerprint:C.fingerprint,reason:J?"Domain does not list this key":"Could not reach the domain"}}function sC(A){let Q=/^([a-z][a-z0-9+.-]*:\/\/)\*\.(.+)$/i.exec(A),B=!!Q,C;try{C=new URL(B?Q[1]+Q[2]:A)}catch{throw Error(`Invalid network endpoint "${A}" (must be an absolute http(s) URL)`)}if(C.protocol!=="http:"&&C.protocol!=="https:")throw Error(`Network endpoint "${A}" must use http or https`);let J=C.hostname.toLowerCase();if(!J)throw Error(`Network endpoint "${A}" has no host`);return{scheme:C.protocol,host:J,wildcard:B,port:C.port,pathPrefix:C.pathname||"/",raw:A}}function PK(A){let Q=[];for(let B of A||[])try{Q.push(sC(B))}catch{}return Q}function DX(A,Q){let B;try{B=new URL(Q)}catch{return!1}if(B.protocol!==A.scheme)return!1;let C=B.hostname.toLowerCase();if(A.wildcard){if(C!==A.host&&!C.endsWith("."+A.host))return!1}else if(C!==A.host)return!1;if(B.port!==A.port)return!1;return B.pathname.startsWith(A.pathPrefix)}function vB(A,Q){return PK(A).some((B)=>DX(B,Q))}function bB(A){return PK(A).map((Q)=>({scheme:Q.scheme.replace(":",""),host:(Q.wildcard?"*.":"")+Q.host+(Q.port?":"+Q.port:""),path:Q.pathPrefix==="/"?"":Q.pathPrefix,raw:Q.raw}))}var XX={files:"Read your files, folders, and search index (via the host).",storage:"Keep its own SQLite database(s) — on the server and/or on this device.",ui:"Show a popup panel and toasts.",commands:"Add commands to the palette, and run the specific host commands it lists.",opener:"Preview/open file types.",indexer:"Add searchable content to your files.",network:"Connect to the internet — only the endpoints it declares (shown below).",media:"Show playback controls on your lock screen and notifications while it plays media.",dock:"Keep its viewer in a small floating window when you navigate away."},iC=new Set;function NK(A){let Q=tC(A,"storage");if(!Q)return{plugin:!1,domain:!1};if(Q===!0||typeof Q==="object"&&!("plugin"in Q)&&!("domain"in Q))return{plugin:!0,domain:!1};return{plugin:!!Q.plugin,domain:!!Q.domain}}function IX(A){return XX[A]||A}function OK(A){let Q=A&&A.capabilities,B={};if(Array.isArray(Q)){for(let C of Q)if(C)B[C]={}}else if(Q&&typeof Q==="object")for(let[C,J]of Object.entries(Q)){if(J===!1||J==null)continue;B[C]=J===!0?{}:J}return B}function rC(A){return Object.keys(OK(A))}function tC(A,Q){let B=OK(A);return Object.prototype.hasOwnProperty.call(B,Q)?B[Q]:null}function UQ(A){let Q=tC(A,"network");if(Q){if(Array.isArray(Q))return Q;if(Array.isArray(Q.endpoints))return Q.endpoints;if(Array.isArray(Q.prefixes))return Q.prefixes}if(Array.isArray(A.network))return A.network;return[]}function wA(A){let Q=A?.displayName??A?.name;return typeof Q==="string"&&Q.trim()?Q:"Plugin"}function jK(A){let Q=tC(A,"commands");if(!Q)return[];if(Array.isArray(Q))return Q.filter(Boolean);if(Array.isArray(Q.execute))return Q.execute.filter(Boolean);return[]}function fB(A,Q,B){if(!Q)return!1;if(JQ(Q)&&vJ(A,Q))return!0;return jK(A).includes(Q)}function FQ(A){let Q;try{Q=WK(A instanceof Uint8Array?A:new Uint8Array(A))}catch(K){throw Error("Not a valid zip archive: "+K.message)}let B=new Map;for(let[K,E]of Object.entries(Q))if(!K.endsWith("/"))B.set(K.replace(/^\.?\//,""),E);let C=B.get("manifest.json");if(!C)throw Error("Package is missing manifest.json");let J;try{J=JSON.parse(new TextDecoder().decode(C))}catch(K){throw Error("manifest.json is not valid JSON: "+K.message)}return $X(J,B),{manifest:J,files:B,raw:A}}function $X(A,Q){let B=(C,J)=>{if(!C)throw Error(J)};if(zB(A),B(A.entry,"manifest.entry (path to the plugin script) is required"),B(Q.has(A.entry),`entry "${A.entry}" is not in the package`),A.capabilities!=null)B(Array.isArray(A.capabilities)||typeof A.capabilities==="object","capabilities must be an object of { capability: options } (or an array of ids)");if(A.icon)B(Q.has(A.icon),`icon "${A.icon}" is not in the package`);for(let C of nA(A)){if(C.entry)B(Q.has(C.entry),`contribution "${C.name}" points at "${C.entry}", which is not in the package`);if(C.type==="keymap")B(Q.has(C.path),`keymap "${C.name}" points at "${C.path}", which is not in the package`)}for(let C of UQ(A))sC(C)}async function zK(A,Q=globalThis.fetch.bind(globalThis)){let B;try{B=await Q(A)}catch(J){throw Error("Could not fetch the plugin: "+J.message)}if(!B.ok)throw Error(`Could not fetch the plugin (HTTP ${B.status})`);let C=new Uint8Array(await B.arrayBuffer());return FQ(C)}function wK(A,Q){let B=A.manifest,C=nA(B).map((E)=>({kind:E.type,name:E.name,uri:E.uri,title:E.title||E.name,detail:E.type==="opener"||E.type==="indexer"?GX(E.match):E.type==="statusItem"?`${E.slot} of the status bar${E.command?` — runs ${E.command}`:""}`:E.type==="keymap"?E.path:"",offline:!!E.offline})),J=Q?.status==="verified",K=NK(B);return{id:bA(B),name:wA(B),version:B.version||"0.0.0",description:B.description||"",author:B.author||"Unknown",domain:B.domain,capabilities:rC(B).map((E)=>({id:E,description:IX(E),adminOnly:iC.has(E)})),contributions:C,settings:(B.settings||[]).map((E)=>({key:E.key,title:E.title||E.key,type:E.type,secret:!!E.secret})),network:bB(UQ(B)),commands:jK(B),storage:K.plugin||K.domain?{plugin:K.plugin,domain:K.domain,domainBlocked:K.domain&&!J}:null,fileCount:A.files.size,sizeBytes:[...A.files.values()].reduce((E,L)=>E+L.length,0),trust:Q}}function eC(A,Q){let B=NK(A);return{plugin:B.plugin,domain:B.domain&&Q?.status==="verified"}}function GX(A){if(!A)return"";let Q=[];if(A.ext?.length)Q.push(A.ext.join(", "));if(A.mime?.length)Q.push(A.mime.join(", "));return Q.join(" · ")}class A0{constructor(){this.owner=null}#A(){return typeof navigator<"u"?navigator.mediaSession:null}apply(A,Q,B={}){let C=this.#A();if(!C)return{ok:!1};if(A&&Q!=="clear")this.owner=A,A.mediaOwner=!0;try{if(Q==="metadata")C.metadata=typeof MediaMetadata<"u"?new MediaMetadata({title:B.title||"",artist:B.artist||"",album:B.album||"",artwork:B.artwork||[]}):C.metadata;else if(Q==="playbackState")C.playbackState=B.state||"none";else if(Q==="position"&&C.setPositionState)C.setPositionState({duration:B.duration||0,position:B.position||0,playbackRate:B.playbackRate||1});else if(Q==="action"){if(C.setActionHandler?.(B.action,B.on?()=>A?.channel?.emit("media:action",{action:B.action}):null),A)A.mediaActions||=new Set,B.on?A.mediaActions.add(B.action):A.mediaActions.delete(B.action)}else if(Q==="clear"){if(A&&this.owner&&this.owner!==A)return{ok:!0};this.releaseActions(A),C.metadata=null,C.playbackState="none",this.owner=null}}catch{}return{ok:!0}}releaseActions(A){let Q=this.#A();if(!Q||!A?.mediaActions)return;for(let B of A.mediaActions)try{Q.setActionHandler?.(B,null)}catch{}A.mediaActions.clear()}releaseFrame(A){if(this.owner===A)this.owner=null,this.apply(A,"clear",{});this.releaseActions(A)}}class Q0{constructor({destroyFrame:A,openFile:Q,onChange:B}={}){this.destroyFrame=A,this.openFile=Q,this.onChange=B||(()=>{}),this.docked=null,this.el=null}place(A,Q,B,C=""){this.stopPlace(A);let J=A.iframe;J.style.cssText=`position:fixed;border:0;visibility:visible;display:block;background:transparent;z-index:${B};margin:0;padding:0;border-radius:${C};`;let K=()=>{let D=Q.getBoundingClientRect(),X=D.width>0&&D.height>0&&document.contains(Q);J.style.left=`${D.left}px`,J.style.top=`${D.top}px`,J.style.width=`${D.width}px`,J.style.height=`${D.height}px`,J.style.visibility=X?"visible":"hidden"};K();let E=typeof ResizeObserver<"u"?new ResizeObserver(K):null;if(E?.observe(Q),document.body)E?.observe(document.body);let L=typeof IntersectionObserver<"u"?new IntersectionObserver(K,{threshold:[0,1]}):null;L?.observe(Q),window.addEventListener("scroll",K,!0),window.addEventListener("resize",K),A.place={target:Q,stop:()=>{E?.disconnect(),L?.disconnect(),window.removeEventListener("scroll",K,!0),window.removeEventListener("resize",K)}}}stopPlace(A){if(A.place)A.place.stop(),A.place=null}hide(A){this.stopPlace(A),A.iframe.style.cssText="position:fixed;left:0;top:0;width:0;height:0;border:0;visibility:hidden;"}releaseFrame(A){if(this.stopPlace(A),this.docked===A)this.docked=null,this.#A()}#A(){if(this.el)this.el.style.display="none"}dock(A){if(this.docked&&this.docked!==A)this.closeDock(this.docked);let Q=A.dock?.minSize||{width:300,height:90},B=this.#Q();B.style.width=`${SK(Q.width,200,480)}px`,B.style.height=`${SK(Q.height,56,360)+26}px`,B.querySelector(".vd-title").textContent=A.node?.name||(A.record.manifest.displayName||A.record.manifest.name),B.style.display="flex",this.place(A,B.querySelector(".vd-body"),61,"0 0 11px 11px"),this.docked=A,A.channel?.emit("dock:state",{docked:!0}),this.onChange()}undock(A){if(this.#A(),this.docked===A)this.docked=null;A.channel?.emit("dock:state",{docked:!1})}closeDock(A){if(this.#A(),this.docked===A)this.docked=null;A.channel?.emit("dock:state",{docked:!1,closed:!0}),this.destroyFrame?.(A),this.onChange()}#Q(){if(this.el)return this.el;let A=document.createElement("div");return A.className="viewer-dock",A.innerHTML='<div class="vd-bar"><span class="vd-title"></span><button class="vd-expand" title="Reopen">↗</button><button class="vd-close" title="Close">✕</button></div><div class="vd-body"></div>',A.querySelector(".vd-expand").addEventListener("click",()=>{let Q=this.docked;if(Q?.node)this.openFile?.(Q.node,Q.openerId)}),A.querySelector(".vd-close").addEventListener("click",()=>{if(this.docked)this.closeDock(this.docked)}),document.body.appendChild(A),this.el=A,A}}function SK(A,Q,B){return Math.max(Q,Math.min(B,A||Q))}class B0{constructor(A,Q={}){if(this.port=A,this.onCall=Q.onCall,this.onEvent=Q.onEvent,this.targetOrigin=Q.targetOrigin,this.seq=0,this.pending=new Map,this._listener=(B)=>this._receive(B.data,B),typeof A.addEventListener==="function")A.addEventListener("message",this._listener);else A.onmessage=this._listener;A.start?.()}_post(A,Q){if(this.targetOrigin)this.port.postMessage(A,this.targetOrigin,Q);else this.port.postMessage(A,Q)}call(A,Q,{timeout:B=30000,transfer:C}={}){let J=++this.seq;return new Promise((K,E)=>{let L=B?setTimeout(()=>{this.pending.delete(J),E(Error(`RPC timeout: ${A}`))},B):null;this.pending.set(J,{resolve:K,reject:E,timer:L}),this._post({__trove:"req",id:J,method:A,params:Q},C)})}emit(A,Q,B){this._post({__trove:"event",method:A,params:Q},B)}async _receive(A,Q){if(!A||A.__trove==null)return;if(A.__trove==="res"){let B=this.pending.get(A.id);if(!B)return;if(this.pending.delete(A.id),B.timer)clearTimeout(B.timer);if(A.error)B.reject(Object.assign(Error(A.error.message),A.error));else B.resolve(A.result);return}if(A.__trove==="event"){try{await this.onEvent?.(A.method,A.params,Q)}catch(B){console.error("rpc event handler error",B)}return}if(A.__trove==="req"){let B,C;try{B=await this.onCall?.(A.method,A.params,Q)}catch(J){C={message:J?.message||String(J),code:J?.code||"error"}}this._post({__trove:"res",id:A.id,result:B,error:C})}}dispose(){if(typeof this.port.removeEventListener==="function")this.port.removeEventListener("message",this._listener);for(let A of this.pending.values()){if(A.timer)clearTimeout(A.timer);A.reject(Error("RPC channel disposed"))}this.pending.clear(),this.port.close?.()}}var C0=`// Injectable browser build of the Trove plugin SDK — a single self-contained IIFE
5
+ // with NO imports, so the host can inline it into a sandboxed iframe's srcdoc
6
+ // alongside the plugin's entry script. The iframe runs on an opaque origin
7
+ // (sandbox="allow-scripts", no allow-same-origin), so it can't fetch its own
8
+ // package files; instead it reaches everything — resources, files, settings,
9
+ // storage — through the host over a transferred MessagePort. Package resources
10
+ // are handed back as raw bytes (or iframe-local blob: URLs), never host URLs, so
11
+ // the plugin only ever holds opaque handles.
12
+ //
13
+ // Plugins use it as: trove.activate(async (ctx) => { ... })
14
+ (function () {
15
+ 'use strict';
16
+ // Wire-protocol version this SDK speaks. MUST equal PROTOCOL_VERSION in
17
+ // protocol.js — this file is injected as text and cannot import it, so
18
+ // protocol.test.js asserts the two stay in step.
19
+ const SDK_PROTOCOL_VERSION = '1.0';
20
+ let port = null, manifest = null, capabilities = [], storageScopes = {}, online = true, seq = 0, role = 'primary';
21
+ const pending = new Map();
22
+ const commandHandlers = new Map();
23
+ const openerHandlers = new Map();
24
+ let onConnectivity = null, onDeactivate = null, onSettingsChange = null, onDock = null;
25
+ const mediaHandlers = {}; // action -> handler, for OS media-session controls
26
+
27
+ const now = () => { try { return Date.now(); } catch { return 0; } };
28
+
29
+ // The HOST times its own calls out; this side did not, and \`pending\` was never
30
+ // rejected — not on a dropped reply, not on port close. A plugin awaiting one hung
31
+ // forever with no way to find out, and the entry leaked with it.
32
+ const CALL_TIMEOUT_MS = 30_000;
33
+
34
+ function call(method, params, transfer) {
35
+ const id = ++seq;
36
+ return new Promise((resolve, reject) => {
37
+ const timer = setTimeout(() => {
38
+ pending.delete(id);
39
+ reject(new Error(\`Timed out waiting for the host to answer "\${method}"\`));
40
+ }, CALL_TIMEOUT_MS);
41
+ if (timer && timer.unref) timer.unref();
42
+ pending.set(id, { resolve, reject, timer });
43
+ port.postMessage({ __trove: 'req', id, method, params }, transfer || []);
44
+ });
45
+ }
46
+ const emit = (method, params) => port.postMessage({ __trove: 'event', method, params });
47
+
48
+ // What this frame reports about itself on every heartbeat. Contributions are the
49
+ // host's own manifest reading — all the plugin can usefully say is which of its
50
+ // declared contributions it actually bound a handler to, plus whether it thinks
51
+ // it's online.
52
+ function buildManifest() {
53
+ return {
54
+ domain: manifest && manifest.domain, name: manifest && manifest.name,
55
+ online, role, ts: now(),
56
+ handlers: [...commandHandlers.keys()],
57
+ };
58
+ }
59
+ const announce = () => port && emit('manifest', buildManifest());
60
+
61
+ function onPort(e) {
62
+ const m = e.data;
63
+ if (!m || m.__trove == null) return;
64
+ if (m.__trove === 'res') {
65
+ const p = pending.get(m.id);
66
+ if (!p) return;
67
+ clearTimeout(p.timer);
68
+ pending.delete(m.id);
69
+ m.error ? p.reject(Object.assign(new Error(m.error.message), m.error)) : p.resolve(m.result);
70
+ } else if (m.__trove === 'req') {
71
+ Promise.resolve().then(() => dispatch(m.method, m.params))
72
+ .then((result) => port.postMessage({ __trove: 'res', id: m.id, result }))
73
+ .catch((err) => port.postMessage({ __trove: 'res', id: m.id, error: { message: err.message } }));
74
+ } else if (m.__trove === 'event') {
75
+ dispatchEvent(m.method, m.params);
76
+ }
77
+ }
78
+
79
+ function dispatch(method, params) {
80
+ if (method === 'command:execute') {
81
+ const h = commandHandlers.get(params.id);
82
+ // Throw, like \`opener:open\` two lines down. Resolving \`undefined\` for an id with
83
+ // no handler told the host the command had RUN when nothing had.
84
+ if (!h) throw new Error(\`No handler registered for command "\${params.id}"\`);
85
+ return h(...(params.args || []));
86
+ }
87
+ if (method === 'opener:open') {
88
+ // An opener frame boots at that opener's entry module and runs exactly one
89
+ // opener, so an unkeyed onOpen(fn) handler is the normal case.
90
+ const f = openerHandlers.get(params.openerId) || openerHandlers.get('*');
91
+ if (!f) throw new Error('no opener ' + params.openerId);
92
+ return f(params.file, params.context);
93
+ }
94
+ if (method === 'manifest') return buildManifest();
95
+ throw new Error('Unknown host call ' + method);
96
+ }
97
+ async function dispatchEvent(method, params) {
98
+ if (method === 'deactivate') return onDeactivate && onDeactivate();
99
+ if (method === 'connectivity') { online = !!params.online; try { onConnectivity && (await onConnectivity({ online })); } catch (e) { console.error(e); } announce(); }
100
+ if (method === 'settings:changed') { try { onSettingsChange && onSettingsChange(params.key, params.value); } catch (e) { console.error(e); } }
101
+ // The OS/host fired a media transport control (play/pause/next/seek…).
102
+ if (method === 'media:action') { try { mediaHandlers[params.action] && mediaHandlers[params.action](params); } catch (e) { console.error(e); } }
103
+ // The host docked or undocked this viewer (see ctx.dock).
104
+ if (method === 'dock:state') { try { onDock && onDock(params); } catch (e) { console.error(e); } }
105
+ }
106
+
107
+ function requireCap(cap) { if (!capabilities.includes(cap)) throw new Error('Plugin lacks capability "' + cap + '"'); }
108
+
109
+ // Storage: one async SQL handle (mirrors the host SqliteDatabase interface) per
110
+ // scope+side, over RPC. Only granted scopes are exposed on ctx.storage.
111
+ function sqlHandle(scope, side) {
112
+ var send = function (op, extra) { return call('storage:sql', Object.assign({ scope: scope, side: side, op: op }, extra)); };
113
+ return {
114
+ exec: function (sql) { return send('exec', { sql: sql }); },
115
+ run: function (sql) { return send('run', { sql: sql, params: [].slice.call(arguments, 1) }); },
116
+ get: function (sql) { return send('get', { sql: sql, params: [].slice.call(arguments, 1) }); },
117
+ all: function (sql) { return send('all', { sql: sql, params: [].slice.call(arguments, 1) }); },
118
+ batch: function (statements) { return send('batch', { statements: statements }); },
119
+ };
120
+ }
121
+ function scopeHandle(scope) {
122
+ return { server: sqlHandle(scope, 'server'), client: sqlHandle(scope, 'client') };
123
+ }
124
+ function makeStorage() {
125
+ var s = {};
126
+ if (storageScopes.plugin) s.plugin = scopeHandle('plugin');
127
+ if (storageScopes.domain) s.domain = scopeHandle('domain');
128
+ return s;
129
+ }
130
+
131
+ function hasHeader(h, name) { name = name.toLowerCase(); for (var k in h) if (k.toLowerCase() === name) return true; return false; }
132
+ // Wrap the host's brokered-fetch result in a minimal Response-like object.
133
+ function makeResponse(r) {
134
+ var bytes = new Uint8Array(r.bytes || new ArrayBuffer(0));
135
+ var decode = function () { return new TextDecoder().decode(bytes); };
136
+ return {
137
+ ok: r.ok, status: r.status, statusText: r.statusText, url: r.url, headers: r.headers || {},
138
+ arrayBuffer: function () { return Promise.resolve(bytes.slice().buffer); },
139
+ bytes: function () { return Promise.resolve(bytes); },
140
+ text: function () { return Promise.resolve(decode()); },
141
+ json: function () { return Promise.resolve(JSON.parse(decode())); },
142
+ };
143
+ }
144
+
145
+ function makeContext() {
146
+ return {
147
+ manifest, capabilities,
148
+ // Which instance this is: 'primary' is the plugin's single background frame
149
+ // (register commands/indexers, do one-time setup here); 'viewer' is a
150
+ // per-open frame hosting an opener for one file (drive media/dock from here).
151
+ role,
152
+ get online() { return online; },
153
+ // Contributions are DECLARED IN THE MANIFEST (openers, indexers, commands,
154
+ // statusItems, keybindings). The host registers them before this code runs, so
155
+ // a plugin never registers anything at runtime — it only supplies the behaviour
156
+ // for what it declared, addressed by id.
157
+ commands: {
158
+ /** Implement a command this plugin's manifest declares, by its short name. */
159
+ handle(name, handler) { commandHandlers.set(name, handler); return this; },
160
+ /**
161
+ * Run a command. Its OWN commands by short name; anyone else's by full address
162
+ * (a built-in like 'explorer.download', or a \`trove+contrib:\` URI) — and only
163
+ * if the manifest's \`commands\` capability lists it.
164
+ */
165
+ execute(id) { const a = [].slice.call(arguments, 1); return call('command:execute', { id, args: a }); },
166
+ },
167
+ /** Implement the opener this frame was booted for (its entry module). The id is
168
+ * optional — an opener frame runs exactly one opener. */
169
+ onOpen(idOrHandler, maybeHandler) {
170
+ const [id, handler] = typeof idOrHandler === 'function' ? ['*', idOrHandler] : [idOrHandler, maybeHandler];
171
+ openerHandlers.set(id, handler);
172
+ return this;
173
+ },
174
+ // NOTE: there is no onIndex(). Indexers run on the SERVER (in its isolate
175
+ // runtime), not in this sandbox — indexing has to happen once per upload for the
176
+ // drive, not in whichever tab is open. An indexer's entry module is plain ESM
177
+ // exporting \`index(node, ctx)\`; it doesn't use this SDK at all. What a plugin can
178
+ // do from here is PUSH contributions for a node via ctx.files.index (the
179
+ // \`indexer\` capability).
180
+ // Package resources — opaque handles. read() copies bytes into the iframe;
181
+ // url() wraps them in an iframe-local blob: URL.
182
+ resources: {
183
+ list() { return call('resources:list', {}); },
184
+ async read(path) { const r = await call('resources:read', { path }); return new Uint8Array(r.bytes); },
185
+ async text(path) { return new TextDecoder().decode(await this.read(path)); },
186
+ async url(path, type) {
187
+ const bytes = await this.read(path);
188
+ return URL.createObjectURL(new Blob([bytes], { type: type || 'application/octet-stream' }));
189
+ },
190
+ },
191
+ ui: {
192
+ toast: (text, opts) => emit('ui:toast', Object.assign({ text }, opts)),
193
+ showPanel: () => call('ui:showPanel', {}),
194
+ setBadge: (text) => emit('ui:badge', { text }),
195
+ /**
196
+ * Drive a status-bar slot this plugin's manifest declares. \`html\` is sanitized
197
+ * by the host down to a small inline-formatting allowlist before it renders.
198
+ * ctx.ui.status('sync').set('<b>3</b> queued')
199
+ * ctx.ui.status('sync').hide()
200
+ */
201
+ status(name) {
202
+ return {
203
+ set: (html, opts) => call('ui:status', Object.assign({ name, html, visible: true }, opts || {})),
204
+ show: () => call('ui:status', { name, visible: true }),
205
+ hide: () => call('ui:status', { name, visible: false }),
206
+ };
207
+ },
208
+ },
209
+ /**
210
+ * Registers — context value slots this plugin's manifest declares, which
211
+ * when-clauses (its own keymap's, its commands') read by contribution URI.
212
+ * ctx.registers.set('busy', true)
213
+ */
214
+ registers: {
215
+ set: (name, value) => call('context:setRegister', { name, value }),
216
+ },
217
+ // Media session — surfaces this viewer's playback to the OS (lock-screen /
218
+ // notification transport controls, so phones can play/pause/seek). The host
219
+ // owns navigator.mediaSession; action handlers are called back over RPC.
220
+ media: {
221
+ setMetadata: (m) => (requireCap('media'), call('media:metadata', m || {})),
222
+ setPlaybackState: (state) => (requireCap('media'), call('media:playbackState', { state })),
223
+ setPositionState: (p) => (requireCap('media'), call('media:position', p || {})),
224
+ setActionHandler: (action, handler) => { requireCap('media'); if (handler) mediaHandlers[action] = handler; else delete mediaHandlers[action]; return call('media:action', { action, on: !!handler }); },
225
+ clear: () => call('media:clear', {}),
226
+ },
227
+ // Dock — register this viewer to persist as a small floating frame when the
228
+ // user navigates away (a docked video = picture-in-picture; docked audio = a
229
+ // mini transport). Enable while playing/active, disable otherwise. \`minSize\`/
230
+ // \`maxSize\` are {width,height} constraints. onDock is notified on (un)dock.
231
+ dock: {
232
+ enable: (opts) => (requireCap('dock'), call('dock:enable', opts || {})),
233
+ disable: () => (requireCap('dock'), call('dock:disable', {})),
234
+ close: () => call('dock:close', {}),
235
+ onChange: (fn) => { onDock = fn; },
236
+ },
237
+ // Network — there is no direct fetch in the sandbox; the host performs the
238
+ // request, but ONLY to endpoints declared in the manifest's \`network\` list
239
+ // (and only with the "network" capability). Returns a Response-like object.
240
+ net: {
241
+ fetch(url, opts) {
242
+ requireCap('network');
243
+ opts = opts || {};
244
+ var body = opts.body;
245
+ var headers = Object.assign({}, opts.headers);
246
+ if (body && typeof body === 'object' && !(body instanceof ArrayBuffer) && !(body instanceof Uint8Array)) {
247
+ body = JSON.stringify(body);
248
+ if (!hasHeader(headers, 'content-type')) headers['Content-Type'] = 'application/json';
249
+ }
250
+ // \`.buffer\` ignores byteOffset/byteLength, so any view produced by \`subarray\` or
251
+ // \`slice\` — or a view into a pooled buffer — sent the WHOLE backing store: the wrong
252
+ // payload, and an out-of-band leak of whatever else was in it.
253
+ if (ArrayBuffer.isView(body)) {
254
+ body = body.buffer.slice(body.byteOffset, body.byteOffset + body.byteLength);
255
+ }
256
+ return call('net:fetch', { url: String(url), method: opts.method || 'GET', headers: headers, body: body })
257
+ .then(makeResponse);
258
+ },
259
+ },
260
+ files: {
261
+ read: (id, opts) => (requireCap('files'), call('files:read', Object.assign({ id }, opts))),
262
+ list: (pathOrId, opts) => (requireCap('files'), call('files:list', Object.assign({ pathOrId }, opts))),
263
+ stat: (id) => (requireCap('files'), call('files:stat', { id })),
264
+ downloadUrl: (id) => (requireCap('files'), call('files:downloadUrl', { id })),
265
+ // index(indexerId, nodeId, contribution) where contribution is
266
+ // { semanticTexts?, tags?, metadata? }. Legacy (indexerId, nodeId, documents[], facet)
267
+ // is still accepted when the 3rd arg is an array of documents.
268
+ index: (indexerId, nodeId, contribution, facet) => {
269
+ requireCap('indexer');
270
+ var payload = Array.isArray(contribution) ? { documents: contribution, facet: facet } : (contribution || {});
271
+ return call('files:index', Object.assign({ indexerId: indexerId, nodeId: nodeId }, payload));
272
+ },
273
+ },
274
+ // Persistent storage: an isolated SQLite database per granted scope. \`plugin\`
275
+ // is private to this plugin; \`domain\` (verified packages only) is shared with
276
+ // the vendor's other plugins. Each scope exposes a \`.server\` handle (and, from
277
+ // Stage 3, an on-device \`.client\` handle) with the same async SQL surface.
278
+ storage: makeStorage(),
279
+ // The plugin's own settings (declared in the manifest). getSecret reads a
280
+ // secret-typed value the host stores separately.
281
+ settings: {
282
+ get: (key) => call('settings:get', { key }),
283
+ getSecret: (key) => call('settings:getSecret', { key }),
284
+ set: (key, value) => call('settings:set', { key, value }),
285
+ onChange: (fn) => { onSettingsChange = fn; },
286
+ },
287
+ onConnectivity: (fn) => { onConnectivity = fn; },
288
+ announce,
289
+ onDeactivate: (fn) => { onDeactivate = fn; },
290
+ };
291
+ }
292
+
293
+ async function activate(setup) {
294
+ await new Promise((resolve) => {
295
+ function onInit(e) {
296
+ if (!e.data || e.data.__trove !== 'init') return;
297
+ window.removeEventListener('message', onInit);
298
+ manifest = e.data.manifest; capabilities = e.data.capabilities || []; storageScopes = e.data.storage || {}; online = e.data.online != null ? e.data.online : true; role = e.data.role || 'primary';
299
+ port = e.ports[0];
300
+ port.onmessage = onPort;
301
+ resolve();
302
+ }
303
+ window.addEventListener('message', onInit);
304
+ parent.postMessage({ __trove: 'ready', protocolVersion: SDK_PROTOCOL_VERSION }, '*');
305
+ });
306
+ const ctx = makeContext();
307
+ try {
308
+ await setup(ctx);
309
+ await call('activated', { ok: true });
310
+ announce();
311
+ } catch (err) {
312
+ await call('activated', { ok: false, error: err && err.message });
313
+ throw err;
314
+ }
315
+ return ctx;
316
+ }
317
+
318
+ globalThis.trove = { activate };
319
+ })();
320
+ `;var J0="1.0";function _K(A){return String(A||"").split(".")[0]||"0"}function TK(A){if(!A)return!0;return _K(A)===_K("1.0")}var xK;(function(A){A[A.Static=1]="Static",A[A.Dynamic=2]="Dynamic",A[A.ImportMeta=3]="ImportMeta",A[A.StaticSourcePhase=4]="StaticSourcePhase",A[A.DynamicSourcePhase=5]="DynamicSourcePhase",A[A.StaticDeferPhase=6]="StaticDeferPhase",A[A.DynamicDeferPhase=7]="DynamicDeferPhase"})(xK||(xK={}));var ZX=new Uint8Array(new Uint16Array([1]).buffer)[0]===1;function K0(A,Q="@"){if(!c)return E0.then(()=>K0(A));let B=A.length+1,C=(c.__heap_base.value||c.__heap_base)+4*B-c.memory.buffer.byteLength;C>0&&c.memory.grow(Math.ceil(C/65536));let J=c.sa(B-1);if((ZX?UX:WX)(A,new Uint16Array(c.memory.buffer,J,B)),!c.parse())throw Object.assign(Error(`Parse error ${Q}:${A.slice(0,c.e()).split(`
321
+ `).length}:${c.e()-A.lastIndexOf(`
322
+ `,c.e()-1)}`),{idx:c.e()});let K=[],E=[];for(;c.ri();){let D=c.is(),X=c.ie(),Y=c.it(),I=c.ai(),$=c.id(),Z=c.ss(),F=c.se(),R;c.ip()&&(R=L(A.slice($===-1?D-1:D,$===-1?X+1:X))),K.push({n:R,t:Y,s:D,e:X,ss:Z,se:F,d:$,a:I})}for(;c.re();){let D=c.es(),X=c.ee(),Y=c.els(),I=c.ele(),$=A.slice(D,X),Z=$[0],F=Y<0?void 0:A.slice(Y,I),R=F?F[0]:"";E.push({s:D,e:X,ls:Y,le:I,n:Z==='"'||Z==="'"?L($):$,ln:R==='"'||R==="'"?L(F):F})}function L(D){try{return(0,eval)(D)}catch(X){}}return[K,E,!!c.f(),!!c.ms()]}function WX(A,Q){let B=A.length,C=0;for(;C<B;){let J=A.charCodeAt(C);Q[C++]=(255&J)<<8|J>>>8}}function UX(A,Q){let B=A.length,C=0;for(;C<B;)Q[C]=A.charCodeAt(C++)}var c,FX=()=>{return A="AGFzbQEAAAABKwhgAX8Bf2AEf39/fwBgAAF/YAAAYAF/AGADf39/AX9gAn9/AX9gA39/fwADMTAAAQECAgICAgICAgICAgICAgICAgIAAwMDBAQAAAUAAAAAAAMDAwAGAAAABwAGAgUEBQFwAQEBBQMBAAEGDwJ/AUHA8gALfwBBwPIACwd6FQZtZW1vcnkCAAJzYQAAAWUAAwJpcwAEAmllAAUCc3MABgJzZQAHAml0AAgCYWkACQJpZAAKAmlwAAsCZXMADAJlZQANA2VscwAOA2VsZQAPAnJpABACcmUAEQFmABICbXMAEwVwYXJzZQAUC19faGVhcF9iYXNlAwEKzkQwaAEBf0EAIAA2AoAKQQAoAtwJIgEgAEEBdGoiAEEAOwEAQQAgAEECaiIANgKECkEAIAA2AogKQQBBADYC4AlBAEEANgLwCUEAQQA2AugJQQBBADYC5AlBAEEANgL4CUEAQQA2AuwJIAEL0wEBA39BACgC8AkhBEEAQQAoAogKIgU2AvAJQQAgBDYC9AlBACAFQSRqNgKICiAEQSBqQeAJIAQbIAU2AgBBACgC1AkhBEEAKALQCSEGIAUgATYCACAFIAA2AgggBSACIAJBAmpBACAGIANGIgAbIAQgA0YiBBs2AgwgBSADNgIUIAVBADYCECAFIAI2AgQgBUEANgIgIAVBA0EBQQIgABsgBBs2AhwgBUEAKALQCSADRiICOgAYAkACQCACDQBBACgC1AkgA0cNAQtBAEEBOgCMCgsLXgEBf0EAKAL4CSIEQRBqQeQJIAQbQQAoAogKIgQ2AgBBACAENgL4CUEAIARBFGo2AogKQQBBAToAjAogBEEANgIQIAQgAzYCDCAEIAI2AgggBCABNgIEIAQgADYCAAsIAEEAKAKQCgsVAEEAKALoCSgCAEEAKALcCWtBAXULHgEBf0EAKALoCSgCBCIAQQAoAtwJa0EBdUF/IAAbCxUAQQAoAugJKAIIQQAoAtwJa0EBdQseAQF/QQAoAugJKAIMIgBBACgC3AlrQQF1QX8gABsLCwBBACgC6AkoAhwLHgEBf0EAKALoCSgCECIAQQAoAtwJa0EBdUF/IAAbCzsBAX8CQEEAKALoCSgCFCIAQQAoAtAJRw0AQX8PCwJAIABBACgC1AlHDQBBfg8LIABBACgC3AlrQQF1CwsAQQAoAugJLQAYCxUAQQAoAuwJKAIAQQAoAtwJa0EBdQsVAEEAKALsCSgCBEEAKALcCWtBAXULHgEBf0EAKALsCSgCCCIAQQAoAtwJa0EBdUF/IAAbCx4BAX9BACgC7AkoAgwiAEEAKALcCWtBAXVBfyAAGwslAQF/QQBBACgC6AkiAEEgakHgCSAAGygCACIANgLoCSAAQQBHCyUBAX9BAEEAKALsCSIAQRBqQeQJIAAbKAIAIgA2AuwJIABBAEcLCABBAC0AlAoLCABBAC0AjAoL3Q0BBX8jAEGA0ABrIgAkAEEAQQE6AJQKQQBBACgC2Ak2ApwKQQBBACgC3AlBfmoiATYCsApBACABQQAoAoAKQQF0aiICNgK0CkEAQQA6AIwKQQBBADsBlgpBAEEAOwGYCkEAQQA6AKAKQQBBADYCkApBAEEAOgD8CUEAIABBgBBqNgKkCkEAIAA2AqgKQQBBADoArAoCQAJAAkACQANAQQAgAUECaiIDNgKwCiABIAJPDQECQCADLwEAIgJBd2pBBUkNAAJAAkACQAJAAkAgAkGbf2oOBQEICAgCAAsgAkEgRg0EIAJBL0YNAyACQTtGDQIMBwtBAC8BmAoNASADEBVFDQEgAUEEakGCCEEKEC8NARAWQQAtAJQKDQFBAEEAKAKwCiIBNgKcCgwHCyADEBVFDQAgAUEEakGMCEEKEC8NABAXC0EAQQAoArAKNgKcCgwBCwJAIAEvAQQiA0EqRg0AIANBL0cNBBAYDAELQQEQGQtBACgCtAohAkEAKAKwCiEBDAALC0EAIQIgAyEBQQAtAPwJDQIMAQtBACABNgKwCkEAQQA6AJQKCwNAQQAgAUECaiIDNgKwCgJAAkACQAJAAkACQAJAIAFBACgCtApPDQAgAy8BACICQXdqQQVJDQYCQAJAAkACQAJAAkACQAJAAkACQCACQWBqDgoQDwYPDw8PBQECAAsCQAJAAkACQCACQaB/ag4KCxISAxIBEhISAgALIAJBhX9qDgMFEQYJC0EALwGYCg0QIAMQFUUNECABQQRqQYIIQQoQLw0QEBYMEAsgAxAVRQ0PIAFBBGpBjAhBChAvDQ8QFwwPCyADEBVFDQ4gASkABELsgISDsI7AOVINDiABLwEMIgNBd2oiAUEXSw0MQQEgAXRBn4CABHFFDQwMDQtBAEEALwGYCiIBQQFqOwGYCkEAKAKkCiABQQN0aiIBQQE2AgAgAUEAKAKcCjYCBAwNC0EALwGYCiIDRQ0JQQAgA0F/aiIDOwGYCkEALwGWCiICRQ0MQQAoAqQKIANB//8DcUEDdGooAgBBBUcNDAJAIAJBAnRBACgCqApqQXxqKAIAIgMoAgQNACADQQAoApwKQQJqNgIEC0EAIAJBf2o7AZYKIAMgAUEEajYCDAwMCwJAQQAoApwKIgEvAQBBKUcNAEEAKALwCSIDRQ0AIAMoAgQgAUcNAEEAQQAoAvQJIgM2AvAJAkAgA0UNACADQQA2AiAMAQtBAEEANgLgCQtBAEEALwGYCiIDQQFqOwGYCkEAKAKkCiADQQN0aiIDQQZBAkEALQCsChs2AgAgAyABNgIEQQBBADoArAoMCwtBAC8BmAoiAUUNB0EAIAFBf2oiATsBmApBACgCpAogAUH//wNxQQN0aigCAEEERg0EDAoLQScQGgwJC0EiEBoMCAsgAkEvRw0HAkACQCABLwEEIgFBKkYNACABQS9HDQEQGAwKC0EBEBkMCQsCQAJAAkACQEEAKAKcCiIBLwEAIgMQG0UNAAJAAkAgA0FVag4EAAkBAwkLIAFBfmovAQBBK0YNAwwICyABQX5qLwEAQS1GDQIMBwsgA0EpRw0BQQAoAqQKQQAvAZgKIgJBA3RqKAIEEBxFDQIMBgsgAUF+ai8BAEFQakH//wNxQQpPDQULQQAvAZgKIQILAkACQCACQf//A3EiAkUNACADQeYARw0AQQAoAqQKIAJBf2pBA3RqIgQoAgBBAUcNACABQX5qLwEAQe8ARw0BIAQoAgRBlghBAxAdRQ0BDAULIANB/QBHDQBBACgCpAogAkEDdGoiAigCBBAeDQQgAigCAEEGRg0ECyABEB8NAyADRQ0DIANBL0ZBAC0AoApBAEdxDQMCQEEAKAL4CSICRQ0AIAEgAigCAEkNACABIAIoAgRNDQQLIAFBfmohAUEAKALcCSECAkADQCABQQJqIgQgAk0NAUEAIAE2ApwKIAEvAQAhAyABQX5qIgQhASADECBFDQALIARBAmohBAsCQCADQf//A3EQIUUNACAEQX5qIQECQANAIAFBAmoiAyACTQ0BQQAgATYCnAogAS8BACEDIAFBfmoiBCEBIAMQIQ0ACyAEQQJqIQMLIAMQIg0EC0EAQQE6AKAKDAcLQQAoAqQKQQAvAZgKIgFBA3QiA2pBACgCnAo2AgRBACABQQFqOwGYCkEAKAKkCiADakEDNgIACxAjDAULQQAtAPwJQQAvAZYKQQAvAZgKcnJFIQIMBwsQJEEAQQA6AKAKDAMLECVBACECDAULIANBoAFHDQELQQBBAToArAoLQQBBACgCsAo2ApwKC0EAKAKwCiEBDAALCyAAQYDQAGokACACCxoAAkBBACgC3AkgAEcNAEEBDwsgAEF+ahAmC/4KAQZ/QQBBACgCsAoiAEEMaiIBNgKwCkEAKAL4CSECQQEQKSEDAkACQAJAAkACQAJAAkACQAJAQQAoArAKIgQgAUcNACADEChFDQELAkACQAJAAkACQAJAAkAgA0EqRg0AIANB+wBHDQFBACAEQQJqNgKwCkEBECkhA0EAKAKwCiEEA0ACQAJAIANB//8DcSIDQSJGDQAgA0EnRg0AIAMQLBpBACgCsAohAwwBCyADEBpBAEEAKAKwCkECaiIDNgKwCgtBARApGgJAIAQgAxAtIgNBLEcNAEEAQQAoArAKQQJqNgKwCkEBECkhAwsgA0H9AEYNA0EAKAKwCiIFIARGDQ8gBSEEIAVBACgCtApNDQAMDwsLQQAgBEECajYCsApBARApGkEAKAKwCiIDIAMQLRoMAgtBAEEAOgCUCgJAAkACQAJAAkACQCADQZ9/ag4MAgsEAQsDCwsLCwsFAAsgA0H2AEYNBAwKC0EAIARBDmoiAzYCsAoCQAJAAkBBARApQZ9/ag4GABICEhIBEgtBACgCsAoiBSkAAkLzgOSD4I3AMVINESAFLwEKECFFDRFBACAFQQpqNgKwCkEAECkaC0EAKAKwCiIFQQJqQbIIQQ4QLw0QIAUvARAiAkF3aiIBQRdLDQ1BASABdEGfgIAEcUUNDQwOC0EAKAKwCiIFKQACQuyAhIOwjsA5Ug0PIAUvAQoiAkF3aiIBQRdNDQYMCgtBACAEQQpqNgKwCkEAECkaQQAoArAKIQQLQQAgBEEQajYCsAoCQEEBECkiBEEqRw0AQQBBACgCsApBAmo2ArAKQQEQKSEEC0EAKAKwCiEDIAQQLBogA0EAKAKwCiIEIAMgBBACQQBBACgCsApBfmo2ArAKDwsCQCAEKQACQuyAhIOwjsA5Ug0AIAQvAQoQIEUNAEEAIARBCmo2ArAKQQEQKSEEQQAoArAKIQMgBBAsGiADQQAoArAKIgQgAyAEEAJBAEEAKAKwCkF+ajYCsAoPC0EAIARBBGoiBDYCsAoLQQAgBEEGajYCsApBAEEAOgCUCkEBECkhBEEAKAKwCiEDIAQQLCEEQQAoArAKIQIgBEHf/wNxIgFB2wBHDQNBACACQQJqNgKwCkEBECkhBUEAKAKwCiEDQQAhBAwEC0EAQQE6AIwKQQBBACgCsApBAmo2ArAKC0EBECkhBEEAKAKwCiEDAkAgBEHmAEcNACADQQJqQawIQQYQLw0AQQAgA0EIajYCsAogAEEBEClBABArIAJBEGpB5AkgAhshAwNAIAMoAgAiA0UNBSADQgA3AgggA0EQaiEDDAALC0EAIANBfmo2ArAKDAMLQQEgAXRBn4CABHFFDQMMBAtBASEECwNAAkACQCAEDgIAAQELIAVB//8DcRAsGkEBIQQMAQsCQAJAQQAoArAKIgQgA0YNACADIAQgAyAEEAJBARApIQQCQCABQdsARw0AIARBIHJB/QBGDQQLQQAoArAKIQMCQCAEQSxHDQBBACADQQJqNgKwCkEBECkhBUEAKAKwCiEDIAVBIHJB+wBHDQILQQAgA0F+ajYCsAoLIAFB2wBHDQJBACACQX5qNgKwCg8LQQAhBAwACwsPCyACQaABRg0AIAJB+wBHDQQLQQAgBUEKajYCsApBARApIgVB+wBGDQMMAgsCQCACQVhqDgMBAwEACyACQaABRw0CC0EAIAVBEGo2ArAKAkBBARApIgVBKkcNAEEAQQAoArAKQQJqNgKwCkEBECkhBQsgBUEoRg0BC0EAKAKwCiEBIAUQLBpBACgCsAoiBSABTQ0AIAQgAyABIAUQAkEAQQAoArAKQX5qNgKwCg8LIAQgA0EAQQAQAkEAIARBDGo2ArAKDwsQJQuFDAEKf0EAQQAoArAKIgBBDGoiATYCsApBARApIQJBACgCsAohAwJAAkACQAJAAkACQAJAAkAgAkEuRw0AQQAgA0ECajYCsAoCQEEBECkiAkHkAEYNAAJAIAJB8wBGDQAgAkHtAEcNB0EAKAKwCiICQQJqQZwIQQYQLw0HAkBBACgCnAoiAxAqDQAgAy8BAEEuRg0ICyAAIAAgAkEIakEAKALUCRABDwtBACgCsAoiAkECakGiCEEKEC8NBgJAQQAoApwKIgMQKg0AIAMvAQBBLkYNBwtBACEEQQAgAkEMajYCsApBASEFQQUhBkEBECkhAkEAIQdBASEIDAILQQAoArAKIgIpAAJC5YCYg9CMgDlSDQUCQEEAKAKcCiIDECoNACADLwEAQS5GDQYLQQAhBEEAIAJBCmo2ArAKQQIhCEEHIQZBASEHQQEQKSECQQEhBQwBCwJAAkACQAJAIAJB8wBHDQAgAyABTQ0AIANBAmpBoghBChAvDQACQCADLwEMIgRBd2oiB0EXSw0AQQEgB3RBn4CABHENAgsgBEGgAUYNAQtBACEHQQchBkEBIQQgAkHkAEYNAQwCC0EAIQRBACADQQxqIgI2ArAKQQEhBUEBECkhCQJAQQAoArAKIgYgAkYNAEHmACECAkAgCUHmAEYNAEEFIQZBACEHQQEhCCAJIQIMBAtBACEHQQEhCCAGQQJqQawIQQYQLw0EIAYvAQgQIEUNBAtBACEHQQAgAzYCsApBByEGQQEhBEEAIQVBACEIIAkhAgwCCyADIABBCmpNDQBBACEIQeQAIQICQCADKQACQuWAmIPQjIA5Ug0AAkACQCADLwEKIgRBd2oiB0EXSw0AQQEgB3RBn4CABHENAQtBACEIIARBoAFHDQELQQAhBUEAIANBCmo2ArAKQSohAkEBIQdBAiEIQQEQKSIJQSpGDQRBACADNgKwCkEBIQRBACEHQQAhCCAJIQIMAgsgAyEGQQAhBwwCC0EAIQVBACEICwJAIAJBKEcNAEEAKAKkCkEALwGYCiICQQN0aiIDQQAoArAKNgIEQQAgAkEBajsBmAogA0EFNgIAQQAoApwKLwEAQS5GDQRBAEEAKAKwCiIDQQJqNgKwCkEBECkhAiAAQQAoArAKQQAgAxABAkACQCAFDQBBACgC8AkhAQwBC0EAKALwCSIBIAY2AhwLQQBBAC8BlgoiA0EBajsBlgpBACgCqAogA0ECdGogATYCAAJAIAJBIkYNACACQSdGDQBBAEEAKAKwCkF+ajYCsAoPCyACEBpBAEEAKAKwCkECaiICNgKwCgJAAkACQEEBEClBV2oOBAECAgACC0EAQQAoArAKQQJqNgKwCkEBECkaQQAoAvAJIgMgAjYCBCADQQE6ABggA0EAKAKwCiICNgIQQQAgAkF+ajYCsAoPC0EAKALwCSIDIAI2AgQgA0EBOgAYQQBBAC8BmApBf2o7AZgKIANBACgCsApBAmo2AgxBAEEALwGWCkF/ajsBlgoPC0EAQQAoArAKQX5qNgKwCg8LAkAgBEEBcyACQfsAR3INAEEAKAKwCiECQQAvAZgKDQUDQAJAAkACQCACQQAoArQKTw0AQQEQKSICQSJGDQEgAkEnRg0BIAJB/QBHDQJBAEEAKAKwCkECajYCsAoLQQEQKSEDQQAoArAKIQICQCADQeYARw0AIAJBAmpBrAhBBhAvDQcLQQAgAkEIajYCsAoCQEEBECkiAkEiRg0AIAJBJ0cNBwsgACACQQAQKw8LIAIQGgtBAEEAKAKwCkECaiICNgKwCgwACwsCQAJAIAJBWWoOBAMBAQMACyACQSJGDQILQQAoArAKIQYLIAYgAUcNAEEAIABBCmo2ArAKDwsgAkEqRyAHcQ0DQQAvAZgKQf//A3ENA0EAKAKwCiECQQAoArQKIQEDQCACIAFPDQECQAJAIAIvAQAiA0EnRg0AIANBIkcNAQsgACADIAgQKw8LQQAgAkECaiICNgKwCgwACwsQJQsPC0EAIAJBfmo2ArAKDwtBAEEAKAKwCkF+ajYCsAoLRwEDf0EAKAKwCkECaiEAQQAoArQKIQECQANAIAAiAkF+aiABTw0BIAJBAmohACACLwEAQXZqDgQBAAABAAsLQQAgAjYCsAoLmAEBA39BAEEAKAKwCiIBQQJqNgKwCiABQQZqIQFBACgCtAohAgNAAkACQAJAIAFBfGogAk8NACABQX5qLwEAIQMCQAJAIAANACADQSpGDQEgA0F2ag4EAgQEAgQLIANBKkcNAwsgAS8BAEEvRw0CQQAgAUF+ajYCsAoMAQsgAUF+aiEBC0EAIAE2ArAKDwsgAUECaiEBDAALC4gBAQR/QQAoArAKIQFBACgCtAohAgJAAkADQCABIgNBAmohASADIAJPDQEgAS8BACIEIABGDQICQCAEQdwARg0AIARBdmoOBAIBAQIBCyADQQRqIQEgAy8BBEENRw0AIANBBmogASADLwEGQQpGGyEBDAALC0EAIAE2ArAKECUPC0EAIAE2ArAKC2wBAX8CQAJAIABBX2oiAUEFSw0AQQEgAXRBMXENAQsgAEFGakH//wNxQQZJDQAgAEEpRyAAQVhqQf//A3FBB0lxDQACQCAAQaV/ag4EAQAAAQALIABB/QBHIABBhX9qQf//A3FBBElxDwtBAQsuAQF/QQEhAQJAIABBpglBBRAdDQAgAEGWCEEDEB0NACAAQbAJQQIQHSEBCyABC0YBA39BACEDAkAgACACQQF0IgJrIgRBAmoiAEEAKALcCSIFSQ0AIAAgASACEC8NAAJAIAAgBUcNAEEBDwsgBBAmIQMLIAMLgwEBAn9BASEBAkACQAJAAkACQAJAIAAvAQAiAkFFag4EBQQEAQALAkAgAkGbf2oOBAMEBAIACyACQSlGDQQgAkH5AEcNAyAAQX5qQbwJQQYQHQ8LIABBfmovAQBBPUYPCyAAQX5qQbQJQQQQHQ8LIABBfmpByAlBAxAdDwtBACEBCyABC7QDAQJ/QQAhAQJAAkACQAJAAkACQAJAAkACQAJAIAAvAQBBnH9qDhQAAQIJCQkJAwkJBAUJCQYJBwkJCAkLAkACQCAAQX5qLwEAQZd/ag4EAAoKAQoLIABBfGpByghBAhAdDwsgAEF8akHOCEEDEB0PCwJAAkACQCAAQX5qLwEAQY1/ag4DAAECCgsCQCAAQXxqLwEAIgJB4QBGDQAgAkHsAEcNCiAAQXpqQeUAECcPCyAAQXpqQeMAECcPCyAAQXxqQdQIQQQQHQ8LIABBfGpB3AhBBhAdDwsgAEF+ai8BAEHvAEcNBiAAQXxqLwEAQeUARw0GAkAgAEF6ai8BACICQfAARg0AIAJB4wBHDQcgAEF4akHoCEEGEB0PCyAAQXhqQfQIQQIQHQ8LIABBfmpB+AhBBBAdDwtBASEBIABBfmoiAEHpABAnDQQgAEGACUEFEB0PCyAAQX5qQeQAECcPCyAAQX5qQYoJQQcQHQ8LIABBfmpBmAlBBBAdDwsCQCAAQX5qLwEAIgJB7wBGDQAgAkHlAEcNASAAQXxqQe4AECcPCyAAQXxqQaAJQQMQHSEBCyABCzQBAX9BASEBAkAgAEF3akH//wNxQQVJDQAgAEGAAXJBoAFGDQAgAEEuRyAAEChxIQELIAELMAEBfwJAAkAgAEF3aiIBQRdLDQBBASABdEGNgIAEcQ0BCyAAQaABRg0AQQAPC0EBC04BAn9BACEBAkACQCAALwEAIgJB5QBGDQAgAkHrAEcNASAAQX5qQfgIQQQQHQ8LIABBfmovAQBB9QBHDQAgAEF8akHcCEEGEB0hAQsgAQveAQEEf0EAKAKwCiEAQQAoArQKIQECQAJAAkADQCAAIgJBAmohACACIAFPDQECQAJAAkAgAC8BACIDQaR/ag4FAgMDAwEACyADQSRHDQIgAi8BBEH7AEcNAkEAIAJBBGoiADYCsApBAEEALwGYCiICQQFqOwGYCkEAKAKkCiACQQN0aiICQQQ2AgAgAiAANgIEDwtBACAANgKwCkEAQQAvAZgKQX9qIgA7AZgKQQAoAqQKIABB//8DcUEDdGooAgBBA0cNAwwECyACQQRqIQAMAAsLQQAgADYCsAoLECULC3ABAn8CQAJAA0BBAEEAKAKwCiIAQQJqIgE2ArAKIABBACgCtApPDQECQAJAAkAgAS8BACIBQaV/ag4CAQIACwJAIAFBdmoOBAQDAwQACyABQS9HDQIMBAsQLhoMAQtBACAAQQRqNgKwCgwACwsQJQsLNQEBf0EAQQE6APwJQQAoArAKIQBBAEEAKAK0CkECajYCsApBACAAQQAoAtwJa0EBdTYCkAoLQwECf0EBIQECQCAALwEAIgJBd2pB//8DcUEFSQ0AIAJBgAFyQaABRg0AQQAhASACEChFDQAgAkEuRyAAECpyDwsgAQs9AQJ/QQAhAgJAQQAoAtwJIgMgAEsNACAALwEAIAFHDQACQCADIABHDQBBAQ8LIABBfmovAQAQICECCyACC2gBAn9BASEBAkACQCAAQV9qIgJBBUsNAEEBIAJ0QTFxDQELIABB+P8DcUEoRg0AIABBRmpB//8DcUEGSQ0AAkAgAEGlf2oiAkEDSw0AIAJBAUcNAQsgAEGFf2pB//8DcUEESSEBCyABC5wBAQN/QQAoArAKIQECQANAAkACQCABLwEAIgJBL0cNAAJAIAEvAQIiAUEqRg0AIAFBL0cNBBAYDAILIAAQGQwBCwJAAkAgAEUNACACQXdqIgFBF0sNAUEBIAF0QZ+AgARxRQ0BDAILIAIQIUUNAwwBCyACQaABRw0CC0EAQQAoArAKIgNBAmoiATYCsAogA0EAKAK0CkkNAAsLIAILMQEBf0EAIQECQCAALwEAQS5HDQAgAEF+ai8BAEEuRw0AIABBfGovAQBBLkYhAQsgAQumBAEBfwJAIAFBIkYNACABQSdGDQAQJQ8LQQAoArAKIQMgARAaIAAgA0ECakEAKAKwCkEAKALQCRABAkAgAkEBSA0AQQAoAvAJQQRBBiACQQFGGzYCHAtBAEEAKAKwCkECajYCsAoCQAJAAkACQEEAECkiAUHhAEYNACABQfcARg0BQQAoArAKIQEMAgtBACgCsAoiAUECakHACEEKEC8NAUEGIQIMAgtBACgCsAoiAS8BAkHpAEcNACABLwEEQfQARw0AQQQhAiABLwEGQegARg0BC0EAIAFBfmo2ArAKDwtBACABIAJBAXRqNgKwCgJAQQEQKUH7AEYNAEEAIAE2ArAKDwtBACgCsAoiACECA0BBACACQQJqNgKwCgJAAkACQEEBECkiAkEiRg0AIAJBJ0cNAUEnEBpBAEEAKAKwCkECajYCsApBARApIQIMAgtBIhAaQQBBACgCsApBAmo2ArAKQQEQKSECDAELIAIQLCECCwJAIAJBOkYNAEEAIAE2ArAKDwtBAEEAKAKwCkECajYCsAoCQEEBECkiAkEiRg0AIAJBJ0YNAEEAIAE2ArAKDwsgAhAaQQBBACgCsApBAmo2ArAKAkACQEEBECkiAkEsRg0AIAJB/QBGDQFBACABNgKwCg8LQQBBACgCsApBAmo2ArAKQQEQKUH9AEYNAEEAKAKwCiECDAELC0EAKALwCSIBIAA2AhAgAUEAKAKwCkECajYCDAttAQJ/AkACQANAAkAgAEH//wNxIgFBd2oiAkEXSw0AQQEgAnRBn4CABHENAgsgAUGgAUYNASAAIQIgARAoDQJBACECQQBBACgCsAoiAEECajYCsAogAC8BAiIADQAMAgsLIAAhAgsgAkH//wNxC6sBAQR/AkACQEEAKAKwCiICLwEAIgNB4QBGDQAgASEEIAAhBQwBC0EAIAJBBGo2ArAKQQEQKSECQQAoArAKIQUCQAJAIAJBIkYNACACQSdGDQAgAhAsGkEAKAKwCiEEDAELIAIQGkEAQQAoArAKQQJqIgQ2ArAKC0EBECkhA0EAKAKwCiECCwJAIAIgBUYNACAFIARBACAAIAAgAUYiAhtBACABIAIbEAILIAMLcgEEf0EAKAKwCiEAQQAoArQKIQECQAJAA0AgAEECaiECIAAgAU8NAQJAAkAgAi8BACIDQaR/ag4CAQQACyACIQAgA0F2ag4EAgEBAgELIABBBGohAAwACwtBACACNgKwChAlQQAPC0EAIAI2ArAKQd0AC0kBA39BACEDAkAgAkUNAAJAA0AgAC0AACIEIAEtAAAiBUcNASABQQFqIQEgAEEBaiEAIAJBf2oiAg0ADAILCyAEIAVrIQMLIAMLC+wBAgBBgAgLzgEAAHgAcABvAHIAdABtAHAAbwByAHQAZgBvAHIAZQB0AGEAbwB1AHIAYwBlAHIAbwBtAHUAbgBjAHQAaQBvAG4AcwBzAGUAcgB0AHYAbwB5AGkAZQBkAGUAbABlAGMAbwBuAHQAaQBuAGkAbgBzAHQAYQBuAHQAeQBiAHIAZQBhAHIAZQB0AHUAcgBkAGUAYgB1AGcAZwBlAGEAdwBhAGkAdABoAHIAdwBoAGkAbABlAGkAZgBjAGEAdABjAGYAaQBuAGEAbABsAGUAbABzAABB0AkLEAEAAAACAAAAAAQAAEA5AAA=",typeof Buffer<"u"?Buffer.from(A,"base64"):Uint8Array.from(atob(A),(Q)=>Q.charCodeAt(0));var A},E0=WebAssembly.compile(FX()).then(WebAssembly.instantiate).then(({exports:A})=>{c=A});var RX=/\.m?js$/i;function uB(A){return/^src\//i.test(A)&&RX.test(A)}function gK(A){return uB(A.entry||"")}function MX(A){let Q=A.lastIndexOf("/");return(Q<0?"":A.slice(0,Q)).split("/").filter(Boolean)}function VX(A,Q){let B=MX(A);for(let C of Q.split("/"))if(C===""||C===".")continue;else if(C==="..")B.pop();else B.push(C);return B.join("/")}async function kK(A){await E0;let Q={};for(let[K,E]of A.files)if(uB(K))Q[K]=new TextDecoder().decode(E);let B=(K)=>Object.prototype.hasOwnProperty.call(Q,K),C=(K,E)=>{let L=VX(K,E);if(B(L))return L;if(B(L+".js"))return L+".js";if(B(L+".mjs"))return L+".mjs";if(B(L+"/index.js"))return L+"/index.js";return L},J={};for(let[K,E]of Object.entries(Q))J[K]=qX(E,K,C);return{modules:J,entry:A.manifest.entry}}function qX(A,Q,B){let[C]=K0(A),J="",K=0;for(let E of C){if(E.n==null)continue;if(E.n[0]!==".")continue;let L="trove:/"+B(Q,E.n),D=E.d===-1?L:JSON.stringify(L);J+=A.slice(K,E.s)+D,K=E.e}return J+A.slice(K)}var PX=15000;class L0{constructor({media:A,dock:Q}={}){this.media=A,this.dock=Q}async spawn(A,Q,B){let C=document.createElement("iframe");C.style.cssText=NX,C.setAttribute("sandbox","allow-scripts allow-forms"),C.setAttribute("referrerpolicy","no-referrer");let J=B?.entry;if(J)A._entrySrcdoc||={},A._entrySrcdoc[J]||=await yK({...A.manifest,entry:J},A.files),C.srcdoc=A._entrySrcdoc[J];else A._srcdoc||=await yK(A.manifest,A.files),C.srcdoc=A._srcdoc;let K={role:Q,iframe:C,channel:null,record:A,place:null,dock:null,mediaActions:null};document.body.appendChild(C);try{await this.#A(A,K,B)}catch(E){try{K.channel?.dispose()}catch{}throw C.remove(),E}return K}#A(A,Q,{onCall:B,onEvent:C,online:J}){return new Promise((K,E)=>{let{iframe:L}=Q,D=A.manifest,X=!1,Y=0,I=()=>{if(window.removeEventListener("message",Z),Y)clearTimeout(Y)},$=(F)=>{if(X)return;X=!0,I(),E(Error(F))},Z=(F)=>{if(F.source!==L.contentWindow)return;if(F.data?.__trove==="boot-error")return $(F.data.error||"Plugin failed to load its modules");if(F.data?.__trove!=="ready")return;if(!TK(F.data.protocolVersion))return $(`Plugin speaks protocol ${F.data.protocolVersion}, this host speaks ${J0}`);window.removeEventListener("message",Z);let R=new MessageChannel;Q.channel=new B0(R.port1,{onCall:(P,z)=>B(A,P,z,Q),onEvent:(P,z)=>C(A,P,z,Q)}),Q.resolveActivated=(P)=>{if(X)return;if(X=!0,Y)clearTimeout(Y);K(P)},Q.rejectActivated=(P)=>{if(X)return;if(X=!0,Y)clearTimeout(Y);E(P)},L.contentWindow.postMessage({__trove:"init",manifest:D,capabilities:A.grants,storage:A.storage,online:J,role:Q.role,protocolVersion:J0},"*",[R.port2])};Y=setTimeout(()=>$("Plugin handshake timed out"),PX),window.addEventListener("message",Z),L.addEventListener("error",()=>$("Failed to load plugin iframe"))})}destroy(A){if(!A)return;this.dock?.releaseFrame(A),this.media?.releaseFrame(A);try{A.channel?.emit("deactivate")}catch{}try{A.channel?.dispose()}catch{}A.iframe.remove(),A.record?.frames?.delete(A)}}var NX="position:fixed;left:0;top:0;width:0;height:0;border:0;visibility:hidden;",OX=["default-src 'none'","script-src 'unsafe-inline' 'unsafe-eval' blob:","style-src 'unsafe-inline'","img-src blob: data:","media-src blob: data:","font-src 'none'","connect-src 'none'","base-uri 'none'","form-action 'none'"].join("; "),vK=`<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="${OX}"></head><body>`;async function yK(A,Q){if(gK(A))return jX(await kK({manifest:A,files:Q}));let B=new TextDecoder().decode(Q.get(A.entry)??new Uint8Array);return`${vK}
323
+ <script>${C0}</script>
324
+ <script>${B}</script>
325
+ </body></html>`}function hK(A){return JSON.stringify(A).replace(/</g,"\\u003c").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}function jX(A){let Q=hK("trove:/"+A.entry);return`${vK}
326
+ <script>${C0}</script>
327
+ <script id="__trove_src" type="application/json">${hK(A.modules)}</script>
328
+ <script>
329
+ (function () {
330
+ var src = JSON.parse(document.getElementById('__trove_src').textContent);
331
+ var imports = {};
332
+ for (var p in src) imports['trove:/' + p] = URL.createObjectURL(new Blob([src[p] + '\\n//# sourceURL=trove:/' + p], { type: 'text/javascript' }));
333
+ imports['trove'] = URL.createObjectURL(new Blob(['export const activate = globalThis.trove.activate;\\nexport default globalThis.trove;'], { type: 'text/javascript' }));
334
+ var im = document.createElement('script');
335
+ im.type = 'importmap';
336
+ im.textContent = JSON.stringify({ imports: imports });
337
+ document.head.appendChild(im);
338
+ import(${Q}).catch(function (e) {
339
+ try { parent.postMessage({ __trove: 'boot-error', error: String((e && e.message) || e) }, '*'); } catch (_) {}
340
+ });
341
+ })();
342
+ </script>
343
+ </body></html>`}var zX=/\b(ATTACH|DETACH|VACUUM|PRAGMA)\b/i;function wX(A){let Q="",B=0;while(B<A.length){let C=A[B];if(C==="-"&&A[B+1]==="-"){let J=A.indexOf(`
344
+ `,B);B=J<0?A.length:J;continue}if(C==="/"&&A[B+1]==="*"){let J=A.indexOf("*/",B+2);B=J<0?A.length:J+2,Q+=" ";continue}if(C==="'"||C==='"'||C==="`"){let J=C;B++;while(B<A.length){if(A[B]===J){if(A[B+1]===J){B+=2;continue}B++;break}B++}Q+=" ";continue}if(C==="["){let J=A.indexOf("]",B);B=J<0?A.length:J+1,Q+=" ";continue}Q+=C,B++}return Q}function Y0(A){if(typeof A!=="string"||!A)throw V.invalid("SQL statement is required");if(zX.test(wX(A)))throw V.invalid("ATTACH, DETACH, VACUUM and PRAGMA are not permitted in plugin storage")}var SX=26214400;async function _X(A,Q){let B=Number(A.headers.get("content-length")||0);if(B&&B>Q)throw Error("Response too large");let C=A.body?.getReader?.();if(!C){let D=await A.arrayBuffer();if(D.byteLength>Q)throw Error("Response too large");return D}let J=[],K=0;for(;;){let{done:D,value:X}=await C.read();if(D)break;if(K+=X.byteLength,K>Q)throw await C.cancel().catch(()=>{}),Error("Response too large");J.push(X)}let E=new Uint8Array(K),L=0;for(let D of J)E.set(D,L),L+=D.byteLength;return E.buffer}class D0{constructor({platform:A,clientDb:Q,media:B,dock:C,onChange:J}={}){this.platform=A,this.clientDb=Q,this.media=B,this.dock=C,this.onChange=J||(()=>{})}async hostCall(A,Q,B,C){let J=(E)=>{if(!A.grants.includes(E))throw Error(`Capability "${E}" not granted`)},K=A.id;switch(Q){case"activated":{let E=C||A.frame;if(clearTimeout(E?._timer),B.ok)E?.resolveActivated?.(E);else E?.rejectActivated?.(Error(B.error||"activate() failed"));return{ok:!0}}case"command:execute":{let E=this.#A(A,B.id);if(!fB(A.manifest,E))throw Error(`Command "${B.id}" is not in this plugin's declared commands`);return{ok:!0,result:await this.platform.commands.execute(E,...B.args||[])??null}}case"ui:status":{J("ui");let E=this.#Q(A,B.name,"statusItem");return this.platform.contributions.update(E.uri,{...B.html!==void 0?{html:String(B.html??"")}:{},...B.tooltip!==void 0?{tooltip:String(B.tooltip??"")}:{},...B.visible!==void 0?{visible:!!B.visible}:{visible:!0}}),{ok:!0}}case"context:setRegister":{let E=this.#Q(A,B.name,"register");return this.platform.context.set(E.uri,B.value),{ok:!0}}case"resources:list":return[...A.files.keys()].filter(fK);case"resources:read":{if(!fK(B.path))throw Error(`No such resource ${B.path}`);let E=A.files.get(B.path);if(!E)throw Error(`No such resource ${B.path}`);return{bytes:E.slice().buffer}}case"files:read":return J("files"),{text:await this.platform.api.readText(B.id)};case"files:list":return J("files"),this.platform.api.list(B.collection||B.pathOrId,{sort:B.sort,order:B.order,limit:B.limit,cursor:B.cursor});case"files:stat":return J("files"),this.platform.api.stat(B.id);case"files:downloadUrl":return J("files"),{url:this.platform.api.downloadUrl(B.id)};case"files:index":{J("indexer");let E=JQ(B.indexerId)?B.indexerId:CQ(A.manifest,B.indexerId||"default");return this.platform.api.pushIndex(E,B.nodeId,{semanticTexts:B.semanticTexts,tags:B.tags,metadata:B.metadata,documents:B.documents,facet:B.facet})}case"net:fetch":return J("network"),this.#C(A,B);case"storage:sql":return J("storage"),this.#J(A,B);case"settings:get":return this.platform.settings.get(`${K}.${B.key}`);case"settings:getSecret":return A.secrets?.[B.key]??null;case"settings:set":return this.platform.settings.set(`${K}.${B.key}`,B.value),{ok:!0};case"ui:showPanel":return J("ui"),A.hasUi=!0,this.platform.openPluginPanel?.(K),this.onChange(),{ok:!0};case"media:metadata":{J("media");let E=(B.artwork||[]).filter((L)=>this.#B(A,L?.src));return this.media.apply(C,"metadata",{...B,artwork:E})}case"media:playbackState":return J("media"),this.media.apply(C,"playbackState",B);case"media:position":return J("media"),this.media.apply(C,"position",B);case"media:action":return J("media"),this.media.apply(C,"action",B);case"media:clear":return this.media.apply(C,"clear",B);case"dock:enable":if(J("dock"),C)C.dock={enabled:!0,minSize:B.minSize,maxSize:B.maxSize,dismissed:!1};return{ok:!0};case"dock:disable":if(J("dock"),C?.dock)C.dock.enabled=!1;if(C&&this.dock.docked===C)this.dock.closeDock(C);return{ok:!0};case"dock:close":if(C)this.dock.closeDock(C);return{ok:!0};default:throw Error(`Unknown host method ${Q}`)}}hostEvent(A,Q,B,C){switch(Q){case"manifest":if(C&&C.role!=="primary")break;A.live=B,A.responsive=!0,this.onChange();break;case"ui:toast":this.platform.notifications[B.level||"info"](`${wA(A.manifest)}: ${B.text}`);break;case"ui:badge":A.badge=B.text,this.onChange();break}}#A(A,Q){if(!Q||JQ(Q))return Q;let B=this.platform.contributions.get(CQ(A.manifest,Q));return B?.type==="command"?B.uri:Q}#Q(A,Q,B){let C=Q?this.platform.contributions.get(CQ(A.manifest,Q)):null;if(!C||C.pluginId!==A.id||C.type!==B)throw Error(`"${Q}" is not a ${B} declared by this plugin`);return C}#B(A,Q){if(!Q)return!1;if(/^(blob:|data:image\/)/i.test(Q))return!0;return vB(UQ(A.manifest),Q)}async#C(A,{url:Q,method:B="GET",headers:C,body:J}){let K=UQ(A.manifest);if(bK(Q,this.platform.api?.baseUrl))throw Error("Blocked: a plugin may not call the drive's own API through the network broker");if(!vB(K,Q))throw Error(`Blocked: "${Q}" is not one of this plugin's declared network endpoints`);let E={method:B,credentials:"omit",redirect:"follow",headers:xX(C)};if(J!=null&&B!=="GET"&&B!=="HEAD")E.body=J instanceof ArrayBuffer?new Uint8Array(J):J;let L=await fetch(Q,E);if(L.url&&L.url!==Q){if(bK(L.url,this.platform.api?.baseUrl))throw Error("Blocked: request redirected onto the drive's own API");if(!vB(K,L.url))throw Error(`Blocked: request redirected off this plugin's declared endpoints (${L.url})`)}let D=await _X(L,SX),X={};return L.headers.forEach((Y,I)=>{X[I]=Y}),{ok:L.ok,status:L.status,statusText:L.statusText,url:L.url,headers:X,bytes:D}}async#J(A,{scope:Q="plugin",side:B="server",op:C,sql:J,params:K=[],statements:E}){if(!A.storage?.[Q])throw Error(`Storage scope "${Q}" not granted${Q==="domain"?" (needs a verified domain)":""}`);if(B==="client"){if(C==="batch")for(let I of Array.isArray(E)?E:[])Y0(I?.sql);else Y0(J);let X=Q==="domain"?`dom:${A.manifest.domain}`:`plg:${A.id}`,Y=await this.clientDb.obtain(X);return gX(Y,C,J,K,E)}let L={scope:Q,op:C,sql:J,params:K,statements:E,domain:Q==="domain"?A.manifest.domain:void 0};return(await this.platform.api.request("POST",`/api/plugins/${encodeURIComponent(A.id)}/sql`,{body:L})).result}}function bK(A,Q){try{let B=new URL(Q||"",globalThis.location?.href||"http://localhost/");return new URL(A,B).origin===B.origin}catch{return!1}}function fK(A){return A!=="manifest.json"&&!uB(A)}var TX=new Set(["host","cookie","cookie2","set-cookie","origin","referer","content-length","connection"]);function xX(A){let Q={};for(let[B,C]of Object.entries(A||{}))if(!TX.has(String(B).toLowerCase()))Q[B]=C;return Q}function gX(A,Q,B,C=[],J){switch(Q){case"exec":return A.exec(B);case"run":return A.run(B,...C);case"get":return A.get(B,...C);case"all":return A.all(B,...C);case"batch":return A.batch(J);default:throw Error(`Unknown storage op "${Q}"`)}}var uK=["files","storage","ui","commands","indexer","opener","network","media","dock"];class X0{constructor(A,{heartbeatMs:Q=20000}={}){this.platform=A,this.plugins=new Map,this.registry=new lC,this.clientDb=new nC({onError:(B,C)=>this.platform.notifications.error(`A plugin's on-device data couldn't be saved (${C}): ${B.message}`)}),this.online=typeof navigator<"u"?navigator.onLine:!0,this.heartbeatMs=Q,this._heartbeat=null,this._probing=!1,this.cell=A.reactive.cell([]),this.media=new A0,this.dock=new Q0({destroyFrame:(B)=>this.frames.destroy(B),openFile:(B,C)=>this.platform.workbench.openFile(B,C),onChange:()=>this.#A()}),this.frames=new L0({media:this.media,dock:this.dock}),this.rpc=new D0({platform:A,clientDb:this.clientDb,media:this.media,dock:this.dock,onChange:()=>this.#A()})}observe(){return this.cell}#A(){this.cell.setValue(this.list())}#Q(A,Q,B){return this.frames.spawn(A,Q,{onCall:(C,J,K,E)=>this.rpc.hostCall(C,J,K,E),onEvent:(C,J,K,E)=>this.rpc.hostEvent(C,J,K,E),online:this.online,entry:B})}#B(A){let Q=A.id,B=this.platform.contributions,C=(K)=>A.disposers.push(K),J=wA(A.manifest);for(let K of nA(A.manifest)){let E={...K,pluginId:Q};switch(K.type){case"opener":if(A.grants.includes("opener"))C(B.register(K.uri,E));break;case"command":C(this.platform.commands.register({id:K.uri,title:K.title||`${J}: ${K.name}`,category:K.category||J,icon:K.icon,when:K.when,offline:K.offline,palette:K.palette,pluginId:Q,handler:(...L)=>A.channel?.call("command:execute",{id:K.name,args:L})}));break;case"statusItem":{let L=K.command?this.#J(A,K.command,J,`status item “${K.name}”`):null;C(B.register(K.uri,{...E,command:L,html:"",visible:!1}));break}case"register":C(B.register(K.uri,E)),this.platform.context.set(K.uri,K.default),C(()=>this.platform.context.remove(K.uri));break;case"keymap":{let L=A.files.get(K.path);if(!L){this.platform.notifications.warn(`Plugin "${J}": keymap file "${K.path}" is not in the package.`);break}try{let D=this.#C(A,uJ(new TextDecoder().decode(L)),J);C(B.register(K.uri,{...E,bindings:D}))}catch(D){this.platform.notifications.warn(`Plugin "${J}": ${D.message}`)}break}case"indexer":break}}}#C(A,Q,B){let C=[];for(let J of Q){let K=this.#J(A,J.command,B,`shortcut ${J.key}`);if(K)C.push({...J,command:K})}return C}#J(A,Q,B,C){let J=CQ(A.manifest,Q);if(nA(A.manifest).some((E)=>E.uri===J&&E.type==="command"))return J;if(!fB(A.manifest,Q))return this.platform.notifications.warn(`Plugin "${B}": ${C} runs "${Q}", which it isn't allowed to run — ignored.`),null;return Q}list(){return[...this.plugins.values()].map((A)=>({id:A.id,name:wA(A.manifest),version:A.manifest.version,status:A.status,capabilities:A.grants,error:A.error||null,hasUi:A.hasUi,badge:A.badge||null,trust:A.trust||null,settingsSchema:A.manifest.settings||[],endpoints:bB(UQ(A.manifest)),responsive:!!A.responsive,manifest:A.live||null,features:this.#K(A)}))}#K(A){let Q;try{Q=nA(A.manifest)}catch{return[]}return Q.map((B)=>({kind:B.type,id:B.uri,name:B.name,title:B.title||B.name,offline:!!B.offline,available:this.#E(A,B)}))}#E(A,Q){if(A.status!=="active"||!A.responsive)return!1;return this.online||!!Q.offline}isAvailable(A){if(!A?.pluginId)return!0;let Q=this.plugins.get(A.pluginId);if(!Q)return!1;return this.#E(Q,A)}canGrant(A,Q){return!iC.has(A)||!!Q}async install(A,{grants:Q,trust:B}={}){let C=bA(A.manifest),J=rC(A.manifest),K=(Q||J).filter((X)=>uK.includes(X)&&J.includes(X)),E=hX(A.manifest,K)?"account":"device";if(E==="account"){if(!A.raw)throw Error("Package bytes unavailable for a server install");await this.platform.api.installPlugin(A.raw,K)}let L=K.includes("storage")?eC(A.manifest,B):{plugin:!1,domain:!1},D={id:C,manifest:A.manifest,files:Object.fromEntries([...A.files.entries()]),grants:K,storage:L,trust:B||null,scope:E,settings:{},secrets:{},installedAt:Date.now()};return await this.registry.save(D),this.#Y(D),await this.#D(D),this.plugins.get(C)}async restore(){let A=[];try{A=await this.registry.list()}catch{}for(let Q of A)try{this.#Y(Q),this.#D(Q).catch((B)=>console.error("restore plugin failed",Q.id,B))}catch(B){console.error("skipping corrupt plugin record",Q?.id,B),this.platform.notifications.warn(`Couldn't restore plugin "${Q?.manifest?wA(Q.manifest):Q?.id||"unknown"}" — its saved data looks corrupt.`)}this.#L(A).catch(()=>{})}async#L(A){let Q;try{Q=(await this.platform.api.installedPlugins()).plugins||[]}catch{return}let B=new Set(Q.map((L)=>L.pluginId)),C=new Set(A.map((L)=>L.id)),J=0,K=0,E=0;for(let L of A){if(L.scope!=="account"||B.has(L.id))continue;try{await this.platform.api.installPlugin(ZK(yX(L.files)),L.grants||[])}catch(D){console.error("re-upload plugin failed",L.id,D),J++}}for(let L of Q){if(C.has(L.pluginId))continue;try{let D=FQ(await this.platform.api.pluginPackage(L.pluginId)),X=L.grants||[],Y={id:L.pluginId,manifest:D.manifest,files:Object.fromEntries([...D.files.entries()]),grants:X,storage:X.includes("storage")?{plugin:!0,domain:!!L.sharedStorage}:{plugin:!1,domain:!1},trust:null,scope:"account",settings:{},secrets:{},installedAt:L.createdAt||Date.now()};await this.registry.save(Y),this.#Y(Y),await this.#D(Y),K++}catch(D){console.error("sync plugin failed",L.pluginId,D),E++}}if(K)this.platform.notifications.info(`Synced ${K} account plugin${K>1?"s":""} from the server.`);if(J||E){let L=[];if(E)L.push(`${E} couldn't be downloaded`);if(J)L.push(`${J} couldn't be uploaded`);this.platform.notifications.warn(`Some account plugins didn't sync: ${L.join(", ")}.`)}}#Y(A){let Q=(A.manifest.settings||[]).filter((B)=>!B.secret);if(Q.length)A._settingsDispose=this.platform.settings.scopedFor(A.id).register(Q.map((B)=>({...B,category:wA(A.manifest)})))}async#D(A){if(this.plugins.get(A.id)?.status==="active")return;let Q={...A,iframe:null,status:"loading",error:null,disposers:[],channel:null,hasUi:!1,responsive:!1,frame:null,frames:new Set,storage:A.storage||(A.grants?.includes("storage")?eC(A.manifest,A.trust):{plugin:!1,domain:!1}),files:kX(A.files)};this.plugins.set(A.id,Q);try{this.#B(Q)}catch(B){console.error("registering contributions failed",A.id,B)}this.#A();try{let B=await this.#Q(Q,"primary");if(this.plugins.get(A.id)!==Q)return this.frames.destroy(B),Q;Q.frame=B,Q.iframe=B.iframe,Q.channel=B.channel,Q.status="active",Q.responsive=!0,this.#I(Q).then(()=>this.#A()),this.#X()}catch(B){Q.status="error",Q.error=B?.message||String(B),this.platform.notifications.error(`Plugin "${wA(A.manifest)}" failed to load: ${Q.error}`)}return this.#A(),Q}async setSecret(A,Q,B){let C=await this.registry.get(A);if(!C)return;C.secrets={...C.secrets,[Q]:B},await this.registry.save(C);let J=this.plugins.get(A);if(J)J.secrets=C.secrets;J?.channel?.emit("settings:changed",{key:Q,value:"••••"})}async getSecret(A,Q){return(await this.registry.get(A))?.secrets?.[Q]??""}#X(){if(this._heartbeat||!this.heartbeatMs)return;if(this._heartbeat=setInterval(()=>this.#H(),this.heartbeatMs),this._heartbeat?.unref)this._heartbeat.unref()}#$(){if(this._heartbeat)clearInterval(this._heartbeat);this._heartbeat=null}async#H(){if(this._probing)return;this._probing=!0;try{let A=!1;for(let Q of this.plugins.values())if(Q.status==="active")A=await this.#I(Q)||A;if(A)this.#A()}finally{this._probing=!1}}setHeartbeat(A){if(this.heartbeatMs=A,this.#$(),A&&[...this.plugins.values()].some((Q)=>Q.status==="active"))this.#X()}async#I(A){if(A.status!=="active"||!A.channel)return!1;let Q={responsive:A.responsive,sig:mK(A.live)};try{A.live=await A.channel.call("manifest",{},{timeout:4000}),A.responsive=!0}catch{A.responsive=!1}return Q.responsive!==A.responsive||Q.sig!==mK(A.live)}async setOnline(A){if(this.online===A)return;this.online=A,await Promise.all([...this.plugins.values()].filter((Q)=>Q.status==="active").map(async(Q)=>{try{Q.channel?.emit("connectivity",{online:A})}catch{}for(let B of Q.frames||[])try{B.channel?.emit("connectivity",{online:A})}catch{}await this.#I(Q)})),this.#A()}async refresh(A){let Q=this.plugins.get(A);if(Q)await this.#I(Q),this.#A()}mountPanel(A,Q,{width:B=380,height:C=480}={}){let J=this.plugins.get(A);if(!J?.frame)return null;return Q.style.width=`${B}px`,Q.style.height=`${C}px`,this.dock.place(J.frame,Q,50),J.hasUi=!0,()=>this.dock.hide(J.frame)}mountViewer(A,Q,B,C,J={}){let K=this.plugins.get(A);if(!K)return J.onError?.("Plugin is not available"),null;let E=this.dock.docked;if(E&&E.record===K&&E.node?.id===B.id&&E.openerId===C)return this.dock.undock(E),this.dock.place(E,Q,3),J.onReady?.(),()=>this.#G(E);let L=this.platform.contributions.get(C),D={cancelled:!1,frame:null};return this.#Q(K,"viewer",L?.entry).then(async(X)=>{if(D.cancelled){this.frames.destroy(X);return}D.frame=X,X.node=B,X.openerId=C,K.frames.add(X),this.dock.place(X,Q,3);try{if(await X.channel?.call("opener:open",{openerId:C,file:B,context:{}}),!D.cancelled)J.onReady?.()}catch(Y){if(!D.cancelled)J.onError?.(Y?.message||"Failed to open")}}).catch((X)=>{if(console.error("viewer frame failed to load",X),!D.cancelled)J.onError?.(X?.message||"This viewer failed to load")}),K.hasUi=!0,()=>{if(D.cancelled=!0,D.frame)this.#G(D.frame)}}#G(A){if(A.dock?.enabled&&!A.dock.dismissed)this.dock.dock(A);else this.frames.destroy(A)}async uninstall(A,{wipeData:Q=!0}={}){let B=this.plugins.get(A),C=B?.manifest?wA(B.manifest):A,J=B?.scope==="account"||(await this.registry.get(A).catch(()=>null))?.scope==="account";if(Q&&J)try{await this.platform.api.uninstallPluginServer(A)}catch(L){this.platform.notifications.error(`Couldn't uninstall "${C}" from the server: ${L.message}. It's still installed.`);return}if(B){try{B.channel?.emit("deactivate")}catch{}for(let L of B.disposers)try{L()}catch{}B._settingsDispose?.();for(let L of[...B.frames||[]])this.frames.destroy(L);if(B.frame)this.dock.stopPlace(B.frame),this.media.releaseActions(B.frame);B.channel?.dispose(),B.iframe?.remove(),this.plugins.delete(A)}let K=[];if(Q){if(!J)await this.platform.api.request("DELETE",`/api/plugins/${encodeURIComponent(A)}/data`).catch(()=>K.push("server-side data"));await this.clientDb.drop(`plg:${A}`).catch(()=>K.push("on-device data"))}let E=!1;try{await this.registry.remove(A)}catch(L){E=!0,console.error("removing the persisted plugin record failed",A,L)}if(![...this.plugins.values()].some((L)=>L.status==="active"))this.#$();if(this.#A(),E)this.platform.notifications.error(`Removed "${C}", but its saved record couldn't be deleted — it may come back when you reload.`);else if(K.length)this.platform.notifications.warn(`Uninstalled "${C}", but couldn't clear its ${K.join(" and ")}.`)}fetchAssetlinks=async(A)=>{return(await this.platform.api.request("GET","/api/plugins/assetlinks",{query:{domain:A}}))?.assetlinks||null};assessTrust(A){return qK(A,this.fetchAssetlinks)}}function kX(A){let Q=new Map;for(let[B,C]of Object.entries(A))Q.set(B,C instanceof Uint8Array?C:new Uint8Array(C));return Q}function yX(A){let Q={};for(let[B,C]of Object.entries(A||{}))Q[B]=C instanceof Uint8Array?C:new Uint8Array(C);return Q}function hX(A,Q){if(Q.includes("storage"))return!0;return WC(A).length>0}function mK(A){if(!A)return"";return`${A.online?1:0}|${[...A.handlers||[]].sort().join(",")}`}class I0{constructor(A){this.context=A,this.state={palette:null,dialog:null,contextMenu:null,pluginPanel:null},this.cell=u(this.state)}observe(){return this.cell}#A(A){this.state={...this.state,...A},this.cell.setValue(this.state)}openPalette(A="commands",Q=""){this.#A({palette:{mode:A,query:Q,index:0}}),this.context.set("palette.open",!0)}setPaletteQuery(A){if(this.state.palette)this.#A({palette:{...this.state.palette,query:A,index:0}})}movePalette(A,Q){if(!this.state.palette||!Q)return;this.#A({palette:{...this.state.palette,index:$0(this.state.palette.index,A,Q)}})}setPaletteIndex(A){if(this.state.palette)this.#A({palette:{...this.state.palette,index:A}})}closePalette(){this.#A({palette:null}),this.context.set("palette.open",!1)}showDialog(A){this.#A({dialog:A})}updateDialog(A){if(this.state.dialog)this.#A({dialog:{...this.state.dialog,...A}})}closeDialog(){this.#A({dialog:null})}showContextMenu(A,Q,B){this.#A({contextMenu:{x:A,y:Q,items:B}})}closeContextMenu(){this.#A({contextMenu:null})}openPluginPanel(A){this.#A({pluginPanel:A})}closePluginPanel(){this.#A({pluginPanel:null})}}function $0(A,Q,B){return(A+Q+B)%B}var pK="trove.recents",vX=12;class G0{constructor(A){this.context=A,this.state={stack:[{kind:"search"}],activeTabId:null,activeFile:null,recents:bX()},this.cell=u(this.state)}observe(){return this.cell}#A(A){this.state={...this.state,...A},this.cell.setValue(this.state)}#Q(){return this.state.stack[this.state.stack.length-1]}activeTab(){let A=this.#Q();return A?.kind==="file"?A:null}#B(A,{history:Q=!0}={}){let B=A[A.length-1],C=B&&B.kind==="file"?B:null;if(this.#A({stack:A,activeTabId:C?C.id:null,activeFile:C?C.node:null}),this.context.setMany({"editor.open":!!C,"editor.openerId":C?.openerId||"","editor.contentType":C?.node.contentType||""}),Q)this.#C()}reset(){this.#B([{kind:"search"}])}openFile(A,Q,{reset:B=!1}={}){let C={kind:"file",id:A.id,node:A,openerId:Q},J;if(B)J=[{kind:"search"},C];else{let K=this.state.stack.findIndex((E)=>E.kind==="file"&&E.id===A.id);if(K>=0)J=this.state.stack.slice(0,K+1),J[K]=C;else J=[...this.state.stack,C]}this.#J(A),this.#B(J)}back(){if(this.state.stack.length<=1)return;try{history.back()}catch{this.pop()}}pop(){if(this.state.stack.length>1)this.#B(this.state.stack.slice(0,-1),{history:!1})}closeTab(A){let Q=this.state.stack.filter((B)=>!(B.kind==="file"&&B.id===A));this.#B(Q.length?Q:[{kind:"search"}],{history:!1})}updateTabNode(A){let Q=this.state.stack.map((B)=>B.kind==="file"&&B.id===A.id?{...B,node:A}:B);this.#B(Q,{history:!1})}#C(A=!1){let Q=this.#Q(),B=Q?.node,C={troveDepth:this.state.stack.length,node:B?{id:B.id,name:B.name,contentType:B.contentType,collectionId:B.collectionId}:null,openerId:Q?.openerId||null};try{(A?history.replaceState:history.pushState).call(history,C,"")}catch{}}onPopState(A){let Q=A?.state||{},B=Q.troveDepth||1;if(B<=this.state.stack.length)this.#B(this.state.stack.slice(0,B),{history:!1});else if(Q.node)this.#B([...this.state.stack,{kind:"file",id:Q.node.id,node:Q.node,openerId:Q.openerId}],{history:!1})}#J(A){if(!A)return;let B=[{id:A.id,name:A.name,contentType:A.contentType||"",collectionId:A.collectionId},...this.state.recents.filter((C)=>C.id!==A.id)].slice(0,vX);this.#A({recents:B}),fX(B)}}function bX(){try{return JSON.parse(localStorage.getItem(pK))||[]}catch{return[]}}function fX(A){try{localStorage.setItem(pK,JSON.stringify(A))}catch{}}class H0{constructor(A){this.context=A,this.overlay=new I0(A),this.nav=new G0(A),this.state={activity:"home",sidebarVisible:!0,launch:{query:"",index:0},searchModal:!1,infoPanel:!1,sheet:null},this.cell=u(this.state)}observe(){return this.cell}observeOverlay(){return this.overlay.observe()}observeNav(){return this.nav.observe()}#A(A){this.state={...this.state,...A},this.cell.setValue(this.state)}touch(){this.#A({})}openPalette(A,Q){this.overlay.openPalette(A,Q)}setPaletteQuery(A){this.overlay.setPaletteQuery(A)}movePalette(A,Q){this.overlay.movePalette(A,Q)}closePalette(){this.overlay.closePalette()}showDialog(A){this.overlay.showDialog(A)}updateDialog(A){this.overlay.updateDialog(A)}closeDialog(){this.overlay.closeDialog()}showContextMenu(A,Q,B){this.overlay.showContextMenu(A,Q,B)}closeContextMenu(){this.overlay.closeContextMenu()}openPluginPanel(A){this.overlay.openPluginPanel(A)}closePluginPanel(){this.overlay.closePluginPanel()}activeTab(){return this.nav.activeTab()}back(){this.nav.back()}pop(){this.nav.pop()}closeTab(A){this.nav.closeTab(A)}updateTabNode(A){this.nav.updateTabNode(A)}onPopState(A){this.nav.onPopState(A)}setActivity(A){this.#A({activity:A,sidebarVisible:!0}),this.context.set("view.active",A)}showHome(){this.#A({activity:"home",searchModal:!1}),this.nav.reset(),this.context.set("view.active","home")}setLaunchQuery(A){this.#A({launch:{query:A,index:0}})}moveLaunch(A,Q){if(!Q)return;this.#A({launch:{...this.state.launch,index:$0(this.state.launch.index,A,Q)}})}setPaletteIndex(A){this.overlay.setPaletteIndex?.(A)}setLaunchIndex(A){this.#A({launch:{...this.state.launch,index:A}})}openSearchModal(){this.#A({searchModal:!0,launch:{query:"",index:0}}),this.context.set("searchModal.open",!0)}closeSearchModal(){this.#A({searchModal:!1}),this.context.set("searchModal.open",!1)}openFile(A,Q,B={}){this.#A({activity:"home",searchModal:!1}),this.nav.openFile(A,Q,B)}openSheet(A){this.#A({sheet:this.state.sheet===A?null:A}),this.context.set("sheet.open",this.state.sheet||"")}closeSheet(){if(!this.state.sheet)return;this.#A({sheet:null}),this.context.set("sheet.open","")}toggleInfoPanel(A){this.#A({infoPanel:A??!this.state.infoPanel}),this.context.set("infoPanel.open",this.state.infoPanel)}closeOverlays(){let A=this.overlay.state;if(A.contextMenu)return this.overlay.closeContextMenu(),!0;if(A.dialog)return this.overlay.closeDialog(),!0;if(this.state.sheet)return this.closeSheet(),!0;if(this.state.searchModal)return this.closeSearchModal(),!0;if(A.palette)return this.overlay.closePalette(),!0;if(A.pluginPanel)return this.overlay.closePluginPanel(),!0;if(this.nav.state.stack.length>1)return this.nav.back(),!0;return!1}}var cK=["auto","desktop","phone","tv"],uX=720,mX=1100,pX=/\b(smart-?tv|smarttv|appletv|googletv|android\s*tv|hbbtv|netcast|web0s|webos|tizen|viera|bravia|aquos|crkey|nettv|dtv|philipstv|roku|aft[a-z]{1,3})\b/i;function cX(A="",Q=0){if(!A)return!1;return pX.test(A)&&Q>=mX}class Z0{constructor({window:A=globalThis,settings:Q=null,context:B=null}={}){this.window=A,this.settings=Q,this.context=B,this.urlOverride=nX(A),this.state=this.#Q(),this.cell=u(this.state),this._onResize=()=>this.refresh()}observe(){return this.cell}install(){if(this.window.addEventListener?.("resize",this._onResize),this.window.addEventListener?.("orientationchange",this._onResize),this.settings)gA(this.settings.observe(),()=>this.refresh());return this.#A(this.state),this}dispose(){this.window.removeEventListener?.("resize",this._onResize),this.window.removeEventListener?.("orientationchange",this._onResize)}refresh(){let A=this.#Q();if(A.mode===this.state.mode&&A.width===this.state.width&&A.height===this.state.height&&A.coarse===this.state.coarse)return;this.state=A,this.#A(A),this.cell.setValue(A)}#A(A){this.context?.set("viewport.mode",A.mode),this.context?.set("viewport.phone",A.mode==="phone"),this.context?.set("viewport.tv",A.mode==="tv");let Q=this.window.document?.documentElement;if(Q)Q.dataset.layout=A.mode}#Q(){let A=this.window,Q=A.innerWidth||1280,B=A.innerHeight||800,C=dX(A,"(pointer: coarse)"),J=A.navigator?.userAgent||"",K=this.urlOverride||this.settings?.get?.("workbench.layout")||"auto";return{mode:K!=="auto"&&cK.includes(K)?K:lX({width:Q,coarse:C,ua:J}),width:Q,height:B,coarse:C,forced:K!=="auto"}}}function lX({width:A,coarse:Q,ua:B}){if(cX(B,A))return"tv";if(A<=uX)return"phone";return"desktop"}function dX(A,Q){try{return!!A.matchMedia?.(Q)?.matches}catch{return!1}}function nX(A){try{let Q=new URL(A.location.href).searchParams.get("ui");return Q&&cK.includes(Q)?Q:null}catch{return null}}var nK='a[href], button:not([disabled]), input:not([disabled]), select, textarea, [tabindex]:not([tabindex="-1"])',oK=".launch-item, .grid-tile, .sheet-row, .inbox-item, .plugin-card, .act-task, .act-issue, .chapter",oX=`${nK}, ${oK}`,aX=new Set(["BrowserBack","GoBack","Backspace"]),sX=new Set([10009,461]),iX={ArrowLeft:"left",ArrowRight:"right",ArrowUp:"up",ArrowDown:"down"},rX=new Set(["A","BUTTON","INPUT","SELECT","TEXTAREA"]);class W0{constructor({workbench:A,viewport:Q,window:B=globalThis}){this.workbench=A,this.viewport=Q,this.window=B,this.active=!1,this._onKey=(C)=>this.handleKey(C),this._observer=null,this._pending=0,this._bootstrapped=!1}install(){if(this.viewport)gA(this.viewport.observe(),(A)=>this.setActive(A.mode==="tv"));return this.setActive(this.viewport?.state?.mode==="tv"),this}setActive(A){if(A===this.active)return;if(this.active=A,A)this.window.addEventListener?.("keydown",this._onKey),this.#A(),this.prime(),this.window.setTimeout?.(()=>this.prime(),60);else this.window.removeEventListener?.("keydown",this._onKey),this._observer?.disconnect(),this._observer=null,this._bootstrapped=!1}prime(){this.candidates(),this.focusFirst()}#A(){let A=this.window.MutationObserver;if(!A||this._observer)return;this._observer=new A(()=>{if(this._pending)return;this._pending=this.window.requestAnimationFrame?.(()=>{if(this._pending=0,this.active)this.prime()})||0}),this._observer.observe(this.window.document.body,{childList:!0,subtree:!0})}handleKey(A){if(!this.active||A.defaultPrevented||A.altKey||A.ctrlKey||A.metaKey)return;let Q=this.window.document,B=Q.activeElement;if(aX.has(A.key)||sX.has(A.keyCode)){if(A.key==="Backspace"&&lK(B)&&(B.value??"").length>0)return;A.preventDefault(),this.goBack();return}let C=iX[A.key];if(!C){if(A.key==="Enter"&&B&&!rX.has(B.tagName)&&B.matches(oK))A.preventDefault(),B.click();return}if((C==="left"||C==="right")&&lK(B)&&!tX(B,C))return;let J=B&&B!==Q.body?B:null,K=this.find(C,J);if(!K)return;A.preventDefault(),dK(K)}goBack(){if(this.workbench?.closeOverlays())return;this.window.history?.back?.()}candidates(){let A=this.window.document,Q=[];for(let B of A.querySelectorAll(oX)){if(B.getAttribute?.("aria-hidden")==="true"||B.hasAttribute?.("disabled"))continue;let C=B.getBoundingClientRect();if(C.width<2||C.height<2)continue;if(C.bottom<0||C.top>this.window.innerHeight||C.right<0||C.left>this.window.innerWidth)continue;if(!B.matches(nK)&&!B.hasAttribute("tabindex"))B.setAttribute("tabindex","0");Q.push({el:B,rect:C})}return Q}find(A,Q){let B=this.candidates();if(!B.length)return null;let C=Q&&Q.getBoundingClientRect&&Q.getBoundingClientRect().width?Q.getBoundingClientRect():null;if(!C)return B[0].el;let J=null,K=1/0;for(let{el:E,rect:L}of B){if(E===Q)continue;let D=eX(C,L,A);if(D==null||D>=K)continue;K=D,J=E}return J}focusFirst(){if(this._bootstrapped)return;let A=this.window.document;if(A?.activeElement&&A.activeElement!==A.body)return;let Q=this.candidates();if(!Q.length)return;let B=Q.find((C)=>C.el.classList?.contains("launch-input"))||Q[0];dK(B.el),this._bootstrapped=!0}}function tX(A,Q){let{selectionStart:B,selectionEnd:C}=A;if(B==null||C==null)return!0;if(B!==C)return!1;return Q==="left"?B===0:C>=(A.value??"").length}function lK(A){if(!A)return!1;let Q=A.tagName;if(Q==="TEXTAREA")return!0;if(A.isContentEditable)return!0;if(Q!=="INPUT")return!1;return!["checkbox","radio","button","submit","range","file"].includes(A.type)}function dK(A){A.focus?.({preventScroll:!0}),A.scrollIntoView?.({block:"nearest",inline:"nearest"})}function eX(A,Q,B){let C=B==="up"||B==="down",[J,K]=C?B==="down"?[A.bottom,Q.top]:[A.top,Q.bottom]:B==="right"?[A.right,Q.left]:[A.left,Q.right],L=B==="down"||B==="right"?K-J:J-K;if(L<-2)return null;let[D,X,Y,I]=C?[A.left,A.right,Q.left,Q.right]:[A.top,A.bottom,Q.top,Q.bottom],$=Math.max(0,Math.max(D,Y)-Math.min(X,I)),Z=Math.abs((D+X)/2-(Y+I)/2);return Math.max(0,L)+$*3+Z*0.2}function YB(){if(typeof window>"u")return null;return window.SpeechRecognition||window.webkitSpeechRecognition||null}function mB(){let A=YB();return!!A&&typeof A.available==="function"}var U0=(A)=>({langs:[A],processLocally:!0});async function aK(A=navigator.language||"en-US"){if(!mB())return"unavailable";try{return await YB().available(U0(A))}catch{return"unavailable"}}async function sK(A=navigator.language||"en-US"){if(typeof YB()?.install!=="function")return!1;try{return await YB().install(U0(A))}catch{return!1}}function iK({lang:A=navigator.language||"en-US",onText:Q,onEnd:B,onError:C}={}){if(!mB())throw Error("On-device speech recognition is not available here");let J=new(YB());J.lang=A,J.interimResults=!0,J.continuous=!1,J.options=U0(A),J.processLocally=!0;let K=!1;J.onresult=(E)=>{let L="",D=!1;for(let X=E.resultIndex;X<E.results.length;X++)if(L+=E.results[X][0].transcript,E.results[X].isFinal)D=!0;Q?.(L.trim(),{final:D})},J.onerror=(E)=>{if(E.error==="no-speech"||E.error==="aborted")return;C?.(Error(E.error||"Speech recognition failed"))},J.onend=()=>{if(!K)K=!0,B?.()};try{J.start()}catch(E){K=!0,C?.(E),B?.()}return{stop(){if(K)return;K=!0;try{J.stop()}catch{}B?.()}}}class F0{constructor({workbench:A,notifications:Q,settings:B}={}){this.workbench=A,this.notifications=Q,this.settings=B,this.session=null,this.state={supported:mB(),status:"unknown",listening:!1},this.cell=u(this.state)}observe(){return this.cell}#A(A){this.state={...this.state,...A},this.cell.setValue(this.state)}async refresh(){if(!this.state.supported)return"unavailable";let A=await aK(this.#Q());return this.#A({status:A}),A}#Q(){return this.settings?.get?.("search.voiceLanguage")||navigator.language||"en-US"}canListen(){return this.state.supported&&(this.state.status==="available"||this.state.status==="downloadable")}async run({onText:A}={}){if(this.openSearchSurface(),await this.focusInput(),!this.state.supported)return{listening:!1,reason:"unsupported"};let Q=this.state.status==="unknown"?await this.refresh():this.state.status;if(Q==="downloadable"){this.notifications?.info("Downloading the on-device voice model — this happens once.");let B=await sK(this.#Q());if(this.#A({status:B?"available":"unavailable"}),!B)return{listening:!1,reason:"install-failed"}}else if(Q!=="available")return{listening:!1,reason:Q};return this.toggle({onText:A})}toggle({onText:A}={}){if(this.session)return this.stop(),{listening:!1};try{return this.session=iK({lang:this.#Q(),onText:A,onEnd:()=>{this.session=null,this.#A({listening:!1})},onError:(Q)=>{if(this.session=null,this.#A({listening:!1}),!/not-allowed|service-not-allowed|denied/i.test(Q.message))this.notifications?.warn(`Couldn't listen: ${Q.message}`)}}),this.#A({listening:!0}),{listening:!0}}catch(Q){return this.notifications?.warn(`Couldn't listen: ${Q.message}`),{listening:!1,reason:"error"}}}stop(){this.session?.stop(),this.session=null,this.#A({listening:!1})}openSearchSurface(){let A=this.workbench;if(!A)return;if(A.state.activity==="home"&&!A.nav?.state?.activeTabId)A.closeSearchModal?.();else A.openSearchModal()}focusInput({tries:A=12}={}){return new Promise((Q)=>{let B=A,C=()=>{let J=document.querySelector(".search-modal .launch-input")||document.querySelector(".launch-input");if(J){J.focus();try{J.setSelectionRange(J.value.length,J.value.length)}catch{}Q(document.activeElement===J);return}if(--B<=0){Q(!1);return}requestAnimationFrame(C)};C()})}}class R0{constructor({api:A,settings:Q=null}){this.api=A,this.settings=Q,this.cache=new Map,this._queue=new Map,this._timer=null}get needed(){let A=this.settings?.get("media.signedUrls");if(A==="always")return!0;if(A==="never")return!1;return!!this.api.token?.()}cacheKey(A){return this.api.downloadUrl(A)}async url(A,{op:Q="media"}={}){if(!this.needed)return{url:this.api.downloadUrl(A,{attachment:Q==="download"}),expiresAt:1/0};let B=`${Q}:${A}`,C=this.cache.get(B);if(C&&this.#A(C))return C;return this.#Q(A,Q)}invalidate(A,Q="media"){if(A==null)this.cache.clear();else this.cache.delete(`${Q}:${A}`)}#A(A){if(A.expiresAt===1/0)return!0;let Q=A.expiresAt-A.mintedAt;return Date.now()<A.mintedAt+Q*0.8}#Q(A,Q){if(!this._queue.has(Q))this._queue.set(Q,new Map);let B=this._queue.get(Q),C=B.get(A);if(C)return C.promise;let J,K,E=new Promise((L,D)=>{J=L,K=D});if(B.set(A,{resolve:J,reject:K,promise:E}),B.size>=200)this.#B();else if(!this._timer)this._timer=setTimeout(()=>this.#B(),20);return E}async#B(){clearTimeout(this._timer),this._timer=null;let A=this._queue;this._queue=new Map;for(let[Q,B]of A){let C=[...B.keys()];try{let J=await this.api.mintUrls(C,Q),K=Date.now();for(let[E,L]of B){let D=J.urls?.[E];if(D){let X={url:D.url,expiresAt:D.expiresAt,mintedAt:K};this.cache.set(`${Q}:${E}`,X),L.resolve(X)}else L.reject(Error(J.failed?.[E]==="not_found"?"That file is gone":"You cannot open that file"))}}catch(J){for(let K of B.values())K.reject(J)}}}}function AI(){try{return localStorage.getItem("trove.token")||null}catch{return null}}function rK({baseUrl:A=""}={}){let Q=new UC,B=new RC({"view.active":"home","sidebar.visible":!0}),C=new NC,J=new MC(Q,B,C),K=new PC,E=new fQ(Q,J,B,K),L=new TC({baseUrl:A,token:()=>AI()}),D=new H0(B),X=new Z0({settings:K,context:B}),Y=new W0({workbench:D,viewport:X}),I=new F0({workbench:D,notifications:C,settings:K}),$={reactive:_J,contributions:Q,context:B,commands:J,keybindings:E,settings:K,notifications:C,api:L,workbench:D,viewport:X,spatialNav:Y,voice:I,capabilities:null,openPluginPanel:null};return $.mediaUrls=new R0({api:$.api,settings:K}),$.plugins=new X0($),J.availability=(Z)=>$.plugins.isAvailable(Z),QI($),X.refresh(),$}function QI(A){A.settings.register([{key:"workbench.theme",type:"enum",enum:["dark","light","midnight"],enumLabels:["Dark","Light","Midnight"],default:"dark",title:"Color theme",category:"Appearance",order:1},{key:"workbench.density",type:"enum",enum:["comfortable","compact"],default:"comfortable",title:"List density",category:"Appearance",order:2},{key:"workbench.layout",type:"enum",enum:["auto","desktop","phone","tv"],enumLabels:["Automatic","Desktop","Phone","TV / remote"],default:"auto",title:"Layout",description:"Automatic follows the screen size. Choose TV for d-pad remote navigation.",category:"Appearance",order:3},{key:"explorer.sort",type:"enum",enum:["name","size","updatedAt"],enumLabels:["Name","Size","Modified"],default:"name",title:"Sort files by",category:"Explorer",order:1},{key:"explorer.sortOrder",type:"enum",enum:["asc","desc"],default:"asc",title:"Sort order",category:"Explorer",order:2},{key:"explorer.confirmDelete",type:"boolean",default:!0,title:"Confirm before deleting",category:"Explorer",order:3},{key:"search.mode",type:"enum",enum:["hybrid","semantic","keyword"],default:"hybrid",title:"Search mode",description:"Hybrid blends semantic meaning with keyword matches.",category:"Search",order:1},{key:"uploads.concurrency",type:"number",minimum:1,maximum:8,default:4,title:"Parallel upload parts",category:"Transfers",order:1},{key:"openers.associations",type:"object",hidden:!0,title:"Default viewers",default:{".md":"core.markdown",".markdown":"core.markdown"}},{key:"explorer.view",type:"string",hidden:!0,title:"Results view"},{key:"media.signedUrls",type:"enum",enum:["auto","always","never"],default:"auto",hidden:!0,title:"Signed media URLs"}]),A.contributions.register("keymap.default",{type:"keymap",bindings:[{key:"mod+shift+p",command:"workbench.showCommandPalette"},{key:"mod+p",command:"workbench.quickOpen"},{key:"mod+shift+f",command:"workbench.view.home"},{key:"mod+shift+e",command:"workbench.view.home"},{key:"mod+,",command:"workbench.openSettings"},{key:"mod+shift+l",command:"explorer.copyLink"},{key:"mod+u",command:"explorer.upload"},{key:"delete",command:"explorer.delete",when:"view.active == 'home' && explorer.hasSelection"},{key:"escape",command:"workbench.closeOverlays"},{key:"f5",command:"explorer.refresh"},{key:"mod+shift+i",command:"workbench.toggleInfoPanel"},{key:"mod+shift+v",command:"search.voice"},{key:"browsersearch",command:"search.voice"}]})}function NA(A){console.error(A)}var uQ="The provider has been disposed";class EQ{static deps=[];async obtain(A={}){throw Error("obtain() not implemented")}release(A,Q={}){}async flush(){}static fromSingleton(A,{dispose:Q,deps:B=[]}={}){return class extends EQ{static deps=B;#A;#Q=!1;constructor(J={}){super();this.#A=J}async obtain(){return A}release(){}async dispose(){if(this.#Q)return;if(this.#Q=!0,typeof Q==="function")await Q(A,this.#A)}}}static fromPool(A,Q,{size:B=1,deps:C=[]}={}){if(!Number.isInteger(B)||B<1)throw RangeError("fromPool() requires an integer size of at least 1");return class extends EQ{static deps=C;#A;#Q=[];#B=new Set;#C=[];#J=0;#K=!1;constructor(K={}){super();this.#A=K}async#E(K){try{await Q(K,this.#A)}catch(E){NA(E)}}#L(){while(this.#C.length>0){if(this.#Q.length>0){let E=this.#Q.shift();this.#B.add(E),this.#C.shift().resolve(E);continue}if(this.#J>=B)return;let K=this.#C.shift();this.#J++,Promise.resolve().then(()=>A(this.#A)).then((E)=>{if(this.#K){this.#J--,this.#E(E),K.reject(Error(uQ));return}this.#B.add(E),K.resolve(E)},(E)=>{this.#J--,K.reject(E),this.#L()})}}async obtain(){if(this.#K)throw Error(uQ);let K=Promise.withResolvers();return this.#C.push(K),this.#L(),await K.promise}release(K){if(!this.#B.delete(K))return;if(this.#K){this.#J--,this.#E(K);return}this.#Q.push(K),this.#L()}async dispose(){if(this.#K)return;this.#K=!0;let K=this.#C.splice(0);for(let{reject:L}of K)L(Error(uQ));let E=this.#Q.splice(0);this.#J-=E.length,await Promise.all(E.map((L)=>this.#E(L)))}}}static fromLazySingleton(A,Q,{deps:B=[]}={}){return class extends EQ{static deps=B;#A;#Q=null;#B=null;#C=!1;constructor(J={}){super();this.#A=J}async obtain(){if(this.#C)throw Error(uQ);this.#Q??=Promise.resolve().then(()=>A(this.#A));try{return this.#B=await this.#Q,this.#B}catch(J){throw this.#Q=null,this.#B=null,J}}release(){}async dispose(){if(this.#C)return;if(this.#C=!0,!this.#Q||typeof Q!=="function")return;let J=this.#B??await this.#Q.catch(()=>null);if(J!=null)await Q(J,this.#A)}}}static fromRefCounted(A,Q,{deps:B=[]}={}){return class extends EQ{static deps=B;#A;#Q=0;#B=null;#C=null;#J=null;#K=!1;constructor(J={}){super();this.#A=J}async obtain(){if(this.#K)throw Error(uQ);this.#Q++;while(this.#J)await this.#J;if(this.#K)throw this.#Q--,Error(uQ);if(!this.#B)this.#B=Promise.resolve().then(()=>A(this.#A));try{return this.#C=await this.#B,this.#C}catch(J){if(this.#Q--,this.#Q<=0)this.#Q=0,this.#B=null,this.#C=null;throw J}}async release(){if(this.#Q<=0)return;if(this.#Q--,this.#Q>0)return;let J=this.#C,K=this.#B;if(this.#C=null,this.#B=null,!K)return;this.#J=(async()=>{try{let E=J??await K.catch(()=>null);if(E!=null)await Q(E,this.#A)}catch(E){NA(E)}finally{this.#J=null}})(),await this.#J}async dispose(){if(this.#K=!0,this.#Q>0)this.#Q=1,await this.release();while(this.#J)await this.#J}}}}class M0{#A;#Q=!1;constructor(A,Q){this.resources=A,this.#A=Q}get released(){return this.#Q}async release(){if(this.#Q)return;this.#Q=!0;for(let{name:A,provider:Q,options:B}of this.#A)try{await Q.release(this.resources[A],B)}catch(C){NA(C)}this.#A=[]}}class LQ{#A=new Map;#Q=new WeakMap;#B;#C=!1;constructor({providers:A,feed:Q}={}){if(this.#B=Q??new EventTarget,!A)return;let B=(C,J)=>{if(this.#A.has(C))return this.#A.get(C);let K=A[C];if(!K)throw Error(`Dependency not found: ${C}`);let E=[...J,C];if(J.includes(C))throw Error(`Cyclic dependency detected: ${E.join(" -> ")}`);let L={};for(let X of K.deps??[])L[X]=B(X,E);let D=new K(L,{engineFeed:this.#B,container:this});return this.#A.set(C,D),D};for(let C of Object.keys(A))B(C,[])}get feed(){return this.#B}get disposed(){return this.#C}has(A){return this.#A.has(A)}get(A){let Q=this.#A.get(A);if(!Q)throw Error(`Dependency not found: ${A}`);return Q}resolve(A){if(!A)return{};let Q=this.#Q.get(A);if(Q)return Q;let B={};if(Array.isArray(A))for(let C of A)B[C]={provider:this.get(C),options:void 0};else for(let C of Object.keys(A))B[C]={provider:this.get(C),options:A[C]};return this.#Q.set(A,B),B}resolveAll(...A){let Q=A.filter(Boolean);if(Q.length===1)return this.resolve(Q[0]);return Object.assign({},...Q.map((B)=>this.resolve(B)))}async lease(...A){if(this.#C)throw Error("The container has been disposed");let Q=this.resolveAll(...A),B={},C=[];try{for(let[J,{provider:K,options:E}]of Object.entries(Q))B[J]=await K.obtain(E),C.push({name:J,provider:K,options:E})}catch(J){throw await new M0(B,C).release(),J}return new M0(B,C)}async use(A,Q){let B=await this.lease(A);try{return await Q(B.resources)}finally{await B.release()}}async dispose(){if(this.#C)return;this.#C=!0;let A=[...this.#A.values()].reverse();for(let Q of A)try{await Q.flush?.()}catch(B){NA(B)}for(let Q of A)try{await Q.dispose?.()}catch(B){NA(B)}}}var BI=typeof ErrorEvent==="function"?ErrorEvent:class extends Event{constructor(Q,{error:B,message:C=""}={}){super(Q);this.error=B,this.message=C}};function CI(A){return A&&typeof A.message==="string"?A.message:String(A)}class AE extends Event{constructor({reason:A,error:Q=null}={}){super("abort");this.reason=A,this.error=Q}}var tK=["complete","error","abort"];function JI(){return typeof DOMException==="function"?new DOMException("The dispatch was aborted","AbortError"):Object.assign(Error("The dispatch was aborted"),{name:"AbortError"})}class DB{execute(){throw Error("execute() not implemented")}}class V0 extends EventTarget{#A=new AbortController;#Q;#B=null;constructor(){super();for(let A of tK)this.addEventListener(A,(Q)=>{this.#B??={type:A,event:Q}},{once:!0})}get signal(){return this.#A.signal}get settled(){return this.#B?.type??null}get reason(){return this.#Q}abort(A){if(this.#A.signal.aborted)return;this.#Q=A??JI(),this.#A.abort(this.#Q)}next(A,{signal:Q}={}){let B=new Set(Array.isArray(A)?A:[A]);if(B.size===0)throw TypeError("next() requires at least one event name");let C=B.has("abort");return new Promise((J,K)=>{if(Q?.aborted){K(Q.reason);return}if(this.#A.signal.aborted&&!C&&!this.#B){K(this.#Q);return}if(this.#B){this.#C(J,K,this.#B,B);return}let E=new AbortController,L={signal:E.signal},D=(X)=>(Y)=>{E.abort(),X(Y)};for(let X of B)this.addEventListener(X,D(J),L);for(let X of tK){if(B.has(X))continue;this.addEventListener(X,(Y)=>D(K)(eK(X,Y,B)),L)}if(!C)this.#A.signal.addEventListener("abort",()=>D(K)(this.#Q),L);Q?.addEventListener("abort",()=>D(K)(Q.reason),L)})}#C(A,Q,B,C){if(C.has(B.type))A(B.event);else Q(eK(B.type,B.event,C))}}function eK(A,Q,B){if(A==="error")return Q.error;if(A==="abort")return Q.reason;return KI(B)}function KI(A){return Error(`The dispatch completed without emitting ${[...A].map((Q)=>`'${Q}'`).join(" or ")}`)}class pB{#A;#Q;constructor({container:A,interceptors:Q}={}){this.#A=A??new LQ,this.#Q=Q?[...Q]:[]}get container(){return this.#A}get feed(){return this.#A.feed}dispatch(A){if(!(A instanceof DB))throw TypeError("dispatch() requires an instance of Action");let Q=this.#A,B=this.#Q,C=Q.feed,J=new V0;return setTimeout(async()=>{let K=[],E={},L=null,D=(X)=>{if(X!==void 0)E=X};try{for(let Y of B){if(K.push(Y),!Y.enter)continue;D(await Q.use(Y.deps,(I)=>Y.enter(I,{dispatchFeed:J,engineFeed:C,signal:J.signal,state:E,action:A})))}let X=await Q.lease(A.constructor.deps,A.deps);try{await A.execute(X.resources,{dispatchFeed:J,engineFeed:C,signal:J.signal,state:E})}finally{await X.release()}}catch(X){L=X}finally{for(let X=K.length-1;X>=0;X--){let Y=K[X],I=J.signal.aborted;try{if(I&&Y.abort)D(await Q.use(Y.deps,($)=>Y.abort($,{dispatchFeed:J,engineFeed:C,signal:J.signal,action:A,state:E,reason:J.reason,error:L})));else if(L&&Y.error){let $={dispatchFeed:J,engineFeed:C,signal:J.signal,action:A,state:E,error:L,handled:()=>{L=null}};D(await Q.use(Y.deps,(Z)=>Y.error(Z,$)))}else if(!L&&Y.leave)D(await Q.use(Y.deps,($)=>Y.leave($,{dispatchFeed:J,engineFeed:C,signal:J.signal,state:E,action:A})))}catch($){L=$}}if(J.signal.aborted)J.dispatchEvent(new AE({reason:J.reason,error:L}));else if(L)J.dispatchEvent(new BI("error",{error:L,message:CI(L)}));else J.dispatchEvent(new Event("complete"))}}),J}}class cB{boot(){throw Error("boot() not implemented, and no fetch() to fall back to")}kill(){}}class QE{#A;#Q;#B=null;#C=null;#J=!1;#K=null;#E=Promise.withResolvers();#L=!1;#Y=void 0;#D=!1;#X=void 0;#$=void 0;observers=new Set;constructor(A,Q){this.#A=A,this.#Q=Q,this.notify=this.notify.bind(this)}get hasValue(){return this.#L}get currentValue(){return this.#Y}get received(){return this.#E.promise}get bootFeed(){return this.#X}get killFeed(){return this.#$}#H(A,Q){let B=this.#A._dispatch(A);return B.addEventListener("error",(C)=>{NA(Error(`${this.#Q.constructor.name} ${Q} (${A.constructor.name}) failed`,{cause:C.error}))},{once:!0}),B}notify(A){if(this.#D)return;if(this.#Y=A,!this.#L)this.#L=!0,this.#E.resolve(!0);for(let Q of[...this.observers])try{Q.next?.(A)}catch(B){NA(B)}}boot(){if(this.#C)return this.#C;return this.#C=(async()=>{try{if(this.#Q.bootAction)this.#X=this.#H(this.#Q.bootAction,"bootAction");this.#B=await this.#A._container.lease(this.#Q.constructor.deps,this.#Q.deps);let A={notify:this.notify,engineFeed:this.#A._container.feed,bootFeed:this.#X};if(this.#Q.boot===cB.prototype.boot){if(typeof this.#Q.fetch!=="function")throw Error(`${this.#Q.constructor.name} implements neither boot() nor fetch()`);this.notify(await this.#Q.fetch(this.#B.resources,A)),await this.#G()}else await this.#Q.boot(this.#B.resources,A)}catch(A){NA(A),await this.#G(A)}finally{this.#J=!0}})(),this.#C}kill(){if(this.#K)return this.#K;return this.#K=this.#J?this.#I():Promise.resolve(this.#C).then(()=>this.#I()),this.#K}async#I(){if(this.#D)return;try{if(this.#Q.killAction)this.#$=this.#H(this.#Q.killAction,"killAction");if(this.#Q.kill)await this.#Q.kill(this.#B?.resources??{},{bootFeed:this.#X,killFeed:this.#$,engineFeed:this.#A._container.feed,notify:this.notify})}catch(A){NA(A)}finally{await this.#G()}}async#G(A){if(this.#D)return;this.#D=!0,this.#A._evict(this.#Q,this);let Q=[...this.observers];this.observers.clear();for(let C of Q)try{if(A!==void 0&&C.error)C.error(A);else C.complete?.()}catch(J){NA(J)}if(!this.#L)this.#E.resolve(!1);let B=this.#B;if(this.#B=null,B)await B.release()}}class lB{#A;#Q;#B;#C=!1;constructor({container:A,dispatcher:Q,createControllerMap:B}={}){this.#A=A??new LQ,this.#Q=Q??null,this.#B=B?.()??new Map}get container(){return this.#A}get feed(){return this.#A.feed}get _container(){return this.#A}_dispatch(A){if(!this.#Q)throw Error("A query declared a bootAction/killAction but no dispatcher was given to QueryStore");return this.#Q.dispatch(A)}_evict(A,Q){if(this.#B.get(A)===Q)this.#B.delete(A)}#J(A){return[A.constructor.deps,A.deps]}query(A){if(!(A instanceof cB))throw TypeError("query() requires an instance of Query");return{subscribe:(Q)=>{if(this.#C)throw Error("The query store has been disposed");let B=typeof Q==="function"?{next:Q}:Q||{},C=this.#B.get(A);if(C){if(C.observers.add(B),C.hasValue)try{B.next?.(C.currentValue)}catch(K){NA(K)}}else C=new QE(this,A),this.#B.set(A,C),C.observers.add(B),C.boot();let J=!1;return{get closed(){return J},unsubscribe:()=>{if(J)return;if(J=!0,C.observers.delete(B),C.observers.size===0)this._evict(A,C),C.kill()}}},peek:async()=>{let Q=this.#B.get(A);if(Q&&await Q.received)return Q.currentValue;if(typeof A.fetch!=="function")throw TypeError(`${A.constructor.name} is not active and does not implement fetch()`);let B=await this.#A.lease(...this.#J(A));try{return await A.fetch(B.resources,{engineFeed:this.#A.feed,bootFeed:Q?.bootFeed,killFeed:Q?.killFeed})}finally{await B.release()}}}}async dispose(){if(this.#C)return;this.#C=!0;for(let A of[...this.#B.values?.()??[]])await A.kill()}}class dB{#A;#Q;#B;#C=!1;constructor({providers:A,interceptors:Q,hooks:B,container:C,dispatcher:J,queries:K}={}){this.#A=C??new LQ({providers:A}),this.#Q=J??new pB({container:this.#A,interceptors:Q}),this.#B=K??new lB({container:this.#A,dispatcher:this.#Q,createControllerMap:B?.createQueryControllersMap})}get container(){return this.#A}get dispatcher(){return this.#Q}get queries(){return this.#B}get feed(){return this.#A.feed}dispatch(A){return this.#Q.dispatch(A)}query(A){return this.#B.query(A)}async dispose(){if(this.#C)return;this.#C=!0,await this.#B.dispose(),await this.#A.dispose()}}class q0{constructor(A){this.settings=A,this.state={items:[],loading:!1,error:null,selection:[],sort:A.get("explorer.sort"),order:A.get("explorer.sortOrder"),collectionId:null,collections:[],canCreateCollection:!1,gate:null,stats:null,usage:null,nextCursor:null,loadingMore:!1,trash:null},this.cell=u(this.state)}observe(){return this.cell}set(A){this.state={...this.state,...A},this.cell.setValue(this.state)}select(A,{additive:Q=!1,nodes:B=null}={}){let C=Q?Array.from(new Set([...this.state.selection,...A])):A;if(C.length===this.state.selection.length&&C.every((K,E)=>K===this.state.selection[E]))return;this.set({selection:C,selectionNodes:B&&!Q?B:null})}selectedNodes(){let A=this.state.selectionNodes;if(A?.length)return A.filter((Q)=>this.state.selection.includes(Q.id));return this.state.items.filter((Q)=>this.state.selection.includes(Q.id))}}class P0{constructor(){this.state={keys:[],loading:!1,loaded:!1,error:null,minted:null,busy:null,draft:null},this.cell=u(this.state)}startDraft(){this.set({draft:{name:"",expiresInDays:"",caps:{}},error:null})}cancelDraft(){this.set({draft:null})}patchDraft(A){if(!this.state.draft)return;this.set({draft:{...this.state.draft,...A}})}toggleCap(A,Q){if(!this.state.draft)return;let B={...this.state.draft.caps},C=new Set(B[A]||[]);if(C.has(Q))C.delete(Q);else C.add(Q);if(C.size)B[A]=[...C];else delete B[A];this.patchDraft({caps:B})}draftScopes(){let A=this.state.draft?.caps||{},Q=Object.entries(A).filter(([,B])=>B.length).map(([B,C])=>({collectionId:B,capabilities:C}));return Q.length?Q:null}observe(){return this.cell}set(A){this.state={...this.state,...A},this.cell.setValue(this.state)}clearMinted(){if(this.state.minted)this.set({minted:null})}}class N0{constructor(){this.state={query:"",mode:"hybrid",results:[],loading:!1,error:null,ran:!1,paletteFiles:[],paletteQuery:"",paletteLoading:!1,paletteError:null},this.cell=u(this.state)}observe(){return this.cell}set(A){this.state={...this.state,...A},this.cell.setValue(this.state)}}class O0{constructor(A=null){this.state={items:[]},this.cell=u(this.state),this._controllers=new Map,this.activity=A,this._tasks=new Map,this._retries=new Map}observe(){return this.cell}#A(){this.cell.setValue(this.state)}start(A,Q,B,C,{retry:J=null}={}){if(this._controllers.set(A,C),J)this._retries.set(A,J);this.state={items:[...this.state.items,{id:A,name:Q,direction:"up",ratio:0,loaded:0,total:B,status:"active",error:null,retryable:!!J}]},this.#A(),this.#Q(A,Q,B)}#Q(A,Q,B){let C=this.activity?.start({kind:"transfer",title:`Uploading ${Q}`,total:B||null,unit:"bytes",onCancel:()=>this.cancel(A)});if(C)this._tasks.set(A,C)}retry(A){let Q=this._retries.get(A);if(!Q)return null;let B=this.state.items.find((C)=>C.id===A);if(!B||B.status==="active")return null;return Q()}restart(A,Q){this._controllers.set(A,Q);let B=this.state.items.find((C)=>C.id===A);this.state={items:this.state.items.map((C)=>C.id===A?{...C,status:"active",error:null,ratio:0,loaded:0}:C)},this.#A(),this.#Q(A,B?.name||"file",B?.total||null)}progress(A,{loaded:Q,total:B,ratio:C}){this.state={items:this.state.items.map((J)=>J.id===A?{...J,loaded:Q,total:B,ratio:C}:J)},this.#A(),this._tasks.get(A)?.progress({done:Q,total:B||null})}finish(A,Q="done",B=null){this.state={items:this.state.items.map((J)=>J.id===A?{...J,status:Q,error:B,ratio:Q==="done"?1:J.ratio}:J)},this._controllers.delete(A),this.#A();let C=this._tasks.get(A);if(C){if(Q==="done")C.succeed();else if(Q==="cancelled")C.cancel();else C.fail(B||Error("Upload failed"));this._tasks.delete(A)}if(Q==="done")setTimeout(()=>this.dismiss(A),4000)}cancel(A){this._controllers.get(A)?.abort(),this.finish(A,"cancelled")}dismiss(A){this.state={items:this.state.items.filter((Q)=>Q.id!==A)},this._retries.delete(A),this.#A()}clearDone(){let A=this.state.items.filter((B)=>B.status==="active"),Q=new Set(A.map((B)=>B.id));for(let B of[...this._retries.keys()])if(!Q.has(B))this._retries.delete(B);this.state={items:A},this.#A()}}class j0{constructor(A){this.platform=A,this.api=A.api,this.state={me:null,notifications:{items:[],unread:0},inboxOpen:!1,pushSupported:"serviceWorker"in navigator&&"PushManager"in window,pushEnabled:!1,sidecar:null,backlinks:null,posting:!1,replyTo:null},this.cell=u(this.state),this._pollTimer=null}observe(){return this.cell}#A(A){this.state={...this.state,...A},this.cell.setValue(this.state)}async init(){try{let A=await this.api.me();this.#A({me:A.principal,admin:!!A.admin})}catch{}if(await this.refreshNotifications(),this._pollTimer=setInterval(()=>this.refreshNotifications(),45000),this._pollTimer.unref)this._pollTimer.unref();this.#B(),window.addEventListener("focus",()=>this.refreshNotifications()),navigator.serviceWorker?.addEventListener?.("message",(A)=>{if(A.data?.type==="trove-push")this.refreshNotifications()})}async refreshNotifications(){try{let A=await this.api.notifications();this.#A({notifications:A})}catch{}}toggleInbox(A){let Q=A??!this.state.inboxOpen;if(this.#A({inboxOpen:Q}),Q&&this.state.notifications.unread)this.markAllRead()}async markAllRead(){try{await this.api.markNotificationsRead(),this.#A({notifications:{...this.state.notifications,unread:0,items:this.state.notifications.items.map((A)=>({...A,read:!0}))}})}catch{}}async loadSidecar(A){if(!A)return this.#A({sidecar:null,backlinks:null});this.#A({sidecar:{nodeId:A,loading:!0,tags:[],comments:[],subscribers:[]}}),this.loadBacklinks(A);try{let Q=await this.api.sidecar(A);if(this.state.sidecar?.nodeId!==A)return;this.#A({sidecar:{...Q,loading:!1}})}catch(Q){if(this.state.sidecar?.nodeId!==A)return;this.#A({sidecar:{nodeId:A,loading:!1,error:Q.message,tags:[],comments:[]}})}}async loadBacklinks(A){if(!A)return this.#A({backlinks:null});this.#A({backlinks:{nodeId:A,items:[],loading:!0,error:null}});try{let Q=await this.api.backlinks(A);if(this.state.backlinks?.nodeId!==A)return;this.#A({backlinks:{nodeId:A,items:Q.items||[],loading:!1,error:null}})}catch(Q){if(this.state.backlinks?.nodeId!==A)return;this.#A({backlinks:{nodeId:A,items:[],loading:!1,error:Q.message}})}}async#Q(){if(this.state.sidecar?.nodeId)await this.loadSidecar(this.state.sidecar.nodeId)}setReplyTo(A){this.#A({replyTo:A})}async comment(A){let Q=this.state.sidecar?.nodeId;if(!Q||!A.trim())return;let B=this.state.replyTo?.id||null;if(this.offline&&!this.offline.state.online){await this.offline.queueOp({method:"POST",path:`/api/items/${encodeURIComponent(Q)}/comments`,body:{body:A,parentId:B}}),this.#A({replyTo:null}),this.platform.notifications.info("Offline — your comment will post when you reconnect.");return}this.#A({posting:!0});try{await this.api.addComment(Q,{body:A,parentId:B}),this.#A({replyTo:null}),await this.#Q()}catch(C){this.platform.notifications.error(`Couldn't post comment: ${C.message}`)}finally{this.#A({posting:!1})}}async deleteComment(A){let Q=this.state.sidecar?.nodeId;await this.api.deleteComment(Q,A).catch((B)=>this.platform.notifications.error(B.message)),await this.#Q()}async react(A,Q){let B=this.state.sidecar?.nodeId,J=!(BE(this.state.sidecar?.comments||[],A)?.reactions?.[Q]||[]).includes(this.state.me?.id);try{await this.api.reactComment(B,A,Q,J)}catch(K){this.platform.notifications.error(`Couldn't react: ${K.message}`)}await this.#Q()}async addTag(A,Q){let B=this.state.sidecar?.nodeId;if(!A.trim())return;if(this.offline&&!this.offline.state.online){await this.offline.queueOp({method:"POST",path:`/api/items/${encodeURIComponent(B)}/tags`,body:{name:A.trim(),value:Q}}),this.platform.notifications.info("Offline — tag will sync when you reconnect.");return}await this.api.setTag(B,A.trim(),Q).catch((C)=>this.platform.notifications.error(C.message)),await this.#Q()}async removeTag(A){let Q=this.state.sidecar?.nodeId;if(this.offline&&!this.offline.state.online){await this.offline.queueOp({method:"DELETE",path:`/api/items/${encodeURIComponent(Q)}/tags/${encodeURIComponent(A)}`}),this.platform.notifications.info("Offline — tag removal will sync when you reconnect.");return}try{await this.api.removeTag(Q,A)}catch(B){this.platform.notifications.error(`Couldn't remove tag: ${B.message}`)}await this.#Q()}async#B(){if(!this.state.pushSupported)return;try{let Q=await(await navigator.serviceWorker.getRegistration())?.pushManager?.getSubscription();this.#A({pushEnabled:!!Q})}catch{}}async enablePush(){if(!this.state.pushSupported){this.platform.notifications.warn("Push notifications are not supported in this browser.");return}try{let{publicKey:A}=await this.api.vapidKey();if(!A){this.platform.notifications.warn("This server has no VAPID key configured for web push.");return}let Q=await navigator.serviceWorker.register("/sw.js");if(await navigator.serviceWorker.ready,await Notification.requestPermission()!=="granted")return this.platform.notifications.info("Notifications permission was denied.");let C=await Q.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:EI(A)});await this.api.subscribePush(C.toJSON()),this.#A({pushEnabled:!0}),this.platform.notifications.success("Notifications enabled — you’ll be pinged when someone @mentions you.")}catch(A){this.platform.notifications.error(`Couldn't enable notifications: ${A.message}`)}}}function BE(A,Q){for(let B of A){if(B.id===Q)return B;let C=BE(B.replies||[],Q);if(C)return C}return null}function EI(A){let Q="=".repeat((4-A.length%4)%4),B=(A+Q).replace(/-/g,"+").replace(/_/g,"/"),C=atob(B),J=new Uint8Array(C.length);for(let K=0;K<C.length;K++)J[K]=C.charCodeAt(K);return J}class z0{get dimensions(){return 0}async embed(A){throw V.unsupported("embed not implemented")}async embedOne(A){return(await this.embed([A]))[0]}}var LI=new Set("a an the of to in on for and or is are be as at by with from this that it".split(" "));function YI(A){return String(A).toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/).filter((Q)=>Q.length>1&&!LI.has(Q))}function DI(A){let Q=2166136261;for(let B=0;B<A.length;B++)Q^=A.charCodeAt(B),Q=Math.imul(Q,16777619);return Q>>>0}class w0 extends z0{constructor({dimensions:A=256}={}){super();this._dim=A}get dimensions(){return this._dim}async embed(A){return A.map((Q)=>this.#A(Q))}#A(A){let Q=new Float64Array(this._dim),B=YI(A),C=[...B];for(let K=0;K<B.length-1;K++)C.push(B[K]+"_"+B[K+1]);for(let K of C){let E=DI(K),L=E%this._dim,D=E>>31&1?-1:1;Q[L]+=D}let J=0;for(let K=0;K<Q.length;K++)J+=Q[K]*Q[K];return J=Math.sqrt(J)||1,Array.from(Q,(K)=>K/J)}}class XI extends z0{constructor(A){super();if(!A?.url||!A?.dimensions)throw V.invalid("HttpEmbedding requires url and dimensions");this.cfg=A}get dimensions(){return this.cfg.dimensions}async embed(A){let Q=this.cfg.batchSize??64,B=[];for(let C=0;C<A.length;C+=Q){let J=A.slice(C,C+Q);B.push(...await this.#A(J))}return B}async#A(A){return WQ(async()=>{let Q;try{Q=await fetch(this.cfg.url,{method:"POST",headers:{"content-type":"application/json",...this.cfg.apiKey?{authorization:`Bearer ${this.cfg.apiKey}`}:{}},body:JSON.stringify({model:this.cfg.model,input:A})})}catch(J){throw QB(J)}if(Q.status===429||Q.status>=500)throw V.transient(`Embedding endpoint ${Q.status}`);if(!Q.ok)throw V.internal(`Embedding endpoint failed: ${Q.status}`);let B=await Q.json();return(B.data??B.embeddings??[]).map((J)=>J.embedding??J)})}}var S0="trove:",II=255;var $I=/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/;function nB(A){if(typeof A!=="string"||!A.toLowerCase().startsWith(S0))return null;let Q;try{Q=new URL(A)}catch{return null}let B=Q.pathname,C=B.indexOf("/"),J=C<0?B:B.slice(0,C);if(!$I.test(J))return null;let K=Q.searchParams.get("id"),E=Q.searchParams.get("name"),L="";if(C>=0)try{L=decodeURIComponent(B.slice(C+1))}catch{return null}if(K!=null&&(E!=null||L))return null;let D=K!=null?"id":"name",X=K!=null?K:E!=null?E:L;if(!X||X.length>II)return null;return{collection:J,by:D,value:X}}function oB(A,Q="name"){let B=A?.collectionId||"default";if(Q==="id"){if(!A?.id)throw V.invalid("trove: link by id needs a node id");return`${S0}${B}?id=${encodeURIComponent(A.id)}`}if(!A?.name)throw V.invalid("trove: link by name needs a node name");return`${S0}${B}?name=${encodeURIComponent(A.name)}`}function CE(A,Q,B){let C=[],J=0;while(J<A.length){let K=Math.min(J+Q,A.length);if(K<A.length){let E=A.slice(J,K),L=Math.max(E.lastIndexOf(`
345
+
346
+ `),E.lastIndexOf(". "),E.lastIndexOf(`
347
+ `));if(L>Q*0.75)K=J+L+1}if(C.push(A.slice(J,K).trim()),K>=A.length)break;J=K-B}return C.filter(Boolean)}var GI=new Set("a an the of to in on for and or is are be as at by with from this that it".split(" "));function _0(A){return String(A).toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/).filter((Q)=>Q.length>1&&!GI.has(Q))}function XB(A){let Q=(A?.name||"").toLowerCase();return Q.includes(".")?Q.slice(Q.lastIndexOf(".")):""}var JE=[{kind:"audio",icon:"file-audio",mime:["audio/"],ext:[".mp3",".flac",".wav",".opus",".ogg",".m4a",".m4b"]},{kind:"image",icon:"file-image",mime:["image/"],ext:[".png",".jpg",".jpeg",".gif",".webp",".svg",".avif"]},{kind:"video",icon:"file-video",mime:["video/"],ext:[".mp4",".webm",".mkv",".mov"]},{kind:"text",icon:"file-text",mime:["text/","application/json"],ext:[".txt",".md",".markdown",".json",".js",".mjs",".ts",".jsx",".tsx",".css",".html",".xml",".yaml",".yml",".toml",".ini",".log",".csv",".py",".rb",".go",".rs",".sh",".c",".h",".cpp",".java"]}];function HI(A,Q,B){if(A.ext.includes(Q))return!0;return A.mime.some((C)=>C.endsWith("/")?B.startsWith(C):B===C)}function KE(A){let Q=XB(A),B=A?.contentType||"";for(let C of JE)if(HI(C,Q,B))return C.kind;return"file"}var ZI={...Object.fromEntries(JE.map((A)=>[A.kind,A.icon])),file:"file"};function aA(A){return ZI[KE(A)]||"file"}function EE(A){return KE(A)==="text"}var WI="trove-offline",LE="trove-files-v1",T0=new w0({dimensions:256});class k0{constructor(A){this.platform=A,this.api=A.api,this.db=null,this.state={online:navigator.onLine,pins:[],queued:0,syncing:!1},this.cell=u(this.state)}observe(){return this.cell}#A(A){this.state={...this.state,...A},this.cell.setValue(this.state)}async init(){if(this.db=await UI(),await this.#C(),await this.#J(),window.addEventListener("online",()=>this.#Q()),window.addEventListener("offline",()=>this.#B()),this.state.online&&!await this.api.reachable())this.#A({online:!1});if(this.platform.plugins?.setOnline?.(this.state.online),this.state.online)this.flushQueue()}async#Q(){if(!await this.api.reachable()){this.#A({online:!1}),await this.platform.plugins?.setOnline?.(!1);return}this.#A({online:!0}),await this.platform.plugins?.setOnline?.(!0),await this.flushQueue()}async#B(){this.#A({online:!1}),await this.platform.plugins?.setOnline?.(!1)}isPinned(A){return this.state.pins.some((Q)=>Q.id===A)}async pin(A){if(!A?.id)return;try{if("caches"in window){let J=await caches.open(LE),K=this.platform.mediaUrls,E=K.cacheKey(A.id),{url:L}=await K.url(A.id,{op:"download"}),D=await fetch(L);if(!D.ok)throw Error(`Couldn't fetch the file (${D.status})`);await J.put(new Request(E),D)}let Q=[],B="";if(EE(A))try{B=await this.api.readText(A.id);let J=CE(B,1000,150),K=await T0.embed(J.length?J:[A.name]);Q=(J.length?J:[A.name]).map((E,L)=>({text:E,vector:K[L]}))}catch{}let C=(await T0.embed([A.name]))[0];await RI(this.db,"pins",A.id,{node:A,text:B,chunks:Q,nameVec:C,pinnedAt:Date.now()}),await this.#C(),this.platform.notifications.success(`“${A.name}” is available offline`)}catch(Q){this.platform.notifications.error(`Couldn't make available offline: ${Q.message}`)}}async unpin(A){if(this.state.pins.find((B)=>B.id===A)&&"caches"in window)await(await caches.open(LE)).delete(this.platform.mediaUrls.cacheKey(A),{ignoreVary:!0}).catch(()=>{});await x0(this.db,"pins",A),await this.#C()}async#C(){let A=await g0(this.db,"pins");this.#A({pins:A.map((Q)=>({id:Q.node.id,name:Q.node.name,contentType:Q.node.contentType,collectionId:Q.node.collectionId,pinnedAt:Q.pinnedAt}))})}async searchOffline(A,{limit:Q=40}={}){let B=await g0(this.db,"pins");if(!B.length)return[];let C=_0(A),J=(await T0.embed([A]))[0],K=[];for(let E of B){let L=_0(`${E.node.name} ${E.text||""}`),D=qI(C,new Set(L)),X=YE(J,E.nameVec);for(let I of E.chunks||[])X=Math.max(X,YE(J,I.vector));let Y=0.6*X+0.4*D;if(Y>0.02)K.push({nodeId:E.node.id,node:E.node,score:Y,snippet:PI(E.text,C),indexerId:"offline"})}return K.sort((E,L)=>L.score-E.score).slice(0,Q)}async queueOp(A){await MI(this.db,"queue",{...A,at:Date.now()}),await this.#J()}async#J(){let A=await g0(this.db,"queue");this.#A({queued:A.length})}async flushQueue(){if(!this.state.online||this.state.syncing)return;this.#A({syncing:!0});let A=0,Q=0;try{let B=await VI(this.db,"queue");for(let{key:C,value:J}of B)try{await this.api.request(J.method,J.path,{body:J.body}),await x0(this.db,"queue",C),A++}catch(K){if(["transient","timeout","unauthorized","quota"].includes(K.code))break;await x0(this.db,"queue",C),Q++}}finally{if(await this.#J(),this.#A({syncing:!1}),Q)this.platform.notifications.warn(`${Q} offline change${Q>1?"s":""} couldn't be applied and ${Q>1?"were":"was"} discarded.`);if(A&&this.state.queued===0)this.platform.notifications.info(`${A} offline change${A>1?"s":""} synced.`)}}}function UI(){return new Promise((A,Q)=>{let B=indexedDB.open(WI,1);B.onupgradeneeded=()=>{let C=B.result;if(!C.objectStoreNames.contains("pins"))C.createObjectStore("pins");if(!C.objectStoreNames.contains("queue"))C.createObjectStore("queue",{autoIncrement:!0})},B.onsuccess=()=>A(B.result),B.onerror=()=>Q(B.error)})}function IB(A,Q,B,C){return new Promise((J,K)=>{let E=A.transaction(Q,B),L=E.objectStore(Q),D;Promise.resolve(C(L)).then((X)=>D=X),E.oncomplete=()=>J(D),E.onerror=()=>K(E.error)})}var FI=(A)=>new Promise((Q,B)=>{A.onsuccess=()=>Q(A.result),A.onerror=()=>B(A.error)}),RI=(A,Q,B,C)=>IB(A,Q,"readwrite",(J)=>J.put(C,B)),MI=(A,Q,B)=>IB(A,Q,"readwrite",(C)=>C.add(B)),x0=(A,Q,B)=>IB(A,Q,"readwrite",(C)=>C.delete(B)),g0=(A,Q)=>IB(A,Q,"readonly",(B)=>FI(B.getAll()));function VI(A,Q){return IB(A,Q,"readonly",(B)=>new Promise((C,J)=>{let K=[],E=B.openCursor();E.onsuccess=()=>{let L=E.result;if(!L)return C(K);K.push({key:L.key,value:L.value}),L.continue()},E.onerror=()=>J(E.error)}))}function qI(A,Q){if(!A.length||!Q.size)return 0;let B=0;for(let C of A)if(Q.has(C))B++;return B/A.length}function YE(A,Q){if(!A||!Q)return 0;let B=0;for(let C=0;C<A.length;C++)B+=A[C]*Q[C];return B}function PI(A,Q){if(!A)return null;let B=A.toLowerCase(),C=-1;for(let K of Q){let E=B.indexOf(K);if(E>=0){C=E;break}}if(C<0)return A.slice(0,160).trim();let J=Math.max(0,C-60);return(J>0?"…":"")+A.slice(J,J+200).trim()+"…"}var NI=1000,OI=60000;class y0{constructor(A){this.platform=A,this.api=A.api,this.state={tasks:[],issues:[],issuesLoading:!1,tasksError:null,issuesError:null,open:!1},this.cell=u(this.state),this._local=new Map,this._server=[],this._timer=null,this._pollMs=null}observe(){return this.cell}#A(A){this.state={...this.state,...A},this.cell.setValue(this.state)}#Q(){this.#A({tasks:[...this._local.values(),...this._server]})}start(A={}){let Q=A.id||`local_${Math.random().toString(36).slice(2,10)}`,B={id:Q,source:"local",kind:A.kind||"general",title:A.title||"Working",detail:A.detail??null,status:"running",done:0,total:A.total??null,unit:A.unit||null,cancellable:!!A.onCancel,startedAt:Date.now(),endedAt:null,error:null};if(this._local.set(Q,B),this._cancels||=new Map,A.onCancel)this._cancels.set(Q,A.onCancel);this.#Q(),this.#J();let C=(J)=>{let K=this._local.get(Q);if(!K||K.status!=="running")return;this._local.set(Q,{...K,...J}),this.#Q()};return{id:Q,progress:(J={})=>C({done:J.done??this._local.get(Q)?.done??0,total:J.total===void 0?this._local.get(Q)?.total:J.total,unit:J.unit??this._local.get(Q)?.unit,detail:J.detail??this._local.get(Q)?.detail}),succeed:(J)=>{C({status:"done",endedAt:Date.now(),detail:J??this._local.get(Q)?.detail}),this.#B(Q)},fail:(J)=>{C({status:"failed",endedAt:Date.now(),error:J?.message||String(J||"failed")})},cancel:()=>{C({status:"cancelled",endedAt:Date.now()}),this.#B(Q)}}}#B(A,Q=5000){setTimeout(()=>{this._local.delete(A),this._cancels?.delete(A),this.#Q()},Q)}async cancel(A){if(this._local.get(A)){this._cancels?.get(A)?.();return}try{await this.api.cancelTask(A),await this.refreshTasks()}catch(B){this.#A({tasksError:B.message})}}dismiss(A){if(this._local.delete(A)){this.#Q();return}this.api.dismissTask(A).catch(()=>{}),this._server=this._server.filter((Q)=>Q.id!==A),this.#Q()}async init(){await this.refresh(),this.#J(),window.addEventListener("focus",()=>this.refresh())}async refresh(){await Promise.all([this.refreshTasks(),this.refreshIssues()])}async refreshTasks(){let A=this.running.length>0;try{let{tasks:Q}=await this.api.tasks();this._server=(Q||[]).map((B)=>({...B,source:"server"})),this.#A({tasksError:null}),this.#Q()}catch(Q){this._server=[],this.#A({tasksError:Q.message}),this.#Q()}if(A&&!this.running.length)this.refreshIssues();this.#J()}async refreshIssues(){this.#A({issuesLoading:!0});try{let{issues:A}=await this.api.issues();this.#A({issues:A||[],issuesLoading:!1,issuesError:null})}catch(A){this.#A({issuesLoading:!1,issuesError:A.message})}}async retryIssue(A){try{await this.api.retryIssue(A),await this.refreshTasks(),this.#C(),this.platform.notifications?.info?.("Retrying — watch its progress in Activity")}catch(Q){this.platform.notifications?.error?.(`Couldn't retry: ${Q.message}`)}}async dismissIssue(A){let Q=this.state.issues;this.#A({issues:Q.filter((B)=>B.id!==A)});try{await this.api.dismissIssue(A)}catch(B){this.#A({issues:Q}),this.platform.notifications?.error?.(`Couldn't dismiss: ${B.message}`)}}#C(){for(let A of[400,1500])setTimeout(()=>{this.refreshTasks(),this.refreshIssues()},A)?.unref?.()}async rebuildIndex(){try{let A=await this.api.reindex();if(await this.refreshTasks(),this.togglePanel(!0),A.alreadyRunning)this.platform.notifications?.info?.("A rebuild is already running");return A}catch(A){throw this.platform.notifications?.error?.(`Couldn't rebuild the index: ${A.message}`),A}}async scanCollection(A){try{let Q=await this.api.scanCollection(A);if(await this.refreshTasks(),this.togglePanel(!0),Q.alreadyRunning)this.platform.notifications?.info?.("A scan of this collection is already running");return this.#C(),Q}catch(Q){throw this.platform.notifications?.error?.(`Couldn't scan “${A}”: ${Q.message}`),Q}}async checkStorage(){try{let A=await this.api.checkStorage();await this.refresh(),this.togglePanel(!0);let Q=(A.results||[]).reduce((B,C)=>B+(C.findings?.length||0),0);if(Q)this.platform.notifications?.warn?.(`Found ${Q} storage problem${Q===1?"":"s"} — see Activity`);else if(!A.checked)this.platform.notifications?.info?.("There are no collections to check yet");else if(!A.corsChecked)this.platform.notifications?.info?.("Stores are reachable. Browser access was not checked — this drive has no public URL configured.");else this.platform.notifications?.success?.("Stores are reachable and allow browser access");return A}catch(A){throw this.platform.notifications?.error?.(`Couldn't check the stores: ${A.message}`),A}}togglePanel(A){if(this.#A({open:A??!this.state.open}),this.state.open)this.refresh()}get running(){return this.state.tasks.filter((A)=>A.status==="running")}#J(){let A=this.running.length?NI:OI;if(this._timer&&this._pollMs===A)return;clearTimeout(this._timer),this._pollMs=A,this._timer=setTimeout(()=>{this._timer=null,this.refreshTasks().then(()=>{if(!this.running.length)this.refreshIssues()})},A),this._timer?.unref?.()}dispose(){clearTimeout(this._timer),this._timer=null}}function jI(A,Q=null){return{...A?.meta||{},...Q||A?.tags||{}}}function zI(A,Q){if(Q.present)return A!=null&&A!==!1&&A!=="";if(A==null)return!1;let B=Number(A),C=Number(Q.value),J=A!==""&&A!==!0&&A!==!1&&Q.value!==""&&Q.value!=null&&!Number.isNaN(B)&&!Number.isNaN(C),K=J?B:String(A).toLowerCase(),E=J?C:String(Q.value).toLowerCase();switch(Q.op){case"!=":return K!==E;case"<":return K<E;case"<=":return K<=E;case">":return K>E;case">=":return K>=E;default:return K===E}}function DE(A,Q,B=null){let C=jI(A,B);return(Q||[]).every((J)=>zI(C[J.key],J))}var wI=/#([\w.-]+)(?::(<=|>=|!=|=|<|>)?("[^"]*"|[^#\s]+)?)?/g;function aB(A){let Q=[],B=A;for(let C of A.matchAll(wI)){let[,J,K,E]=C,L=E&&E.startsWith('"')?E.slice(1,-1):E;Q.push(L==null||L===""?{key:J,present:!0}:{key:J,op:K||"=",value:L,present:!1}),B=B.replace(C[0]," ")}return{text:B.replace(/\s+/g," ").trim(),filters:Q}}function XE(A,Q){if(!Q||!Q.length)return!0;return DE(A,Q)}function h0(A){return A.present?`#${A.key}`:`#${A.key}:${A.op}${A.value}`}var sB="openers.associations";function IE(A){return XB(A)||A?.contentType||""}function $E(A){let Q=XB(A);if(Q)return`${Q} files`;let B=A?.contentType||"";return B?`${B} files`:"this file type"}function iB(A,Q){let B=(J)=>A.context.evaluate(J),C=(J)=>A.plugins.isAvailable(J);return A.contributions.openersFor(Q).filter((J)=>(!J.when||B(J.when))&&C(J)).sort((J,K)=>(K.priority??0)-(J.priority??0))}function GE(A,Q){let B=A.settings.get(sB)||{},C=XB(Q),J=Q?.contentType||"",K=J.includes("/")?`${J.slice(0,J.indexOf("/")+1)}*`:"";return C&&B[C]||J&&B[J]||K&&B[K]||null}function rB(A,Q,B){if(!Q)return;let C={...A.settings.get(sB)||{}};if(B)C[Q]=B;else delete C[Q];A.settings.set(sB,C)}function HE(A){let Q=A.settings.get(sB)||{};return Object.entries(Q).map(([B,C])=>{let J=A.contributions.get(C);return{typeKey:B,openerId:C,openerTitle:J?.title||C,missing:!J}})}function ZE(A,Q){if(!Q?.pluginId)return"Built-in";return A.plugins.plugins.get(Q.pluginId)?.manifest?.displayName||Q.pluginId}class CA extends DB{static deps=["app"]}class SA extends CA{constructor(A){super();this.collectionId=A}async execute({app:A}){let{explorer:Q,platform:B}=A,C=this.collectionId||Q.state.collectionId;if(!C){Q.set({loading:!1,gate:"choose"});return}let J=C!==Q.state.collectionId;Q.set({loading:!0,error:null,collectionId:C,...J?{trash:null}:{}});try{let K=B.settings.get("explorer.sort"),E=B.settings.get("explorer.sortOrder"),L=await B.api.list(C,{sort:K,order:E});Q.set({items:L.items,loading:!1,selection:[],sort:K,order:E,collectionId:L.collectionId||C,stats:L.stats||null,usage:L.usage||null,nextCursor:L.nextCursor||null}),B.settings.set?.("explorer.lastCollection",C),Q.set({gate:null})}catch(K){Q.set({loading:!1,error:K.message}),B.notifications.error(`Couldn't load this collection: ${K.message}`)}}}class tB extends CA{async execute({app:A}){try{let Q=await A.platform.api.collections(),B=Q.collections||[];return A.explorer.set({collections:B,canCreateCollection:!!Q.canCreate}),B}catch{return[]}}}class eB extends CA{async execute({app:A}){let Q=[],B=!1;try{let K=await A.platform.api.collections();Q=K.collections||[],B=!!K.canCreate,A.explorer.set({collections:Q,canCreateCollection:B})}catch(K){A.explorer.set({loading:!1,error:`Couldn't load your collections: ${K.message}`});return}let C=Q.map((K)=>K.id),J=A.platform.settings.get("explorer.lastCollection");if(!C.length){A.explorer.set({loading:!1,items:[],collections:[],gate:B?"create":null,error:B?null:"You do not have access to any collections yet. Ask an administrator to grant you one."});return}if(!J||!C.includes(J)){A.explorer.set({loading:!1,items:[],gate:"choose",error:null});return}return A.explorer.set({gate:null}),A.engine.dispatch(new SA(J))}}class v0 extends CA{constructor(A){super();this.record=A}async execute({app:A}){try{let Q=await A.platform.api.createCollection(this.record);A.platform.notifications.success(`Created collection “${Q.collection.name}”`),await A.engine.dispatch(new tB),A.engine.dispatch(new SA(Q.collection.id))}catch(Q){A.platform.notifications.error(`Couldn’t create collection: ${Q.message}`)}}}class b0 extends CA{async execute({app:A}){let{explorer:Q,platform:B}=A,C=Q.state.nextCursor;if(!C||Q.state.loadingMore)return;Q.set({loadingMore:!0});try{let J=await B.api.list(Q.state.collectionId,{sort:Q.state.sort,order:Q.state.order,cursor:C});Q.set({items:[...Q.state.items,...J.items],nextCursor:J.nextCursor||null,loadingMore:!1})}catch(J){Q.set({loadingMore:!1}),B.notifications.error(`Couldn't load more: ${J.message}`)}}}class $B extends CA{async execute({app:A}){return A.engine.dispatch(new SA(A.explorer.state.collectionId))}}class RQ extends CA{constructor(A="list",Q=null){super();this.op=A,this.id=Q}async execute({app:A}){let{explorer:Q,platform:B}=A,C=Q.state.collectionId;if(this.op==="hide"){Q.set({trash:null});return}try{if(this.op==="restore"){let{node:K}=await B.api.restore(this.id);B.notifications.success(`Restored “${K.name}”`)}else if(this.op==="purge")await B.api.purgeTrash({id:this.id});else if(this.op==="empty"){let{purged:K}=await B.api.purgeTrash({collection:C});B.notifications.success(`Deleted ${K} item${K===1?"":"s"} for good`)}let{items:J}=await B.api.trash(C);if(Q.set({trash:J}),this.op!=="list")await A.engine.dispatch(new SA(C))}catch(J){B.notifications.error(`Trash: ${J.message}`)}}}class f0 extends CA{constructor(A){super();this.ids=A}async execute({app:A}){try{for(let Q of this.ids)await A.platform.api.remove(Q);A.platform.notifications.info(`Deleted ${this.ids.length} item${this.ids.length>1?"s":""}`);for(let Q of this.ids)A.platform.workbench.closeTab(Q)}catch(Q){A.platform.notifications.error(`Couldn’t delete: ${Q.message}`)}A.engine.dispatch(new $B)}}class u0 extends CA{constructor(A,Q){super();this.id=A,this.newName=Q}async execute({app:A}){try{let Q=await A.platform.api.rename(this.id,this.newName);A.platform.workbench.updateTabNode(Q.node),A.engine.dispatch(new $B)}catch(Q){A.platform.notifications.error(`Couldn’t rename: ${Q.message}`)}}}class _A extends CA{constructor(A,Q={}){super();this.node=A,this.opts=Q}async execute({app:A}){if(!this.node)return;let{platform:Q}=A,B=(K)=>Q.workbench.openFile(this.node,K,{reset:!!this.opts.reset});if(this.opts.openerId)return B(this.opts.openerId);let C=iB(Q,this.node),J=GE(Q,this.node);if(J&&C.some((K)=>K.id===J))return B(J);if(C.length>1)return Q.workbench.showDialog({kind:"opener-chooser",node:this.node,openers:C,reset:!!this.opts.reset});B(C[0]?.id||"core.fallback")}}class GB extends CA{constructor(A,Q){super();this.files=A,this.collectionId=Q}async execute({app:A}){let Q=this.collectionId||A.explorer.state.collectionId;if(!Q){A.platform.notifications.error("Open a collection before uploading");return}let B=A.platform.settings.get("uploads.concurrency"),C=[...this.files].map((J)=>this.#A(A,J,Q,B));await Promise.allSettled(C),A.engine.dispatch(new SA(Q))}async#A(A,Q,B,C,J=null){let{transfers:K,platform:E}=A,L=J||xJ("xfer"),D=new AbortController;if(J)K.restart(L,D);else K.start(L,Q.name,Q.size,D,{retry:()=>this.#A(A,Q,B,C,L)});let X=null;try{let Y=await E.api.upload(Q,{collection:B,concurrency:C,signal:D.signal,onStart:(I)=>{X=I},onProgress:(I)=>K.progress(L,I)});if(K.finish(L,"done"),Y?.name&&Y.name!==Q.name)E.notifications.info(`"${Q.name}" already existed — saved as "${Y.name}".`)}catch(Y){if(X)E.api.abortUpload(X).catch(()=>{});if(Y.code==="aborted")K.finish(L,"cancelled");else K.finish(L,"error",Y.message),E.notifications.error(`Upload failed: ${Q.name} — ${Y.message}. Retry it from the transfers tray.`)}}}class HB extends CA{constructor(A,Q){super();this.filters=A||[],this.text=Q||""}async execute({app:A}){let{search:Q,platform:B}=A;if(!this.filters.length){Q.set({results:[],ran:!1,filtered:!1});return}if(Q.set({query:this.text,loading:!0,error:null,filtered:!0}),A.offline&&!A.offline.state.online){let C=(A.explorer.state.items||[]).filter((J)=>XE(J,this.filters));Q.set({results:C.map((J)=>({node:J})),loading:!1,ran:!0,filtered:!0,offline:!0});return}try{let C=await B.api.tagSearch(this.filters,this.text.trim()||void 0,{limit:100});Q.set({results:(C.items||[]).map((J)=>({node:J})),loading:!1,ran:!0,filtered:!0,offline:!1})}catch(C){Q.set({loading:!1,error:C.message,ran:!0,filtered:!0})}}}class m0 extends CA{constructor(A){super();this.query=A}async execute({app:A}){let{search:Q,platform:B}=A,C=(this.query||"").trim();if(!C){Q.set({paletteFiles:[],paletteQuery:"",paletteError:null,paletteLoading:!1});return}Q.set({paletteQuery:C,paletteLoading:!0,paletteError:null});try{let J=await B.api.search(C,{mode:"keyword",limit:30});if(Q.state.paletteQuery!==C)return;Q.set({paletteFiles:J.results||[],paletteLoading:!1})}catch(J){if(Q.state.paletteQuery!==C)return;Q.set({paletteFiles:[],paletteLoading:!1,paletteError:J?.message||"Search failed"})}}}class YQ extends CA{constructor(A,Q){super();this.query=A,this.mode=Q}async execute({app:A}){let{search:Q,platform:B}=A,C=this.query.trim();if(!C){Q.set({query:"",results:[],ran:!1,error:null,resolved:null});return}let J=this.mode||B.settings.get("search.mode");Q.set({query:this.query,mode:J,loading:!0,error:null,resolved:null});let K=A.offline;if(K&&!K.state.online){try{let E=await K.searchOffline(C,{limit:40});Q.set({results:E,loading:!1,ran:!0,offline:!0,resolved:null})}catch(E){Q.set({results:[],loading:!1,ran:!0,offline:!0,error:E.message})}return}try{let E=B.contributions.ofType("view").map((D)=>({id:D.id,title:D.title||D.id})),L=await B.api.query(C,{mode:J,limit:40,views:E});Q.set({results:L.results,resolved:L.resolved||null,loading:!1,ran:!0,offline:!1})}catch(E){if(K){let L=await K.searchOffline(C,{limit:40});Q.set({results:L,loading:!1,ran:!0,offline:!0,error:L.length?null:E.message})}else Q.set({loading:!1,error:E.message,ran:!0})}}}class p0 extends CA{async execute({app:A}){A.apiKeys.set({loading:!0,error:null});try{let Q=await A.platform.api.apiKeys();A.apiKeys.set({keys:Q.keys||[],loading:!1,loaded:!0,error:null})}catch(Q){A.apiKeys.set({loading:!1,loaded:!0,error:Q?.message||"Could not load API keys"})}}}class c0 extends CA{constructor(A){super();this.spec=A}async execute({app:A}){A.apiKeys.set({busy:"mint",error:null});try{let{key:Q,secret:B}=await A.platform.api.mintApiKey(this.spec);A.apiKeys.set({minted:{key:Q,secret:B},busy:null});let C=await A.platform.api.apiKeys().catch(()=>null);if(C)A.apiKeys.set({keys:C.keys||[]});return Q}catch(Q){return A.apiKeys.set({busy:null,error:Q?.message||"Could not create the key"}),A.platform.notifications.error(Q?.message||"Could not create the key"),null}}}class l0 extends CA{constructor(A){super();this.id=A}async execute({app:A}){A.apiKeys.set({busy:this.id,error:null});try{await A.platform.api.revokeApiKey(this.id);let Q=await A.platform.api.apiKeys().catch(()=>null);A.apiKeys.set({busy:null,...Q?{keys:Q.keys||[]}:{}}),A.platform.notifications.success("Key revoked")}catch(Q){A.apiKeys.set({busy:null}),A.platform.notifications.error(Q?.message||"Could not revoke the key")}}}async function WE(A,Q){try{let B=new Uint8Array(await Q.arrayBuffer());await FE(A,FQ(B))}catch(B){A.platform.notifications.error(`Couldn't read the plugin: ${B.message}`)}}async function UE(A,Q){try{let B=await zK(Q,(C,J)=>fetch(C,J));await FE(A,B)}catch(B){A.platform.notifications.error(`Couldn't fetch the plugin: ${B.message}`)}}async function FE(A,Q){let B=wA(Q.manifest);if(A.platform.plugins.plugins.has(bA(Q.manifest))){A.platform.notifications.warn(`“${B}” is already installed.`);return}let C={status:"unverified"};try{C=await A.platform.plugins.assessTrust(Q)}catch{}let J=wK(Q,C);A.platform.workbench.showDialog({kind:"plugin-review",summary:J,isAdmin:!!A.social.state.admin,onInstall:async(K)=>{A.platform.workbench.closeDialog(),A.platform.workbench.setActivity("plugins");let E=A.platform.notifications.info(`Installing “${B}”…`,{sticky:!0});try{await A.platform.plugins.install(Q,{grants:K,trust:C}),A.platform.notifications.dismiss(E),A.platform.notifications.success(`Installed “${B}”`)}catch(L){A.platform.notifications.dismiss(E),A.platform.notifications.error(`Install failed: ${L.message}`)}}})}function RE(A){let{platform:Q,engine:B,explorer:C}=A,{commands:J,workbench:K}=Q,E=(Y)=>B.dispatch(Y),L=(Y,I,$,Z={})=>J.register({id:Y,title:I,handler:$,...Z});L("workbench.showCommandPalette","Show All Commands",()=>K.openPalette("commands"),{category:"View",icon:"command"}),L("workbench.quickOpen","Go to File…",()=>K.openPalette("files"),{category:"File",icon:"search"}),L("workbench.view.home","Go Home (search & browse)",()=>K.showHome(),{category:"View",icon:"search"}),L("workbench.view.plugins","Show Plugins",()=>K.setActivity("plugins"),{category:"View"}),L("workbench.openSettings","Open Settings",()=>K.setActivity("settings"),{category:"Preferences",icon:"gear"}),L("workbench.closeOverlays","Close",()=>K.closeOverlays(),{palette:!1}),L("search.voice","Search by Voice",async()=>{await Q.voice.run({onText:(Y,{final:I})=>{if(!Y)return;if(K.setLaunchQuery(Y),I)E(new YQ(Y))}})},{category:"View",icon:"search"}),L("workbench.showActivity","Show Activity (running work & problems)",()=>A.activity.togglePanel(!0),{category:"View",icon:"refresh"}),L("workbench.rebuildIndex","Rebuild Search Index",()=>A.activity.rebuildIndex().catch(()=>{}),{category:"View",icon:"refresh"}),L("workbench.scanCollection","Scan Collection for Outside Changes",()=>{let Y=C.state.collectionId;if(!Y)return Q.notifications.info("Open a collection first — a scan is per collection.");return A.activity.scanCollection(Y).catch(()=>{})},{category:"Explorer",icon:"refresh"}),L("workbench.checkStorage","Check Storage Configuration",()=>A.activity.checkStorage().catch(()=>{}),{category:"View",icon:"plug"}),L("explorer.refresh","Refresh",()=>E(new $B),{category:"Explorer",icon:"refresh"}),L("explorer.loadMore","Show More Items",()=>E(new b0),{palette:!1}),L("explorer.upload","Upload Files…",()=>{SI((Y)=>Y.length&&E(new GB(Y,C.state.collectionId)))},{category:"Explorer",icon:"upload"});let D=(Y)=>{let I=Y||C.selectedNodes()[0]||K.activeTab()?.node;if(!I)Q.notifications.info("Pick a file first — highlight one in the list, or open it.");return I};L("explorer.copyLink","Copy Link to Item",async()=>{let Y=D();if(!Y)return;let I=oB(Y);try{await navigator.clipboard.writeText(I),Q.notifications.success(`Copied ${I}`)}catch{Q.notifications.info(I,{sticky:!0})}},{category:"Explorer",icon:"link"}),L("explorer.rename","Rename",()=>{let Y=D();if(!Y)return;K.showDialog({kind:"prompt",title:"Rename",label:"New name",value:Y.name,confirmLabel:"Rename",onSubmit:(I)=>{if(K.closeDialog(),I?.trim()&&I!==Y.name)E(new u0(Y.id,I.trim()))}})},{category:"Explorer"}),L("explorer.delete","Delete",()=>{let Y=C.selectedNodes(),I=Y.length?null:K.activeTab()?.node;if(I)Y.push(I);if(!Y.length){Q.notifications.info("Pick a file first — highlight one in the list, or open it.");return}let $=()=>E(new f0(Y.map((Z)=>Z.id)));if(Q.settings.get("explorer.confirmDelete"))K.showDialog({kind:"confirm",title:`Move ${Y.length} item${Y.length>1?"s":""} to the trash?`,body:Y.length===1?`"${Y[0].name}" leaves the drive but is kept, and can be restored from the trash.`:"They leave the drive but are kept, and can be restored from the trash.",confirmLabel:"Move to trash",onConfirm:()=>{K.closeDialog(),$()}});else $()},{category:"Explorer",icon:"trash"}),L("explorer.showTrash","Show Trash",()=>{E(new RQ("list")),K.showHome()},{category:"Explorer",icon:"trash"}),L("keys.load","Load API Keys",()=>E(new p0),{palette:!1}),L("keys.new","New API Key",()=>A.apiKeys.startDraft(),{palette:!1}),L("keys.cancel","Cancel API Key",()=>A.apiKeys.cancelDraft(),{palette:!1}),L("keys.dismissMinted","Dismiss API Key",()=>A.apiKeys.clearMinted(),{palette:!1}),L("keys.revoke","Revoke API Key",(Y)=>Y&&E(new l0(Y)),{palette:!1}),L("keys.mint","Create API Key",()=>{let Y=A.apiKeys.state.draft,I=A.apiKeys.draftScopes();if(!Y?.name?.trim()||!I)return;let $=Number(Y.expiresInDays),Z=Y.expiresInDays!==""&&Number.isFinite($)&&$>0?Date.now()+$*86400000:null;return A.apiKeys.cancelDraft(),E(new c0({name:Y.name.trim(),scopes:I,expiresAt:Z}))},{palette:!1}),L("explorer.hideTrash","Hide Trash",()=>E(new RQ("hide")),{palette:!1}),L("explorer.restore","Restore from Trash",(Y)=>Y&&E(new RQ("restore",Y)),{palette:!1}),L("explorer.purgeOne","Delete Forever",(Y)=>Y&&E(new RQ("purge",Y)),{palette:!1}),L("explorer.emptyTrash","Empty Trash",()=>{K.showDialog({kind:"confirm",title:"Empty the trash?",body:"Everything in the trash will be destroyed. This cannot be undone.",danger:!0,confirmLabel:"Delete forever",onConfirm:()=>{K.closeDialog(),E(new RQ("empty"))}})},{category:"Explorer",icon:"trash"}),L("explorer.open","Open",(Y)=>E(new _A(Y||C.selectedNodes()[0])),{palette:!1}),L("explorer.download","Download",async(Y)=>{let I=Y||C.selectedNodes()[0]||K.activeTab()?.node;if(!I?.id)return;try{let{url:$,revoke:Z}=await Q.api.download(I.id,I.name);if(TI($,I.name),Z)setTimeout(()=>URL.revokeObjectURL($),60000)}catch($){Q.notifications.error(`Couldn't download ${I.name}: ${$.message}`)}},{category:"Explorer",icon:"download"}),L("offline.pin","Make Available Offline",(Y)=>{let I=Y||C.selectedNodes()[0]||K.activeTab()?.node;if(I?.id)A.offline.pin(I)},{category:"Offline",icon:"download"}),L("offline.unpin","Remove from Offline",(Y)=>{let I=Y||C.selectedNodes()[0]||K.activeTab()?.node;if(I)A.offline.unpin(I.id)},{palette:!1});let X=()=>{let Y=C.state.collectionId,I=(C.state.collections||[]).map(($)=>({label:$.name||$.id,icon:$.id===Y?"check":"files",run:()=>J.execute("collections.switch",$.id)}));if(C.state.canCreateCollection){if(I.length)I.push({sep:!0});I.push({label:"New collection…",icon:"plus",run:()=>J.execute("collections.create")})}return I};A.collectionMenu=X,L("collections.switch","Switch Collection…",(Y)=>{if(Y){E(new SA(Y)),K.showHome();return}let I=X();if(!I.length)return Q.notifications.info("This drive has one collection.");let $=typeof window>"u"?800:window.innerWidth;K.showContextMenu(Math.max(12,Math.round($/2)-110),120,I)},{category:"Collections",icon:"files"}),L("collections.create","New Collection…",()=>{K.showDialog({kind:"collection",title:"New collection",onSubmit:(Y)=>{if(K.closeDialog(),Y)E(new v0(Y))}})},{category:"Collections",icon:"files"}),L("workbench.toggleInfoPanel","Toggle Details & Conversation",()=>{if(!K.activeTab()){Q.notifications.info("Open a file to see its details and conversation.");return}K.toggleInfoPanel()},{category:"View",icon:"info"}),L("notifications.show","Show Notifications",()=>A.social.toggleInbox(!0),{category:"View"}),L("notifications.enablePush","Enable Push Notifications",()=>A.social.enablePush(),{category:"Notifications"}),L("plugins.installFromUrl","Install Plugin from URL…",()=>{K.showDialog({kind:"prompt",title:"Install plugin from URL",label:"Plugin package (.zip) URL",placeholder:"https://example.com/plugin.zip",confirmLabel:"Fetch",onSubmit:(Y)=>{if(K.closeDialog(),Y?.trim())UE(A,Y.trim())}})},{category:"Plugins",icon:"plug"}),L("plugins.installFromFile","Install Plugin from File…",()=>{_I((Y)=>Y&&WE(A,Y))},{category:"Plugins",icon:"plug"})}function ME(A,Q){let B=document.createElement("input");B.type="file",Q(B),B.style.display="none",document.body.appendChild(B);let C=()=>{B.remove(),window.removeEventListener("focus",J)},J=()=>setTimeout(()=>{if(!B.files.length)C()},300);B.addEventListener("change",()=>{A(B.files),C()},{once:!0}),window.addEventListener("focus",J),B.click()}function SI(A){ME((Q)=>A(Q),(Q)=>{Q.multiple=!0})}function _I(A){ME((Q)=>A(Q[0]),(Q)=>{Q.accept=".zip,application/zip"})}function TI(A,Q){let B=document.createElement("a");B.href=A,B.download=Q||"",document.body.appendChild(B),B.click(),B.remove()}function VE(A){let Q=new q0(A.settings),B=new N0,C=new P0,J=new y0(A),K=new O0(J),E=new j0(A),L=new k0(A);E.offline=L;let D={platform:A,explorer:Q,search:B,transfers:K,social:E,offline:L,activity:J,apiKeys:C,engine:null},X=new dB({providers:{app:EQ.fromSingleton(D)}});D.engine=X,RE(D),A.openPluginPanel=(I)=>A.workbench.openPluginPanel(I),A.context.setMany({"explorer.collectionId":null,"explorer.hasSelection":!1}),gA(Q.observe(),(I)=>{A.context.setMany({"explorer.collectionId":I.collectionId??null,"explorer.hasSelection":(I.selection?.length||0)>0})});let Y=null;return gA(A.workbench.observeNav(),(I)=>{if(I.activeTabId!==Y)Y=I.activeTabId,E.loadSidecar(I.activeFile?I.activeFile.id:null)}),E.init(),L.init(),J.init(),X.dispatch(new tB),{engine:X,app:D}}var{svg:xI,h:gI}=x,d0={link:[{d:"M10 13a5 5 0 0 0 7.07 0l3-3A5 5 0 0 0 13 3l-1.5 1.5"},{d:"M14 11a5 5 0 0 0-7.07 0l-3 3A5 5 0 0 0 11 21l1.5-1.5"}],file:[{d:"M6 3h8l5 5v13a1 1 0 0 1-1 1H6a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1z"},{d:"M14 3v5h5"}],"file-text":[{d:"M6 3h8l5 5v13a1 1 0 0 1-1 1H6a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1z"},{d:"M14 3v5h5M9 13h6M9 17h6M9 9h2"}],"file-image":[{d:"M6 3h8l5 5v13a1 1 0 0 1-1 1H6a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1z"},{d:"M14 3v5h5"},{d:"M8.5 15l2-2 3 3 2-1.5"},{d:"M10 12a1 1 0 1 0 0-.01"}],"file-audio":[{d:"M6 3h8l5 5v13a1 1 0 0 1-1 1H6a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1z"},{d:"M14 3v5h5M10 12v5M13 10v9"}],"file-video":[{d:"M6 3h8l5 5v13a1 1 0 0 1-1 1H6a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1z"},{d:"M14 3v5h5M10 12l4 2.5-4 2.5z"}],book:[{d:"M4 5a2 2 0 0 1 2-2h13v16H6a2 2 0 0 0-2 2z"},{d:"M4 19a2 2 0 0 1 2-2h13"}],search:[{d:"M11 4a7 7 0 1 0 0 14 7 7 0 0 0 0-14zM20 20l-3.5-3.5"}],mic:[{d:"M12 3a3 3 0 0 0-3 3v6a3 3 0 0 0 6 0V6a3 3 0 0 0-3-3z"},{d:"M5 11a7 7 0 0 0 14 0M12 18v3M9 21h6"}],command:[{d:"M8 6a2 2 0 1 0-2 2h12a2 2 0 1 0-2-2v12a2 2 0 1 0 2-2H6a2 2 0 1 0 2 2z"}],gear:[{d:"M12 9a3 3 0 1 0 0 6 3 3 0 0 0 0-6z"},{d:"M19 12a7 7 0 0 0-.1-1.2l2-1.6-2-3.4-2.4 1a7 7 0 0 0-2-1.2L14 2h-4l-.5 2.6a7 7 0 0 0-2 1.2l-2.4-1-2 3.4 2 1.6A7 7 0 0 0 5 12a7 7 0 0 0 .1 1.2l-2 1.6 2 3.4 2.4-1a7 7 0 0 0 2 1.2L10 22h4l.5-2.6a7 7 0 0 0 2-1.2l2.4 1 2-3.4-2-1.6A7 7 0 0 0 19 12z"}],upload:[{d:"M12 16V4M7 9l5-5 5 5M4 20h16"}],download:[{d:"M12 4v12M7 11l5 5 5-5M4 20h16"}],trash:[{d:"M4 7h16M9 7V4h6v3M6 7l1 13h10l1-13M10 11v6M14 11v6"}],refresh:[{d:"M20 11a8 8 0 1 0-.5 4M20 5v6h-6"}],"chevron-right":[{d:"M9 6l6 6-6 6"}],"chevron-left":[{d:"M15 6l-6 6 6 6"}],"chevron-down":[{d:"M6 9l6 6 6-6"}],close:[{d:"M6 6l12 12M18 6L6 18"}],tag:[{d:"M4 4h6.5a1 1 0 0 1 .7.3l8.5 8.5a1 1 0 0 1 0 1.4l-5.5 5.5a1 1 0 0 1-1.4 0L4.3 11.2a1 1 0 0 1-.3-.7V4z"},{d:"M8 8a0.6 0.6 0 1 0 0-.01"}],play:[{d:"M8 5v14l11-7z",fill:"currentColor",stroke:"none"}],pause:[{d:"M8 5h3v14H8zM13 5h3v14h-3z",fill:"currentColor",stroke:"none"}],"skip-back":[{d:"M11 6v12L3 12zM13 6l8 6-8 6zM21 6v12",fill:"none"}],"skip-forward":[{d:"M13 6v12l8-6zM3 6l8 6-8 6zM3 6v12"}],"back-30":[{d:"M11 8a7 7 0 1 0 7 7"},{d:"M11 4l-3 4 4 1"}],"fwd-30":[{d:"M13 8a7 7 0 1 1-7 7"},{d:"M13 4l3 4-4 1"}],plug:[{d:"M9 3v6M15 3v6M6 9h12v3a6 6 0 0 1-12 0zM12 18v3"}],bell:[{d:"M18 8a6 6 0 1 0-12 0c0 7-3 9-3 9h18s-3-2-3-9z"},{d:"M13.73 21a2 2 0 0 1-3.46 0"}],files:[{d:"M4 4h9l3 3v3M8 8h8a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2v-9a2 2 0 0 1 2-2z"}],dots:[{d:"M5 12h.01M12 12h.01M19 12h.01"}],check:[{d:"M5 12l5 5L20 6"}],plus:[{d:"M12 5v14M5 12h14"}],"arrow-up":[{d:"M12 19V5M6 11l6-6 6 6"}],star:[{d:"M12 3l2.7 5.6 6.1.9-4.4 4.3 1 6.1L12 17l-5.4 2.9 1-6.1L3.2 9.5l6.1-.9z"}],info:[{d:"M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18zM12 11v5M12 8h.01"}],warn:[{d:"M12 3l9 16H3zM12 10v4M12 17h.01"}],x:[{d:"M6 6l12 12M18 6L6 18"}],list:[{d:"M8 6h12M8 12h12M8 18h12M4 6h.01M4 12h.01M4 18h.01"}],grid:[{d:"M4 4h7v7H4zM13 4h7v7h-7zM4 13h7v7H4zM13 13h7v7h-7z"}]};function U(A,{size:Q=18,strokeWidth:B=1.6,className:C}={}){let J=Object.hasOwn(d0,A)?d0[A]:d0.file;return xI({$attrs:{viewBox:"0 0 24 24",width:Q,height:Q,fill:"none",stroke:"currentColor","stroke-width":B,"stroke-linecap":"round","stroke-linejoin":"round",...C?{class:C}:{}}},...J.map((K)=>gI("path",{$attrs:kI(K)})))}function kI(A){let Q={d:A.d};if(A.fill)Q.fill=A.fill;if(A.stroke)Q.stroke=A.stroke;return Q}function QA(A){if(A==null||Number.isNaN(A))return"—";let Q=["B","KB","MB","GB","TB"],B=0,C=A;while(C>=1024&&B<Q.length-1)C/=1024,B++;return`${C>=100||B===0?Math.round(C):C.toFixed(1)} ${Q[B]}`}function n0(A){if(!A)return"";let Q=Date.now()-A,B=86400000;if(Q<60000)return"just now";if(Q<3600000)return`${Math.floor(Q/60000)}m ago`;if(Q<B)return`${Math.floor(Q/3600000)}h ago`;if(Q<7*B)return`${Math.floor(Q/B)}d ago`;return new Date(A).toLocaleDateString(void 0,{month:"short",day:"numeric",year:Q>330*B?"numeric":void 0})}var{div:k,span:JA,button:qA,textarea:yI,input:hI,p:UZ}=x,vI=["\uD83D\uDC4D","❤️","\uD83C\uDF89","\uD83D\uDC40","\uD83D\uDE80"];function qE(A){let Q=A.so.me;if(!Q||Q.anonymous)return null;let B=(Q.name||Q.id||"?")[0].toUpperCase();return k({className:"principal",title:Q.email||Q.name||Q.id},Q.picture?x.img({src:Q.picture,alt:"",className:"avatar-img"}):JA({className:"avatar-txt"},B))}function PE(A,Q){let B=A.so.notifications,C=Q.app.social;return k({className:"bell-wrap"},qA({className:"iconbtn bell",title:"Notifications"},U("bell",{size:19}),B.unread?JA({className:"bell-badge"},String(B.unread>9?"9+":B.unread)):null).on({click:()=>C.toggleInbox()}),A.so.inboxOpen?bI(A,Q):null)}function bI(A,Q){let B=A.so.notifications.items,C=Q.app.social;return k({},k({className:"scrim",$styling:{background:"transparent","z-index":"54"}}).on({click:()=>C.toggleInbox(!1)}),k({className:"inbox"},k({className:"inbox-head"},JA("Notifications"),A.so.pushSupported&&!A.so.pushEnabled?qA({className:"link"},"Enable push").on({click:()=>C.enablePush()}):A.so.pushEnabled?JA({className:"muted"},U("check",{size:13})):null),B.length?k({className:"inbox-items"},...B.slice(0,30).map((J)=>fI(J,Q))):k({className:"inbox-empty"},U("info",{size:24}),JA("You’re all caught up."))))}function fI(A,Q){let B=A.items?.[0];return k({className:`inbox-item ${A.read?"":"unread"}`},k({className:"ii-title"},A.title),B?.excerpt?k({className:"ii-excerpt"},"“"+B.excerpt+"”"):null,k({className:"ii-time"},n0(A.createdAt))).on({click:()=>{if(B?.nodeId)Q.platform.api.stat(B.nodeId).then((C)=>{Q.go(new _A(C.node)),Q.platform.workbench.toggleInfoPanel(!0)}).catch((C)=>{Q.platform.notifications.warn(C?.status===403||C?.code==="forbidden"?"You no longer have access to that item.":"That item no longer exists.")});Q.app.social.toggleInbox(!1)}})}function o0(A,Q){let B=A.nav,C=B.activeFile?{id:B.activeTabId,node:B.activeFile}:null,J=A.so.sidecar;return k({className:"infopanel"},k({className:"ip-head"},U("info",{size:15}),JA("Details"),qA({className:"iconbtn",title:"Close"},U("close",{size:14})).on({click:()=>Q.platform.workbench.toggleInfoPanel(!1)})),!C?k({className:"ip-empty"},JA("Open a file to see its tags and conversation.")):k({className:"ip-body"},uI(C.node,A,Q),mI(C.node,A,Q),cI(J,Q),lI(A,J,Q)))}function uI(A,Q,B){let C=B.app.offline.isPinned(A.id);return k({className:"ip-file"},k({className:"ip-name"},A.name),k({className:"ip-path"},A.contentType||""),qA({className:`btn small ${C?"on":""}`,$styling:{"margin-top":"10px"}},U(C?"check":"download",{size:14}),C?"Available offline":"Make available offline").on({click:()=>C?B.exec("offline.unpin",A):B.exec("offline.pin",A)}))}function mI(A,Q,B){let C=Q.so.backlinks,J=A.collectionId?oB(A):null,K=C&&C.nodeId===A.id?C:null;return k({className:"ip-section"},k({className:"ip-label"},"Links"),J?qA({className:"ip-uri",title:"Copy this item’s link"},U("link",{size:12}),JA(J)).on({click:()=>pI(B,J)}):null,k({className:"ip-label",$styling:{"margin-top":"10px"}},"Linked from"),K?.loading?k({className:"ip-muted"},"Loading…"):K?.error?k({className:"ip-muted error"},`Couldn’t load links: ${K.error}`):K?.items?.length?k({className:"ip-backlinks"},...K.items.map((E)=>qA({className:"ip-backlink",title:E.name},U("file-text",{size:12}),JA(E.name)).on({click:()=>B.go(new _A(E))}))):k({className:"ip-muted"},"Nothing links here yet."))}async function pI(A,Q){try{await navigator.clipboard.writeText(Q),A.platform.notifications.success(`Copied ${Q}`)}catch{A.platform.notifications.info(Q,{sticky:!0})}}function cI(A,Q){let B=A?.tags||[];return k({className:"ip-section"},k({className:"ip-label"},"Tags"),k({className:"tags"},...B.map((C)=>JA({className:"tag"},C.value?`${C.name}: ${C.value}`:C.name,qA({className:"tag-x"},U("close",{size:11})).on({click:()=>Q.app.social.removeTag(C.name)}))),hI({className:"tag-input",placeholder:"+ tag",value:""}).on({keydown:(C)=>{if(C.key==="Enter"&&C.target.value.trim()){let J=C.target.value.trim(),[K,...E]=J.split(":");Q.app.social.addTag(K.trim(),E.join(":").trim()||void 0),C.target.value=""}}})))}function lI(A,Q,B){if(Q?.loading)return k({className:"ip-section"},k({className:"spinner"}));let C=Q?.comments||[],J=Q?.error?k({className:"conv-empty"},JA(`Couldn't load the conversation: ${Q.error}`),qA({className:"btn",$styling:{"margin-top":"8px"}},"Retry").on({click:()=>B.app.social.loadSidecar(Q.nodeId)})):C.length?k({className:"thread"},...C.map((K)=>NE(K,A,B,0))):k({className:"conv-empty"},"No comments yet. Start the discussion — use @ to mention someone.");return k({className:"ip-section conv"},k({className:"ip-label"},`Conversation${Q?.commentCount?` · ${Q.commentCount}`:""}`),J,Q?.error?null:dI(A,B))}function NE(A,Q,B,C){let J=Q.so.me,K=B.app.social,E=J&&A.author?.id===J.id;return k({className:"comment",$styling:C?{marginLeft:"18px"}:{}},k({className:"c-head"},JA({className:"c-avatar"},(A.author?.name||"?")[0].toUpperCase()),JA({className:"c-author"},A.author?.name||A.author?.id||"Someone"),JA({className:"c-time"},n0(A.createdAt),A.edited?" · edited":"")),A.deleted?k({className:"c-body deleted"},"comment deleted"):k({className:"c-body"},nI(A.body)),!A.deleted?k({className:"c-actions"},...vI.map((L)=>{let D=A.reactions?.[L]||[];return qA({className:`react ${D.includes(J?.id)?"on":""}`},L,D.length?JA({className:"rc"},String(D.length)):null).on({click:()=>K.react(A.id,L)})}),qA({className:"c-link"},"Reply").on({click:()=>K.setReplyTo({id:A.id,author:A.author})}),E?qA({className:"c-link danger"},"Delete").on({click:()=>K.deleteComment(A.id)}):null):null,(A.replies||[]).length?k({className:"replies"},...A.replies.map((L)=>NE(L,Q,B,C+1))):null).key(A.id)}function dI(A,Q){let B=Q.app.social,C=A.so.me,J=A.so.replyTo;if(!C){if(!A.off?.online)return k({className:"conv-signin"},"You’re offline. Conversations come back when you reconnect.");return k({className:"conv-signin"},JA("You’re signed out, so you can read this conversation but not add to it."),qA({className:"c-link"},"Reload to sign in").on({click:()=>window.location.reload()}))}return k({className:"composer"},J?k({className:"replying"},`Replying to ${J.author?.name||"comment"}`,qA({className:"c-link"},"cancel").on({click:()=>B.setReplyTo(null)})):null,yI({className:"composer-input",placeholder:"Write a comment… @mention someone",rows:2,value:""}).on({keydown:(K)=>{if(K.key==="Enter"&&(K.metaKey||K.ctrlKey))B.comment(K.target.value),K.target.value=""}}),k({className:"composer-actions"},JA({className:"muted"},"⌘/Ctrl + Enter"),qA({className:"btn primary",disabled:A.so.posting},"Comment").on({click:(K)=>{let E=K.target.closest(".composer").querySelector(".composer-input");B.comment(E.value),E.value=""}})))}function nI(A){let Q=[],B=/@\[([^\]]+)\]\(([^)]+)\)|(?:^|\s)@([a-zA-Z0-9._@-]{2,})/g,C=0,J;while(J=B.exec(A)){if(J.index>C)Q.push(A.slice(C,J.index+(J[3]?J[0].startsWith(" ")?1:0:0)));Q.push(JA({className:"mention"},"@"+(J[1]||J[3]))),C=B.lastIndex}if(C<A.length)Q.push(A.slice(C));return Q}var{div:OE,button:a0,span:oI,img:aI}=x,sI=[{id:"home",icon:"search",title:"Search & files",command:"workbench.view.home"},{id:"plugins",icon:"plug",title:"Plugins",command:"workbench.view.plugins"}];function s0(A,Q){let B=A.wb.activity,C=A.plugins?.filter((J)=>J.status==="active").length||0;return OE({className:"activitybar"},a0({className:"brand-mark",title:"Trove — home"},aI({src:"/icon.svg",alt:"Trove"})).on({click:()=>Q.exec("workbench.view.home")}),...sI.map((J)=>a0({className:`item ${B===J.id?"active":""}`,title:J.title},U(J.icon,{size:22}),J.id==="plugins"&&C?oI({className:"badge"},String(C)):null).on({click:()=>Q.exec(J.command)})),OE({className:"spacer"}),PE(A,Q),a0({className:`item ${B==="settings"?"active":""}`,title:"Settings"},U("gear",{size:21})).on({click:()=>Q.exec("workbench.openSettings")}),qE(A))}var iI=new Set(["SPAN","B","STRONG","I","EM","CODE","SMALL","BR","S","U"]),rI=new Set(["class","title"]);function jE(A){let Q=document.createDocumentFragment();if(typeof A!=="string"||!A)return Q;let B=document.createElement("template");B.innerHTML=A.slice(0,4096);let C={nodes:200};for(let J of B.content.childNodes){let K=_E(J,C);if(K)Q.appendChild(K)}return Q}function zE(A){return(jE(A).textContent||"").trim()}function wE(A,Q){return[...jE(A).childNodes].map((B)=>SE(B,Q)).filter((B)=>B!=null)}function SE(A,Q){if(A.nodeType===Node.TEXT_NODE)return A.nodeValue;let B=Q[A.tagName.toLowerCase()];if(!B)return A.textContent;let C={};if(A.className)C.className=A.className;if(A.title)C.title=A.title;return B(C,...[...A.childNodes].map((J)=>SE(J,Q)).filter((J)=>J!=null))}function _E(A,Q){if(Q.nodes--<=0)return null;if(A.nodeType===Node.TEXT_NODE)return document.createTextNode(A.nodeValue);if(A.nodeType!==Node.ELEMENT_NODE)return null;if(!iI.has(A.tagName))return null;let B=document.createElement(A.tagName.toLowerCase());for(let C of A.attributes){let J=C.name.toLowerCase();if(!rI.has(J))continue;B.setAttribute(J,C.value.slice(0,200))}for(let C of A.childNodes){let J=_E(C,Q);if(J)B.appendChild(J)}return B}var{div:MQ,button:VQ,span:KA}=x;function TE(A,Q){if(A.visible===!1||!A.html)return null;if(A.when&&!Q.platform.context.evaluate(A.when))return null;if(!Q.platform.plugins.isAvailable(A))return null;let B=wE(A.html,x);if(!B.length)return null;let C=A.tooltip?zE(A.tooltip):"";return A.command?VQ({className:"seg",title:C},...B).on({click:()=>Q.exec(A.command)}):KA({className:"seg",title:C},...B)}function tI(A,Q){let B=A.act||{tasks:[],issues:[]},C=B.tasks.filter((E)=>E.status==="running"),J=()=>Q.app.activity.togglePanel(!0),K=[];if(C.length){let E=C[0],D=E.total!=null&&E.total>0?Math.round((E.done||0)/E.total*100):null;K.push(VQ({className:"seg sb-activity",title:C.map((X)=>X.title).join(`
348
+ `)},MQ({className:"spinner",$styling:{width:"11px",height:"11px"}}),KA(C.length>1?`${C.length} running`:`${E.title}${D==null?"":` ${D}%`}`)).on({click:J}))}if(B.issues.length)K.push(VQ({className:"seg sb-attention",title:B.issues.map((E)=>E.title).join(`
349
+ `)},U("info",{size:12}),KA(`${B.issues.length} need${B.issues.length===1?"s":""} attention`)).on({click:J}));return K}function i0(A){let Q=A.usage;if(!Q?.total)return null;let B=Q.available/Q.total,C=Math.min(100,Math.round(Q.used/Q.total*100)),J=B<0.05?"critical":B<0.1?"low":"";return KA({className:`seg sb-usage ${J}`,title:`${QA(Q.used)} used of ${QA(Q.total)} — ${QA(Q.available)} free on this volume`},MQ({className:"usage-bar"},MQ({className:"usage-fill",$styling:{width:`${C}%`}})),KA(`${QA(Q.available)} free`))}function AC(A,Q){let B=A.ex,C=B.items||[],J=A.act||{tasks:[],issues:[]};return{collectionId:B.collectionId??null,collectionLabel:xE(B),totalItems:B.stats?.items??C.length,totalKnown:B.stats?.items!=null,totalBytes:B.stats?.bytes??C.reduce((K,E)=>K+(E.size||0),0),shown:C.length,partial:!!B.nextCursor,usage:B.usage,uploading:A.tr.items.filter((K)=>K.status==="active"),running:J.tasks.filter((K)=>K.status==="running"),issues:J.issues,off:A.off||{online:!0,pins:[],queued:0,syncing:!1},caps:Q.platform.capabilities}}function xE(A){if(!A?.collectionId)return"no collection";return(A.collections||[]).find((B)=>B.id===A.collectionId)?.name||A.collectionId}function r0(A,Q){let B=A.ex,C=B.items||[],J=AC(A,Q),{totalItems:K,totalBytes:E,caps:L}=J,D=J.uploading,X=[...A.statusItems||[]].sort((Z,F)=>(Z.order??0)-(F.order??0)||Z.name.localeCompare(F.name)),Y=X.filter((Z)=>Z.slot==="left").map((Z)=>TE(Z,Q)),I=X.filter((Z)=>Z.slot!=="left").map((Z)=>TE(Z,Q)),$=J.off;return MQ({className:"statusbar"},!$.online?KA({className:"seg offline-badge",title:"You are offline — pinned files and cached data are available"},U("info",{size:12}),KA("Offline")):$.syncing?KA({className:"seg",title:"Syncing offline changes"},MQ({className:"spinner",$styling:{width:"11px",height:"11px"}}),KA("Syncing…")):null,$.queued?KA({className:"seg",title:"Changes waiting to sync"},`${$.queued} queued`):null,$.pins.length?VQ({className:"seg",title:`${$.pins.length} file(s) available offline`},U("download",{size:12}),KA(`${$.pins.length} offline`),U("chevron-down",{size:11})).on({click:(Z)=>{let F=$.pins.slice(0,12).flatMap((P)=>[{label:P.name,icon:"file-text",run:()=>Q.exec("explorer.open",P)},{label:`Remove “${P.name}” from offline`,icon:"close",run:()=>Q.exec("offline.unpin",P)},{sep:!0}]);if($.pins.length>12)F.push({label:`…and ${$.pins.length-12} more`,run:()=>{}});let R=Z.currentTarget.getBoundingClientRect();Q.platform.workbench.showContextMenu(R.left,R.top-8-F.length*34,F)}}):null,VQ({className:"seg",title:"Switch collection"},U("files",{size:13}),KA(xE(B)),(B.collections||[]).length>1||B.canCreateCollection?U("chevron-down",{size:11}):null).on({click:(Z)=>{let F=Q.app.collectionMenu?.()||[];if(F.length>1||B.canCreateCollection){let R=Z.currentTarget.getBoundingClientRect();Q.platform.workbench.showContextMenu(R.left,R.top-8-F.length*34,F)}else Q.exec("workbench.view.home")}}),D.length?VQ({className:"seg",title:"Active uploads — click to cancel"},MQ({className:"spinner",$styling:{width:"11px",height:"11px"}}),KA(`${D.length} uploading`)).on({click:(Z)=>Q.platform.workbench.showContextMenu(Z.clientX,Z.clientY,D.map((F)=>({label:`Cancel ${F.name} (${Math.round((F.ratio||0)*100)}%)`,icon:"close",danger:!0,run:()=>Q.app.transfers.cancel(F.id)})))}):KA({className:"seg",title:B.nextCursor?`Showing ${C.length} of ${J.totalKnown?K:"more"}`:""},`${K.toLocaleString()}${J.totalKnown||!J.partial?"":"+"} item${K===1?"":"s"}`),...Y,MQ({className:"spacer"}),...tI(A,Q),...I,KA({className:"seg",title:J.totalKnown||!J.partial?"Total size of this collection":`Size of the ${J.shown.toLocaleString()} items loaded so far — this server doesn’t report a collection total`},`${QA(E)}${J.totalKnown||!J.partial?"":"+"}`),i0(B),L?KA({className:"seg",title:"Storage backend capabilities"},U(L.storage?.presignDownload?"download":"files",{size:12}),KA(L.storage?.presignDownload?"S3 direct":"proxied")):null,L?.features?.semanticSearch?VQ({className:"seg",title:"Semantic search enabled"},U("star",{size:12}),KA("semantic")).on({click:()=>Q.exec("workbench.view.home")}):null)}var{div:gE,span:kE,button:eI}=x;function QC(A){return gE({className:"launch-h"},gE({className:"lh-title"},kE(A.title),A.verbatim?kE({className:"lh-verbatim"},A.verbatim):null),A.action||null)}function BC(A,Q,B){if(!A.menu)return null;return eI({className:"launch-more",title:`Actions for ${A.title}`,$attrs:{"aria-label":`Actions for ${A.title}`}},U("dots",{size:14})).on({click:(C)=>{C.stopPropagation(),qQ(C.currentTarget,A,Q,null,B)}})}function qQ(A,Q,B,C,J){let K=A?.getBoundingClientRect?.(),E=C?.clientX??(K?K.right-8:0),L=C?.clientY??(K?K.bottom:0),D=Q.menu(B);J?.(),B.platform.workbench.showContextMenu(E,L,D)}var{div:ZB,span:t0}=x;function CC({groups:A,index:Q,handlers:B,ui:C}){let J=-1;return ZB({className:"launch-view view-list"},...A.map((K)=>ZB({className:"launch-group"},QC(K),K.items.length?ZB({className:"launch-list"},...K.items.map((E)=>{let L=++J;return A1(E,L===Q,{hover:()=>B.hover(L),select:()=>B.select(L)},C)})):ZB({className:"launch-empty"},K.empty||"Nothing here."))))}function A1(A,Q,{hover:B,select:C},J){return ZB({className:`launch-item ${Q?"active":""}`},U(A.icon,{size:15}),t0({className:"name"},A.title),A.detail?t0({className:"launch-detail"},A.detail):null,A.badge?t0({className:"launch-kind"},A.badge):null,BC(A,J,C)).on({click:A.run,mouseenter:B,...A.menu?{contextmenu:(K)=>{K.preventDefault(),qQ(K.currentTarget,A,J,K,C)}}:{}})}function mQ(A,Q,B,{op:C="media",onError:J}={}){let K=B.platform.mediaUrls,E=null,L=!1,D=!1,X=()=>{clearTimeout(E),E=null},Y=(F)=>{if(X(),!Number.isFinite(F))return;let R=Math.max(1000,(F-Date.now())*0.8);E=setTimeout(()=>I({resume:!0}),Math.min(R,2147483647))};async function I({resume:F}){if(L)return;let R=Q1(A),P=R&&F?A.currentTime:0,z=R&&F?!A.paused&&!A.ended:!1,h;try{h=await K.url(Q.id,{op:C})}catch(M){if(!L)J?.(M.message);return}if(L)return;if(A.src=h.url,R){if(A.load(),P>0||z){let M=()=>{if(A.removeEventListener("loadedmetadata",M),P>0&&Number.isFinite(A.duration)&&A.duration>P)A.currentTime=P;if(z)A.play().catch(()=>{})};A.addEventListener("loadedmetadata",M)}}Y(h.expiresAt)}let $=()=>{D=!1};A.addEventListener("load",$),A.addEventListener("loadeddata",$);let Z=()=>{if(L)return;if(D){J?.(null);return}D=!0,K.invalidate(Q.id,C),I({resume:!0})};return A.addEventListener("error",Z),I({resume:!1}),()=>{L=!0,X(),A.removeEventListener("error",Z),A.removeEventListener("load",$),A.removeEventListener("loadeddata",$)}}function Q1(A){return typeof A?.play==="function"&&typeof A?.load==="function"}var{div:PQ,span:B1,img:C1}=x;function yE({groups:A,index:Q,handlers:B,ui:C}){let J=-1;return PQ({className:"launch-view view-grid"},...A.map((K)=>PQ({className:"launch-group"},QC(K),K.items.length?PQ({className:"grid-list"},...K.items.map((E)=>{let L=++J;return K1(E,L===Q,{hover:()=>B.hover(L),select:()=>B.select(L)},C)})):PQ({className:"launch-empty"},K.empty||"Nothing here."))))}function hE({key:A,textual:Q}){if(A==="ArrowLeft")return Q?null:-1;if(A==="ArrowRight")return Q?null:1;let B=J1();if(A==="ArrowUp")return-B;if(A==="ArrowDown")return B;return null}function J1(){let A=document.querySelectorAll(".grid-list .grid-tile");if(A.length<2)return 1;let Q=A[0].offsetTop,B=0;for(let C of A){if(C.offsetTop!==Q)break;B++}return B||1}function K1(A,Q,{hover:B,select:C},J){let K=A.node,E=(K?.contentType||"").startsWith("image/");return PQ({className:`grid-tile ${Q?"active":""}`,title:A.detail?`${A.title} — ${A.detail}`:A.title},PQ({className:"gt-media"},U(K?aA(K):A.icon,{size:26}),E?C1({className:"gt-img",alt:"",loading:"lazy",decoding:"async"}).on({$attach:(L)=>{L._detachMedia=mQ(L,K,J,{onError:()=>{L.style.display="none"}})},$detach:(L)=>{L._detachMedia?.(),L._detachMedia=null}}).opaque():null,A.badge?B1({className:"gt-badge"},A.badge):null,BC(A,J,C)),PQ({className:"gt-name"},A.title)).on({click:A.run,mouseenter:B,...A.menu?{contextmenu:(L)=>{L.preventDefault(),qQ(L.currentTarget,A,J,L,C)}}:{}})}var{div:e0,button:E1,span:L1}=x,Y1={"core.view.list":{title:"List",icon:"list",priority:50,render:CC},"core.view.grid":{title:"Grid",icon:"grid",priority:40,match:{mime:["image/*","video/*"]},render:yE,move:hE}};function vE(A){for(let[Q,B]of Object.entries(Y1))A.contributions.register(Q,{type:"view",...B})}var bE="explorer.view";function fE(A){return A.contributions.ofType("view").filter((Q)=>!Q.when||A.context.evaluate(Q.when)).sort((Q,B)=>(B.priority??0)-(Q.priority??0))}function uE(A,Q=[],B=null){let C=fE(A);if(!C.length)return null;let J=A.settings.get(bE),K=J&&C.find((D)=>D.id===J);if(K)return K;let E=B&&C.find((D)=>D.id===B);if(E)return E;let L=Q.map((D)=>D.node).filter(Boolean);if(L.length>=3){let D=(Y)=>Y.match&&Object.keys(Y.match).length&&L.filter((I)=>D1(Y,I)).length/L.length>0.6,X=C.find(D);if(X)return X}return C[0]}function D1(A,Q){let B=Q.contentType||"",C=(Q.name||"").toLowerCase(),J=C.includes(".")?C.slice(C.lastIndexOf(".")):"";if((A.match.ext||[]).includes(J))return!0;return(A.match.mime||[]).some((K)=>K.endsWith("/*")?B.startsWith(K.slice(0,-1)):B===K)}function X1(A,Q){A.settings.set(bE,Q||void 0)}function mE(A,Q){let B=fE(A);if(B.length<2)return null;return e0({className:"view-switch"},...B.map((C)=>E1({className:`vs-btn ${C.id===Q?.id?"on":""}`,title:`${C.title||C.name} view`,"aria-pressed":C.id===Q?.id?"true":"false"},U(C.icon||"list",{size:14})).on({click:()=>X1(A,C.id)})))}function pE(A,Q,B){try{let C=A?.move?.({key:Q,...B});return Number.isFinite(C)&&C!==0?C:null}catch{return null}}function cE(A,Q){try{if(typeof A?.render==="function")return A.render(Q)}catch(B){return console.error(`view "${A?.id}" failed`,B),e0({},e0({className:"view-error"},U("warn",{size:13}),L1(`The “${A?.title||A?.id}” view could not be drawn — showing the list instead.`)),CC(Q))}return CC(Q)}var{div:sA,span:pQ,input:I1,button:NQ}=x,$1=new Set(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"]);function G1(A,{compact:Q=!1,modal:B=!1}={}){let C=A.platform.capabilities?.searchPrompt,J=(Q?C?.short||C?.placeholder:C?.placeholder)||(Q?"Search files":"Search files · # filter by tag");return Q||B?J:`${J} · ! run a command`}var KC=null;function H1(A,Q){clearTimeout(KC),KC=setTimeout(()=>A.go(new YQ(Q)),240)}function lE(A){A.platform.workbench.setLaunchQuery(""),A.go(new YQ(""))}function Z1(A,Q,B){clearTimeout(KC),KC=setTimeout(()=>A.go(new HB(Q,B)),200)}function EC(A,Q,B={}){let C=Q.platform.workbench,J=!!B.modal,K=A.wb.launch.query,E=K.startsWith("!")?"command":K.includes("#")?"filter":"search",L=F1(A,Q,K,E,J),D=L.flatMap((M)=>M.items),X=D.length?Math.min(A.wb.launch.index,D.length-1):0,Y=(M)=>{let S=M.target.value;if(C.setLaunchQuery(S),S.startsWith("!"))return;let{text:y,filters:w}=aB(S);if(w.length)Z1(Q,w,y);else H1(Q,y)},I=(M)=>C.setLaunchIndex(M),$=(M)=>{C.setLaunchIndex(M),dE(Q,D[M])},Z=(M)=>{C.moveLaunch(M,D.length),dE(Q,D[C.state.launch.index])},F=uE(Q.platform,D,E==="search"?A.se.resolved?.view:null),R=(M)=>{let S=$1.has(M.key)?pE(F,M.key,{index:X,count:D.length,textual:K.length>0}):null;if(S!==null)M.preventDefault(),Z(S);else if(M.key==="ArrowDown")M.preventDefault(),Z(1);else if(M.key==="ArrowUp")M.preventDefault(),Z(-1);else if(M.key==="Enter")M.preventDefault(),D[X]?.run();else if(M.key==="Escape"&&K)M.preventDefault(),lE(Q);else if(M.key==="ContextMenu"||M.shiftKey&&M.key==="F10"){let y=D[X];if(y?.menu)M.preventDefault(),qQ(document.querySelector(".launch-item.active, .grid-tile.active"),y,Q)}},P=E==="search"?A.se.resolved:null,z=P&&(P.source==="llm"||P.tagFilters&&P.tagFilters.length||(P.semanticText||"").trim()!==K.trim()),h=sA({className:"launcher"},sA({className:"launch-box"},U(E==="command"?"command":E==="filter"?"tag":"search",{size:18}),I1({className:"launch-input",value:K,autofocus:!0,spellcheck:!1,placeholder:G1(Q,{compact:A.vp?.mode==="phone",modal:J})}).on({input:Y,keydown:R}),K?NQ({className:"launch-clear",title:"Clear"},U("close",{size:14})).on({click:()=>lE(Q)}):null,Q.platform.voice?.canListen()?NQ({className:`launch-mic ${A.voice?.listening?"on":""}`,title:A.voice?.listening?"Stop listening":"Search by voice","aria-pressed":A.voice?.listening?"true":"false"},U("mic",{size:15})).on({click:()=>Q.exec("search.voice")}):null,J?null:mE(Q.platform,F)),z?W1(P):null,sA({className:"launch-body"},cE(F,{groups:L,index:X,handlers:{hover:I,select:$},state:A,ui:Q}),U1(A,Q,E)));return J?h:sA({className:"editor"},h)}function W1(A){return sA({className:"launch-resolved"},pQ({className:"rq-label"},A.source==="llm"?"Interpreted as":"Searching"),(A.semanticText||"").trim()?pQ({className:"rq-text"},`“${A.semanticText.trim()}”`):null,...(A.tagFilters||[]).map((Q)=>pQ({className:"rq-chip"},U("tag",{size:11}),h0(Q))))}function dE(A,Q){let B=Q?.node;A.app.explorer.select(B?.id?[B.id]:[],{nodes:B?[B]:null})}function U1(A,Q,B){if(B==="command")return null;let C=A.se;if(!C.ran||C.loading||C.error||(C.results||[]).length)return null;let J=Q.platform.capabilities?.searchPrompt;if(!J?.hint&&!J?.examples?.length)return null;let K=Q.platform.workbench,E=(L)=>()=>{K.setLaunchQuery(L);let{text:D,filters:X}=aB(L);if(X.length)Q.go(new HB(X,D));else Q.go(new YQ(D))};return sA({className:"launch-help"},J.hint?sA({className:"lh-hint"},U("info",{size:13}),pQ(J.hint)):null,J.examples?.length?sA({className:"lh-examples"},...J.examples.map((L)=>NQ({className:"lh-example",title:L.label||"Try this search"},pQ({className:"lh-q"},L.query),L.label?pQ({className:"lh-label"},L.label):null).on({click:E(L.query)}))):null)}function F1(A,Q,B,C,J){let K=()=>{if(J)Q.platform.workbench.closeSearchModal()};if(C==="command"){let M=B.slice(1).trim().toLowerCase();return[{title:"Commands",items:Q.platform.commands.paletteCommands().map((y)=>({hay:`${y.category||""} ${y.title}`.toLowerCase(),c:y})).map(({hay:y,c:w})=>({s:q1(y,M),c:w})).filter((y)=>M===""||y.s>0).sort((y,w)=>w.s-y.s).slice(0,40).map(({c:y})=>({icon:"command",title:y.title,detail:y.category,badge:"command",run:()=>{Q.exec(y.id),K()}})),empty:"No matching commands."}]}let{text:E,filters:L}=aB(B),D=(A.se.results||[]).map((M)=>M.node),X=A.se.error,Y=(M)=>NQ({className:"launch-up",title:"Retry"},U("refresh",{size:13}),"Retry").on({click:()=>Q.go(M)});if(L.length){let M=L.map(h0).join(" ")+(E.trim()?` · "${E.trim()}"`:"");return[{title:A.se.loading?"Filtering…":X?"Filter failed":"Filtered",verbatim:A.se.loading||X?null:M,action:X?Y(new HB(L,E)):null,items:D.map((S)=>JC(S,Q,J)),empty:A.se.loading?"Filtering…":X?`Couldn’t filter: ${X}`:"No files match those filters."}]}if(E.trim())return[{title:A.se.loading?"Searching…":X?"Search failed":"Results",action:X?Y(new YQ(B)):null,items:D.map((M)=>JC(M,Q,J)),empty:A.se.loading?"Searching…":X?`Couldn’t search: ${X}`:"No files match."}];let I=[],$=(A.nav.recents||[]).map((M)=>JC(M,Q,J));if($.length)I.push({title:"Recent",items:$});let Z=A.ex,F=(Z.items||[]).length,R=Z.stats?.items??null,P=R??F,z=R!=null?R.toLocaleString():`${F.toLocaleString()}+`,h=(Z.items||[]).map((M)=>JC(M,Q,J));if(Z.nextCursor)h.push({icon:"refresh",title:Z.loadingMore?"Loading…":R!=null?`Show more (${(R-F).toLocaleString()} more)`:"Show more",detail:"or search to jump straight to something",run:()=>Q.exec("explorer.loadMore")});if(Z.trash)I.push({title:Z.trash.length?`Trash · ${Z.trash.length} item${Z.trash.length===1?"":"s"}`:"Trash",action:sA({className:"lh-actions"},Z.trash.length?NQ({className:"launch-up",title:"Destroy everything in the trash"},U("trash",{size:13}),"Empty trash").on({click:()=>Q.exec("explorer.emptyTrash")}):null,NQ({className:"launch-up",title:"Hide the trash"},U("close",{size:13}),"Close").on({click:()=>Q.exec("explorer.hideTrash")})),items:Z.trash.length?Z.trash.map((M)=>({icon:"trash",title:M.name,detail:`deleted ${new Date(M.deletedAt).toLocaleString()} — restore`,run:()=>Q.exec("explorer.restore",M.id),menu:()=>M1(M,Q)})):[],empty:"The trash is empty."});return I.push({title:Z.nextCursor?`All items · showing ${F.toLocaleString()} of ${z}`:"All items",action:J?null:NQ({className:"launch-up",title:"Upload files to this collection"},U("upload",{size:13}),"Upload").on({click:()=>Q.exec("explorer.upload")}),items:h,empty:Z.loading?"Loading…":Z.error?`Couldn’t load this collection: ${Z.error}`:"Nothing here yet — upload a file to get started."}),I}function JC(A,Q,B){return{icon:V1(A),title:A.name,detail:A.contentType||"",node:A,run:()=>{if(Q.go(new _A(A,{reset:!!B})),B)Q.platform.workbench.closeSearchModal()},menu:()=>R1(A,Q)}}function R1(A,Q){let B=(Q.app.offline?.state?.pins||[]).some((J)=>J.id===A.id),C=(J)=>Q.platform.keybindings.labelFor(J)||void 0;return[{label:"Open",icon:"file-text",run:()=>Q.exec("explorer.open",A)},{label:"Download",icon:"download",run:()=>Q.exec("explorer.download",A)},{label:"Copy link",icon:"link",kbd:C("explorer.copyLink"),run:()=>Q.exec("explorer.copyLink")},{sep:!0},{label:"Rename…",run:()=>Q.exec("explorer.rename")},B?{label:"Remove from offline",icon:"close",run:()=>Q.exec("offline.unpin",A)}:{label:"Make available offline",icon:"download",run:()=>Q.exec("offline.pin",A)},{sep:!0},{label:"Move to trash",icon:"trash",danger:!0,kbd:C("explorer.delete"),run:()=>Q.exec("explorer.delete")}]}function M1(A,Q){return[{label:"Restore",icon:"refresh",run:()=>Q.exec("explorer.restore",A.id)},{sep:!0},{label:"Delete forever",icon:"trash",danger:!0,run:()=>Q.exec("explorer.purgeOne",A.id)}]}function V1(A){let Q=A.contentType||"";if(Q.startsWith("image/"))return"file-image";if(Q.startsWith("audio/"))return"file-audio";if(Q.startsWith("video/"))return"file-video";return"file-text"}function q1(A,Q){if(!Q)return 1;let B=A.indexOf(Q);if(B>=0)return 1000-B;let C=0;for(let J=0;J<A.length&&C<Q.length;J++)if(A[J]===Q[C])C++;return C===Q.length?1:0}var{div:q,h2:P1,h3:lQ,p:OQ,span:EA,select:N1,option:O1,input:cQ,label:aE,button:pA,ul:J5,li:K5,code:j1}=x;function QJ(A,Q){let B=Q.platform.settings.grouped();return q({className:"editor"},q({className:"stage"},q({className:"settings"},P1("Settings"),OQ({className:"sub"},"Preferences are stored in this browser. Plugins contribute their own settings here too."),...B.map((C)=>z1(C,Q)),_1(Q),x1(A,Q),b1(Q),f1(Q))))}function z1(A,Q){return q({className:"group"},lQ(A.category),...A.items.map((B)=>w1(B,Q)))}function w1(A,Q){return q({className:"setting"},q({className:"info"},q({className:"t"},A.title||A.key),A.description?q({className:"d"},A.description):null),q({className:"control"},S1(A,Q)))}function S1(A,Q){let B=(C)=>Q.platform.settings.set(A.key,C);if(A.type==="boolean")return aE({className:"switch"},cQ({type:"checkbox",checked:!!A.value}).on({change:(C)=>B(C.target.checked)}),EA({className:"track"}));if(A.type==="enum")return N1({className:"input"},...A.enum.map((C,J)=>O1({value:C,selected:A.value===C},A.enumLabels&&A.enumLabels[J]||C))).on({change:(C)=>B(C.target.value)});if(A.type==="number"){let C=(J)=>{let K=Number(J.target.value);if(J.target.value===""||Number.isNaN(K)){J.target.value=A.value;return}if(A.minimum!=null)K=Math.max(A.minimum,K);if(A.maximum!=null)K=Math.min(A.maximum,K);J.target.value=K,B(K)};return cQ({className:"input",type:"number",value:A.value,$attrs:{min:A.minimum??"",max:A.maximum??""}}).on({change:C})}return cQ({className:"input",value:A.value??""}).on({change:(C)=>B(C.target.value)})}function _1(A){let Q=A.platform.capabilities;if(!Q)return null;let B=Q.mcp,C=Q.auth||{authorizationServers:[],source:"none"};if(!B?.enabled)return q({className:"group"},lQ("AI agents (MCP)"),OQ({className:"sub"},"MCP is switched off on this server. Set TROVE_MCP=on to enable it."));let J=(L)=>()=>{navigator.clipboard?.writeText(L).then(()=>A.platform.notifications.success("Copied")).catch(()=>A.platform.notifications.info(L,{sticky:!0}))},K=C.authorizationServers||[],E=C.source==="jwt-issuer"?"from TROVE_JWT_ISSUER":C.source==="configured"?"from TROVE_AUTH_SERVER":null;return q({className:"group"},lQ("AI agents (MCP)"),OQ({className:"sub"},"Point an AI assistant at this drive. It signs in as you and sees exactly the collections you can see."),q({className:"setting"},q({className:"info"},q({className:"t"},"Server URL"),q({className:"d"},"Paste this into your assistant’s MCP settings.")),q({className:"control mcp-url"},EA({className:"mono"},B.endpoint),pA({className:"btn small",title:"Copy"},U("link",{size:13})).on({click:J(B.endpoint)}))),q({className:"setting"},q({className:"info"},q({className:"t"},"Sign-in required"),q({className:"d"},B.requiresAuth?"Agents must present a token, the same one this browser uses.":"This drive is open, so agents connect without a token — exactly like the web app does.")),q({className:"control"},EA({className:"mono"},B.requiresAuth?"Yes":"No"))),B.needsAuthorizationServer?q({className:"mcp-warn"},U("warn",{size:15}),EA("This drive requires a token but no authorization server is set, so an agent has nowhere to sign in. Set TROVE_AUTH_SERVER (or TROVE_JWT_ISSUER) to the issuer URL of your identity provider and restart.")):null,q({className:"setting"},q({className:"info"},q({className:"t"},"Authorization server"),q({className:"d"},"Where clients are sent to sign in — for the whole drive, not just for agents. "+"Set with TROVE_AUTH_SERVER; defaults to TROVE_JWT_ISSUER when that is set.")),q({className:"control"},K.length?EA({className:"mono"},K.join(", ")+(E?` (${E})`:"")):EA({className:"mono muted"},"not set"))),q({className:"setting"},q({className:"info"},q({className:"t"},"Discovery document"),q({className:"d"},"What a client reads to find out how to authenticate (RFC 9728).")),q({className:"control mcp-url"},EA({className:"mono small"},C.metadataUrl))))}var T1=[{id:"read",label:"Read",hint:"list and download"},{id:"write",label:"Write",hint:"upload and rename"},{id:"delete",label:"Delete",hint:"trash and purge"},{id:"admin",label:"Admin",hint:"includes all of the above"}],sE="*",nE=!1;function x1(A,Q){let B=A.keys||{};if(!nE&&!B.loaded&&!B.loading)nE=!0,Q.exec("keys.load");if(B.error&&!B.keys?.length)return null;if(!B.loaded)return null;let C=A.ex?.collections||[];return q({className:"group"},lQ("API keys"),OQ({className:"sub"},"Give a script or a service access without giving it an account. A key carries capabilities and no identity, so anything it does is attributed to the key rather "+"than to a person — and it can only reach the collections you scope it to."),B.minted?g1(B.minted,Q):null,B.draft?k1(B,C,Q):null,!B.draft&&!B.minted?q({className:"keys-actions"},pA({className:"btn"},U("plus",{size:14}),"New key").on({click:()=>Q.exec("keys.new")})):null,B.keys?.length?q({className:"keys-list"},...B.keys.map((J)=>y1(J,B,C,Q))):q({className:"keys-empty"},"No keys yet."))}function g1(A,Q){let B=()=>{navigator.clipboard?.writeText(A.secret).then(()=>Q.platform.notifications.success("Key copied")).catch(()=>Q.platform.notifications.info(A.secret,{sticky:!0}))};return q({className:"key-minted"},q({className:"key-minted-head"},U("warn",{size:15}),EA(`“${A.key.name}” is ready — copy it now.`)),OQ({className:"key-minted-note"},"This is the only time it can be shown. It is stored as a hash, so it cannot be "+"recovered — if it is lost, revoke the key and make another."),q({className:"key-secret"},j1({className:"mono"},A.secret),pA({className:"btn small",title:"Copy"},U("link",{size:13})).on({click:B})),q({className:"keys-actions"},pA({className:"btn"},"Done").on({click:()=>Q.exec("keys.dismissMinted")})))}function k1(A,Q,B){let C=A.draft,J=B.app.apiKeys.draftScopes(),K=!!C.name.trim()&&!!J;return q({className:"key-form"},q({className:"setting"},q({className:"info"},q({className:"t"},"Name"),q({className:"d"},"What it is for. This is what the list shows, so make it recognisable.")),q({className:"control"},cQ({className:"input",value:C.name,$attrs:{placeholder:"CI uploader"}}).on({input:(E)=>B.app.apiKeys.patchDraft({name:E.target.value})}))),q({className:"setting"},q({className:"info"},q({className:"t"},"Expires after"),q({className:"d"},"Days from now. Leave blank and it never expires.")),q({className:"control"},cQ({className:"input",type:"number",value:C.expiresInDays,$attrs:{min:"1",max:"3650",placeholder:"never"}}).on({input:(E)=>B.app.apiKeys.patchDraft({expiresInDays:E.target.value})}))),q({className:"key-scopes"},q({className:"key-scopes-head"},q({className:"t"},"What it may do"),q({className:"d"},"Per collection. A key with nothing ticked grants nothing and cannot be created.")),oE({id:sE,name:"All collections",wildcard:!0},C,B),...Q.map((E)=>oE(E,C,B))),q({className:"keys-actions"},pA({className:"btn primary",$attrs:K?{}:{disabled:"true"}},A.busy==="mint"?"Creating…":"Create key").on({click:()=>K&&B.exec("keys.mint")}),pA({className:"btn"},"Cancel").on({click:()=>B.exec("keys.cancel")})))}function oE(A,Q,B){let C=new Set(Q.caps[A.id]||[]);return q({className:`key-scope ${A.wildcard?"wildcard":""}`},q({className:"key-scope-name"},U(A.wildcard?"grid":"files",{size:14}),EA(A.name||A.id)),q({className:"key-scope-caps"},...T1.map((J)=>aE({className:`cap ${C.has(J.id)?"on":""}`,title:J.hint},cQ({type:"checkbox",checked:C.has(J.id)}).on({change:()=>B.app.apiKeys.toggleCap(A.id,J.id)}),EA(J.label)))))}function y1(A,Q,B,C){let J=!!A.revokedAt,K=A.expiresAt!=null&&A.expiresAt<=Date.now(),E=J||K;return q({className:`key-row ${E?"dead":""}`},q({className:"key-row-main"},q({className:"key-row-name"},EA({className:"t"},A.name),J?EA({className:"key-tag"},"revoked"):K?EA({className:"key-tag"},"expired"):null),q({className:"key-row-scopes"},...h1(A,B)),q({className:"key-row-meta"},v1(A))),!E?pA({className:"btn small danger",$attrs:Q.busy===A.id?{disabled:"true"}:{}},Q.busy===A.id?"…":"Revoke").on({click:()=>C.exec("keys.revoke",A.id)}):null)}function h1(A,Q){let B=(C)=>Q.find((J)=>J.id===C)?.name||C;return(A.scopes||[]).map((C)=>EA({className:"key-chip"},EA({className:"where"},C.collectionId===sE?"all collections":B(C.collectionId)),EA({className:"what"},C.capabilities.join(" · "))))}function v1(A){let Q=(C)=>new Date(C).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"}),B=[`created ${Q(A.createdAt)}`];if(A.createdBy)B.push(`by ${A.createdBy}`);if(B.push(A.lastUsedAt?`last used ${Q(A.lastUsedAt)}`:"never used"),A.expiresAt)B.push(`expires ${Q(A.expiresAt)}`);return B.join(" · ")}function b1(A){let Q=HE(A.platform);return q({className:"group"},lQ("Default Openers"),Q.length?q({},...Q.map((B)=>q({className:"setting"},q({className:"info"},q({className:"t"},B.typeKey),q({className:"d"},B.missing?`${B.openerTitle} (no longer installed)`:`Opens with ${B.openerTitle}`)),q({className:"control"},pA({className:"iconbtn",title:"Forget this default"},U("close",{size:14})).on({click:()=>rB(A.platform,B.typeKey,null)}))))):OQ({className:"sub",$styling:{margin:0}},"No default openers set yet. When a file type has more than one viewer, you can pick one and check “Always use this”."))}var AJ=null;function f1(A){let Q=A.platform.keybindings,B=Q.resolved(),C=A.platform.contributions,J=Q.overrides(),K=()=>{AJ=null,A.rerender?.()},E=new Map;for(let L of B)E.set(L.key,(E.get(L.key)||0)+1);return q({className:"group"},lQ("Keyboard Shortcuts"),OQ({className:"sub"},"Click a shortcut to record a new one. Esc cancels; Backspace clears it."),...B.map((L)=>{let D=C.get(L.command),X=AJ===L.bindingId,Y=!!J[L.bindingId],I=E.get(L.key)>1;return q({className:"setting"},q({className:"info"},q({className:"t"},D?.title||L.command),q({className:"d"},L.command)),q({className:"control"},I&&!X?EA({className:"kbd-clash",title:"Another command answers to this shortcut too — the one registered last wins"},U("warn",{size:12})):null,pA({className:`kbd-edit ${X?"listening":""} ${I?"clash":""}`,title:X?"Press the new shortcut":"Click to rebind"},X?EA("Press keys…"):x.h("kbd",BB(L.key))).on({click:()=>{AJ=X?null:L.bindingId,A.rerender?.()},blur:()=>{if(X)K()},keydown:($)=>{if(!X)return;if($.preventDefault(),$.stopPropagation(),$.key==="Escape")return K();if($.key==="Backspace")return Q.rebind(L,null),K();if(["Control","Meta","Alt","Shift"].includes($.key))return;Q.rebind(L,qC($)),K()},$attach:($)=>{if(X)queueMicrotask(()=>$.focus())}}),Y?pA({className:"c-link",title:"Back to the default"},"reset").on({click:()=>{Q.rebind(L,null),A.rerender?.()}}):null))}))}var{div:yA,h2:iE,p:rE,button:CJ,span:BJ}=x;function JJ(A,Q){let B=A.ex||{};return yA({className:"editor"},yA({className:"stage"},yA({className:"gate"},B.gate==="create"?u1(Q):m1(B,Q))))}function u1(A){return yA({className:"gate-card"},yA({className:"gate-icon"},U("files",{size:26})),iE("Make your first collection"),rE({className:"gate-sub"},"A collection is a backing store you own — a bucket, a directory, a mount. Files "+"live in one, and permissions are granted on one. Nothing can be uploaded until there is somewhere to put it."),yA({className:"gate-actions"},CJ({className:"btn primary"},U("plus",{size:14}),"New collection").on({click:()=>A.exec("collections.create")})))}function m1(A,Q){let B=A.collections||[];return yA({className:"gate-card"},yA({className:"gate-icon"},U("grid",{size:26})),iE(B.length===1?"Open your collection":"Choose a collection"),rE({className:"gate-sub"},B.length===1?"This is the one you have access to. Opening it will be remembered for next time.":"Files, search and uploads all belong to one collection. Your choice is remembered for next time, and you can switch from the status bar whenever you like."),yA({className:"gate-list"},...B.map((C)=>CJ({className:"gate-choice"},yA({className:"gate-choice-main"},BJ({className:"n"},C.name||C.id),BJ({className:"d"},C.driver?`${C.driver}${C.description?` · ${C.description}`:""}`:C.description||"")),BJ({className:"gate-caps"},(C.capabilities||[]).join(" · "))).on({click:()=>Q.exec("collections.switch",C.id)}))),A.canCreateCollection?yA({className:"gate-actions"},CJ({className:"btn"},U("plus",{size:14}),"New collection").on({click:()=>Q.exec("collections.create")})):null)}var{div:l,span:WA,p:p1,button:WB,h2:c1,input:KJ,label:l1}=x;function EJ(A,Q){let B=A.plugins||[];return l({className:"editor"},l({className:"stage"},l({className:"plugins"},c1("Plugins"),p1({className:"sub",$styling:{color:"var(--text-dim)",margin:"0 0 8px"}},"Plugins are sandboxed packages you install from a file or URL. They run in an isolated iframe and reach Trove only through a message channel, using the capabilities you granted."),l({className:"plugin-install"},WB({className:"btn primary"},U("upload",{size:15}),"Install from file…").on({click:()=>Q.exec("plugins.installFromFile")}),WB({className:"btn"},U("plug",{size:15}),"Install from URL…").on({click:()=>Q.exec("plugins.installFromUrl")})),B.length?l({$styling:{display:"flex","flex-direction":"column",gap:"12px","margin-top":"14px"}},...B.map((C)=>d1(C,A,Q))):l({className:"empty",$styling:{padding:"48px"}},U("plug",{size:30}),WA("No plugins installed yet.")))))}function d1(A,Q,B){let C=!A.responsive?"not responding":A.manifest?.online===!1?"offline":"connected",J=A.features||[];return l({className:"plugin-card"},l({className:"top"},l({className:"avatar"},(A.name||"?")[0].toUpperCase()),l({$styling:{flex:"1"}},l({className:"name"},A.name,A.version?WA({$styling:{color:"var(--text-faint)","font-weight":"400","margin-left":"6px"}},"v"+A.version):null),l({$styling:{"font-size":"11px",color:"var(--text-faint)"}},A.id)),a1(A.trust),WA({className:`status ${A.status}`},A.status)),A.error?l({className:"desc",$styling:{color:"var(--danger)"}},A.error):null,l({className:"caps"},...(A.capabilities||[]).map((K)=>WA({className:"cap"},K))),(A.endpoints||[]).length?l({className:"plugin-endpoints",$styling:{"font-size":"11px",color:"var(--text-faint)","margin-top":"2px"}},U("plug",{size:11})," Network: ",(A.endpoints||[]).map((K)=>K.host).join(", ")):null,A.status==="active"?l({className:"plugin-features"},l({className:"pf-head"},WA(`Features · ${C}`),WA({className:"muted"},`${J.filter((K)=>K.available).length}/${J.length} available`)),J.length?l({className:"pf-list"},...J.map(i1)):l({className:"muted",$styling:{"font-size":"12px"}},A.responsive?"No contributions announced.":"No manifest received — the plugin may not be running.")):null,(A.settingsSchema||[]).length?n1(A,B):null,l({className:"actions"},A.hasUi?WB({className:"btn"},U("command",{size:14}),"Open panel").on({click:()=>B.platform.workbench.openPluginPanel(A.id)}):null,WB({className:"btn"},U("refresh",{size:14}),"Refresh").on({click:()=>B.platform.plugins.refresh(A.id)}),WB({className:"btn danger"},"Uninstall").on({click:()=>B.platform.workbench.showDialog({kind:"confirm",title:`Uninstall ${A.name}?`,danger:!0,confirmLabel:"Uninstall",body:"The plugin and all data it stored will be removed.",onConfirm:()=>{B.platform.workbench.closeDialog(),B.uninstallPlugin(A.id)}})})))}function n1(A,Q){return l({className:"plugin-features"},l({className:"pf-head"},WA("Settings")),l({$styling:{display:"flex","flex-direction":"column",gap:"8px"}},...A.settingsSchema.map((B)=>o1(A,B,Q))))}function o1(A,Q,B){let C=`${A.id}.${Q.key}`,J=Q.secret?"":B.platform.settings.get(C)??Q.default??"";return l({className:"setting",$styling:{padding:"6px 0"}},l({className:"info"},l({className:"t"},Q.title||Q.key),Q.description?l({className:"d"},Q.description):null),l({className:"control"},Q.secret?KJ({className:"input",type:"password",placeholder:"Set secret…"}).on({change:(K)=>{if(K.target.value)B.platform.plugins.setSecret(A.id,Q.key,K.target.value),K.target.value="",K.target.placeholder="Saved ✓"}}):Q.type==="boolean"?l1({className:"switch"},KJ({type:"checkbox",checked:!!J}).on({change:(K)=>B.platform.settings.set(C,K.target.checked)}),WA({className:"track"})):KJ({className:"input",value:J}).on({change:(K)=>B.platform.settings.set(C,K.target.value)})))}function a1(A){if(!A)return null;if(A.status==="verified")return WA({className:"trust verified",title:"Signed by "+A.domain},U("check",{size:12}),A.domain);if(A.status==="signed")return WA({className:"trust signed"},U("info",{size:12}),"signed");if(A.status==="invalid")return WA({className:"trust invalid",title:A.reason||"The signature did not verify — this package may have been altered"},U("warn",{size:12}),"invalid signature");return WA({className:"trust unverified"},U("warn",{size:12}),"unverified")}var s1={command:"command",opener:"file",indexer:"search",statusItem:"info"};function i1(A){return l({className:`pf-row ${A.available?"":"off"}`},U(s1[A.kind]||"command",{size:13}),WA({className:"pf-title"},A.title),WA({className:"pf-kind"},A.kind),A.offline?WA({className:"pf-badge offline-ok",title:"Works offline"},"offline ✓"):null,WA({className:`pf-dot ${A.available?"on":"no"}`,title:A.available?"Available now":"Unavailable now"}))}async function tE(A,Q,{from:B}={}){let C=nB(Q),J=A.platform.notifications;if(!C)return J.warn(`"${Q}" isn’t a valid Trove link.`),null;try{let K=await A.platform.api.stat(Q);if(!K?.node)throw Error("not found");return A.go(new _A(K.node)),K.node}catch(K){return J.warn(r1(C,K,B)),null}}function r1(A,Q,B){let C=B?.name?` (linked from "${B.name}")`:"";if(Q?.status===403||Q?.code==="forbidden")return`You don’t have access to that item in "${A.collection}"${C}.`;if(A.by==="name")return`Nothing named "${A.value}" in "${A.collection}"${C} — it may have been renamed or deleted.`;return`That item no longer exists in "${A.collection}"${C}.`}var{div:jQ,span:YJ,h1:t1,h2:e1,h3:A6,p:J8,ul:Q6,ol:B6,li:C6,pre:J6,code:K8,a:eE,em:K6,strong:E6,blockquote:L6,hr:Y6,br:D6}=x;function E8(A,Q){let B=AB(()=>Q.platform.api.readTextCapped(A.id,{maxBytes:LJ,size:A.size}).then((C)=>C.text));return x.alias(()=>Q.platform.reactive.watch(B,(C)=>{try{return jQ({className:"viewer markdown"},jQ({className:"md"},...L8(C,A,Q)))}catch(J){return console.error("markdown render failed",J),A8(`This document couldn’t be displayed: ${J.message}`)}},{placeholder:()=>jQ({className:"viewer"},jQ({className:"loading"},jQ({className:"spinner"}),YJ("Loading…"))),error:(C)=>A8(C.message)}))()}function A8(A){return jQ({className:"viewer"},jQ({className:"fallback"},U("warn",{size:40}),YJ(A)))}var LJ=524288,X6=5000,I6=2000;function L8(A,Q,B){let C=String(A??""),J=C.length>LJ,K=(J?C.slice(0,LJ):C).split(/\r?\n/),E=[],L=0;while(L<K.length){if(E.length>=X6)return[...E,Q8()];let D=K[L],X=/^\s*(```+|~~~+)(.*)$/.exec(D);if(X){let R=X[1][0].repeat(3),P=[];L++;while(L<K.length&&!K[L].trimStart().startsWith(R))P.push(K[L++]);L++,E.push(J6({className:"md-code"},K8(P.join(`
350
+ `))));continue}if(!D.trim()){L++;continue}let Y=/^(#{1,6})\s+(.*)$/.exec(D);if(Y){let R=Y[1].length,P=R===1?t1:R===2?e1:A6;E.push(P({className:`md-h md-h${R}`},...UB(Y[2],Q,B))),L++;continue}if(/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(D)){E.push(Y6({className:"md-hr"})),L++;continue}if(/^\s*>/.test(D)){let R=[];while(L<K.length&&/^\s*>/.test(K[L]))R.push(K[L++].replace(/^\s*>\s?/,""));E.push(L6({className:"md-quote"},...L8(R.join(`
351
+ `),Q,B)));continue}let I=/^\s*([-*+]|\d+[.)])\s+/.exec(D);if(I){let R=/\d/.test(I[1]),P=[];while(L<K.length){let z=/^\s*([-*+]|\d+[.)])\s+(.*)$/.exec(K[L]);if(!z||/\d/.test(z[1])!==R)break;P.push(C6({className:"md-li"},...UB(z[2],Q,B))),L++}E.push((R?B6:Q6)({className:"md-list"},...P));continue}let $=[];while(L<K.length&&K[L].trim()&&!$6(K[L]))$.push(K[L++]);let Z=$.join(`
352
+ `),F=[];Z.split(`
353
+ `).forEach((R,P)=>{if(P)F.push(D6());F.push(...UB(R,Q,B))}),E.push(J8({className:"md-p"},...F))}return J?[...E,Q8()]:E}function Q8(){return J8({className:"md-truncated"},"This document is too large to display in full. Download it to read the rest.")}function $6(A){return/^(#{1,6}\s|\s*>|\s*([-*+]|\d+[.)])\s|\s*(```|~~~))/.test(A)||/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(A)}var G6=[{re:/`([^`]+)`/,node:(A)=>K8({className:"md-inline-code"},A[1])},{re:/\[([^\]]*)\]\(([^)\s]+)(?:\s+"[^"]*")?\)/,node:(A,Q,B)=>C8(A[2],A[1]||A[2],Q,B)},{re:/(\*\*|__)(.+?)\1/,node:(A,Q,B,C)=>E6(...UB(A[2],Q,B,C+1))},{re:/(\*|_)(.+?)\1/,node:(A,Q,B,C)=>K6(...UB(A[2],Q,B,C+1))},{re:/(trove:[^\s<>"'`)\]}]+|https?:\/\/[^\s<>"'`)\]}]+)/,node:(A,Q,B)=>C8(B8(A[1]),B8(A[1]),Q,B)}];function UB(A,Q,B,C=0){if(!A)return[];if(C>12)return[A];let J=[],K=A;while(K){if(J.length>=I6){J.push(K);break}let E=null;for(let X of G6){let Y=X.re.exec(K);if(Y&&(E===null||Y.index<E.m.index))E={m:Y,rule:X}}if(!E){J.push(K);break}let{m:L,rule:D}=E;if(L.index)J.push(K.slice(0,L.index));J.push(D.node(L,Q,B,C)),K=K.slice(L.index+L[0].length)}return J}function B8(A){return A.replace(/[.,;:!?]+$/,"")}function C8(A,Q,B,C){if(nB(A))return eE({className:"md-link md-trove",href:"#",title:A},Q).on({click:(K)=>{K.preventDefault(),tE(C,A,{from:B})}});if(/^https?:\/\//i.test(A))return eE({className:"md-link",href:A,target:"_blank",rel:"noopener noreferrer",title:A},Q);return YJ({className:"md-deadlink",title:`Unsupported link: ${A}`},Q)}var{div:RA,pre:H6,img:Z6,span:zQ,button:W6,video:U6,audio:F6}=x,R6={"core.audio":{title:"Audio Player",priority:20,match:{mime:["audio/*"],ext:[".mp3",".flac",".wav",".opus",".ogg",".m4a",".m4b"]},component:N6},"core.video":{title:"Video Player",priority:20,match:{mime:["video/*"],ext:[".mp4",".webm",".mkv",".mov"]},component:O6},"core.image":{title:"Image Viewer",priority:20,match:{mime:["image/*"],ext:[".png",".jpg",".jpeg",".gif",".webp",".svg",".avif"]},component:P6},"core.markdown":{title:"Markdown",priority:30,match:{ext:[".md",".markdown"],mime:["text/markdown"]},component:E8},"core.text":{title:"Text Viewer",priority:10,match:{mime:["text/*","application/json"],ext:[".txt",".md",".json",".js",".mjs",".ts",".jsx",".tsx",".css",".html",".xml",".yaml",".yml",".toml",".ini",".log",".csv",".py",".rb",".go",".rs",".sh",".c",".h",".cpp",".java"]},component:V6}};function Y8(A){for(let[Q,B]of Object.entries(R6))A.contributions.register(Q,{type:"opener",...B})}function D8(A,Q,B){let C=B.platform.contributions.get(Q);if(C?.component)try{return C.component(A,B)}catch(J){return I8(J.message)}if(C?.pluginId)return j6(C,A,B);return X8(A,B)}var M6=524288;function V6(A,Q){let B=AB(()=>Q.platform.api.readTextCapped(A.id,{maxBytes:M6,size:A.size}));return x.alias(()=>Q.platform.reactive.watch(B,({text:C,truncated:J,total:K})=>RA({className:"viewer text"},H6(C),J?RA({className:"md-truncated"},`Showing the first ${Math.round(C.length/1024)} KB${K?` of ${(K/1048576).toFixed(1)} MB`:""}. `,zQ("Download the file to read all of it.")):null),{placeholder:()=>RA({className:"viewer"},RA({className:"loading"},RA({className:"spinner"}),zQ("Loading…"))),error:(C)=>I8(C.message)}))()}var q6="This file couldn't be loaded — it may be missing or in an unsupported format.";function DJ(A,Q,B){let C=u({error:null}),K=B((E)=>C.setValue({error:E||q6}));return x.alias(()=>OB(C,(E)=>E.error?X8(A,Q,E.error):K))()}var XJ=(A,Q,B,C)=>A.on({$attach:(J)=>{J._detachMedia=mQ(J,Q,B,{onError:C})},$detach:(J)=>{J._detachMedia?.(),J._detachMedia=null}}).opaque();function P6(A,Q){return DJ(A,Q,(B)=>RA({className:"viewer image"},XJ(Z6({alt:A.name}),A,Q,B)))}function N6(A,Q){return DJ(A,Q,(B)=>RA({className:"viewer",$styling:{display:"grid","place-items":"center",gap:"16px",padding:"40px"}},U("file-audio",{size:48}),zQ({$styling:{color:"var(--text-dim)"}},A.name),XJ(F6({controls:!0,$styling:{width:"min(520px, 90%)"}}),A,Q,B)))}function O6(A,Q){return DJ(A,Q,(B)=>RA({className:"viewer",$styling:{display:"grid","place-items":"center",background:"#000"}},XJ(U6({controls:!0,$styling:{"max-width":"100%","max-height":"100%"}}),A,Q,B)))}function X8(A,Q,B){return RA({className:"viewer"},RA({className:"fallback"},U(B?"warn":"file",{size:44}),zQ({$styling:{"font-weight":600}},A.name),zQ(`${A.contentType||"Unknown type"} · ${QA(A.size)}`),zQ({$styling:{color:"var(--text-faint)","max-width":"340px"}},B||"No preview available for this file type. Install a plugin that handles it, or download the file."),W6({className:"btn primary"},U("download",{size:15}),"Download").on({click:()=>Q.exec("explorer.download",A)})))}function j6(A,Q,B){return RA({className:"viewer plugin-viewer"},RA({className:"pv-status"}).on({$attach:(C)=>{C.innerHTML='<div class="loading"><div class="spinner"></div><span>Opening…</span></div>',C._ready=()=>{C.style.display="none"},C._error=(J)=>{C.style.display="grid",C.innerHTML="",C.appendChild(z6(J))}}}).opaque(),RA({className:"pv-host"}).on({$attach:(C)=>{let J=C.parentElement?.querySelector(".pv-status");C._detach=B.platform.plugins.mountViewer(A.pluginId,C,Q,A.id,{onReady:()=>J?._ready?.(),onError:(K)=>J?._error?.(K||"This viewer failed to load")})},$detach:(C)=>{C._detach?.(),C._detach=null}}).opaque())}function z6(A){let Q=document.createElement("div");Q.className="fallback";let B=document.createElement("span");return B.textContent=A||"Failed to open",Q.appendChild(B),Q}function I8(A){return RA({className:"viewer"},RA({className:"fallback"},U("warn",{size:40}),zQ(A||"Failed to open")))}var{div:nQ,span:$8,button:dQ}=x,LC=new Map;function YC(A,Q){let B=A.wb,C=A.nav.stack.filter((K)=>K.kind==="file");T6(C);let J=C[C.length-1];if(!J)return nQ({className:"editor"});return nQ({className:"editor"},w6(C,J,Q),nQ({className:"stage"},_6(J,Q)))}function w6(A,Q,B){let C=B.platform.workbench;return nQ({className:"viewer-nav"},dQ({className:"vn-back",title:"Back (Esc)"},U("chevron-left",{size:16})).on({click:()=>C.back()}),nQ({className:"vn-trail"},dQ({className:"vn-crumb"},U("search",{size:13}),$8("Search")).on({click:()=>C.showHome()}),...A.map((J)=>dQ({className:`vn-crumb ${J.id===Q.id?"active":""}`,title:J.node.name},U(aA(J.node),{size:13}),$8({className:"label"},J.node.name)).on({click:()=>C.openFile(J.node,J.openerId)}))),nQ({className:"vn-actions"},S6(Q,B),dQ({className:"iconbtn",title:"Details & comments"},U("info",{size:15})).on({click:()=>C.toggleInfoPanel()}),dQ({className:"iconbtn",title:"Close (Esc)"},U("close",{size:15})).on({click:()=>C.showHome()})))}function S6(A,Q){let B=iB(Q.platform,A.node);if(B.length<=1)return null;return dQ({className:"iconbtn",title:"Open with…"},U("dots",{size:15})).on({click:()=>Q.platform.workbench.showDialog({kind:"opener-chooser",node:A.node,openers:B,current:A.openerId})})}function _6(A,Q){let B=`${A.id}:${A.openerId}`,C=LC.get(B);if(!C)C=()=>D8(A.node,A.openerId,Q),LC.set(B,C);return x.alias(C)().key(A.id)}function T6(A){let Q=new Set(A.map((B)=>`${B.id}:${B.openerId}`));for(let B of LC.keys())if(!Q.has(B))LC.delete(B)}var{div:TA,input:x6,span:DQ}=x;function IJ(A,Q){let B=A.overlay.palette;if(!B)return null;let C=Q.platform.workbench,J=B.mode==="files"?B.query.trim()?A.se.paletteFiles||[]:[]:v6(A,Q,B.query),K=Math.min(B.index,Math.max(0,J.length-1)),E=(L)=>{if(!L)return;if(C.closePalette(),B.mode==="files")Q.go(new _A(L.node));else Q.exec(L.id)};return TA({},TA({className:"scrim"}).on({click:()=>C.closePalette()}),TA({className:"palette"},TA({className:"search"},U(B.mode==="files"?"search":"command",{size:18}),x6({type:"text",value:B.query,autofocus:!0,placeholder:B.mode==="files"?"Search files by name…":"Type a command…"}).on({input:(L)=>u6(Q,L.target.value),keydown:(L)=>f6(L,Q,J,K,E),$attach:(L)=>{if(queueMicrotask(()=>L.focus()),L.value!==B.query)L.value=B.query}})),TA({className:"results"},J.length?J.map((L,D)=>{let X=()=>C.setPaletteIndex(D);return B.mode==="files"?h6(L,D===K,E,X):k6(L,D===K,Q,E,X)}):g6(B,A))))}function g6(A,Q){if(A.mode!=="files")return TA({className:"none"},"No matching commands");if(Q.se.paletteError)return TA({className:"none error"},U("warn",{size:14}),` ${Q.se.paletteError}`);if(Q.se.paletteLoading)return TA({className:"none"},TA({className:"spinner"})," Searching…");return TA({className:"none"},A.query.trim()?"No files found":"Type to search files by name")}function k6(A,Q,B,C,J){let K=B.platform.keybindings.labelFor(A.id),E=B.platform.commands.isAvailable(A);return TA({className:`opt ${Q?"active":""} ${E?"":"unavailable"}`},DQ({className:"ico"},U(A.icon||"command",{size:16})),A.category?DQ({className:"cat"},A.category+" ›"):null,DQ({className:"title"},A.title),!E?DQ({className:"offline-tag"},"offline"):null,K?DQ({className:"kbd"},x.h("kbd",BB(y6(B,A.id)))):null).on({click:()=>C(A),mouseenter:J})}function y6(A,Q){let B=A.platform.keybindings.resolved().find((C)=>C.command===Q);return B?B.key:""}function h6(A,Q,B,C){return TA({className:`opt ${Q?"active":""}`},DQ({className:"ico"},U(aA(A.node),{size:16})),DQ({className:"title"},A.node.name),DQ({className:"sub"},A.node.contentType||"")).on({click:()=>B(A),mouseenter:C})}function v6(A,Q,B){let C=Q.platform.commands.paletteCommands(),J=B.trim().toLowerCase();if(!J)return C.slice(0,60);let K=[];for(let E of C){let L=`${E.category||""} ${E.title}`.toLowerCase(),D=b6(L,J);if(D>0)K.push([D,E])}return K.sort((E,L)=>L[0]-E[0]).slice(0,60).map((E)=>E[1])}function b6(A,Q){let B=0,C=0;for(let J of Q){let K=A.indexOf(J,C);if(K<0)return 0;B+=K===C?3:1,C=K+1}if(A.includes(Q))B+=10;return B}function f6(A,Q,B,C,J){let K=Q.platform.workbench;if(A.key==="ArrowDown")A.preventDefault(),K.movePalette(1,B.length);else if(A.key==="ArrowUp")A.preventDefault(),K.movePalette(-1,B.length);else if(A.key==="Enter")A.preventDefault(),J(B[C]);else if(A.key==="Escape")A.preventDefault(),K.closePalette()}var G8=null;function u6(A,Q){let B=A.platform.workbench;if(B.setPaletteQuery(Q),clearTimeout(G8),B.overlay.state.palette?.mode!=="files")return;G8=setTimeout(()=>A.go(new m0(Q)),200)}var{div:d,span:t,button:H8,h3:u5,p:m6,label:p6,input:c6}=x,wQ={ref:null,grants:null};function W8(A,Q){let B=Q.platform.workbench,C=A.summary;if(wQ.ref!==A)wQ={ref:A,grants:new Set(C.capabilities.filter((K)=>!K.adminOnly||A.isAdmin).map((K)=>K.id))};let J=(K)=>{wQ.grants.has(K)?wQ.grants.delete(K):wQ.grants.add(K),Q.rerender?.()};return d({},d({className:"scrim"}).on({click:()=>B.closeDialog()}),d({className:"dialog review",$styling:{width:"min(560px, 96vw)"}},l6(C),d({className:"review-body"},C.description?m6({className:"review-desc"},C.description):null,oQ("Capabilities it requests",C.capabilities.length?d({className:"cap-list"},...C.capabilities.map((K)=>n6(K,A.isAdmin,wQ.grants.has(K.id),()=>J(K.id)))):t6("None — this plugin only runs in its sandbox.")),(C.network||[]).length?oQ("Network access",d({className:"contrib-list"},...C.network.map(s6))):null,(C.commands||[]).length?oQ("Commands it can run",d({className:"contrib-list"},...C.commands.map((K)=>a6(K,Q)))):null,C.storage?oQ("Storage",i6(C.storage)):null,C.contributions.length?oQ("What it adds",d({className:"contrib-list"},...C.contributions.map(o6))):null,C.settings.length?oQ("Settings",d({className:"contrib-list"},...C.settings.map(r6))):null,d({className:"review-meta"},`${C.fileCount} files · ${QA(C.sizeBytes)} · id ${C.id}`)),d({className:"row-actions"},H8({className:"btn"},"Cancel").on({click:()=>B.closeDialog()}),H8({className:"btn primary"},U("plug",{size:15}),"Install").on({click:()=>A.onInstall([...wQ.grants])}))))}function l6(A){let Q=A.trust||{status:"unverified"};return d({className:"review-head"},d({className:"avatar"},(A.name||"?")[0].toUpperCase()),d({className:"rh-main"},d({className:"rh-name"},A.name,t({className:"rh-ver"},"v"+A.version)),d({className:"rh-author"},"by "+A.author)),d6(Q))}function d6(A){if(A.status==="verified")return t({className:"trust verified",title:`Signed by a key published at ${A.domain}`},U("check",{size:13}),"Verified · "+A.domain);if(A.status==="signed")return t({className:"trust signed",title:A.reason||"Signed, but the domain does not vouch for the key"},U("info",{size:13}),"Signed");if(A.status==="invalid")return t({className:"trust invalid",title:A.reason||"Invalid signature — the package may have been tampered with"},U("warn",{size:13}),"Invalid signature");return t({className:"trust unverified",title:A.reason||"This plugin is not signed"},U("warn",{size:13}),"Unverified")}function n6(A,Q,B,C){let J=A.adminOnly&&!Q;return p6({className:`cap-row ${J?"blocked":""}`},c6({type:"checkbox",checked:B&&!J,disabled:J}).on({change:()=>!J&&C()}),d({className:"cap-info"},d({className:"cap-name"},A.id,A.adminOnly?t({className:"pf-badge",$styling:{color:"var(--warn)","margin-left":"6px"}},"admin only"):null),d({className:"cap-desc"},A.description+(J?" — requires an administrator":""))))}function o6(A){let Q={command:"command",opener:"file",indexer:"search",statusItem:"info",register:"info",keymap:"command"}[A.kind]||"command";return d({className:"contrib-row"},U(Q,{size:13}),t({className:"cr-title"},A.title),A.detail?t({className:"cr-detail"},A.detail):null,A.offline?t({className:"pf-badge offline-ok"},"offline"):null,t({className:"pf-kind"},A.kind))}function a6(A,Q){let B=Q?.platform?.contributions?.get?.(A),C=B?.pluginId?"plugin":B?"built-in":"not installed";return d({className:`contrib-row ${B?"":"blocked"}`},U("command",{size:13}),t({className:"cr-title"},B?.title||A),t({className:"cr-detail"},A),t({className:"pf-kind"},C))}function s6(A){return d({className:"contrib-row"},U("plug",{size:13}),t({className:"cr-title"},A.host),A.path?t({className:"cr-detail"},A.path):null,t({className:"pf-kind"},A.scheme))}function i6(A){let Q=[];if(A.plugin)Q.push(Z8("Private database","A SQLite store just for this plugin (server + this device).",!1));if(A.domain)Q.push(Z8("Shared database","Shared with other plugins from its domain (SQLite).",A.domainBlocked));return d({className:"contrib-list"},...Q)}function Z8(A,Q,B){return d({className:`contrib-row ${B?"blocked":""}`},U("plug",{size:13}),t({className:"cr-title"},A),t({className:"cr-detail"},B?Q+" — needs a verified domain":Q),B?t({className:"pf-badge",$styling:{color:"var(--warn)"}},"unavailable"):null)}function r6(A){return d({className:"contrib-row"},U("gear",{size:13}),t({className:"cr-title"},A.title),A.secret?t({className:"pf-badge",$styling:{color:"var(--warn)"}},"secret"):t({className:"pf-kind"},A.type))}function oQ(A,Q){return d({className:"review-section"},d({className:"rs-title"},A),Q)}function t6(A){return d({className:"muted",$styling:{"font-size":"12.5px"}},A)}var{div:g,span:hA,button:OA,input:aQ,h3:GJ,p:o5,select:e6,option:A$,label:sQ,textarea:a5}=x;function U8(A,Q){let B=A.overlay.dialog;if(!B)return null;if(B.kind==="collection")return B$(B,Q);if(B.kind==="plugin-review")return W8(B,Q);if(B.kind==="opener-chooser")return Q$(B,Q);let C=Q.platform.workbench,J=B.value??"",K=()=>B.kind==="confirm"?B.onConfirm?.():B.onSubmit?.(J);return g({},g({className:"scrim"}).on({click:()=>C.closeDialog()}),g({className:"dialog"},GJ(B.title),B.body?g({className:"body"},B.body):null,B.kind==="prompt"?g({className:"field"},B.label?hA({$styling:{"font-size":"12px",color:"var(--text-dim)"}},B.label):null,aQ({className:"input",value:B.value??"",placeholder:B.placeholder||"",autofocus:!0}).on({input:(E)=>{J=E.target.value},keydown:(E)=>{if(E.key==="Enter")K();if(E.key==="Escape")C.closeDialog()},$attach:(E)=>queueMicrotask(()=>{E.focus(),E.select()})})):null,g({className:"row-actions"},OA({className:"btn"},"Cancel").on({click:()=>C.closeDialog()}),OA({className:`btn ${B.danger?"danger":"primary"}`},B.confirmLabel||"OK").on({click:K}))))}function Q$(A,Q){let B=Q.platform.workbench,C=Q.platform,J=A.openerId||A.current||A.openers[0]?.id,K=!!A.remember,E=()=>{if(K&&J)rB(C,IE(A.node),J);B.closeDialog(),B.openFile(A.node,J,{reset:!!A.reset})};return g({},g({className:"scrim"}).on({click:()=>B.closeDialog()}),g({className:"dialog opener-chooser"},GJ(`Open “${A.node.name}” with…`),g({className:"opener-list"},...A.openers.map((L)=>sQ({className:`opener-opt ${L.id===J?"sel":""}`},aQ({type:"radio",name:"opener-choice",checked:L.id===J}).on({change:()=>B.updateDialog({openerId:L.id})}),U(L.icon||aA(A.node),{size:18}),g({className:"oo-main"},hA({className:"oo-title"},L.title||L.id),hA({className:"oo-src"},ZE(C,L)))).on({click:()=>B.updateDialog({openerId:L.id})}))),sQ({className:"opener-remember"},aQ({type:"checkbox",checked:K}).on({change:(L)=>B.updateDialog({remember:L.target.checked})}),hA(`Always use this for ${$E(A.node)}`)),g({className:"row-actions"},OA({className:"btn"},"Cancel").on({click:()=>B.closeDialog()}),OA({className:"btn primary"},"Open").on({click:E}))))}var $J={ref:null,form:null};function B$(A,Q){let B=Q.platform.workbench,C=Q.platform.capabilities?.storageDrivers||[];if($J.ref!==A)$J={ref:A,form:{name:"",description:"",driver:C[0]?.key||""}};let J=$J.form,K=C.find((Y)=>Y.key===J.driver)||C[0],E=(Y)=>(I)=>{if(J[Y]=I.target.type==="checkbox"?I.target.checked:I.target.value,Y==="driver")Q.rerender?.()},L=()=>{let Y={driver:J.driver};for(let I of K?.fields||[]){let $=J[I.name];if($!==void 0&&$!=="")Y[I.name]=I.type==="number"?Number($):$}A.onSubmit?.({name:J.name,description:J.description,store:Y})},D=(Y,I,$="")=>g({className:"field",$styling:{"margin-bottom":"10px"}},sQ(Y),aQ({className:"input",placeholder:$}).on({input:E(I)})),X=!!J.name.trim()&&!!J.driver&&(K?.fields||[]).every((Y)=>!Y.required||String(J[Y.name]??"").trim());return g({},g({className:"scrim"}).on({click:()=>B.closeDialog()}),g({className:"dialog",$styling:{width:"min(480px, 94vw)"}},GJ("New collection"),g({className:"body"},"A collection is a backing store you own. Configure where its files live."),D("Name","name","Team Vault"),C.length?g({className:"field",$styling:{"margin-bottom":"10px"}},sQ("Backing store"),e6({className:"input"},...C.map((Y)=>A$({value:Y.key,selected:J.driver===Y.key},Y.label))).on({change:E("driver")})):g({className:"body"},"This server has no storage drivers registered, so a collection cannot be created."),K?C$(K,J,E):null,g({className:"row-actions"},OA({className:"btn"},"Cancel").on({click:()=>B.closeDialog()}),OA({className:"btn primary",$attrs:X?{}:{disabled:"true"}},"Create collection").on({click:()=>X&&L()}))))}function C$(A,Q,B){if(!A.fields.length)return g({className:"body",$styling:{"font-size":"12px"}},A.description||"This store needs no configuration.");return g({},A.description?g({className:"body",$styling:{"font-size":"12px","margin-bottom":"10px"}},A.description):null,...A.fields.map((C)=>C.type==="boolean"?g({className:"field",$styling:{"margin-bottom":"10px"}},sQ({},aQ({type:"checkbox"}).on({change:B(C.name)}),` ${C.label}`),C.help?g({className:"body",$styling:{"font-size":"11.5px"}},C.help):null):g({className:"field",$styling:{"margin-bottom":"10px"}},sQ(C.label+(C.required?"":" (optional)")),aQ({className:"input",placeholder:C.placeholder,autocomplete:"off",type:C.type==="password"||C.secret?"password":C.type==="number"?"number":"text"}).on({input:B(C.name)}),C.help?g({className:"body",$styling:{"font-size":"11.5px"}},C.help):null)))}function F8(A,Q){let B=A.overlay.contextMenu;if(!B||!B.items?.length)return null;let C=Q.platform.workbench,J=Math.min(B.items.length*34+20,window.innerHeight-24),K=Math.max(8,Math.min(B.x,window.innerWidth-220)),E=Math.max(8,Math.min(B.y,window.innerHeight-J));return g({},g({className:"scrim",$styling:{background:"transparent"}}).on({click:()=>C.closeContextMenu(),contextmenu:(L)=>{L.preventDefault(),C.closeContextMenu()}}),g({className:"menu",$styling:{left:K+"px",top:E+"px"}},...B.items.map((L,D)=>L.sep?g({className:"sep"}):OA({className:`mi ${L.danger?"danger":""}`,autofocus:D===0},L.icon?U(L.icon,{size:15}):null,hA(L.label),L.kbd?hA({className:"kbd"},L.kbd):null).on({click:()=>{C.closeContextMenu(),L.run?.()},keydown:(X)=>{if(X.key==="Escape")X.preventDefault(),C.closeContextMenu()},$attach:(X)=>{if(D===0)queueMicrotask(()=>X.focus())}}))))}function R8(A,Q){let B=A.notif||[];if(!B.length)return null;return g({className:"toasts"},...B.slice(-5).map((C)=>g({className:`toast ${C.level}`},g({className:"bar"}),g({className:"msg"},C.message),OA({className:"x"},U("close",{size:14})).on({click:()=>Q.platform.notifications.dismiss(C.id)})).key(C.id)))}function M8(A,Q){let B=A.tr.items;if(!B.length)return null;return g({className:"tray"},g({className:"head"},U("upload",{size:14}),hA({$styling:{"margin-left":"6px"}},"Transfers"),g({className:"actions"},OA({className:"iconbtn",title:"Clear finished"},U("check",{size:14})).on({click:()=>Q.app.transfers.clearDone()}))),g({className:"items"},...B.map((C)=>g({className:`xfer ${C.status}`},g({className:"top"},U(C.status==="error"?"warn":C.status==="done"?"check":"upload",{size:14}),hA({className:"name"},C.name),C.status==="active"?OA({className:"iconbtn",title:"Cancel"},U("close",{size:13})).on({click:()=>Q.app.transfers.cancel(C.id)}):hA({className:"pct"},C.status==="done"?QA(C.total):C.status)),C.status==="active"?g({className:"progress"},g({$styling:{width:`${Math.round(C.ratio*100)}%`}})):C.error?g({$styling:{"font-size":"11px",color:"var(--danger)","margin-top":"4px"}},C.error):null,C.status==="active"?g({className:"pct",$styling:{"margin-top":"4px"}},`${QA(C.loaded)} / ${QA(C.total)}`):null,(C.status==="error"||C.status==="cancelled")&&C.retryable?g({className:"xfer-actions"},OA({className:"btn small"},U("refresh",{size:12}),hA("Retry")).on({click:()=>Q.app.transfers.retry(C.id)}),OA({className:"btn small ghost"},"Dismiss").on({click:()=>Q.app.transfers.dismiss(C.id)})):null).key(C.id))))}function V8(A,Q){let B=A.overlay.pluginPanel;if(!B)return null;let C=(A.plugins||[]).find((J)=>J.id===B);return g({className:"plugin-panel",$styling:{width:"380px"}},g({className:"head"},U("plug",{size:14}),hA(C?.name||B),OA({className:"iconbtn x"},U("close",{size:14})).on({click:()=>Q.platform.workbench.closePluginPanel()})),g({className:"host"}).on({$attach:(J)=>{J._detach=Q.platform.plugins.mountPanel(B,J,{width:380,height:460})},$detach:(J)=>J._detach?.()}))}var{div:m,button:iA,span:FB,h3:J$,p:q8,pre:K$}=x,E$={running:"refresh",done:"check",failed:"close",cancelled:"close"};function L$(A,Q){navigator.clipboard?.writeText(A).then(()=>Q.platform.notifications.success("Copied")).catch(()=>Q.platform.notifications.info(A,{sticky:!0}))}function P8(A){if(A.total==null)return null;return A.unit==="bytes"?`${QA(A.done||0)} of ${QA(A.total)}`:`${A.done||0} of ${A.total}${A.unit?` ${A.unit}`:""}`}function N8(A,Q){let B=A.status==="running",C=B&&A.total!=null&&A.total>0,J=C?Math.min(100,Math.round((A.done||0)/A.total*100)):0;return m({className:`act-task act-${A.status}`,"data-task-id":A.id},m({className:"act-row"},B?m({className:"spinner",$styling:{width:"12px",height:"12px"}}):U(E$[A.status]||"info",{size:13}),m({className:"act-body"},m({className:"act-title"},A.title),A.detail?m({className:"act-detail"},A.detail):null,A.error?m({className:"act-error"},A.error):null),B&&A.cancellable?iA({className:"act-action",title:"Cancel"},U("close",{size:12})).on({click:()=>Q.app.activity.cancel(A.id)}):!B?iA({className:"act-action",title:"Dismiss"},U("close",{size:12})).on({click:()=>Q.app.activity.dismiss(A.id)}):null),B?m({className:`act-bar ${C?"":"indeterminate"}`},m({className:"act-fill",$styling:C?{width:`${J}%`}:{}})):null,B&&P8(A)?m({className:"act-amount"},P8(A)):null)}function Y$(A,Q){let B=new Date(A.firstAt||A.lastAt).toLocaleString();return m({className:`act-issue act-sev-${A.severity||"error"}`,"data-issue-id":A.id},m({className:"act-row"},U(A.severity==="warning"?"info":"close",{size:13}),m({className:"act-body"},m({className:"act-title"},A.title),A.detail?m({className:"act-detail"},A.detail):null,A.remedy?K$({className:"act-remedy"},A.remedy):null,m({className:"act-meta"},A.count>1?`${A.count} times, since ${B}`:`since ${B}`))),m({className:"act-actions"},A.remedy?iA({className:"btn small ghost"},"Copy fix").on({click:()=>L$(A.remedy,Q)}):null,A.retryable?iA({className:"btn small act-retry"},U("refresh",{size:12}),FB("Retry")).on({click:()=>Q.app.activity.retryIssue(A.id)}):null,iA({className:"btn small ghost act-dismiss"},"Dismiss").on({click:()=>Q.app.activity.dismissIssue(A.id)})))}function HJ(A,Q){let B=A.act||{tasks:[],issues:[]};if(!B.open)return null;let C=B.tasks.filter((K)=>K.status==="running"),J=B.tasks.filter((K)=>K.status!=="running");return m({className:"activity-panel"},m({className:"act-head"},J$("Activity"),iA({className:"act-action",title:"Close"},U("close",{size:13})).on({click:()=>Q.app.activity.togglePanel(!1)})),B.tasksError||B.issuesError?m({className:"act-offline"},U("info",{size:12}),FB(`Couldn't reach the server — this list may be out of date (${B.issuesError||B.tasksError})`)):null,m({className:"act-section"},m({className:"act-section-title"},"Running"),C.length?m(...C.map((K)=>N8(K,Q))):q8({className:"act-empty"},"Nothing running.")),B.issues.length?m({className:"act-section"},m({className:"act-section-title"},`Needs attention (${B.issues.length})`),m(...B.issues.map((K)=>Y$(K,Q)))):m({className:"act-section"},m({className:"act-section-title"},"Needs attention"),q8({className:"act-empty"},B.issuesError?"Could not load the list of problems.":B.issuesLoading?"Checking…":"No standing problems.")),J.length?m({className:"act-section"},m({className:"act-section-title"},"Recently finished"),m(...J.map((K)=>N8(K,Q)))):null,m({className:"act-foot act-actions"},iA({className:"btn small ghost act-rebuild"},U("refresh",{size:12}),FB("Rebuild search index")).on({click:()=>Q.exec("workbench.rebuildIndex")}),iA({className:"btn small ghost act-scan"},U("refresh",{size:12}),FB("Scan for outside changes")).on({click:()=>Q.exec("workbench.scanCollection")}),iA({className:"btn small ghost act-storage"},U("plug",{size:12}),FB("Check storage")).on({click:()=>Q.exec("workbench.checkStorage")})))}var{div:LA,button:SQ,span:cA,img:j8}=x,O8=[{id:"home",icon:"search",label:"Files",command:"workbench.view.home"},{id:"upload",icon:"upload",label:"Upload",command:"explorer.upload"},{id:"plugins",icon:"plug",label:"Plugins",command:"workbench.view.plugins"}];function D$(A){if(!A.off.online)return{icon:"info",tone:"warn",label:"Offline"};if(A.issues.length)return{icon:"warn",tone:"danger",label:`${A.issues.length} need attention`,badge:A.issues.length};if(A.running.length||A.uploading.length||A.off.syncing)return{spinner:!0,tone:"",label:"Working…"};if(A.usage?.total&&A.usage.available/A.usage.total<0.1)return{icon:"info",tone:"warn",label:"Low on space"};return{icon:"info",tone:"",label:"Status"}}function z8(A,Q){let B=AC(A,Q),C=D$(B),J=A.wb.activity==="settings"?"Settings":A.wb.activity==="plugins"?"Plugins":B.collectionLabel;return LA({className:"phonebar top"},SQ({className:"pb-brand",title:"Trove — home"},j8({src:"/icon.svg",alt:"Trove"})).on({click:()=>Q.exec("workbench.view.home")}),LA({className:"pb-title"},J),SQ({className:`pb-status ${C.tone}`,title:C.label,$attrs:{"aria-label":C.label}},C.spinner?LA({className:"spinner",$styling:{width:"15px",height:"15px"}}):U(C.icon,{size:18}),C.badge?cA({className:"pb-badge"},String(C.badge>9?"9+":C.badge)):null).on({click:()=>Q.platform.workbench.openSheet("status")}))}function w8(A,Q){let B=A.wb.activity,C=A.wb.sheet,J=A.so.notifications.unread;return LA({className:"phonebar bottom"},...O8.map((K)=>SQ({className:`pb-tab ${!C&&B===K.id?"active":""}`,$attrs:{"aria-label":K.label}},U(K.icon,{size:21}),cA({className:"pb-label"},K.label)).on({click:()=>{Q.platform.workbench.closeSheet(),Q.exec(K.command)}})),SQ({className:`pb-tab ${C==="more"||!C&&!O8.some((K)=>K.id===B)?"active":""}`,$attrs:{"aria-label":"More"}},U("dots",{size:21}),J?cA({className:"pb-badge"},String(J>9?"9+":J)):null,cA({className:"pb-label"},"More")).on({click:()=>Q.platform.workbench.openSheet("more")}))}function MA({icon:A,label:Q,value:B,danger:C,onClick:J}){let K=[U(A,{size:18}),cA({className:"sr-label"},Q),B!=null?cA({className:"sr-value"},B):null,J?U("chevron-right",{size:16,className:"sr-go"}):null];return J?SQ({className:`sheet-row ${C?"danger":""}`},...K).on({click:J}):LA({className:"sheet-row static"},...K)}function S8(A,Q){let B=A.wb.sheet;if(!B)return null;let C=Q.platform.workbench;return LA({className:"sheet-wrap"},LA({className:"scrim"}).on({click:()=>C.closeSheet()}),LA({className:"sheet"},LA({className:"sheet-grip"}).on({click:()=>C.closeSheet()}),B==="status"?X$(A,Q):I$(A,Q)))}function X$(A,Q){let B=AC(A,Q),C=Q.platform.workbench,J=(K)=>()=>{C.closeSheet(),Q.exec(K)};return LA({className:"sheet-body"},LA({className:"sheet-title"},B.collectionLabel),B.issues.length?MA({icon:"warn",danger:!0,label:`${B.issues.length} need${B.issues.length===1?"s":""} attention`,onClick:()=>{C.closeSheet(),Q.app.activity.togglePanel(!0)}}):null,B.running.length||B.uploading.length?MA({icon:"refresh",label:`${B.running.length+B.uploading.length} running`,onClick:()=>{C.closeSheet(),Q.app.activity.togglePanel(!0)}}):null,!B.off.online?MA({icon:"info",label:"Offline",value:`${B.off.pins.length} pinned`}):null,B.off.queued?MA({icon:"upload",label:"Waiting to sync",value:String(B.off.queued)}):null,MA({icon:"files",label:"Items",value:B.partial?`${B.shown.toLocaleString()} of ${B.totalKnown?B.totalItems.toLocaleString():"more"}`:B.totalItems.toLocaleString()}),MA({icon:"file",label:"Size",value:`${QA(B.totalBytes)}${B.totalKnown||!B.partial?"":"+"}`}),B.usage?.total?LA({className:"sheet-row static usage"},U("download",{size:18}),cA({className:"sr-label"},"Free space"),i0({usage:B.usage})):null,B.caps?MA({icon:B.caps.storage?.presignDownload?"download":"files",label:"Transfers",value:B.caps.storage?.presignDownload?"Direct to storage":"Through the server"}):null,B.caps?.features?.semanticSearch?MA({icon:"star",label:"Search",value:"Semantic + keyword"}):null,LA({className:"sheet-actions"},SQ({className:"btn small ghost"},U("refresh",{size:13}),cA("Scan for changes")).on({click:J("workbench.scanCollection")}),SQ({className:"btn small ghost"},U("refresh",{size:13}),cA("Activity")).on({click:()=>{Q.platform.workbench.closeSheet(),Q.app.activity.togglePanel(!0)}})))}function I$(A,Q){let B=Q.platform.workbench,C=(E)=>()=>{B.closeSheet(),Q.exec(E)},J=A.so.me,K=A.so.notifications.unread;return LA({className:"sheet-body"},J&&!J.anonymous?LA({className:"sheet-me"},J.picture?j8({src:J.picture,alt:"",className:"avatar-img"}):cA({className:"avatar-txt"},(J.name||J.id||"?")[0].toUpperCase()),LA({},LA({className:"sm-name"},J.name||J.id),J.email?LA({className:"sm-sub"},J.email):null)):null,MA({icon:"bell",label:K?`Notifications (${K})`:"Notifications",onClick:()=>{B.closeSheet(),Q.app.social.toggleInbox(!0)}}),MA({icon:"refresh",label:"Activity & problems",onClick:()=>{B.closeSheet(),Q.app.activity.togglePanel(!0)}}),MA({icon:"info",label:"Details & conversation",onClick:C("workbench.toggleInfoPanel")}),MA({icon:"trash",label:"Trash",onClick:C("explorer.showTrash")}),MA({icon:"refresh",label:"Refresh",onClick:C("explorer.refresh")}),MA({icon:"command",label:"All commands",onClick:C("workbench.showCommandPalette")}),MA({icon:"gear",label:"Settings",onClick:C("workbench.openSettings")}))}var{alias:$$,div:_Q}=x;function ZJ({engine:A,app:Q,platform:B,plugins:C}){let J=u(0),K={engine:A,app:Q,platform:B,go:(D)=>A.dispatch(D),exec:(D,...X)=>B.commands.execute(D,...X),rerender:()=>J.update((D)=>D+1),uninstallPlugin:(D)=>C?.uninstall(D)},{watch:E}=B.reactive,L=ZQ([B.workbench.observe(),B.workbench.observeOverlay(),B.workbench.observeNav(),Q.explorer.observe(),Q.search.observe(),Q.apiKeys.observe(),Q.transfers.observe(),B.notifications.observe(),B.context.observe(),B.settings.observe(),B.plugins.observe()??PB([]),B.contributions.observeType("statusItem"),Q.social.observe(),Q.offline.observe(),Q.activity.observe(),B.viewport.observe(),B.voice.observe(),J],(D,X,Y,I,$,Z,F,R,P,z,h,M,S,y,w,v,j,T)=>({wb:D,overlay:X,nav:Y,ex:I,se:$,keys:Z,tr:F,notif:R,ctx:P,settings:z,plugins:h,statusItems:M,so:S,off:y,act:w,vp:v,voice:j,_bump:T}));return $$(()=>E(L,(D)=>G$(D,K)))}function G$(A,Q){let B=A.vp?.mode||"desktop",C=B==="phone";return _Q({className:`shell ${B} ${A.settings["workbench.density"]==="compact"?"compact":""}`},C?z8(A,Q):null,_Q({className:"body"},C?null:s0(A,Q),H$(A,Q)),C?w8(A,Q):r0(A,Q),C?S8(A,Q):null,Z$(A,Q),IJ(A,Q),U8(A,Q),F8(A,Q),V8(A,Q),R8(A,Q),M8(A,Q),HJ(A,Q))}function H$(A,Q){if(A.ex?.gate&&A.wb.activity!=="settings")return JJ(A,Q);switch(A.wb.activity){case"settings":return QJ(A,Q);case"plugins":return EJ(A,Q);default:{if(!A.nav.activeTabId)return EC(A,Q);if(!A.wb.infoPanel)return YC(A,Q);return A.vp?.mode==="phone"?o0(A,Q):_Q({className:"editor-split"},YC(A,Q),o0(A,Q))}}}function Z$(A,Q){if(!A.wb.searchModal)return _Q();return _Q({className:"search-modal"},_Q({className:"scrim"}).on({click:()=>Q.platform.workbench.closeSearchModal()}),_Q({className:"search-modal-panel"},EC(A,Q,{modal:!0})))}function T8({root:A=document.querySelector(".workbench"),baseUrl:Q="",openers:B=[],views:C=[],settings:J=[],serviceWorker:K=!0}={}){let E=rK({baseUrl:Q}),{engine:L,app:D}=VE(E);if(Y8(E),vE(E),_8(E,"opener",B),_8(E,"view",C),J.length)E.settings.register(J);E.plugins.restore();let Y=ZJ({engine:L,app:D,platform:E,plugins:{uninstall:($)=>E.plugins.uninstall($)}});x.reconcile(A,[Y()]);let I=()=>{document.documentElement.dataset.theme=E.settings.get("workbench.theme")||"dark"};if(I(),gA(E.settings.observe(),()=>I()),E.viewport.install(),E.voice.refresh().catch(()=>{}),E.spatialNav.install(),E.keybindings.install(window),window.addEventListener("popstate",($)=>E.workbench.onPopState($)),W$(E),K&&"serviceWorker"in navigator)window.addEventListener("load",()=>navigator.serviceWorker.register("/sw.js").catch(()=>{}));return U$(L,D),(async()=>{try{E.capabilities=await E.api.capabilities(),E.workbench.touch()}catch($){E.notifications.error(`Cannot reach the Trove server: ${$.message}`)}L.dispatch(new eB)})(),window.__trove={platform:E,engine:L,app:D,test:{parsePackage:FQ,assessTrust:($)=>E.plugins.assessTrust($),install:($,Z)=>E.plugins.install($,Z),NavigateAction:SA,attachMedia:mQ}},{platform:E,engine:L,app:D}}function _8(A,Q,B){for(let C of B){if(!C?.id)throw Error(`A ${Q} passed to createWorkbench needs an "id"`);let{id:J,...K}=C;A.contributions.register(J,{type:Q,...K})}}function W$(A){let Q=0;window.addEventListener("keydown",(B)=>{if(B.key==="Shift"&&!B.repeat){let C=Date.now();if(C-Q<400)A.workbench.openSearchModal(),Q=0;else Q=C}else if(B.key!=="Shift")Q=0})}function U$(A,Q){let B=0;window.addEventListener("dragenter",(C)=>{if(!C.dataTransfer?.types.includes("Files"))return;B++,document.body.classList.add("dragging-file")}),window.addEventListener("dragover",(C)=>{if(C.dataTransfer?.types.includes("Files"))C.preventDefault()}),window.addEventListener("dragleave",()=>{if(--B<=0)B=0,document.body.classList.remove("dragging-file")}),window.addEventListener("drop",(C)=>{if(!C.dataTransfer?.files?.length)return;C.preventDefault(),B=0,document.body.classList.remove("dragging-file"),A.dispatch(new GB(C.dataTransfer.files,Q.explorer.state.collectionId))})}T8();
354
+
355
+ //# debugId=73AFCABD9F7F7A4C64756E2164756E21
356
+ //# sourceMappingURL=main-y778bpte.js.map