@3sln/trove 0.0.4 → 0.0.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -0
- package/package.json +1 -1
- package/packages/core/src/apiKeys.js +326 -0
- package/packages/core/src/collections/index.js +83 -13
- package/packages/core/src/index.js +14 -2
- package/packages/core/src/issues.js +4 -0
- package/packages/core/src/storage/diagnose.js +234 -0
- package/packages/core/src/storage/drivers.js +83 -0
- package/packages/core/src/storage/filesystem.js +22 -0
- package/packages/core/src/storage/registry.js +162 -0
- package/packages/server/src/adapters/bun.js +6 -0
- package/packages/server/src/adapters/node.js +6 -0
- package/packages/server/src/engine/index.js +1 -1
- package/packages/server/src/engine/providers/access.js +47 -5
- package/packages/server/src/engine/providers/core.js +105 -11
- package/packages/server/src/index.js +123 -11
- package/packages/server/src/mcp/tools.js +40 -8
- package/packages/server/src/router.js +1 -1
- package/packages/server/src/routes.js +135 -32
- package/packages/server/src/scope.js +2 -2
- package/packages/web/dist/assets/main-f0f2tfhp.js +356 -0
- package/packages/web/dist/assets/{main-4cxs7prw.js.map → main-f0f2tfhp.js.map} +17 -16
- package/packages/web/dist/assets/{styles-kcx1x337.css → styles-d3cyysgp.css} +1 -1
- package/packages/web/dist/index.html +2 -2
- package/packages/web/dist/sw.js +58 -9
- package/packages/web/src/bl/actions.js +112 -13
- package/packages/web/src/bl/activity.js +32 -0
- package/packages/web/src/bl/commands.js +41 -2
- package/packages/web/src/bl/index.js +9 -4
- package/packages/web/src/bl/services.js +78 -1
- package/packages/web/src/platform/api.js +57 -14
- package/packages/web/src/platform/pluginRpc.js +7 -4
- package/packages/web/src/styles.css +137 -0
- package/packages/web/src/ui/components/activityPanel.js +28 -1
- package/packages/web/src/ui/components/collectionGate.js +81 -0
- package/packages/web/src/ui/components/overlays.js +64 -34
- package/packages/web/src/ui/components/phoneChrome.js +2 -2
- package/packages/web/src/ui/components/settingsView.js +197 -1
- package/packages/web/src/ui/components/statusBar.js +19 -2
- package/packages/web/src/ui/compositions/workbench.js +9 -2
- package/packages/web/dist/assets/main-4cxs7prw.js +0 -356
|
@@ -0,0 +1,356 @@
|
|
|
1
|
+
import{a as _I,c as hY,d as xI}from"./chunk-4xqbzebh.js";var tQ={};hY(tQ,{wbr:()=>n8,video:()=>t8,vdom:()=>IC,ul:()=>V8,u:()=>d8,track:()=>r8,tr:()=>RL,title:()=>cY,time:()=>l8,thead:()=>WL,th:()=>UL,tfoot:()=>ZL,textarea:()=>xL,template:()=>vL,td:()=>$L,tbody:()=>HL,table:()=>XL,svg:()=>JL,sup:()=>c8,summary:()=>yL,sub:()=>p8,style:()=>nY,strong:()=>m8,special:()=>uY,span:()=>u8,source:()=>KL,small:()=>f8,slot:()=>hL,settings:()=>pY,select:()=>_L,section:()=>L8,script:()=>oY,schedule:()=>bL,samp:()=>b8,s:()=>v8,reconcile:()=>mY,q:()=>h8,progress:()=>TL,pre:()=>M8,portal:()=>EL,picture:()=>CL,param:()=>BL,p:()=>F8,output:()=>wL,option:()=>SL,optgroup:()=>jL,ol:()=>R8,object:()=>QL,noscript:()=>aY,nav:()=>Y8,meter:()=>OL,meta:()=>lY,math:()=>YL,mark:()=>y8,map:()=>i8,main:()=>J8,link:()=>dY,li:()=>W8,legend:()=>zL,label:()=>qL,kbd:()=>g8,ins:()=>k8,input:()=>NL,img:()=>s8,iframe:()=>AL,i:()=>x8,html:()=>MB,hr:()=>U8,header:()=>eY,h6:()=>K8,h5:()=>E8,h4:()=>C8,h3:()=>B8,h2:()=>Q8,h1:()=>A8,h:()=>bY,form:()=>PL,footer:()=>tY,flush:()=>fL,figure:()=>Z8,figcaption:()=>$8,fieldset:()=>VL,embed:()=>e8,em:()=>_8,dt:()=>H8,dodo:()=>WE,dl:()=>X8,div:()=>G8,dialog:()=>gL,dfn:()=>T8,details:()=>kL,del:()=>w8,dd:()=>D8,datalist:()=>ML,data:()=>S8,colgroup:()=>GL,col:()=>DL,code:()=>j8,clear:()=>uL,cite:()=>O8,caption:()=>IL,canvas:()=>LL,button:()=>FL,br:()=>z8,blockquote:()=>I8,b:()=>q8,audio:()=>a8,aside:()=>rY,article:()=>iY,area:()=>o8,alias:()=>fY,address:()=>sY,abbr:()=>N8,a:()=>P8});var XQ=Symbol("ELEMENT_NODE"),FB=Symbol("ALIAS_NODE"),gQ=Symbol("SPECIAL_NODE"),rQ=Symbol("OPAQUE_NODE"),VA=Symbol("NODE_STATE");var OY=new Set(["__proto__","constructor","prototype"]),$E=(A,Q)=>Object.prototype.hasOwnProperty.call(A,Q);function jY(A,Q){return typeof Q==="string"&&A.toLowerCase()===Q.toLowerCase()}class yQ{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!==XQ)throw Error(".opaque() can only be used on element nodes (h).");return this.type=rQ,this}}function SY(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(!$E(Q,C)||A[C]!==Q[C])return!0;return!1}}return!0}function wY(A){return Array.isArray(A)||A!=null&&typeof A[Symbol.iterator]==="function"&&typeof A!=="string"}function TY(A){return(...Q)=>new yQ(FB,A,Q)}function _Y(A){return(...Q)=>new yQ(gQ,A,Q)}function xY(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 ZE(A){return{originalProps:Object.create(null),newVdom:A}}function LC(A,Q,B){let C=A.ownerDocument.createElementNS(xY(A,Q),Q);return C[VA]=ZE(B),C}var UE=new WeakMap;function kY(A){let Q=[],B=A;while(B)if(Q.push(B),B.parentElement)B=B.parentElement;else B=B.getRootNode()?.host;return Q}function HE(A,Q){for(let B of Q)A.add(B)}function gY(A,Q){let B=Q??A?.defaultView??globalThis;return B.Node?.prototype??B.Element?.prototype}function yY(A){let Q=new Set;return A.addEventListener("focusin",(B)=>{Q.clear(),HE(Q,B.composedPath())}),A.addEventListener("focusout",(B)=>{if(!B.relatedTarget)Q.clear()}),HE(Q,kY(A.activeElement)),UE.set(A,Q),Q}var IC=(A)=>{let Q=A?.shouldUpdate??SY,B=A?.isMap??((H)=>H?.constructor===Object),C=A?.mapIter??((H)=>Object.entries(H)),E=A?.mapGet??((H,U)=>H[U]),K=A?.mapMerge??((...H)=>Object.assign({},...H)),J=A?.newMap??((H)=>({...H})),Y=A?.mapPut??((H,U,$)=>{return H[U]=$,H}),I=A?.isSeq??wY,D=A?.seqIter??((H)=>H),L=A?.convertName??((H)=>H),G=A?.convertTagName??L,X=A?.convertPropName??L,Z=A?.convertStyleName??L,R=A?.convertDataName??L,F=A?.convertClassName??L,P=A?.convertHookName??L,g=A?.listenerKey??"listener",f=A?.captureKey??"capture",M=A?.passiveKey??"passive",S=J({});function O(H){if(H==null)return[][Symbol.iterator]();if(typeof H[Symbol.iterator]==="function")return H[Symbol.iterator]();if(typeof H.next==="function")return H;return[H][Symbol.iterator]()}function y(H,U,$,q,j){if(H==null)return;for(let z in H)if($E(H,z))U(z,H[z],$,q,j)}function p(H,U,$,q,j){if(H==null)return;let z=O(C(H)),m;while(!(m=z.next()).done){let BA=m.value;U(BA[0],BA[1],$,q,j)}}let T=A?.mapEach??(A?.mapIter?p:y);function x(H){return H===null||H===void 0||H===!1}function r(H,U,$){let q=O(D(U)),j;while(!(j=q.next()).done){let z=j.value;if($&&x(z))continue;if(!I(z))H.push(z);else r(H,z,$)}}function t(H,U){let $=[];return r($,H,U),$}let a=A?.flattenSeq??t;function hA(H,U){let $=[];for(let q=U;q<H.length;q++){let j=H[q];if(x(j))continue;if(!I(j))$.push(j);else r($,j,!0)}return $}function DA(H){return x(H)?"":String(H)}function GA(H,U,...$){if(!B(U)){if(U!==null&&U!==void 0)$.unshift(U);U=S}return new yQ(XQ,G(H),[U,...$])}function e(H,U,$){$.setProperty(Z(H),U)}function o(H,U,$,q){if(E(q,H)!==void 0)return;$.removeProperty(Z(H))}function LA(H,U,$){let q=H.style;T($,e,q),T(U,o,q,$)}function AA(H,U,$){$.setAttribute(X(H),U)}function DQ(H,U,$,q){if(E(q,H)!==void 0)return;$.removeAttribute(X(H))}function WA(H,U,$){T($,AA,H),T(U,DQ,H,$)}function _A(H,U,$){$.dataset[R(H)]=U}function RA(H,U,$,q){if(E(q,H)!==void 0)return;delete $.dataset[R(H)]}function XA(H,U,$){T($,_A,H),T(U,RA,H,$)}function n(H,U,$){let q=new Set;for(let j of a(U,!0)){let z=F(j);if(z)q.add(z)}for(let j of a($,!0)){let z=F(j);if(!z)continue;q.delete(z),H.classList.add(z)}for(let j of q)H.classList.remove(j)}function zA(H,U,$,q){if(OY.has($)){console.error(`Refusing to assign unsafe prop name '${$}' to a DOM node.`);return}let j=U.originalProps;if(!($ in j))j[$]=H[$];H[$]=q===void 0?j[$]:q}function rA(H,U,$){let q=U.originalProps;if($ in q)H[$]=q[$],delete q[$]}function tA(H,U,$,q,j){let z=X(H),m=E(q,H);if(Object.is(U,m))return;switch(z){case"$styling":{if(!B(U))throw Error("invalid value for styling prop");LA($,m??S,U??S);break}case"$classes":{if(!I(U))throw Error("invalid value for classes prop");n($,m??[],U??[]);break}case"$attrs":{if(!B(U))throw Error("invalid value for attrs prop");WA($,m??S,U??S);break}case"$dataset":{if(!B(U))throw Error("invalid value for dataset prop");XA($,m??S,U??S);break}default:{if(j)zA($,$[VA],z,U);else if(U===void 0)$.removeAttribute(z);else $.setAttribute(z,U);break}}}function TQ(H,U,$,q,j){if(E(q,H)!==void 0)return;let z=X(H);switch(z){case"$styling":LA($,U??S,S);break;case"$classes":n($,U??[],[]);break;case"$attrs":WA($,U??S,S);break;case"$dataset":XA($,U??S,S);break;default:{if(j)rA($,$[VA],z);else $.removeAttribute(z);break}}}function eA(H,U){let $=H[VA],q=H.namespaceURI==="http://www.w3.org/1999/xhtml",j=$.vdom?.args[0]??S;T(U,tA,H,j,q),T(j,TQ,H,U,q)}function AQ(H,U,$){if(typeof $==="function")H.addEventListener(U,$);else if($!=null)H.addEventListener(U,E($,g),{capture:!!E($,f),passive:!!E($,M)})}function QQ(H,U,$){if(typeof $==="function")H.removeEventListener(U,$);else if($!=null)H.removeEventListener(U,E($,g),!!E($,f))}function BQ(H,U,$){let q=P(H);if(q[0]==="$")return;AQ($,q,U)}function sQ(H,U,$,q){let j=P(H);if(j[0]==="$")return;let z=E(q,H);if(U===z)return;QQ($,j,z),AQ($,j,U)}function WY(H,U,$,q){let j=P(H);if(j[0]==="$"||E(q,H)!==void 0)return;QQ($,j,U)}function LE(H,U){let $=H[VA],q=U??S;if(!$.vdom){T(q,BQ,H);return}let j=$.vdom.hooks??S;T(q,sQ,H,j),T(j,WY,H,q)}function YC(H){let U=H[VA],$=U.newVdom,q=U.vdom,j=$.args;switch($.type){case XQ:{eA(H,j[0]),iQ(H,hA(j,1));break}case rQ:{eA(H,j[0]);break}case FB:{let z=$.tag.apply(H,$.args);if(x(z))iQ(H,[]);else if(I(z))iQ(H,a(z,!0));else iQ(H,[z]);break}case gQ:{try{$.tag.update?.(H,$.args,q?.args)}catch(z){console.error(z)}break}}if($.hooks||q?.hooks)LE(H,$.hooks??S);try{$.hooks?.$update?.(H,$,q)}catch(z){console.error(z)}U.vdom=$,delete U.newVdom}function RY(H,U){if(typeof U!=="object"||U===null)return H.ownerDocument.createTextNode(DA(U));let $;switch(U.type){case XQ:case rQ:$=LC(H,U.tag,U);break;case FB:$=LC(H,"udom-alias",U),$.style.display="contents";break;case gQ:$=LC(H,"udom-special",U),$.style.display="contents";break;default:throw Error("Invalid VDOM node")}return $}function IE(H){if(H.children)for(let U of H.children)RB(U)}function RB(H){let U=H[VA];if(!U)return;let{vdom:$}=U;if(!$){delete H[VA];return}if($.hooks)LE(H,S);if($.type===XQ||$.type===rQ)eA(H,S);if($.type===XQ||$.type===FB)IE(H);delete H[VA];try{if($.type===gQ)$.tag.detach?.(H);$.hooks?.$detach?.(H)}catch(q){console.error(q)}}function FY(H,U){let $=H[VA];if(Q($.vdom.args,U.args)||Q($.vdom.hooks,U.hooks))$.newVdom=U;return H}function MY(H){let U=new Map,$={nodes:[],cursor:0};for(let q of H.childNodes){if(q.nodeType===3){$.nodes.push(q);continue}let j=q[VA],z=j?.vdom;if(z===void 0){if(j?.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 m=U.get(z.tag);if(!m)m={nodesForKey:null,nodesWithoutKey:{nodes:[],cursor:0}},U.set(z.tag,m);if(z.k!==void 0){if(!m.nodesForKey)m.nodesForKey=new Map;let BA=m.nodesForKey.get(z.k);if(BA)BA.nodes.push(q);else m.nodesForKey.set(z.k,{nodes:[q],cursor:0})}else m.nodesWithoutKey.nodes.push(q)}return{byTag:U,textNodes:$}}function DE(H){if(!H||H.cursor>=H.nodes.length)return;return H.nodes[H.cursor++]}function VY(H,U,$,q){let j=H.firstChild;for(let z=0;z<U.length;z++){let m=U[z];if(m===j){j=j.nextSibling;continue}(q&&m.isConnected?q:$).call(H,m,j)}}function PY(H,U,$,q){let j=U[q],z=j;for(let BA=q-1;BA>=0;BA--){let lA=U[BA];if(lA!==z.previousSibling)$.call(H,lA,z);z=lA}let m=j.nextSibling;for(let BA=q+1;BA<U.length;BA++){let lA=U[BA];if(lA===m)m=m.nextSibling;else $.call(H,lA,m)}}function NY(H,U){for(let $=0;$<H.length;$++)if(U.has(H[$]))return $;return-1}function qY(H){let U=H[VA];if(!U?.newVdom)return;if(!U.vdom)try{if(U.newVdom.hooks?.$attach?.(H),U.newVdom.type===gQ)U.newVdom.tag.attach?.(H)}catch($){console.error($)}YC(H)}function iQ(H,U){let $=H.firstChild?new Set(H.childNodes):null,{byTag:q,textNodes:j}=MY(H),z=[];for(let HA of U){let GQ;if(HA instanceof yQ){let xQ=q.get(HA.tag),kQ=xQ?DE(HA.k!==void 0?xQ.nodesForKey?.get(HA.k):xQ.nodesWithoutKey):void 0;GQ=kQ?FY(kQ,HA):RY(H,HA)}else{let xQ=DE(j),kQ=DA(HA);if(xQ){if(GQ=xQ,GQ.nodeValue!==kQ)GQ.nodeValue=kQ}else GQ=H.ownerDocument.createTextNode(kQ)}$?.delete(GQ),z.push(GQ)}if($)for(let HA of $)RB(HA),H.removeChild(HA);if(z.length===0)return;let m=H.ownerDocument,BA=gY(m,A?.window),lA=BA.insertBefore,GE=typeof BA.moveBefore==="function"?BA.moveBefore:null,XE=H.isConnected,_Q=-1;if(XE&&!GE){let HA=UE.get(m)??yY(m);if(_Q=NY(z,HA),_Q!==-1&&z[_Q].parentNode!==H)_Q=-1}if(_Q===-1)VY(H,z,lA,XE?GE:null);else PY(H,z,lA,_Q);for(let HA=0;HA<z.length;HA++)qY(z[HA])}function zY(H,U){let $=H[VA];if(U===null||U===void 0){if($)RB(H);else IE(H);H.replaceChildren();return}if(I(U)){iQ(H,a(U,!0));return}if(U instanceof yQ){if($){if($.vdom.type===U.type&&$.vdom.tag===U.tag){if(Q($.vdom.args,U.args)||Q($.vdom.hooks,U.hooks))$.newVdom=U,YC(H);return}RB(H)}switch(U.type){case XQ:case rQ:if(!jY(H.nodeName,G(U.tag)))throw Error("incompatible target for vdom");break}H[VA]=ZE(U);try{if(U.hooks?.$attach?.(H),U.type===gQ)U.tag.attach?.(H)}catch(q){console.error(q)}YC(H);return}throw Error("invalid vdom")}return{h:GA,alias:TY,special:_Y,reconcile:zY,settings:{shouldUpdate:Q,isMap:B,mapIter:C,mapEach:T,mapGet:E,mapMerge:K,newMap:J,mapPut:Y,isSeq:I,flattenSeq:a,seqIter:D,convertTagName:G,convertPropName:X,convertStyleName:Z,convertDataName:R,convertClassName:F,convertHookName:P,convertName:L,listenerKey:g,captureKey:f,passiveKey:M}}};function MB({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 DC({window:A}={}){let Q=!1,B=0,C=[];function E(){return A??globalThis}function K(Z){let R=E().requestAnimationFrame;return typeof R==="function"?R.call(E(),Z):setTimeout(Z,16)}function J(Z){let R=E().cancelAnimationFrame;if(typeof R==="function")R.call(E(),Z);else clearTimeout(Z)}function Y(){return E().performance?.now()??Date.now()}function I(Z){for(let R of Z)try{R()}catch(F){console.error("Error in scheduled function:",F)}}function D(){let Z=Y();B=0;while(C.length>0){let R=C.splice(0,100);if(I(R),Y()-Z>10&&C.length>0){B=K(D);return}}Q=!1}function L(Z,{signal:R}={}){if(R?.aborted)return;let F=Z;if(R)F=()=>{if(!R.aborted)Z()};if(C.push(F),!Q)Q=!0,B=K(D)}function G(){if(B)J(B),B=0;Q=!0;while(C.length>0){let Z=C;C=[],I(Z)}Q=!1}function X(){if(B)J(B);C=[],Q=!1,B=0}return{schedule:L,flush:G,clear:X}}function WE(A){let Q=IC(A),B=MB(Q),C=A?.scheduler??DC(A);return{...Q,...B,...C}}var vY=WE();var{h:bY,alias:fY,special:uY,reconcile:mY,settings:pY,title:cY,meta:lY,link:dY,style:nY,script:oY,noscript:aY,address:sY,article:iY,aside:rY,footer:tY,header:eY,h1:A8,h2:Q8,h3:B8,h4:C8,h5:E8,h6:K8,main:J8,nav:Y8,section:L8,blockquote:I8,dd:D8,div:G8,dl:X8,dt:H8,figcaption:$8,figure:Z8,hr:U8,li:W8,ol:R8,p:F8,pre:M8,ul:V8,a:P8,abbr:N8,b:q8,br:z8,cite:O8,code:j8,data:S8,del:w8,dfn:T8,em:_8,i:x8,ins:k8,kbd:g8,mark:y8,q:h8,s:v8,samp:b8,small:f8,span:u8,strong:m8,sub:p8,sup:c8,time:l8,u:d8,wbr:n8,area:o8,audio:a8,img:s8,map:i8,track:r8,video:t8,embed:e8,iframe:AL,object:QL,param:BL,picture:CL,portal:EL,source:KL,svg:JL,math:YL,canvas:LL,caption:IL,col:DL,colgroup:GL,table:XL,tbody:HL,td:$L,tfoot:ZL,th:UL,thead:WL,tr:RL,button:FL,datalist:ML,fieldset:VL,form:PL,input:NL,label:qL,legend:zL,meter:OL,optgroup:jL,option:SL,output:wL,progress:TL,select:_L,textarea:xL,details:kL,dialog:gL,summary:yL,slot:hL,template:vL,schedule:bL,flush:fL,clear:uL}=vY;function mL(A,{signal:Q}={}){queueMicrotask(()=>{if(!Q?.aborted)A()})}function pL(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 RE(A){return A!=null&&typeof A.special==="function"&&typeof A.reconcile==="function"}function GC(A){let Q=RE(A)?{dodo:A}:A,B=Q?.dodo;if(!RE(B))throw Error("a dodo instance must be provided in settings, e.g. reactive({dodo})");return{schedule:typeof B.schedule==="function"?B.schedule:mL,renderError:pL(B.h),...Q,dodo:B,...B.settings}}var dA=Symbol("dodo.reactive.PENDING"),$A=Symbol("dodo.reactive.NOTHING");function $Q(A){return A!=null&&typeof A.onDirty==="function"&&typeof A.getValue==="function"}function hQ(A){return $Q(A)?A.getValue():A}function cL(A){if(typeof A==="function")return A;if(A&&typeof A.unsubscribe==="function")return()=>A.unsubscribe();return()=>{}}function XC(){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 VB(A,Q){let{listeners:B,notify:C}=XC(),E=null;return{onDirty(K){if(B.add(K),B.size===1)try{E=cL(A(C))}catch(Y){throw B.delete(K),Y}let J=!1;return()=>{if(J)return;if(J=!0,B.delete(K),B.size===0&&E){let Y=E;E=null,Y()}}},getValue(){return Q()}}}function b(A){let Q=A,{listeners:B,notify:C}=XC();return{onDirty(E){return B.add(E),()=>B.delete(E)},getValue(){return Q},setValue(E){if(Object.is(E,Q))return;Q=E,C()},update(E){this.setValue(E(Q))}}}function PB(A){return{onDirty(){return()=>{}},getValue(){return A}}}function ZQ(A,Q){let B=Array.isArray(A)?A:[A],{listeners:C,notify:E}=XC(),K=null,J=$A,Y=()=>{J=$A,E()},I=()=>{let D=Array(B.length);for(let L=0;L<B.length;L++){let G=hQ(B[L]);if(G===dA)return dA;D[L]=G}return Q(...D)};return{onDirty(D){if(C.add(D),C.size===1)J=$A,K=B.map((G)=>$Q(G)?G.onDirty(Y):null);let L=!1;return()=>{if(L)return;if(L=!0,C.delete(D),C.size===0&&K){for(let G of K)G?.();K=null,J=$A}}},getValue(){if(J===$A||!K)J=I();return J}}}function FE(A,Q){return ZQ([A],Q)}function ME(A,{initial:Q=dA}={}){return lL(A,{initial:Q},(B,C)=>B.subscribe({next:C.next,error:C.error,complete:C.complete}))}function lL(A,{initial:Q},B){let C=Q,E=$A;return VB((J)=>{return B(A,{next(I){C=I,E=$A,J()},error(I){E=I,J()},complete(){}})},()=>{if(E!==$A)throw E;return C})}function VE(A){return{subscribe(Q){let B=typeof Q==="function"?{next:Q}:Q??{},C=()=>{let K;try{K=hQ(A)}catch(J){B.error?.(J);return}if(K!==dA)B.next?.(K)},E=$Q(A)?A.onDirty(C):()=>{};return C(),{unsubscribe:E}}}}function xA(A,Q){let B=()=>{let E;try{E=hQ(A)}catch(K){console.error("Error reading cell in effect:",K);return}if(E===dA)return;Q(E)},C=$Q(A)?A.onDirty(B):()=>{};return B(),C}var HQ=Symbol("dodo.reactive.watch");function NB(A){let Q=GC(A),{dodo:B,schedule:C,renderError:E}=Q,{special:K,reconcile:J}=B,Y=Q.mapGet??((G,X)=>G[X]),I=(G,X)=>G==null?void 0:Y(G,X),D=Q.shouldUpdate??((G,X)=>G!==X);return{watch:K({attach(G){G[HQ]={source:$A,builder:null,placeholder:void 0,errorBuilder:void 0,unsubscribe:null,abortController:null,renderScheduled:!1,lastValue:$A,lastBuilder:$A}},update(G,[X,Z,R]){let F=G[HQ];if(!F)return;if(F.builder=Z,F.placeholder=I(R,"placeholder"),F.errorBuilder=I(R,"error"),F.source!==X){if(F.unsubscribe?.(),F.unsubscribe=null,F.abortController?.abort(),F.abortController=new AbortController,F.source=X,F.lastValue=$A,$Q(X))try{F.unsubscribe=X.onDirty(()=>this.invalidate(G))}catch(P){this.renderError(G,P);return}}this.render(G)},invalidate(G){let X=G[HQ];if(!X||X.renderScheduled)return;X.renderScheduled=!0,C(()=>this.render(G),{signal:X.abortController?.signal})},render(G){let X=G[HQ];if(!X)return;X.renderScheduled=!1;let Z;try{Z=hQ(X.source===$A?void 0:X.source)}catch(R){this.renderError(G,R);return}if(X.builder===X.lastBuilder&&X.lastValue!==$A&&!D(X.lastValue,Z))return;X.lastValue=Z,X.lastBuilder=X.builder;try{if(Z===dA)J(G,X.placeholder?[X.placeholder()]:[]);else J(G,[X.builder(Z)])}catch(R){this.renderError(G,R)}},renderError(G,X){let Z=G[HQ];if(!Z)return;Z.lastValue=$A,Z.lastBuilder=$A,console.error("Error in watched cell:",X);try{J(G,[(Z.errorBuilder??E)(X)])}catch(R){console.error("Error rendering the error view:",R)}},detach(G){let X=G[HQ];if(!X)return;X.unsubscribe?.(),X.abortController?.abort(),delete G[HQ],J(G,null)}})}}var{watch:qB}=NB({dodo:tQ});var w=tQ;function eQ(A){let Q={status:"idle"};return VB((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 PE={watch:qB,cell:b,derive:ZQ,constant:PB,mapCell:FE,connectable:VB,fromObservable:ME,fromAsync:eQ,toObservable:VE,effect:xA,isCell:$Q,readCell:hQ,PENDING:dA};var v=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"}),dL=new Set([v.TRANSIENT,v.TIMEOUT,v.QUOTA]),nL={[v.NOT_FOUND]:404,[v.ALREADY_EXISTS]:409,[v.INVALID]:400,[v.CONFLICT]:412,[v.UNAUTHORIZED]:401,[v.FORBIDDEN]:403,[v.UNSUPPORTED]:501,[v.QUOTA]:429,[v.TOO_LARGE]:413,[v.BAD_RANGE]:416,[v.TRANSIENT]:503,[v.TIMEOUT]:504,[v.ABORTED]:499,[v.INTERNAL]:500};class N extends Error{constructor(A,Q,B={}){super(Q,B.cause!==void 0?{cause:B.cause}:void 0);if(this.name="TroveError",this.code=A||v.INTERNAL,this.retryable=B.retryable??dL.has(this.code),this.details=B.details??null,this.status=nL[this.code]??500,this.code===v.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 N(v.NOT_FOUND,A?`${A} not found`:"Not found",Q)}static alreadyExists(A,Q){return new N(v.ALREADY_EXISTS,`${A} already exists`,Q)}static invalid(A,Q){return new N(v.INVALID,A,Q)}static conflict(A,Q){return new N(v.CONFLICT,A,Q)}static unsupported(A,Q){return new N(v.UNSUPPORTED,A,Q)}static transient(A,Q){return new N(v.TRANSIENT,A,{retryable:!0,...Q})}static timeout(A,Q){return new N(v.TIMEOUT,A,{retryable:!0,...Q})}static aborted(A="Operation aborted",Q){return new N(v.ABORTED,A,{retryable:!1,...Q})}static unauthorized(A="Unauthorized",Q){return new N(v.UNAUTHORIZED,A,Q)}static tooLarge(A="Too large",Q){return new N(v.TOO_LARGE,A,{retryable:!1,...Q})}static badRange(A="Range not satisfiable",Q){return new N(v.BAD_RANGE,A,{retryable:!1,...Q})}static forbidden(A="Forbidden",Q){return new N(v.FORBIDDEN,A,Q)}static internal(A="Internal error",Q){return new N(v.INTERNAL,A,Q)}}function AB(A,Q="Unexpected error"){if(A instanceof N)return A;if(A?.name==="AbortError"||A?.code==="ABORT_ERR")return N.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 N.transient(A.message||"Network error",{cause:A});switch(A?.code){case"ENOENT":return N.notFound(null,{cause:A});case"EEXIST":return N.alreadyExists("Path",{cause:A});case"EACCES":case"EPERM":return new N(v.FORBIDDEN,"Permission denied",{cause:A});case"ENOSPC":return new N(v.QUOTA,"The storage volume is full — free some space and try again",{cause:A,retryable:!1});case"EDQUOT":return new N(v.QUOTA,"The storage quota for this volume has been reached",{cause:A,retryable:!1});case"EFBIG":return new N(v.QUOTA,"That file is larger than this filesystem can store",{cause:A,retryable:!1})}return N.internal(A?.message||Q,{cause:A})}function NE(A){if(A instanceof N)return A.retryable;return AB(A).retryable}function qE(A=""){let Q=(globalThis.crypto?.randomUUID?.()??oL()).replace(/-/g,"");return A?`${A}_${Q}`:Q}function oL(){let A="";for(let Q=0;Q<32;Q++)A+=Math.floor(Math.random()*16).toString(16);return A}function zE(A){let Q=String(A||"").lastIndexOf(".");return Q>0?String(A).slice(Q).toLowerCase():""}function OE(A,Q){if(!A||!Q)return!1;if(typeof A.match==="function")try{if(A.match(Q))return!0}catch{}let B=zE(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 vQ="trove+contrib:",jE="core",aL=/^(?:core|[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)+)$/,sL=/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/;function iL(A){return typeof A==="string"&&aL.test(A)}function zB(A){return typeof A==="string"&&sL.test(A)}function vA(A){return OB(A),`${A.domain}/${A.name}`}function CQ(A,Q){if(!zB(Q))throw N.invalid(`Invalid contribution name "${Q}"`);return`${vQ}${vA(A)}/${Q}`}var rL="workbench";function SE(A){return`${vQ}${jE}/${rL}/${A}`}function EQ(A){if(typeof A!=="string"||!A.startsWith(vQ))return null;let Q=A.slice(vQ.length),B=Q.indexOf("/"),C=Q.indexOf("/",B+1);if(B<0||C<0)return null;let E=Q.slice(0,B),K=Q.slice(B+1,C),J=Q.slice(C+1);if(!E||!K||!J)return null;return{domain:E,plugin:K,name:J,pluginId:`${E}/${K}`}}function wE(A,Q){let B=EQ(Q);return!!B&&B.pluginId===`${A.domain}/${A.name}`}function OB(A){if(!iL(A?.domain))throw N.invalid(`Plugin manifest needs a valid "domain" (got ${JSON.stringify(A?.domain)})`);if(!zB(A?.name))throw N.invalid(`Plugin manifest needs a valid "name" (got ${JSON.stringify(A?.name)})`);if(A.domain===jE)throw N.invalid('The "core" domain is reserved for built-in contributions')}var _E={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:TE(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:TE(A.match)})},statusItem:{normalize:(A)=>{let Q=A.slot==="left"?"left":"right",B=A.render||"html";if(B!=="html")throw N.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 N.invalid('keymap contribution needs a "path" to a JSON file in the package');return{path:A.path}}}},HC=Object.keys(_E);function nA(A){let Q=A?.contributes;if(Q==null)return[];if(typeof Q!=="object"||Array.isArray(Q))throw N.invalid('manifest "contributes" must be a map of name -> contribution');let B=[];for(let[C,E]of Object.entries(Q)){if(!E||typeof E!=="object")throw N.invalid(`Contribution "${C}" must be an object`);if(!zB(C))throw N.invalid(`Invalid contribution name "${C}"`);let K=_E[E.type];if(!K)throw N.invalid(`Contribution "${C}" has unknown type ${JSON.stringify(E.type)} (expected one of ${HC.join(", ")})`);let J=E.entry||A.entry;if(K.needsEntry&&!J)throw N.invalid(`Contribution "${C}" (${E.type}) needs an "entry" module`);B.push({name:C,uri:CQ(A,C),pluginId:vA(A),type:E.type,...K.normalize(E),...K.needsEntry?{entry:J}:{}})}return B}function tL(A,Q){return nA(A).filter((B)=>B.type===Q)}function $C(A){return tL(A,"indexer").map((Q)=>({id:Q.uri,name:Q.name,title:Q.title||Q.name,match:Q.match,entry:Q.entry}))}function xE(A){let Q;try{Q=JSON.parse(A)}catch(C){throw N.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 N.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 TE(A){if(!A||typeof A!=="object"||Array.isArray(A))return{};let Q=(K)=>K==null?void 0:(Array.isArray(K)?K:[K]).filter((J)=>typeof J==="string"),B={},C=Q(A.ext),E=Q(A.mime??A.contentType);if(C)B.ext=C;if(E)B.mime=E;if(typeof A.match==="function")B.match=A.match;return B}var eL=[...HC,"view"];function jB(A){return String(A).startsWith(vQ)?A:SE(A)}class ZC{constructor(){this.items=new Map,this.cell=b([]),this.byType=new Map}#A(){this.cell.setValue([...this.items.values()])}register(A,Q){let B=Q?.type;if(!eL.includes(B))throw Error(`Unknown contribution type "${B}" for ${A}`);let C=jB(A),E=EQ(C);if(!E)throw Error(`Not a contribution URI: ${C}`);let K=Q.pluginId??(E.domain==="core"?null:E.pluginId),J={...Q,uri:C,type:B,id:E.domain==="core"?E.name:C,name:E.name,pluginId:K};return this.items.set(C,J),this.#A(),()=>this.unregister(C)}update(A,Q){let B=jB(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(jB(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(jB(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)=>OE(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 UC=new Map;function AI(A){if(!A)return()=>!0;if(UC.has(A))return UC.get(A);let Q;try{Q=new gE(A).parseExpression()}catch(B){console.warn(`Invalid when clause: "${A}" — ${B.message}`),Q=()=>!1}return UC.set(A,Q),Q}function kE(A,Q){return AI(A)(Q||{})}var SB=/\s*(=~|==|!=|>=|<=|&&|\|\||[()!<>]|trove\+contrib:[A-Za-z0-9_./-]+|\/(?:\\.|[^/])*\/|'(?:\\.|[^'])*'|"(?:\\.|[^"])*"|[A-Za-z0-9_.:-]+)/y;class gE{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.#E();if(this.pos!==this.tokens.length)throw Error(`Trailing "${this.#Q()}"`);return A}#E(){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.#J();while(this.#Q()==="&&"){this.#B();let Q=this.#J(),B=A;A=(C)=>B(C)&&Q(C)}return A}#J(){if(this.#Q()==="!"){this.#B();let A=this.#J();return(Q)=>!A(Q)}return this.#Y()}#Y(){let A=this.#L(),Q=this.#Q();if(["==","!=",">=","<=",">","<","=~"].includes(Q)){if(this.#B(),Q==="=~"){let C=this.#B(),E=QI(C);return(K)=>E.test(String(A(K)??""))}let B=this.#L();return(C)=>CI(Q,A(C),B(C))}return(B)=>BI(A(B))}#L(){let A=this.#B();if(A===void 0)throw Error("Unexpected end");if(A==="("){let Q=this.#E();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 QI(A){let Q=/^\/((?:\\.|[^/])*)\/([a-z]*)$/.exec(A);if(!Q)throw Error(`Bad regex ${A}`);return new RegExp(Q[1],Q[2])}function BI(A){return!(A===void 0||A===null||A===!1||A===""||A===0)}function CI(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 WC{constructor(A={}){this.state={platform:yE(),isMac:/mac/i.test(yE()),...A},this.cell=b(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,E]of Object.entries(A))if(B[C]!==E)B[C]=E,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 kE(A,this.state)}scopedFor(A){let Q=`${A}.`;return{set:(B,C)=>this.set(Q+B,C),remove:(B)=>this.remove(Q+B)}}}function yE(){return typeof navigator<"u"?navigator.platform||navigator.userAgent||"":""}class RC{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(E){throw console.error(`Command ${A} failed`,E),this.notifications.error(E?.message||`Command failed: ${A}`),E}}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 FC(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(hE()?"meta":"ctrl");else C=K;return[...["ctrl","meta","alt","shift"].filter((K)=>B.has(K)),C].filter(Boolean).join("+")}function MC(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((E)=>B!==E),B].join("+")}class bQ{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${FC(A.defaultKey||A.key)}`}rebind(A,Q){if(!this.settings)return;let B=typeof A==="string"?this.#A(A):bQ.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?bQ.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=FC(Q.key),C=bQ.bindingId({command:Q.command,defaultKey:B});return{...Q,defaultKey:B,bindingId:C,key:FC(A[C]||Q.key)}})}#Q(A){let Q=this.context.snapshot(),B=this.resolved();for(let C=B.length-1;C>=0;C--){let E=B[C];if(E.key!==A)continue;if(E.when&&!this.context.evaluate(E.when))continue;return E}return null}#B(A){if(A.defaultPrevented)return;let Q=MC(A),B=A.ctrlKey||A.metaKey||A.altKey;if(EI(A.target)&&!B&&A.key!=="Escape"){this.#C();return}let E=this.chordPrefix?`${this.chordPrefix} ${Q}`:Q,K=this.#Q(E);if(K){A.preventDefault(),this.#C(),this.commands.execute(K.command,...K.args||[]);return}if(!this.chordPrefix&&this.resolved().some((J)=>J.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?QB(Q.key):null}}function EI(A){if(!A)return!1;let Q=A.tagName;return Q==="INPUT"||Q==="TEXTAREA"||Q==="SELECT"||A.isContentEditable}function hE(){return typeof navigator<"u"&&/mac/i.test(navigator.platform||navigator.userAgent||"")}function QB(A){let Q=hE(),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((E)=>B[E]||(E.length===1?E.toUpperCase():E[0].toUpperCase()+E.slice(1))).join(Q?"":"+")).join(" ")}var bE="trove.settings";class VC{constructor(){this.schema=new Map,this.values=KI(),this.cell=b(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;vE(this.values),this.cell.setValue(this.effective())}reset(A){delete this.values[A],vE(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 KI(){try{return JSON.parse(localStorage.getItem(bE))||{}}catch{return{}}}function vE(A){try{localStorage.setItem(bE,JSON.stringify(A))}catch{}}var JI=0;class PC{constructor(){this.items=[],this.cell=b([])}observe(){return this.cell}#A(A,Q,B={}){let C={id:++JI,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 YI={retries:4,minDelayMs:250,maxDelayMs:8000,factor:2,jitter:!0};function LI(A,Q){return new Promise((B,C)=>{if(Q?.aborted)return C(N.aborted());let E=(Y)=>(I)=>{clearTimeout(K),Q?.removeEventListener("abort",J),Y(I)},K=setTimeout(()=>E(B)(),A),J=()=>E(C)(N.aborted());Q?.addEventListener("abort",J,{once:!0})})}async function BB(A,Q={}){let B={...YI,...Q},C=B.shouldRetry??NE,E=0;for(;;){if(B.signal?.aborted)throw N.aborted();try{return await A(E)}catch(K){let J=AB(K);if(!(E<B.retries&&C(J)&&J.code!=="aborted"))throw J;let I=Math.min(B.maxDelayMs,B.minDelayMs*B.factor**E),D=B.jitter?Math.random()*I:I;B.onRetry?.({attempt:E+1,delayMs:D,error:J}),await LI(D,B.signal),E++}}}class NC{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:E,raw:K}={}){let J=this.baseUrl+Q+(C?"?"+new URLSearchParams(C):"");return BB(async()=>{let Y=await this._fetch(J,{method:A,headers:{...this.authHeaders(),...B?{"content-type":"application/json"}:{}},body:B?JSON.stringify(B):void 0,signal:E});if(Y.status===429||Y.status>=500){if(!K){let L;try{let G=await Y.text();L=(G?JSON.parse(G):null)?.error}catch{}if(L&&L.retryable===!1)throw new N(L.code,L.message,{retryable:!1,details:L.details});throw N.transient(L?.message||`Server ${Y.status}`)}throw N.transient(`Server ${Y.status}`)}if(K)return Y;let I=await Y.text(),D=I?JSON.parse(I):null;if(!Y.ok){let L=D?.error||{code:"internal",message:`Request failed (${Y.status})`};throw new N(L.code,L.message,{retryable:L.retryable,details:L.details})}return D},{signal:E,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",E=Q?`${this.#A(Q)}/items/resolve`:"/api/items/resolve";return this.request("GET",E,{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 E=B?`${this.#A(B)}/tags/search`:"/api/tags/search";return this.request("POST",E,{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()}),E=await C.json().catch(()=>null);if(!C.ok){let K=E?.error||{code:"internal",message:`Install failed (${C.status})`};throw new N(K.code,K.message,{details:K.details})}return E.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 N("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 E=await this._fetch(C,{headers:this.authHeaders()});if(!E.ok)throw new N("internal",`Download failed (${E.status})`);return{url:URL.createObjectURL(await E.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 N("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 E=B==null||B>Q,K=await this._fetch(this.downloadUrl(A),{signal:C,headers:{...this.authHeaders(),...E?{range:`bytes=0-${Q-1}`}:{}}});if(K.status===416)return{text:"",truncated:!1,total:0};if(!K.ok&&K.status!==206)throw new N("internal",`Download failed (${K.status})`);let J=new Uint8Array(await K.arrayBuffer()),Y=Number(/\/(\d+)$/.exec(K.headers.get("content-range")||"")?.[1])||null,I=J.length>=Q&&(Y==null||Y>J.length),D=new TextDecoder("utf-8",{fatal:!1}).decode(J);if(I){let L=D.lastIndexOf(`
|
|
4
|
+
`);if(L>0)D=D.slice(0,L)}return{text:D,truncated:I,total:Y}}async upload(A,Q){let B=Q.name||A.name||"untitled",C=A.size,E=await this.request("POST",`${this.#A(Q.collection)}/uploads`,{body:{name:B,size:C,contentType:A.type||void 0},signal:Q.signal});if(E.uploadId)Q.onStart?.(E.uploadId);let K=new fE(C,Q.onProgress),J=E.transfer||{},Y=E.endpoints?.complete||`/api/uploads/${E.uploadId}/complete`;if(E.strategy==="single")return await wB(J.url||E.url,A,{headers:J.requiredHeaders,signal:Q.signal,onProgress:(y)=>K.set("single",y)}),(await this.request("POST",Y,{body:{},signal:Q.signal})).node;if(E.strategy==="direct-single")return await wB(this.baseUrl+this.#Q(E,1),A,{headers:{...this.authHeaders(),...J.authHeaders},signal:Q.signal,onProgress:(y)=>K.set(1,y)}),(await this.request("POST",Y,{body:{},signal:Q.signal})).node;let I=E.partSize,D=E.partCount??Math.ceil(C/I),L=new Set;try{let O=E.endpoints?.status||`/api/uploads/${E.uploadId}/status`,y=await this.request("GET",O,{signal:Q.signal});L=new Set(y.received||[])}catch{}let G=[],X=[];for(let O=1;O<=D;O++){let y=(O-1)*I,p=A.slice(y,Math.min(y+I,C));X.push({n:O,blob:p})}let Z=Array(D),R=Math.min(Q.concurrency??4,X.length),F=0,P=new AbortController,g=()=>P.abort();if(Q.signal)if(Q.signal.aborted)P.abort();else Q.signal.addEventListener("abort",g,{once:!0});let f=async()=>{while(F<X.length){if(P.signal.aborted)return;let{n:O,blob:y}=X[F++];if(L.has(O)){K.set(O,y.size);continue}let p=await BB(()=>this.#B(E,O,y,{signal:P.signal,onProgress:(T)=>K.set(O,T)}),{signal:P.signal,retries:4});Z[O-1]={partNumber:O,etag:p}}};try{await Promise.all(Array.from({length:R},f))}catch(O){throw P.abort(),O}finally{Q.signal?.removeEventListener("abort",g)}let M=Z.filter(Boolean);return(await this.request("POST",Y,{body:{parts:M},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,B,{signal:C,onProgress:E}){let K=A.transfer||{};if(A.strategy==="presign"){let I=(K.parts||A.parts)?.find((X)=>X.partNumber===Q)?.url;if(!I){let X=A.endpoints?.sign||`/api/uploads/${A.uploadId}/parts/{partNumber}/sign`;I=(await this.request("POST",X.replace("{partNumber}",String(Q)),{signal:C})).url}let L=(await wB(I,B,{signal:C,onProgress:E,wantEtag:!0})).etag,G=A.endpoints?.report||`/api/uploads/${A.uploadId}/parts/{partNumber}/report`;return await this.request("POST",G.replace("{partNumber}",String(Q)),{body:{etag:L},signal:C}),L}return(await wB(this.baseUrl+this.#Q(A,Q),B,{headers:{...this.authHeaders(),...K.authHeaders},signal:C,onProgress:E,wantJson:!0})).json?.etag}async abortUpload(A){return this.request("DELETE",`/api/uploads/${A}`)}}class fE{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 E=Math.min(C,this.total);this.cb({loaded:E,total:this.total,ratio:this.total?E/this.total:1})}}function wB(A,Q,{signal:B,onProgress:C,wantEtag:E,wantJson:K,headers:J}={}){return new Promise((Y,I)=>{let D=new XMLHttpRequest;D.open("PUT",A,!0);for(let[L,G]of Object.entries(J||{}))try{D.setRequestHeader(L,G)}catch{}if(B){if(B.aborted)return D.abort(),I(N.aborted());B.addEventListener("abort",()=>D.abort(),{once:!0})}D.upload.onprogress=(L)=>C?.(L.loaded),D.onload=()=>{if(D.status>=200&&D.status<300){let L={status:D.status};if(E)L.etag=D.getResponseHeader("ETag")||D.getResponseHeader("etag");if(K)try{L.json=JSON.parse(D.responseText)}catch{}Y(L)}else if(D.status===429||D.status>=500)I(N.transient(`Upload part failed (${D.status})`));else I(new N("internal",`Upload failed (${D.status})`))},D.onerror=()=>I(N.transient("Network error during upload")),D.onabort=()=>I(N.aborted()),D.send(Q)})}var s=Uint8Array,NA=Uint16Array,gC=Int32Array,TB=new s([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]),_B=new s([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]),SC=new s([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),nE=function(A,Q){var B=new NA(31);for(var C=0;C<31;++C)B[C]=Q+=1<<A[C-1];var E=new gC(B[30]);for(var C=1;C<30;++C)for(var K=B[C];K<B[C+1];++K)E[K]=K-B[C]<<5|C;return{b:B,r:E}},oE=nE(TB,2),aE=oE.b,wC=oE.r;aE[28]=258,wC[258]=28;var sE=nE(_B,0),II=sE.b,uE=sE.r,TC=new NA(32768);for(h=0;h<32768;++h)bA=(h&43690)>>1|(h&21845)<<1,bA=(bA&52428)>>2|(bA&13107)<<2,bA=(bA&61680)>>4|(bA&3855)<<4,TC[h]=((bA&65280)>>8|(bA&255)<<8)>>1;var bA,h,uA=function(A,Q,B){var C=A.length,E=0,K=new NA(Q);for(;E<C;++E)if(A[E])++K[A[E]-1];var J=new NA(Q);for(E=1;E<Q;++E)J[E]=J[E-1]+K[E-1]<<1;var Y;if(B){Y=new NA(1<<Q);var I=15-Q;for(E=0;E<C;++E)if(A[E]){var D=E<<4|A[E],L=Q-A[E],G=J[A[E]-1]++<<L;for(var X=G|(1<<L)-1;G<=X;++G)Y[TC[G]>>I]=D}}else{Y=new NA(C);for(E=0;E<C;++E)if(A[E])Y[E]=TC[J[A[E]-1]++]>>15-A[E]}return Y},KQ=new s(288);for(h=0;h<144;++h)KQ[h]=8;var h;for(h=144;h<256;++h)KQ[h]=9;var h;for(h=256;h<280;++h)KQ[h]=7;var h;for(h=280;h<288;++h)KQ[h]=8;var h,KB=new s(32);for(h=0;h<32;++h)KB[h]=5;var h,DI=uA(KQ,9,0),GI=uA(KQ,9,1),XI=uA(KB,5,0),HI=uA(KB,5,1),qC=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},zC=function(A,Q){var B=Q/8|0;return(A[B]|A[B+1]<<8|A[B+2]<<16)>>(Q&7)},yC=function(A){return(A+7)/8|0},JB=function(A,Q,B){if(Q==null||Q<0)Q=0;if(B==null||B>A.length)B=A.length;return new s(A.subarray(Q,B))};var $I=["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||$I[A]);if(C.code=A,Error.captureStackTrace)Error.captureStackTrace(C,ZA);if(!B)throw C;return C},ZI=function(A,Q,B,C){var E=A.length,K=C?C.length:0;if(!E||Q.f&&!Q.l)return B||new s(0);var J=!B,Y=J||Q.i!=2,I=Q.i;if(J)B=new s(E*3);var D=function(AQ){var QQ=B.length;if(AQ>QQ){var BQ=new s(Math.max(QQ*2,AQ));BQ.set(B),B=BQ}},L=Q.f||0,G=Q.p||0,X=Q.b||0,Z=Q.l,R=Q.d,F=Q.m,P=Q.n,g=E*8;do{if(!Z){L=kA(A,G,1);var f=kA(A,G+1,3);if(G+=3,!f){var M=yC(G)+4,S=A[M-4]|A[M-3]<<8,O=M+S;if(O>E){if(I)ZA(0);break}if(Y)D(X+S);B.set(A.subarray(M,O),X),Q.b=X+=S,Q.p=G=O*8,Q.f=L;continue}else if(f==1)Z=GI,R=HI,F=9,P=5;else if(f==2){var y=kA(A,G,31)+257,p=kA(A,G+10,15)+4,T=y+kA(A,G+5,31)+1;G+=14;var x=new s(T),r=new s(19);for(var t=0;t<p;++t)r[SC[t]]=kA(A,G+t*3,7);G+=p*3;var a=qC(r),hA=(1<<a)-1,DA=uA(r,a,1);for(var t=0;t<T;){var GA=DA[kA(A,G,hA)];G+=GA&15;var M=GA>>4;if(M<16)x[t++]=M;else{var e=0,o=0;if(M==16)o=3+kA(A,G,3),G+=2,e=x[t-1];else if(M==17)o=3+kA(A,G,7),G+=3;else if(M==18)o=11+kA(A,G,127),G+=7;while(o--)x[t++]=e}}var LA=x.subarray(0,y),AA=x.subarray(y);F=qC(LA),P=qC(AA),Z=uA(LA,F,1),R=uA(AA,P,1)}else ZA(1);if(G>g){if(I)ZA(0);break}}if(Y)D(X+131072);var DQ=(1<<F)-1,WA=(1<<P)-1,_A=G;for(;;_A=G){var e=Z[zC(A,G)&DQ],RA=e>>4;if(G+=e&15,G>g){if(I)ZA(0);break}if(!e)ZA(2);if(RA<256)B[X++]=RA;else if(RA==256){_A=G,Z=null;break}else{var XA=RA-254;if(RA>264){var t=RA-257,n=TB[t];XA=kA(A,G,(1<<n)-1)+aE[t],G+=n}var zA=R[zC(A,G)&WA],rA=zA>>4;if(!zA)ZA(3);G+=zA&15;var AA=II[rA];if(rA>3){var n=_B[rA];AA+=zC(A,G)&(1<<n)-1,G+=n}if(G>g){if(I)ZA(0);break}if(Y)D(X+131072);var tA=X+XA;if(X<AA){var TQ=K-AA,eA=Math.min(AA,tA);if(TQ+X<0)ZA(3);for(;X<eA;++X)B[X]=C[TQ+X]}for(;X<tA;++X)B[X]=B[X-AA]}}if(Q.l=Z,Q.p=_A,Q.b=X,Q.f=L,Z)L=1,Q.m=F,Q.d=R,Q.n=P}while(!L);return X!=B.length&&J?JB(B,0,X):B.subarray(0,X)},oA=function(A,Q,B){B<<=Q&7;var C=Q/8|0;A[C]|=B,A[C+1]|=B>>8},CB=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},OC=function(A,Q){var B=[];for(var C=0;C<A.length;++C)if(A[C])B.push({s:C,f:A[C]});var E=B.length,K=B.slice();if(!E)return{t:rE,l:0};if(E==1){var J=new s(B[0].s+1);return J[B[0].s]=1,{t:J,l:1}}B.sort(function(O,y){return O.f-y.f}),B.push({s:-1,f:25001});var Y=B[0],I=B[1],D=0,L=1,G=2;B[0]={s:-1,f:Y.f+I.f,l:Y,r:I};while(L!=E-1)Y=B[B[D].f<B[G].f?D++:G++],I=B[D!=L&&B[D].f<B[G].f?D++:G++],B[L++]={s:-1,f:Y.f+I.f,l:Y,r:I};var X=K[0].s;for(var C=1;C<E;++C)if(K[C].s>X)X=K[C].s;var Z=new NA(X+1),R=_C(B[L-1],Z,0);if(R>Q){var C=0,F=0,P=R-Q,g=1<<P;K.sort(function(y,p){return Z[p.s]-Z[y.s]||y.f-p.f});for(;C<E;++C){var f=K[C].s;if(Z[f]>Q)F+=g-(1<<R-Z[f]),Z[f]=Q;else break}F>>=P;while(F>0){var M=K[C].s;if(Z[M]<Q)F-=1<<Q-Z[M]++-1;else++C}for(;C>=0&&F;--C){var S=K[C].s;if(Z[S]==Q)--Z[S],++F}R=Q}return{t:new s(Z),l:R}},_C=function(A,Q,B){return A.s==-1?Math.max(_C(A.l,Q,B+1),_C(A.r,Q,B+1)):Q[A.s]=B},mE=function(A){var Q=A.length;while(Q&&!A[--Q]);var B=new NA(++Q),C=0,E=A[0],K=1,J=function(I){B[C++]=I};for(var Y=1;Y<=Q;++Y)if(A[Y]==E&&Y!=Q)++K;else{if(!E&&K>2){for(;K>138;K-=138)J(32754);if(K>2)J(K>10?K-11<<5|28690:K-3<<5|12305),K=0}else if(K>3){J(E),--K;for(;K>6;K-=6)J(8304);if(K>2)J(K-3<<5|8208),K=0}while(K--)J(E);K=1,E=A[Y]}return{c:B.subarray(0,C),n:Q}},EB=function(A,Q){var B=0;for(var C=0;C<Q.length;++C)B+=A[C]*Q[C];return B},iE=function(A,Q,B){var C=B.length,E=yC(Q+2);A[E]=C&255,A[E+1]=C>>8,A[E+2]=A[E]^255,A[E+3]=A[E+1]^255;for(var K=0;K<C;++K)A[E+K+4]=B[K];return(E+4+C)*8},pE=function(A,Q,B,C,E,K,J,Y,I,D,L){oA(Q,L++,B),++E[256];var G=OC(E,15),X=G.t,Z=G.l,R=OC(K,15),F=R.t,P=R.l,g=mE(X),f=g.c,M=g.n,S=mE(F),O=S.c,y=S.n,p=new NA(19);for(var T=0;T<f.length;++T)++p[f[T]&31];for(var T=0;T<O.length;++T)++p[O[T]&31];var x=OC(p,7),r=x.t,t=x.l,a=19;for(;a>4&&!r[SC[a-1]];--a);var hA=D+5<<3,DA=EB(E,KQ)+EB(K,KB)+J,GA=EB(E,X)+EB(K,F)+J+14+3*a+EB(p,r)+2*p[16]+3*p[17]+7*p[18];if(I>=0&&hA<=DA&&hA<=GA)return iE(Q,L,A.subarray(I,I+D));var e,o,LA,AA;if(oA(Q,L,1+(GA<DA)),L+=2,GA<DA){e=uA(X,Z,0),o=X,LA=uA(F,P,0),AA=F;var DQ=uA(r,t,0);oA(Q,L,M-257),oA(Q,L+5,y-1),oA(Q,L+10,a-4),L+=14;for(var T=0;T<a;++T)oA(Q,L+3*T,r[SC[T]]);L+=3*a;var WA=[f,O];for(var _A=0;_A<2;++_A){var RA=WA[_A];for(var T=0;T<RA.length;++T){var XA=RA[T]&31;if(oA(Q,L,DQ[XA]),L+=r[XA],XA>15)oA(Q,L,RA[T]>>5&127),L+=RA[T]>>12}}}else e=DI,o=KQ,LA=XI,AA=KB;for(var T=0;T<Y;++T){var n=C[T];if(n>255){var XA=n>>18&31;if(CB(Q,L,e[XA+257]),L+=o[XA+257],XA>7)oA(Q,L,n>>23&31),L+=TB[XA];var zA=n&31;if(CB(Q,L,LA[zA]),L+=AA[zA],zA>3)CB(Q,L,n>>5&8191),L+=_B[zA]}else CB(Q,L,e[n]),L+=o[n]}return CB(Q,L,e[256]),L+o[256]},UI=new gC([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),rE=new s(0),WI=function(A,Q,B,C,E,K){var J=K.z||A.length,Y=new s(C+J+5*(1+Math.ceil(J/7000))+E),I=Y.subarray(C,Y.length-E),D=K.l,L=(K.r||0)&7;if(Q){if(L)I[0]=K.r>>3;var G=UI[Q-1],X=G>>13,Z=G&8191,R=(1<<B)-1,F=K.p||new NA(32768),P=K.h||new NA(R+1),g=Math.ceil(B/3),f=2*g,M=function(sQ){return(A[sQ]^A[sQ+1]<<g^A[sQ+2]<<f)&R},S=new gC(25000),O=new NA(288),y=new NA(32),p=0,T=0,x=K.i||0,r=0,t=K.w||0,a=0;for(;x+2<J;++x){var hA=M(x),DA=x&32767,GA=P[hA];if(F[DA]=GA,P[hA]=DA,t<=x){var e=J-x;if((p>7000||r>24576)&&(e>423||!D)){L=pE(A,I,0,S,O,y,T,r,a,x-a,L),r=p=T=0,a=x;for(var o=0;o<286;++o)O[o]=0;for(var o=0;o<30;++o)y[o]=0}var LA=2,AA=0,DQ=Z,WA=DA-GA&32767;if(e>2&&hA==M(x-WA)){var _A=Math.min(X,e)-1,RA=Math.min(32767,x),XA=Math.min(258,e);while(WA<=RA&&--DQ&&DA!=GA){if(A[x+LA]==A[x+LA-WA]){var n=0;for(;n<XA&&A[x+n]==A[x+n-WA];++n);if(n>LA){if(LA=n,AA=WA,n>_A)break;var zA=Math.min(WA,n-2),rA=0;for(var o=0;o<zA;++o){var tA=x-WA+o&32767,TQ=F[tA],eA=tA-TQ&32767;if(eA>rA)rA=eA,GA=tA}}}DA=GA,GA=F[DA],WA+=DA-GA&32767}}if(AA){S[r++]=268435456|wC[LA]<<18|uE[AA];var AQ=wC[LA]&31,QQ=uE[AA]&31;T+=TB[AQ]+_B[QQ],++O[257+AQ],++y[QQ],t=x+LA,++p}else S[r++]=A[x],++O[A[x]]}}for(x=Math.max(x,t);x<J;++x)S[r++]=A[x],++O[A[x]];if(L=pE(A,I,D,S,O,y,T,r,a,x-a,L),!D)K.r=L&7|I[L/8|0]<<3,L-=7,K.h=P,K.p=F,K.i=x,K.w=t}else{for(var x=K.w||0;x<J+D;x+=65535){var BQ=x+65535;if(BQ>=J)I[L/8|0]=D,BQ=J;L=iE(I,L+1,A.subarray(x,BQ))}K.i=J}return JB(Y,0,C+yC(L)+E)},RI=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}(),FI=function(){var A=-1;return{p:function(Q){var B=A;for(var C=0;C<Q.length;++C)B=RI[B&255^Q[C]]^B>>>8;A=B},d:function(){return~A}}};var MI=function(A,Q,B,C,E){if(!E){if(E={l:1},Q.dictionary){var K=Q.dictionary.subarray(-32768),J=new s(K.length+A.length);J.set(K),J.set(A,K.length),A=J,E.w=K.length}}return WI(A,Q.level==null?6:Q.level,Q.mem==null?E.l?Math.ceil(Math.max(8,Math.min(13,Math.log(A.length)))*1.5):20:12+Q.mem,B,C,E)},tE=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 fA=function(A,Q){return A[Q]|A[Q+1]<<8},OA=function(A,Q){return(A[Q]|A[Q+1]<<8|A[Q+2]<<16|A[Q+3]<<24)>>>0},jC=function(A,Q){return OA(A,Q)+OA(A,Q+4)*4294967296},IA=function(A,Q,B){for(;B;++Q)A[Q]=B,B>>>=8};function VI(A,Q){return MI(A,Q||{},0,0)}function PI(A,Q){return ZI(A,{i:2},Q&&Q.out,Q&&Q.dictionary)}var eE=function(A,Q,B,C){for(var E in A){var K=A[E],J=Q+E,Y=C;if(Array.isArray(K))Y=tE(C,K[1]),K=K[0];if(ArrayBuffer.isView(K))B[J]=[K,Y];else B[J+="/"]=[new s(0),Y],eE(K,J,B,C)}},cE=typeof TextEncoder<"u"&&new TextEncoder,xC=typeof TextDecoder<"u"&&new TextDecoder,NI=0;try{xC.decode(rE,{stream:!0}),NI=1}catch(A){}var qI=function(A){for(var Q="",B=0;;){var C=A[B++],E=(C>127)+(C>223)+(C>239);if(B+E>A.length)return{s:Q,r:JB(A,B-1)};if(!E)Q+=String.fromCharCode(C);else if(E==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(E&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 lE(A,Q){if(Q){var B=new s(A.length);for(var C=0;C<A.length;++C)B[C]=A.charCodeAt(C);return B}if(cE)return cE.encode(A);var E=A.length,K=new s(A.length+(A.length>>1)),J=0,Y=function(L){K[J++]=L};for(var C=0;C<E;++C){if(J+5>K.length){var I=new s(J+8+(E-C<<1));I.set(K),K=I}var D=A.charCodeAt(C);if(D<128||Q)Y(D);else if(D<2048)Y(192|D>>6),Y(128|D&63);else if(D>55295&&D<57344)D=65536+(D&1047552)|A.charCodeAt(++C)&1023,Y(240|D>>18),Y(128|D>>12&63),Y(128|D>>6&63),Y(128|D&63);else Y(224|D>>12),Y(128|D>>6&63),Y(128|D&63)}return JB(K,0,J)}function zI(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(xC)return xC.decode(A);else{var E=qI(A),K=E.s,B=E.r;if(B.length)ZA(8);return K}}var OI=function(A,Q){return Q+30+fA(A,Q+26)+fA(A,Q+28)},jI=function(A,Q,B){var C=fA(A,Q+28),E=fA(A,Q+30),K=zI(A.subarray(Q+46,Q+46+C),!(fA(A,Q+8)&2048)),J=Q+46+C,Y=SI(A,J,E,B,OA(A,Q+20),OA(A,Q+24),OA(A,Q+42)),I=Y[0],D=Y[1],L=Y[2];return[fA(A,Q+10),I,D,K,J+E+fA(A,Q+32),L]},SI=function(A,Q,B,C,E,K,J){var Y=E==4294967295,I=K==4294967295,D=J==4294967295,L=Q+B,G=Y+I+D;if(C&&G){for(;Q+4<L;Q+=4+fA(A,Q+2))if(fA(A,Q)==1)return[Y?jC(A,Q+4+8*I):E,I?jC(A,Q+4):K,D?jC(A,Q+4+8*(I+Y)):J,1];if(C<2)ZA(13)}return[E,K,J,0]},kC=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},dE=function(A,Q,B,C,E,K,J,Y){var I=C.length,D=B.extra,L=Y&&Y.length,G=kC(D);if(IA(A,Q,J!=null?33639248:67324752),Q+=4,J!=null)A[Q++]=20,A[Q++]=B.os;A[Q]=20,Q+=2,A[Q++]=B.flag<<1|(K<0&&8),A[Q++]=E&&8,A[Q++]=B.compression&255,A[Q++]=B.compression>>8;var X=new Date(B.mtime==null?Date.now():B.mtime),Z=X.getFullYear()-1980;if(Z<0||Z>119)ZA(10);if(IA(A,Q,Z<<25|X.getMonth()+1<<21|X.getDate()<<16|X.getHours()<<11|X.getMinutes()<<5|X.getSeconds()>>1),Q+=4,K!=-1)IA(A,Q,B.crc),IA(A,Q+4,K<0?-K-2:K),IA(A,Q+8,B.size);if(IA(A,Q+12,I),IA(A,Q+14,G),Q+=16,J!=null)IA(A,Q,L),IA(A,Q+6,B.attrs),IA(A,Q+10,J),Q+=14;if(A.set(C,Q),Q+=I,G)for(var R in D){var F=D[R],P=F.length;IA(A,Q,+R),IA(A,Q+2,P),A.set(F,Q+4),Q+=4+P}if(L)A.set(Y,Q),Q+=L;return Q},wI=function(A,Q,B,C,E){IA(A,Q,101010256),IA(A,Q+8,B),IA(A,Q+10,B),IA(A,Q+12,C),IA(A,Q+16,E)};function AK(A,Q){if(!Q)Q={};var B={},C=[];eE(A,"",B,Q);var E=0,K=0;for(var J in B){var Y=B[J],I=Y[0],D=Y[1],L=D.level==0?0:8,G=lE(J),X=G.length,Z=D.comment,R=Z&&lE(Z),F=R&&R.length,P=kC(D.extra);if(X>65535)ZA(11);var g=L?VI(I,D):I,f=g.length,M=FI();M.p(I),C.push(tE(D,{size:I.length,crc:M.d(),c:g,f:G,m:R,u:X!=J.length||R&&Z.length!=F,o:E,compression:L})),E+=30+X+P+f,K+=76+2*(X+P)+(F||0)+f}var S=new s(K+22),O=E,y=K-E;for(var p=0;p<C.length;++p){var G=C[p];dE(S,G.o,G,G.f,G.u,G.c.length);var T=30+G.f.length+kC(G.extra);S.set(G.c,G.o+T),dE(S,E,G,G.f,G.u,G.c.length,G.o,G.m),E+=16+T+(G.m?G.m.length:0)}return wI(S,E,C.length,y,O),S}function QK(A,Q){var B={},C=A.length-22;for(;OA(A,C)!=101010256;--C)if(!C||A.length-C>65558)ZA(13);var E=fA(A,C+8);if(!E)return{};var K=OA(A,C+16),J=OA(A,C-20)==117853008;if(J){var Y=OA(A,C-12);if(J=OA(A,Y)==101075792,J)E=OA(A,Y+32),K=OA(A,Y+48)}var I=Q&&Q.filter;for(var D=0;D<E;++D){var L=jI(A,K,J),G=L[0],X=L[1],Z=L[2],R=L[3],F=L[4],P=L[5],g=OI(A,P);if(K=F,!I||I({name:R,size:X,originalSize:Z,compression:G}))if(!G)B[R]=JB(A,g,g+X);else if(G==8)B[R]=PI(A.subarray(g,g+X),{out:new s(Z)});else ZA(14,"unknown compression type "+G)}return B}function TI(){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 xB(A,Q,B){return new Promise((C,E)=>{let K=A.transaction("installs",Q),J=K.objectStore("installs"),Y;Promise.resolve(B(J)).then((I)=>Y=I),K.oncomplete=()=>C(Y),K.onerror=()=>E(K.error)})}var BK=(A)=>new Promise((Q,B)=>{A.onsuccess=()=>Q(A.result),A.onerror=()=>B(A.error)});class hC{constructor(){this._db=null}async#A(){return this._db??=await TI()}async save(A){let Q=await this.#A();return await xB(Q,"readwrite",(B)=>B.put(A)),A}async get(A){let Q=await this.#A();return xB(Q,"readonly",(B)=>BK(B.get(A)))}async list(){let A=await this.#A();return xB(A,"readonly",(Q)=>BK(Q.getAll()))}async remove(A){let Q=await this.#A();await xB(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 kB=null;function kI(){if(!kB)kB=import("./chunk-h05bxfbs.js").then((m)=>_I(m.default,1)).then((A)=>(A.default||A)({locateFile:()=>"/sql-wasm.wasm"})).catch((A)=>{throw kB=null,A});return kB}var gI="trove-plugin-clientdb",gB="dbs";function yI(){return new Promise((A,Q)=>{let B=indexedDB.open(gI,1);B.onupgradeneeded=()=>{let C=B.result;if(!C.objectStoreNames.contains(gB))C.createObjectStore(gB)},B.onsuccess=()=>A(B.result),B.onerror=()=>Q(B.error)})}function vC(A,Q){return yI().then((B)=>new Promise((C,E)=>{let K=B.transaction(gB,A),J;Promise.resolve(Q(K.objectStore(gB))).then((Y)=>J=Y),K.oncomplete=()=>{B.close(),C(J)},K.onerror=()=>{B.close(),E(K.error)}}))}var hI=(A)=>new Promise((Q,B)=>{A.onsuccess=()=>Q(A.result),A.onerror=()=>B(A.error)}),vI=(A)=>vC("readonly",(Q)=>hI(Q.get(A))),bI=(A,Q)=>vC("readwrite",(B)=>B.put(Q,A)),fI=(A)=>vC("readwrite",(Q)=>Q.delete(A));class CK{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 bI(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 bC{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 kI(),C=await vI(A);Q=new CK(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 fI(A)}}var EK=new TextEncoder;function fC(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 KK(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 JK(A){return new Uint8Array(await crypto.subtle.digest("SHA-256",A))}function uI(A){let Q={...A};return delete Q.signature,JSON.stringify(uC(Q))}function uC(A){if(Array.isArray(A))return A.map(uC);if(A&&typeof A==="object"){let Q={};for(let B of Object.keys(A).sort())Q[B]=uC(A[B]);return Q}return A}async function mI(A){let Q=[...A.keys()].filter((J)=>J!=="manifest.json").sort(),B=[];for(let J of Q){let Y=A.get(J),I=EK.encode(J),D=new Uint8Array(4);new DataView(D.buffer).setUint32(0,Y.length),B.push(I,new Uint8Array([0]),D,Y)}let C=B.reduce((J,Y)=>J+Y.length,0),E=new Uint8Array(C),K=0;for(let J of B)E.set(J,K),K+=J.length;return KK(await JK(E))}async function pI(A){return KK(await JK(fC(A)))}async function cI({manifest:A,files:Q}){if(!A.signature||!A.publicKey)return{signed:!1,valid:!1};let B=await mI(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",fC(A.publicKey),{name:"ECDSA",namedCurve:"P-256"},!1,["verify"]);if(!await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},C,fC(A.signature),EK.encode(uI(A))))return{signed:!0,valid:!1,reason:"Signature does not verify"};return{signed:!0,valid:!0,fingerprint:await pI(A.publicKey)}}catch(C){return{signed:!0,valid:!1,reason:"Bad key/signature: "+C.message}}}function lI(A,Q,B){let C=(J)=>(J||"").toLowerCase().replace(/:/g,""),E=C(Q),K=[B.name,`${B.domain}/${B.name}`];for(let J of A?.keys||[]){if(C(J.fingerprint)!==E)continue;if((J.plugins||[]).some((Y)=>Y==="*"||K.includes(Y)))return!0}return!1}async function YK({manifest:A,files:Q},B){let C=await cI({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 E=null;try{E=await B(A.domain)}catch{}if(E&&lI(E,C.fingerprint,A))return{status:"verified",domain:A.domain,fingerprint:C.fingerprint};return{status:"signed",domain:A.domain,fingerprint:C.fingerprint,reason:E?"Domain does not list this key":"Could not reach the domain"}}function mC(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 E=C.hostname.toLowerCase();if(!E)throw Error(`Network endpoint "${A}" has no host`);return{scheme:C.protocol,host:E,wildcard:B,port:C.port,pathPrefix:C.pathname||"/",raw:A}}function LK(A){let Q=[];for(let B of A||[])try{Q.push(mC(B))}catch{}return Q}function dI(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 yB(A,Q){return LK(A).some((B)=>dI(B,Q))}function hB(A){return LK(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 nI={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."},pC=new Set;function IK(A){let Q=lC(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 oI(A){return nI[A]||A}function DK(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,E]of Object.entries(Q)){if(E===!1||E==null)continue;B[C]=E===!0?{}:E}return B}function cC(A){return Object.keys(DK(A))}function lC(A,Q){let B=DK(A);return Object.prototype.hasOwnProperty.call(B,Q)?B[Q]:null}function UQ(A){let Q=lC(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 jA(A){let Q=A?.displayName??A?.name;return typeof Q==="string"&&Q.trim()?Q:"Plugin"}function GK(A){let Q=lC(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 vB(A,Q,B){if(!Q)return!1;if(EQ(Q)&&wE(A,Q))return!0;return GK(A).includes(Q)}function WQ(A){let Q;try{Q=QK(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,J]of Object.entries(Q))if(!K.endsWith("/"))B.set(K.replace(/^\.?\//,""),J);let C=B.get("manifest.json");if(!C)throw Error("Package is missing manifest.json");let E;try{E=JSON.parse(new TextDecoder().decode(C))}catch(K){throw Error("manifest.json is not valid JSON: "+K.message)}return aI(E,B),{manifest:E,files:B,raw:A}}function aI(A,Q){let B=(C,E)=>{if(!C)throw Error(E)};if(OB(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))mC(C)}async function XK(A,Q=globalThis.fetch.bind(globalThis)){let B;try{B=await Q(A)}catch(E){throw Error("Could not fetch the plugin: "+E.message)}if(!B.ok)throw Error(`Could not fetch the plugin (HTTP ${B.status})`);let C=new Uint8Array(await B.arrayBuffer());return WQ(C)}function HK(A,Q){let B=A.manifest,C=nA(B).map((J)=>({kind:J.type,name:J.name,uri:J.uri,title:J.title||J.name,detail:J.type==="opener"||J.type==="indexer"?sI(J.match):J.type==="statusItem"?`${J.slot} of the status bar${J.command?` — runs ${J.command}`:""}`:J.type==="keymap"?J.path:"",offline:!!J.offline})),E=Q?.status==="verified",K=IK(B);return{id:vA(B),name:jA(B),version:B.version||"0.0.0",description:B.description||"",author:B.author||"Unknown",domain:B.domain,capabilities:cC(B).map((J)=>({id:J,description:oI(J),adminOnly:pC.has(J)})),contributions:C,settings:(B.settings||[]).map((J)=>({key:J.key,title:J.title||J.key,type:J.type,secret:!!J.secret})),network:hB(UQ(B)),commands:GK(B),storage:K.plugin||K.domain?{plugin:K.plugin,domain:K.domain,domainBlocked:K.domain&&!E}:null,fileCount:A.files.size,sizeBytes:[...A.files.values()].reduce((J,Y)=>J+Y.length,0),trust:Q}}function dC(A,Q){let B=IK(A);return{plugin:B.plugin,domain:B.domain&&Q?.status==="verified"}}function sI(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 nC{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 oC{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 E=A.iframe;E.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 I=Q.getBoundingClientRect(),D=I.width>0&&I.height>0&&document.contains(Q);E.style.left=`${I.left}px`,E.style.top=`${I.top}px`,E.style.width=`${I.width}px`,E.style.height=`${I.height}px`,E.style.visibility=D?"visible":"hidden"};K();let J=typeof ResizeObserver<"u"?new ResizeObserver(K):null;if(J?.observe(Q),document.body)J?.observe(document.body);let Y=typeof IntersectionObserver<"u"?new IntersectionObserver(K,{threshold:[0,1]}):null;Y?.observe(Q),window.addEventListener("scroll",K,!0),window.addEventListener("resize",K),A.place={target:Q,stop:()=>{J?.disconnect(),Y?.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=`${$K(Q.width,200,480)}px`,B.style.height=`${$K(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 $K(A,Q,B){return Math.max(Q,Math.min(B,A||Q))}class aC{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 E=++this.seq;return new Promise((K,J)=>{let Y=B?setTimeout(()=>{this.pending.delete(E),J(Error(`RPC timeout: ${A}`))},B):null;this.pending.set(E,{resolve:K,reject:J,timer:Y}),this._post({__trove:"req",id:E,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(E){C={message:E?.message||String(E),code:E?.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 sC=`// 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 iC="1.0";function ZK(A){return String(A||"").split(".")[0]||"0"}function UK(A){if(!A)return!0;return ZK(A)===ZK("1.0")}var WK;(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"})(WK||(WK={}));var rI=new Uint8Array(new Uint16Array([1]).buffer)[0]===1;function rC(A,Q="@"){if(!c)return tC.then(()=>rC(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 E=c.sa(B-1);if((rI?eI:tI)(A,new Uint16Array(c.memory.buffer,E,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=[],J=[];for(;c.ri();){let I=c.is(),D=c.ie(),L=c.it(),G=c.ai(),X=c.id(),Z=c.ss(),R=c.se(),F;c.ip()&&(F=Y(A.slice(X===-1?I-1:I,X===-1?D+1:D))),K.push({n:F,t:L,s:I,e:D,ss:Z,se:R,d:X,a:G})}for(;c.re();){let I=c.es(),D=c.ee(),L=c.els(),G=c.ele(),X=A.slice(I,D),Z=X[0],R=L<0?void 0:A.slice(L,G),F=R?R[0]:"";J.push({s:I,e:D,ls:L,le:G,n:Z==='"'||Z==="'"?Y(X):X,ln:F==='"'||F==="'"?Y(R):R})}function Y(I){try{return(0,eval)(I)}catch(D){}}return[K,J,!!c.f(),!!c.ms()]}function tI(A,Q){let B=A.length,C=0;for(;C<B;){let E=A.charCodeAt(C);Q[C++]=(255&E)<<8|E>>>8}}function eI(A,Q){let B=A.length,C=0;for(;C<B;)Q[C]=A.charCodeAt(C++)}var c,AD=()=>{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},tC=WebAssembly.compile(AD()).then(WebAssembly.instantiate).then(({exports:A})=>{c=A});var QD=/\.m?js$/i;function bB(A){return/^src\//i.test(A)&&QD.test(A)}function RK(A){return bB(A.entry||"")}function BD(A){let Q=A.lastIndexOf("/");return(Q<0?"":A.slice(0,Q)).split("/").filter(Boolean)}function CD(A,Q){let B=BD(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 FK(A){await tC;let Q={};for(let[K,J]of A.files)if(bB(K))Q[K]=new TextDecoder().decode(J);let B=(K)=>Object.prototype.hasOwnProperty.call(Q,K),C=(K,J)=>{let Y=CD(K,J);if(B(Y))return Y;if(B(Y+".js"))return Y+".js";if(B(Y+".mjs"))return Y+".mjs";if(B(Y+"/index.js"))return Y+"/index.js";return Y},E={};for(let[K,J]of Object.entries(Q))E[K]=ED(J,K,C);return{modules:E,entry:A.manifest.entry}}function ED(A,Q,B){let[C]=rC(A),E="",K=0;for(let J of C){if(J.n==null)continue;if(J.n[0]!==".")continue;let Y="trove:/"+B(Q,J.n),I=J.d===-1?Y:JSON.stringify(Y);E+=A.slice(K,J.s)+I,K=J.e}return E+A.slice(K)}var KD=15000;class eC{constructor({media:A,dock:Q}={}){this.media=A,this.dock=Q}async spawn(A,Q,B){let C=document.createElement("iframe");C.style.cssText=JD,C.setAttribute("sandbox","allow-scripts allow-forms"),C.setAttribute("referrerpolicy","no-referrer");let E=B?.entry;if(E)A._entrySrcdoc||={},A._entrySrcdoc[E]||=await MK({...A.manifest,entry:E},A.files),C.srcdoc=A._entrySrcdoc[E];else A._srcdoc||=await MK(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(J){try{K.channel?.dispose()}catch{}throw C.remove(),J}return K}#A(A,Q,{onCall:B,onEvent:C,online:E}){return new Promise((K,J)=>{let{iframe:Y}=Q,I=A.manifest,D=!1,L=0,G=()=>{if(window.removeEventListener("message",Z),L)clearTimeout(L)},X=(R)=>{if(D)return;D=!0,G(),J(Error(R))},Z=(R)=>{if(R.source!==Y.contentWindow)return;if(R.data?.__trove==="boot-error")return X(R.data.error||"Plugin failed to load its modules");if(R.data?.__trove!=="ready")return;if(!UK(R.data.protocolVersion))return X(`Plugin speaks protocol ${R.data.protocolVersion}, this host speaks ${iC}`);window.removeEventListener("message",Z);let F=new MessageChannel;Q.channel=new aC(F.port1,{onCall:(P,g)=>B(A,P,g,Q),onEvent:(P,g)=>C(A,P,g,Q)}),Q.resolveActivated=(P)=>{if(D)return;if(D=!0,L)clearTimeout(L);K(P)},Q.rejectActivated=(P)=>{if(D)return;if(D=!0,L)clearTimeout(L);J(P)},Y.contentWindow.postMessage({__trove:"init",manifest:I,capabilities:A.grants,storage:A.storage,online:E,role:Q.role,protocolVersion:iC},"*",[F.port2])};L=setTimeout(()=>X("Plugin handshake timed out"),KD),window.addEventListener("message",Z),Y.addEventListener("error",()=>X("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 JD="position:fixed;left:0;top:0;width:0;height:0;border:0;visibility:hidden;",YD=["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("; "),PK=`<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="${YD}"></head><body>`;async function MK(A,Q){if(RK(A))return LD(await FK({manifest:A,files:Q}));let B=new TextDecoder().decode(Q.get(A.entry)??new Uint8Array);return`${PK}
|
|
323
|
+
<script>${sC}</script>
|
|
324
|
+
<script>${B}</script>
|
|
325
|
+
</body></html>`}function VK(A){return JSON.stringify(A).replace(/</g,"\\u003c").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}function LD(A){let Q=VK("trove:/"+A.entry);return`${PK}
|
|
326
|
+
<script>${sC}</script>
|
|
327
|
+
<script id="__trove_src" type="application/json">${VK(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 ID=/\b(ATTACH|DETACH|VACUUM|PRAGMA)\b/i;function DD(A){let Q="",B=0;while(B<A.length){let C=A[B];if(C==="-"&&A[B+1]==="-"){let E=A.indexOf(`
|
|
344
|
+
`,B);B=E<0?A.length:E;continue}if(C==="/"&&A[B+1]==="*"){let E=A.indexOf("*/",B+2);B=E<0?A.length:E+2,Q+=" ";continue}if(C==="'"||C==='"'||C==="`"){let E=C;B++;while(B<A.length){if(A[B]===E){if(A[B+1]===E){B+=2;continue}B++;break}B++}Q+=" ";continue}if(C==="["){let E=A.indexOf("]",B);B=E<0?A.length:E+1,Q+=" ";continue}Q+=C,B++}return Q}function A0(A){if(typeof A!=="string"||!A)throw N.invalid("SQL statement is required");if(ID.test(DD(A)))throw N.invalid("ATTACH, DETACH, VACUUM and PRAGMA are not permitted in plugin storage")}var GD=26214400;async function XD(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 I=await A.arrayBuffer();if(I.byteLength>Q)throw Error("Response too large");return I}let E=[],K=0;for(;;){let{done:I,value:D}=await C.read();if(I)break;if(K+=D.byteLength,K>Q)throw await C.cancel().catch(()=>{}),Error("Response too large");E.push(D)}let J=new Uint8Array(K),Y=0;for(let I of E)J.set(I,Y),Y+=I.byteLength;return J.buffer}class Q0{constructor({platform:A,clientDb:Q,media:B,dock:C,onChange:E}={}){this.platform=A,this.clientDb=Q,this.media=B,this.dock=C,this.onChange=E||(()=>{})}async hostCall(A,Q,B,C){let E=(J)=>{if(!A.grants.includes(J))throw Error(`Capability "${J}" not granted`)},K=A.id;switch(Q){case"activated":{let J=C||A.frame;if(clearTimeout(J?._timer),B.ok)J?.resolveActivated?.(J);else J?.rejectActivated?.(Error(B.error||"activate() failed"));return{ok:!0}}case"command:execute":{let J=this.#A(A,B.id);if(!vB(A.manifest,J))throw Error(`Command "${B.id}" is not in this plugin's declared commands`);return{ok:!0,result:await this.platform.commands.execute(J,...B.args||[])??null}}case"ui:status":{E("ui");let J=this.#Q(A,B.name,"statusItem");return this.platform.contributions.update(J.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 J=this.#Q(A,B.name,"register");return this.platform.context.set(J.uri,B.value),{ok:!0}}case"resources:list":return[...A.files.keys()].filter(qK);case"resources:read":{if(!qK(B.path))throw Error(`No such resource ${B.path}`);let J=A.files.get(B.path);if(!J)throw Error(`No such resource ${B.path}`);return{bytes:J.slice().buffer}}case"files:read":return E("files"),{text:await this.platform.api.readText(B.id)};case"files:list":return E("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 E("files"),this.platform.api.stat(B.id);case"files:downloadUrl":return E("files"),{url:this.platform.api.downloadUrl(B.id)};case"files:index":{E("indexer");let J=EQ(B.indexerId)?B.indexerId:CQ(A.manifest,B.indexerId||"default");return this.platform.api.pushIndex(J,B.nodeId,{semanticTexts:B.semanticTexts,tags:B.tags,metadata:B.metadata,documents:B.documents,facet:B.facet})}case"net:fetch":return E("network"),this.#C(A,B);case"storage:sql":return E("storage"),this.#E(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 E("ui"),A.hasUi=!0,this.platform.openPluginPanel?.(K),this.onChange(),{ok:!0};case"media:metadata":{E("media");let J=(B.artwork||[]).filter((Y)=>this.#B(A,Y?.src));return this.media.apply(C,"metadata",{...B,artwork:J})}case"media:playbackState":return E("media"),this.media.apply(C,"playbackState",B);case"media:position":return E("media"),this.media.apply(C,"position",B);case"media:action":return E("media"),this.media.apply(C,"action",B);case"media:clear":return this.media.apply(C,"clear",B);case"dock:enable":if(E("dock"),C)C.dock={enabled:!0,minSize:B.minSize,maxSize:B.maxSize,dismissed:!1};return{ok:!0};case"dock:disable":if(E("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"](`${jA(A.manifest)}: ${B.text}`);break;case"ui:badge":A.badge=B.text,this.onChange();break}}#A(A,Q){if(!Q||EQ(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 yB(UQ(A.manifest),Q)}async#C(A,{url:Q,method:B="GET",headers:C,body:E}){let K=UQ(A.manifest);if(NK(Q,this.platform.api?.baseUrl))throw Error("Blocked: a plugin may not call the drive's own API through the network broker");if(!yB(K,Q))throw Error(`Blocked: "${Q}" is not one of this plugin's declared network endpoints`);let J={method:B,credentials:"omit",redirect:"follow",headers:$D(C)};if(E!=null&&B!=="GET"&&B!=="HEAD")J.body=E instanceof ArrayBuffer?new Uint8Array(E):E;let Y=await fetch(Q,J);if(Y.url&&Y.url!==Q){if(NK(Y.url,this.platform.api?.baseUrl))throw Error("Blocked: request redirected onto the drive's own API");if(!yB(K,Y.url))throw Error(`Blocked: request redirected off this plugin's declared endpoints (${Y.url})`)}let I=await XD(Y,GD),D={};return Y.headers.forEach((L,G)=>{D[G]=L}),{ok:Y.ok,status:Y.status,statusText:Y.statusText,url:Y.url,headers:D,bytes:I}}async#E(A,{scope:Q="plugin",side:B="server",op:C,sql:E,params:K=[],statements:J}){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 G of Array.isArray(J)?J:[])A0(G?.sql);else A0(E);let D=Q==="domain"?`dom:${A.manifest.domain}`:`plg:${A.id}`,L=await this.clientDb.obtain(D);return ZD(L,C,E,K,J)}let Y={scope:Q,op:C,sql:E,params:K,statements:J,domain:Q==="domain"?A.manifest.domain:void 0};return(await this.platform.api.request("POST",`/api/plugins/${encodeURIComponent(A.id)}/sql`,{body:Y})).result}}function NK(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 qK(A){return A!=="manifest.json"&&!bB(A)}var HD=new Set(["host","cookie","cookie2","set-cookie","origin","referer","content-length","connection"]);function $D(A){let Q={};for(let[B,C]of Object.entries(A||{}))if(!HD.has(String(B).toLowerCase()))Q[B]=C;return Q}function ZD(A,Q,B,C=[],E){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(E);default:throw Error(`Unknown storage op "${Q}"`)}}var zK=["files","storage","ui","commands","indexer","opener","network","media","dock"];class B0{constructor(A,{heartbeatMs:Q=20000}={}){this.platform=A,this.plugins=new Map,this.registry=new hC,this.clientDb=new bC({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 nC,this.dock=new oC({destroyFrame:(B)=>this.frames.destroy(B),openFile:(B,C)=>this.platform.workbench.openFile(B,C),onChange:()=>this.#A()}),this.frames=new eC({media:this.media,dock:this.dock}),this.rpc=new Q0({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,E,K,J)=>this.rpc.hostCall(C,E,K,J),onEvent:(C,E,K,J)=>this.rpc.hostEvent(C,E,K,J),online:this.online,entry:B})}#B(A){let Q=A.id,B=this.platform.contributions,C=(K)=>A.disposers.push(K),E=jA(A.manifest);for(let K of nA(A.manifest)){let J={...K,pluginId:Q};switch(K.type){case"opener":if(A.grants.includes("opener"))C(B.register(K.uri,J));break;case"command":C(this.platform.commands.register({id:K.uri,title:K.title||`${E}: ${K.name}`,category:K.category||E,icon:K.icon,when:K.when,offline:K.offline,palette:K.palette,pluginId:Q,handler:(...Y)=>A.channel?.call("command:execute",{id:K.name,args:Y})}));break;case"statusItem":{let Y=K.command?this.#E(A,K.command,E,`status item “${K.name}”`):null;C(B.register(K.uri,{...J,command:Y,html:"",visible:!1}));break}case"register":C(B.register(K.uri,J)),this.platform.context.set(K.uri,K.default),C(()=>this.platform.context.remove(K.uri));break;case"keymap":{let Y=A.files.get(K.path);if(!Y){this.platform.notifications.warn(`Plugin "${E}": keymap file "${K.path}" is not in the package.`);break}try{let I=this.#C(A,xE(new TextDecoder().decode(Y)),E);C(B.register(K.uri,{...J,bindings:I}))}catch(I){this.platform.notifications.warn(`Plugin "${E}": ${I.message}`)}break}case"indexer":break}}}#C(A,Q,B){let C=[];for(let E of Q){let K=this.#E(A,E.command,B,`shortcut ${E.key}`);if(K)C.push({...E,command:K})}return C}#E(A,Q,B,C){let E=CQ(A.manifest,Q);if(nA(A.manifest).some((J)=>J.uri===E&&J.type==="command"))return E;if(!vB(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:jA(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:hB(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.#J(A,B)}))}#J(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.#J(Q,A)}canGrant(A,Q){return!pC.has(A)||!!Q}async install(A,{grants:Q,trust:B}={}){let C=vA(A.manifest),E=cC(A.manifest),K=(Q||E).filter((D)=>zK.includes(D)&&E.includes(D)),J=RD(A.manifest,K)?"account":"device";if(J==="account"){if(!A.raw)throw Error("Package bytes unavailable for a server install");await this.platform.api.installPlugin(A.raw,K)}let Y=K.includes("storage")?dC(A.manifest,B):{plugin:!1,domain:!1},I={id:C,manifest:A.manifest,files:Object.fromEntries([...A.files.entries()]),grants:K,storage:Y,trust:B||null,scope:J,settings:{},secrets:{},installedAt:Date.now()};return await this.registry.save(I),this.#L(I),await this.#I(I),this.plugins.get(C)}async restore(){let A=[];try{A=await this.registry.list()}catch{}for(let Q of A)try{this.#L(Q),this.#I(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?jA(Q.manifest):Q?.id||"unknown"}" — its saved data looks corrupt.`)}this.#Y(A).catch(()=>{})}async#Y(A){let Q;try{Q=(await this.platform.api.installedPlugins()).plugins||[]}catch{return}let B=new Set(Q.map((Y)=>Y.pluginId)),C=new Set(A.map((Y)=>Y.id)),E=0,K=0,J=0;for(let Y of A){if(Y.scope!=="account"||B.has(Y.id))continue;try{await this.platform.api.installPlugin(AK(WD(Y.files)),Y.grants||[])}catch(I){console.error("re-upload plugin failed",Y.id,I),E++}}for(let Y of Q){if(C.has(Y.pluginId))continue;try{let I=WQ(await this.platform.api.pluginPackage(Y.pluginId)),D=Y.grants||[],L={id:Y.pluginId,manifest:I.manifest,files:Object.fromEntries([...I.files.entries()]),grants:D,storage:D.includes("storage")?{plugin:!0,domain:!!Y.sharedStorage}:{plugin:!1,domain:!1},trust:null,scope:"account",settings:{},secrets:{},installedAt:Y.createdAt||Date.now()};await this.registry.save(L),this.#L(L),await this.#I(L),K++}catch(I){console.error("sync plugin failed",Y.pluginId,I),J++}}if(K)this.platform.notifications.info(`Synced ${K} account plugin${K>1?"s":""} from the server.`);if(E||J){let Y=[];if(J)Y.push(`${J} couldn't be downloaded`);if(E)Y.push(`${E} couldn't be uploaded`);this.platform.notifications.warn(`Some account plugins didn't sync: ${Y.join(", ")}.`)}}#L(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:jA(A.manifest)})))}async#I(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")?dC(A.manifest,A.trust):{plugin:!1,domain:!1}),files:UD(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.#G(Q).then(()=>this.#A()),this.#D()}catch(B){Q.status="error",Q.error=B?.message||String(B),this.platform.notifications.error(`Plugin "${jA(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 E=this.plugins.get(A);if(E)E.secrets=C.secrets;E?.channel?.emit("settings:changed",{key:Q,value:"••••"})}async getSecret(A,Q){return(await this.registry.get(A))?.secrets?.[Q]??""}#D(){if(this._heartbeat||!this.heartbeatMs)return;if(this._heartbeat=setInterval(()=>this.#$(),this.heartbeatMs),this._heartbeat?.unref)this._heartbeat.unref()}#X(){if(this._heartbeat)clearInterval(this._heartbeat);this._heartbeat=null}async#$(){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.#G(Q)||A;if(A)this.#A()}finally{this._probing=!1}}setHeartbeat(A){if(this.heartbeatMs=A,this.#X(),A&&[...this.plugins.values()].some((Q)=>Q.status==="active"))this.#D()}async#G(A){if(A.status!=="active"||!A.channel)return!1;let Q={responsive:A.responsive,sig:OK(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!==OK(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.#G(Q)})),this.#A()}async refresh(A){let Q=this.plugins.get(A);if(Q)await this.#G(Q),this.#A()}mountPanel(A,Q,{width:B=380,height:C=480}={}){let E=this.plugins.get(A);if(!E?.frame)return null;return Q.style.width=`${B}px`,Q.style.height=`${C}px`,this.dock.place(E.frame,Q,50),E.hasUi=!0,()=>this.dock.hide(E.frame)}mountViewer(A,Q,B,C,E={}){let K=this.plugins.get(A);if(!K)return E.onError?.("Plugin is not available"),null;let J=this.dock.docked;if(J&&J.record===K&&J.node?.id===B.id&&J.openerId===C)return this.dock.undock(J),this.dock.place(J,Q,3),E.onReady?.(),()=>this.#H(J);let Y=this.platform.contributions.get(C),I={cancelled:!1,frame:null};return this.#Q(K,"viewer",Y?.entry).then(async(D)=>{if(I.cancelled){this.frames.destroy(D);return}I.frame=D,D.node=B,D.openerId=C,K.frames.add(D),this.dock.place(D,Q,3);try{if(await D.channel?.call("opener:open",{openerId:C,file:B,context:{}}),!I.cancelled)E.onReady?.()}catch(L){if(!I.cancelled)E.onError?.(L?.message||"Failed to open")}}).catch((D)=>{if(console.error("viewer frame failed to load",D),!I.cancelled)E.onError?.(D?.message||"This viewer failed to load")}),K.hasUi=!0,()=>{if(I.cancelled=!0,I.frame)this.#H(I.frame)}}#H(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?jA(B.manifest):A,E=B?.scope==="account"||(await this.registry.get(A).catch(()=>null))?.scope==="account";if(Q&&E)try{await this.platform.api.uninstallPluginServer(A)}catch(Y){this.platform.notifications.error(`Couldn't uninstall "${C}" from the server: ${Y.message}. It's still installed.`);return}if(B){try{B.channel?.emit("deactivate")}catch{}for(let Y of B.disposers)try{Y()}catch{}B._settingsDispose?.();for(let Y of[...B.frames||[]])this.frames.destroy(Y);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(!E)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 J=!1;try{await this.registry.remove(A)}catch(Y){J=!0,console.error("removing the persisted plugin record failed",A,Y)}if(![...this.plugins.values()].some((Y)=>Y.status==="active"))this.#X();if(this.#A(),J)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 YK(A,this.fetchAssetlinks)}}function UD(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 WD(A){let Q={};for(let[B,C]of Object.entries(A||{}))Q[B]=C instanceof Uint8Array?C:new Uint8Array(C);return Q}function RD(A,Q){if(Q.includes("storage"))return!0;return $C(A).length>0}function OK(A){if(!A)return"";return`${A.online?1:0}|${[...A.handlers||[]].sort().join(",")}`}class C0{constructor(A){this.context=A,this.state={palette:null,dialog:null,contextMenu:null,pluginPanel:null},this.cell=b(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:E0(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 E0(A,Q,B){return(A+Q+B)%B}var jK="trove.recents",FD=12;class K0{constructor(A){this.context=A,this.state={stack:[{kind:"search"}],activeTabId:null,activeFile:null,recents:MD()},this.cell=b(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},E;if(B)E=[{kind:"search"},C];else{let K=this.state.stack.findIndex((J)=>J.kind==="file"&&J.id===A.id);if(K>=0)E=this.state.stack.slice(0,K+1),E[K]=C;else E=[...this.state.stack,C]}this.#E(A),this.#B(E)}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})}#E(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,FD);this.#A({recents:B}),VD(B)}}function MD(){try{return JSON.parse(localStorage.getItem(jK))||[]}catch{return[]}}function VD(A){try{localStorage.setItem(jK,JSON.stringify(A))}catch{}}class J0{constructor(A){this.context=A,this.overlay=new C0(A),this.nav=new K0(A),this.state={activity:"home",sidebarVisible:!0,launch:{query:"",index:0},searchModal:!1,infoPanel:!1,sheet:null},this.cell=b(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:E0(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 SK=["auto","desktop","phone","tv"],PD=720,ND=1100,qD=/\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 zD(A="",Q=0){if(!A)return!1;return qD.test(A)&&Q>=ND}class Y0{constructor({window:A=globalThis,settings:Q=null,context:B=null}={}){this.window=A,this.settings=Q,this.context=B,this.urlOverride=SD(A),this.state=this.#Q(),this.cell=b(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)xA(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=jD(A,"(pointer: coarse)"),E=A.navigator?.userAgent||"",K=this.urlOverride||this.settings?.get?.("workbench.layout")||"auto";return{mode:K!=="auto"&&SK.includes(K)?K:OD({width:Q,coarse:C,ua:E}),width:Q,height:B,coarse:C,forced:K!=="auto"}}}function OD({width:A,coarse:Q,ua:B}){if(zD(B,A))return"tv";if(A<=PD)return"phone";return"desktop"}function jD(A,Q){try{return!!A.matchMedia?.(Q)?.matches}catch{return!1}}function SD(A){try{let Q=new URL(A.location.href).searchParams.get("ui");return Q&&SK.includes(Q)?Q:null}catch{return null}}var _K='a[href], button:not([disabled]), input:not([disabled]), select, textarea, [tabindex]:not([tabindex="-1"])',xK=".launch-item, .grid-tile, .sheet-row, .inbox-item, .plugin-card, .act-task, .act-issue, .chapter",wD=`${_K}, ${xK}`,TD=new Set(["BrowserBack","GoBack","Backspace"]),_D=new Set([10009,461]),xD={ArrowLeft:"left",ArrowRight:"right",ArrowUp:"up",ArrowDown:"down"},kD=new Set(["A","BUTTON","INPUT","SELECT","TEXTAREA"]);class L0{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)xA(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(TD.has(A.key)||_D.has(A.keyCode)){if(A.key==="Backspace"&&wK(B)&&(B.value??"").length>0)return;A.preventDefault(),this.goBack();return}let C=xD[A.key];if(!C){if(A.key==="Enter"&&B&&!kD.has(B.tagName)&&B.matches(xK))A.preventDefault(),B.click();return}if((C==="left"||C==="right")&&wK(B)&&!gD(B,C))return;let E=B&&B!==Q.body?B:null,K=this.find(C,E);if(!K)return;A.preventDefault(),TK(K)}goBack(){if(this.workbench?.closeOverlays())return;this.window.history?.back?.()}candidates(){let A=this.window.document,Q=[];for(let B of A.querySelectorAll(wD)){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(_K)&&!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 E=null,K=1/0;for(let{el:J,rect:Y}of B){if(J===Q)continue;let I=yD(C,Y,A);if(I==null||I>=K)continue;K=I,E=J}return E}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];TK(B.el),this._bootstrapped=!0}}function gD(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 wK(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 TK(A){A.focus?.({preventScroll:!0}),A.scrollIntoView?.({block:"nearest",inline:"nearest"})}function yD(A,Q,B){let C=B==="up"||B==="down",[E,K]=C?B==="down"?[A.bottom,Q.top]:[A.top,Q.bottom]:B==="right"?[A.right,Q.left]:[A.left,Q.right],Y=B==="down"||B==="right"?K-E:E-K;if(Y<-2)return null;let[I,D,L,G]=C?[A.left,A.right,Q.left,Q.right]:[A.top,A.bottom,Q.top,Q.bottom],X=Math.max(0,Math.max(I,L)-Math.min(D,G)),Z=Math.abs((I+D)/2-(L+G)/2);return Math.max(0,Y)+X*3+Z*0.2}function YB(){if(typeof window>"u")return null;return window.SpeechRecognition||window.webkitSpeechRecognition||null}function fB(){let A=YB();return!!A&&typeof A.available==="function"}var I0=(A)=>({langs:[A],processLocally:!0});async function kK(A=navigator.language||"en-US"){if(!fB())return"unavailable";try{return await YB().available(I0(A))}catch{return"unavailable"}}async function gK(A=navigator.language||"en-US"){if(typeof YB()?.install!=="function")return!1;try{return await YB().install(I0(A))}catch{return!1}}function yK({lang:A=navigator.language||"en-US",onText:Q,onEnd:B,onError:C}={}){if(!fB())throw Error("On-device speech recognition is not available here");let E=new(YB());E.lang=A,E.interimResults=!0,E.continuous=!1,E.options=I0(A),E.processLocally=!0;let K=!1;E.onresult=(J)=>{let Y="",I=!1;for(let D=J.resultIndex;D<J.results.length;D++)if(Y+=J.results[D][0].transcript,J.results[D].isFinal)I=!0;Q?.(Y.trim(),{final:I})},E.onerror=(J)=>{if(J.error==="no-speech"||J.error==="aborted")return;C?.(Error(J.error||"Speech recognition failed"))},E.onend=()=>{if(!K)K=!0,B?.()};try{E.start()}catch(J){K=!0,C?.(J),B?.()}return{stop(){if(K)return;K=!0;try{E.stop()}catch{}B?.()}}}class D0{constructor({workbench:A,notifications:Q,settings:B}={}){this.workbench=A,this.notifications=Q,this.settings=B,this.session=null,this.state={supported:fB(),status:"unknown",listening:!1},this.cell=b(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 kK(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 gK(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=yK({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 E=document.querySelector(".search-modal .launch-input")||document.querySelector(".launch-input");if(E){E.focus();try{E.setSelectionRange(E.value.length,E.value.length)}catch{}Q(document.activeElement===E);return}if(--B<=0){Q(!1);return}requestAnimationFrame(C)};C()})}}class G0{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 E,K,J=new Promise((Y,I)=>{E=Y,K=I});if(B.set(A,{resolve:E,reject:K,promise:J}),B.size>=200)this.#B();else if(!this._timer)this._timer=setTimeout(()=>this.#B(),20);return J}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 E=await this.api.mintUrls(C,Q),K=Date.now();for(let[J,Y]of B){let I=E.urls?.[J];if(I){let D={url:I.url,expiresAt:I.expiresAt,mintedAt:K};this.cache.set(`${Q}:${J}`,D),Y.resolve(D)}else Y.reject(Error(E.failed?.[J]==="not_found"?"That file is gone":"You cannot open that file"))}}catch(E){for(let K of B.values())K.reject(E)}}}}function hD(){try{return localStorage.getItem("trove.token")||null}catch{return null}}function hK({baseUrl:A=""}={}){let Q=new ZC,B=new WC({"view.active":"home","sidebar.visible":!0}),C=new PC,E=new RC(Q,B,C),K=new VC,J=new bQ(Q,E,B,K),Y=new NC({baseUrl:A,token:()=>hD()}),I=new J0(B),D=new Y0({settings:K,context:B}),L=new L0({workbench:I,viewport:D}),G=new D0({workbench:I,notifications:C,settings:K}),X={reactive:PE,contributions:Q,context:B,commands:E,keybindings:J,settings:K,notifications:C,api:Y,workbench:I,viewport:D,spatialNav:L,voice:G,capabilities:null,openPluginPanel:null};return X.mediaUrls=new G0({api:X.api,settings:K}),X.plugins=new B0(X),E.availability=(Z)=>X.plugins.isAvailable(Z),vD(X),D.refresh(),X}function vD(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 qA(A){console.error(A)}var fQ="The provider has been disposed";class JQ{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 JQ{static deps=B;#A;#Q=!1;constructor(E={}){super();this.#A=E}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 JQ{static deps=C;#A;#Q=[];#B=new Set;#C=[];#E=0;#K=!1;constructor(K={}){super();this.#A=K}async#J(K){try{await Q(K,this.#A)}catch(J){qA(J)}}#Y(){while(this.#C.length>0){if(this.#Q.length>0){let J=this.#Q.shift();this.#B.add(J),this.#C.shift().resolve(J);continue}if(this.#E>=B)return;let K=this.#C.shift();this.#E++,Promise.resolve().then(()=>A(this.#A)).then((J)=>{if(this.#K){this.#E--,this.#J(J),K.reject(Error(fQ));return}this.#B.add(J),K.resolve(J)},(J)=>{this.#E--,K.reject(J),this.#Y()})}}async obtain(){if(this.#K)throw Error(fQ);let K=Promise.withResolvers();return this.#C.push(K),this.#Y(),await K.promise}release(K){if(!this.#B.delete(K))return;if(this.#K){this.#E--,this.#J(K);return}this.#Q.push(K),this.#Y()}async dispose(){if(this.#K)return;this.#K=!0;let K=this.#C.splice(0);for(let{reject:Y}of K)Y(Error(fQ));let J=this.#Q.splice(0);this.#E-=J.length,await Promise.all(J.map((Y)=>this.#J(Y)))}}}static fromLazySingleton(A,Q,{deps:B=[]}={}){return class extends JQ{static deps=B;#A;#Q=null;#B=null;#C=!1;constructor(E={}){super();this.#A=E}async obtain(){if(this.#C)throw Error(fQ);this.#Q??=Promise.resolve().then(()=>A(this.#A));try{return this.#B=await this.#Q,this.#B}catch(E){throw this.#Q=null,this.#B=null,E}}release(){}async dispose(){if(this.#C)return;if(this.#C=!0,!this.#Q||typeof Q!=="function")return;let E=this.#B??await this.#Q.catch(()=>null);if(E!=null)await Q(E,this.#A)}}}static fromRefCounted(A,Q,{deps:B=[]}={}){return class extends JQ{static deps=B;#A;#Q=0;#B=null;#C=null;#E=null;#K=!1;constructor(E={}){super();this.#A=E}async obtain(){if(this.#K)throw Error(fQ);this.#Q++;while(this.#E)await this.#E;if(this.#K)throw this.#Q--,Error(fQ);if(!this.#B)this.#B=Promise.resolve().then(()=>A(this.#A));try{return this.#C=await this.#B,this.#C}catch(E){if(this.#Q--,this.#Q<=0)this.#Q=0,this.#B=null,this.#C=null;throw E}}async release(){if(this.#Q<=0)return;if(this.#Q--,this.#Q>0)return;let E=this.#C,K=this.#B;if(this.#C=null,this.#B=null,!K)return;this.#E=(async()=>{try{let J=E??await K.catch(()=>null);if(J!=null)await Q(J,this.#A)}catch(J){qA(J)}finally{this.#E=null}})(),await this.#E}async dispose(){if(this.#K=!0,this.#Q>0)this.#Q=1,await this.release();while(this.#E)await this.#E}}}}class X0{#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){qA(C)}this.#A=[]}}class YQ{#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,E)=>{if(this.#A.has(C))return this.#A.get(C);let K=A[C];if(!K)throw Error(`Dependency not found: ${C}`);let J=[...E,C];if(E.includes(C))throw Error(`Cyclic dependency detected: ${J.join(" -> ")}`);let Y={};for(let D of K.deps??[])Y[D]=B(D,J);let I=new K(Y,{engineFeed:this.#B,container:this});return this.#A.set(C,I),I};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[E,{provider:K,options:J}]of Object.entries(Q))B[E]=await K.obtain(J),C.push({name:E,provider:K,options:J})}catch(E){throw await new X0(B,C).release(),E}return new X0(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){qA(B)}for(let Q of A)try{await Q.dispose?.()}catch(B){qA(B)}}}var bD=typeof ErrorEvent==="function"?ErrorEvent:class extends Event{constructor(Q,{error:B,message:C=""}={}){super(Q);this.error=B,this.message=C}};function fD(A){return A&&typeof A.message==="string"?A.message:String(A)}class fK extends Event{constructor({reason:A,error:Q=null}={}){super("abort");this.reason=A,this.error=Q}}var vK=["complete","error","abort"];function uD(){return typeof DOMException==="function"?new DOMException("The dispatch was aborted","AbortError"):Object.assign(Error("The dispatch was aborted"),{name:"AbortError"})}class LB{execute(){throw Error("execute() not implemented")}}class H0 extends EventTarget{#A=new AbortController;#Q;#B=null;constructor(){super();for(let A of vK)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??uD(),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((E,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(E,K,this.#B,B);return}let J=new AbortController,Y={signal:J.signal},I=(D)=>(L)=>{J.abort(),D(L)};for(let D of B)this.addEventListener(D,I(E),Y);for(let D of vK){if(B.has(D))continue;this.addEventListener(D,(L)=>I(K)(bK(D,L,B)),Y)}if(!C)this.#A.signal.addEventListener("abort",()=>I(K)(this.#Q),Y);Q?.addEventListener("abort",()=>I(K)(Q.reason),Y)})}#C(A,Q,B,C){if(C.has(B.type))A(B.event);else Q(bK(B.type,B.event,C))}}function bK(A,Q,B){if(A==="error")return Q.error;if(A==="abort")return Q.reason;return mD(B)}function mD(A){return Error(`The dispatch completed without emitting ${[...A].map((Q)=>`'${Q}'`).join(" or ")}`)}class uB{#A;#Q;constructor({container:A,interceptors:Q}={}){this.#A=A??new YQ,this.#Q=Q?[...Q]:[]}get container(){return this.#A}get feed(){return this.#A.feed}dispatch(A){if(!(A instanceof LB))throw TypeError("dispatch() requires an instance of Action");let Q=this.#A,B=this.#Q,C=Q.feed,E=new H0;return setTimeout(async()=>{let K=[],J={},Y=null,I=(D)=>{if(D!==void 0)J=D};try{for(let L of B){if(K.push(L),!L.enter)continue;I(await Q.use(L.deps,(G)=>L.enter(G,{dispatchFeed:E,engineFeed:C,signal:E.signal,state:J,action:A})))}let D=await Q.lease(A.constructor.deps,A.deps);try{await A.execute(D.resources,{dispatchFeed:E,engineFeed:C,signal:E.signal,state:J})}finally{await D.release()}}catch(D){Y=D}finally{for(let D=K.length-1;D>=0;D--){let L=K[D],G=E.signal.aborted;try{if(G&&L.abort)I(await Q.use(L.deps,(X)=>L.abort(X,{dispatchFeed:E,engineFeed:C,signal:E.signal,action:A,state:J,reason:E.reason,error:Y})));else if(Y&&L.error){let X={dispatchFeed:E,engineFeed:C,signal:E.signal,action:A,state:J,error:Y,handled:()=>{Y=null}};I(await Q.use(L.deps,(Z)=>L.error(Z,X)))}else if(!Y&&L.leave)I(await Q.use(L.deps,(X)=>L.leave(X,{dispatchFeed:E,engineFeed:C,signal:E.signal,state:J,action:A})))}catch(X){Y=X}}if(E.signal.aborted)E.dispatchEvent(new fK({reason:E.reason,error:Y}));else if(Y)E.dispatchEvent(new bD("error",{error:Y,message:fD(Y)}));else E.dispatchEvent(new Event("complete"))}}),E}}class mB{boot(){throw Error("boot() not implemented, and no fetch() to fall back to")}kill(){}}class uK{#A;#Q;#B=null;#C=null;#E=!1;#K=null;#J=Promise.withResolvers();#Y=!1;#L=void 0;#I=!1;#D=void 0;#X=void 0;observers=new Set;constructor(A,Q){this.#A=A,this.#Q=Q,this.notify=this.notify.bind(this)}get hasValue(){return this.#Y}get currentValue(){return this.#L}get received(){return this.#J.promise}get bootFeed(){return this.#D}get killFeed(){return this.#X}#$(A,Q){let B=this.#A._dispatch(A);return B.addEventListener("error",(C)=>{qA(Error(`${this.#Q.constructor.name} ${Q} (${A.constructor.name}) failed`,{cause:C.error}))},{once:!0}),B}notify(A){if(this.#I)return;if(this.#L=A,!this.#Y)this.#Y=!0,this.#J.resolve(!0);for(let Q of[...this.observers])try{Q.next?.(A)}catch(B){qA(B)}}boot(){if(this.#C)return this.#C;return this.#C=(async()=>{try{if(this.#Q.bootAction)this.#D=this.#$(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.#D};if(this.#Q.boot===mB.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.#H()}else await this.#Q.boot(this.#B.resources,A)}catch(A){qA(A),await this.#H(A)}finally{this.#E=!0}})(),this.#C}kill(){if(this.#K)return this.#K;return this.#K=this.#E?this.#G():Promise.resolve(this.#C).then(()=>this.#G()),this.#K}async#G(){if(this.#I)return;try{if(this.#Q.killAction)this.#X=this.#$(this.#Q.killAction,"killAction");if(this.#Q.kill)await this.#Q.kill(this.#B?.resources??{},{bootFeed:this.#D,killFeed:this.#X,engineFeed:this.#A._container.feed,notify:this.notify})}catch(A){qA(A)}finally{await this.#H()}}async#H(A){if(this.#I)return;this.#I=!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(E){qA(E)}if(!this.#Y)this.#J.resolve(!1);let B=this.#B;if(this.#B=null,B)await B.release()}}class pB{#A;#Q;#B;#C=!1;constructor({container:A,dispatcher:Q,createControllerMap:B}={}){this.#A=A??new YQ,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)}#E(A){return[A.constructor.deps,A.deps]}query(A){if(!(A instanceof mB))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){qA(K)}}else C=new uK(this,A),this.#B.set(A,C),C.observers.add(B),C.boot();let E=!1;return{get closed(){return E},unsubscribe:()=>{if(E)return;if(E=!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.#E(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 cB{#A;#Q;#B;#C=!1;constructor({providers:A,interceptors:Q,hooks:B,container:C,dispatcher:E,queries:K}={}){this.#A=C??new YQ({providers:A}),this.#Q=E??new uB({container:this.#A,interceptors:Q}),this.#B=K??new pB({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 $0{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=b(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,J)=>K===this.state.selection[J]))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 Z0{constructor(){this.state={keys:[],loading:!1,loaded:!1,error:null,minted:null,busy:null,draft:null},this.cell=b(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 U0{constructor(){this.state={query:"",mode:"hybrid",results:[],loading:!1,error:null,ran:!1,paletteFiles:[],paletteQuery:"",paletteLoading:!1,paletteError:null},this.cell=b(this.state)}observe(){return this.cell}set(A){this.state={...this.state,...A},this.cell.setValue(this.state)}}class W0{constructor(A=null){this.state={items:[]},this.cell=b(this.state),this._controllers=new Map,this.activity=A,this._tasks=new Map}observe(){return this.cell}#A(){this.cell.setValue(this.state)}start(A,Q,B,C){this._controllers.set(A,C),this.state={items:[...this.state.items,{id:A,name:Q,direction:"up",ratio:0,loaded:0,total:B,status:"active",error:null}]},this.#A();let E=this.activity?.start({kind:"transfer",title:`Uploading ${Q}`,total:B||null,unit:"bytes",onCancel:()=>this.cancel(A)});if(E)this._tasks.set(A,E)}progress(A,{loaded:Q,total:B,ratio:C}){this.state={items:this.state.items.map((E)=>E.id===A?{...E,loaded:Q,total:B,ratio:C}:E)},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((E)=>E.id===A?{...E,status:Q,error:B,ratio:Q==="done"?1:E.ratio}:E)},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.#A()}clearDone(){this.state={items:this.state.items.filter((A)=>A.status==="active")},this.#A()}}class R0{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=b(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,E=!(mK(this.state.sidecar?.comments||[],A)?.reactions?.[Q]||[]).includes(this.state.me?.id);try{await this.api.reactComment(B,A,Q,E)}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:pD(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 mK(A,Q){for(let B of A){if(B.id===Q)return B;let C=mK(B.replies||[],Q);if(C)return C}return null}function pD(A){let Q="=".repeat((4-A.length%4)%4),B=(A+Q).replace(/-/g,"+").replace(/_/g,"/"),C=atob(B),E=new Uint8Array(C.length);for(let K=0;K<C.length;K++)E[K]=C.charCodeAt(K);return E}class F0{get dimensions(){return 0}async embed(A){throw N.unsupported("embed not implemented")}async embedOne(A){return(await this.embed([A]))[0]}}var cD=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 lD(A){return String(A).toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/).filter((Q)=>Q.length>1&&!cD.has(Q))}function dD(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 M0 extends F0{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=lD(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 J=dD(K),Y=J%this._dim,I=J>>31&1?-1:1;Q[Y]+=I}let E=0;for(let K=0;K<Q.length;K++)E+=Q[K]*Q[K];return E=Math.sqrt(E)||1,Array.from(Q,(K)=>K/E)}}class nD extends F0{constructor(A){super();if(!A?.url||!A?.dimensions)throw N.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 E=A.slice(C,C+Q);B.push(...await this.#A(E))}return B}async#A(A){return BB(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(E){throw AB(E)}if(Q.status===429||Q.status>=500)throw N.transient(`Embedding endpoint ${Q.status}`);if(!Q.ok)throw N.internal(`Embedding endpoint failed: ${Q.status}`);let B=await Q.json();return(B.data??B.embeddings??[]).map((E)=>E.embedding??E)})}}var V0="trove:",oD=255;var aD=/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/;function lB(A){if(typeof A!=="string"||!A.toLowerCase().startsWith(V0))return null;let Q;try{Q=new URL(A)}catch{return null}let B=Q.pathname,C=B.indexOf("/"),E=C<0?B:B.slice(0,C);if(!aD.test(E))return null;let K=Q.searchParams.get("id"),J=Q.searchParams.get("name"),Y="";if(C>=0)try{Y=decodeURIComponent(B.slice(C+1))}catch{return null}if(K!=null&&(J!=null||Y))return null;let I=K!=null?"id":"name",D=K!=null?K:J!=null?J:Y;if(!D||D.length>oD)return null;return{collection:E,by:I,value:D}}function dB(A,Q="name"){let B=A?.collectionId||"default";if(Q==="id"){if(!A?.id)throw N.invalid("trove: link by id needs a node id");return`${V0}${B}?id=${encodeURIComponent(A.id)}`}if(!A?.name)throw N.invalid("trove: link by name needs a node name");return`${V0}${B}?name=${encodeURIComponent(A.name)}`}function pK(A,Q,B){let C=[],E=0;while(E<A.length){let K=Math.min(E+Q,A.length);if(K<A.length){let J=A.slice(E,K),Y=Math.max(J.lastIndexOf(`
|
|
345
|
+
|
|
346
|
+
`),J.lastIndexOf(". "),J.lastIndexOf(`
|
|
347
|
+
`));if(Y>Q*0.75)K=E+Y+1}if(C.push(A.slice(E,K).trim()),K>=A.length)break;E=K-B}return C.filter(Boolean)}var sD=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 P0(A){return String(A).toLowerCase().replace(/[^a-z0-9\s]/g," ").split(/\s+/).filter((Q)=>Q.length>1&&!sD.has(Q))}function IB(A){let Q=(A?.name||"").toLowerCase();return Q.includes(".")?Q.slice(Q.lastIndexOf(".")):""}var cK=[{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 iD(A,Q,B){if(A.ext.includes(Q))return!0;return A.mime.some((C)=>C.endsWith("/")?B.startsWith(C):B===C)}function lK(A){let Q=IB(A),B=A?.contentType||"";for(let C of cK)if(iD(C,Q,B))return C.kind;return"file"}var rD={...Object.fromEntries(cK.map((A)=>[A.kind,A.icon])),file:"file"};function aA(A){return rD[lK(A)]||"file"}function dK(A){return lK(A)==="text"}var tD="trove-offline",nK="trove-files-v1",N0=new M0({dimensions:256});class O0{constructor(A){this.platform=A,this.api=A.api,this.db=null,this.state={online:navigator.onLine,pins:[],queued:0,syncing:!1},this.cell=b(this.state)}observe(){return this.cell}#A(A){this.state={...this.state,...A},this.cell.setValue(this.state)}async init(){if(this.db=await eD(),await this.#C(),await this.#E(),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 E=await caches.open(nK),K=this.platform.mediaUrls,J=K.cacheKey(A.id),{url:Y}=await K.url(A.id,{op:"download"}),I=await fetch(Y);if(!I.ok)throw Error(`Couldn't fetch the file (${I.status})`);await E.put(new Request(J),I)}let Q=[],B="";if(dK(A))try{B=await this.api.readText(A.id);let E=pK(B,1000,150),K=await N0.embed(E.length?E:[A.name]);Q=(E.length?E:[A.name]).map((J,Y)=>({text:J,vector:K[Y]}))}catch{}let C=(await N0.embed([A.name]))[0];await QG(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(nK)).delete(this.platform.mediaUrls.cacheKey(A),{ignoreVary:!0}).catch(()=>{});await q0(this.db,"pins",A),await this.#C()}async#C(){let A=await z0(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 z0(this.db,"pins");if(!B.length)return[];let C=P0(A),E=(await N0.embed([A]))[0],K=[];for(let J of B){let Y=P0(`${J.node.name} ${J.text||""}`),I=EG(C,new Set(Y)),D=oK(E,J.nameVec);for(let G of J.chunks||[])D=Math.max(D,oK(E,G.vector));let L=0.6*D+0.4*I;if(L>0.02)K.push({nodeId:J.node.id,node:J.node,score:L,snippet:KG(J.text,C),indexerId:"offline"})}return K.sort((J,Y)=>Y.score-J.score).slice(0,Q)}async queueOp(A){await BG(this.db,"queue",{...A,at:Date.now()}),await this.#E()}async#E(){let A=await z0(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 CG(this.db,"queue");for(let{key:C,value:E}of B)try{await this.api.request(E.method,E.path,{body:E.body}),await q0(this.db,"queue",C),A++}catch(K){if(["transient","timeout","unauthorized","quota"].includes(K.code))break;await q0(this.db,"queue",C),Q++}}finally{if(await this.#E(),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 eD(){return new Promise((A,Q)=>{let B=indexedDB.open(tD,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 DB(A,Q,B,C){return new Promise((E,K)=>{let J=A.transaction(Q,B),Y=J.objectStore(Q),I;Promise.resolve(C(Y)).then((D)=>I=D),J.oncomplete=()=>E(I),J.onerror=()=>K(J.error)})}var AG=(A)=>new Promise((Q,B)=>{A.onsuccess=()=>Q(A.result),A.onerror=()=>B(A.error)}),QG=(A,Q,B,C)=>DB(A,Q,"readwrite",(E)=>E.put(C,B)),BG=(A,Q,B)=>DB(A,Q,"readwrite",(C)=>C.add(B)),q0=(A,Q,B)=>DB(A,Q,"readwrite",(C)=>C.delete(B)),z0=(A,Q)=>DB(A,Q,"readonly",(B)=>AG(B.getAll()));function CG(A,Q){return DB(A,Q,"readonly",(B)=>new Promise((C,E)=>{let K=[],J=B.openCursor();J.onsuccess=()=>{let Y=J.result;if(!Y)return C(K);K.push({key:Y.key,value:Y.value}),Y.continue()},J.onerror=()=>E(J.error)}))}function EG(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 oK(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 KG(A,Q){if(!A)return null;let B=A.toLowerCase(),C=-1;for(let K of Q){let J=B.indexOf(K);if(J>=0){C=J;break}}if(C<0)return A.slice(0,160).trim();let E=Math.max(0,C-60);return(E>0?"…":"")+A.slice(E,E+200).trim()+"…"}var JG=1000,YG=60000;class j0{constructor(A){this.platform=A,this.api=A.api,this.state={tasks:[],issues:[],issuesLoading:!1,tasksError:null,issuesError:null,open:!1},this.cell=b(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.#E();let C=(E)=>{let K=this._local.get(Q);if(!K||K.status!=="running")return;this._local.set(Q,{...K,...E}),this.#Q()};return{id:Q,progress:(E={})=>C({done:E.done??this._local.get(Q)?.done??0,total:E.total===void 0?this._local.get(Q)?.total:E.total,unit:E.unit??this._local.get(Q)?.unit,detail:E.detail??this._local.get(Q)?.detail}),succeed:(E)=>{C({status:"done",endedAt:Date.now(),detail:E??this._local.get(Q)?.detail}),this.#B(Q)},fail:(E)=>{C({status:"failed",endedAt:Date.now(),error:E?.message||String(E||"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.#E(),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.#E()}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")}#E(){let A=this.running.length?JG:YG;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 LG(A,Q=null){return{...A?.meta||{},...Q||A?.tags||{}}}function IG(A,Q){if(Q.present)return A!=null&&A!==!1&&A!=="";if(A==null)return!1;let B=Number(A),C=Number(Q.value),E=A!==""&&A!==!0&&A!==!1&&Q.value!==""&&Q.value!=null&&!Number.isNaN(B)&&!Number.isNaN(C),K=E?B:String(A).toLowerCase(),J=E?C:String(Q.value).toLowerCase();switch(Q.op){case"!=":return K!==J;case"<":return K<J;case"<=":return K<=J;case">":return K>J;case">=":return K>=J;default:return K===J}}function aK(A,Q,B=null){let C=LG(A,B);return(Q||[]).every((E)=>IG(C[E.key],E))}var DG=/#([\w.-]+)(?::(<=|>=|!=|=|<|>)?("[^"]*"|[^#\s]+)?)?/g;function nB(A){let Q=[],B=A;for(let C of A.matchAll(DG)){let[,E,K,J]=C,Y=J&&J.startsWith('"')?J.slice(1,-1):J;Q.push(Y==null||Y===""?{key:E,present:!0}:{key:E,op:K||"=",value:Y,present:!1}),B=B.replace(C[0]," ")}return{text:B.replace(/\s+/g," ").trim(),filters:Q}}function sK(A,Q){if(!Q||!Q.length)return!0;return aK(A,Q)}function S0(A){return A.present?`#${A.key}`:`#${A.key}:${A.op}${A.value}`}var oB="openers.associations";function iK(A){return IB(A)||A?.contentType||""}function rK(A){let Q=IB(A);if(Q)return`${Q} files`;let B=A?.contentType||"";return B?`${B} files`:"this file type"}function aB(A,Q){let B=(E)=>A.context.evaluate(E),C=(E)=>A.plugins.isAvailable(E);return A.contributions.openersFor(Q).filter((E)=>(!E.when||B(E.when))&&C(E)).sort((E,K)=>(K.priority??0)-(E.priority??0))}function tK(A,Q){let B=A.settings.get(oB)||{},C=IB(Q),E=Q?.contentType||"",K=E.includes("/")?`${E.slice(0,E.indexOf("/")+1)}*`:"";return C&&B[C]||E&&B[E]||K&&B[K]||null}function sB(A,Q,B){if(!Q)return;let C={...A.settings.get(oB)||{}};if(B)C[Q]=B;else delete C[Q];A.settings.set(oB,C)}function eK(A){let Q=A.settings.get(oB)||{};return Object.entries(Q).map(([B,C])=>{let E=A.contributions.get(C);return{typeKey:B,openerId:C,openerTitle:E?.title||C,missing:!E}})}function AJ(A,Q){if(!Q?.pluginId)return"Built-in";return A.plugins.plugins.get(Q.pluginId)?.manifest?.displayName||Q.pluginId}class CA extends LB{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 E=C!==Q.state.collectionId;Q.set({loading:!0,error:null,collectionId:C,...E?{trash:null}:{}});try{let K=B.settings.get("explorer.sort"),J=B.settings.get("explorer.sortOrder"),Y=await B.api.list(C,{sort:K,order:J});Q.set({items:Y.items,loading:!1,selection:[],sort:K,order:J,collectionId:Y.collectionId||C,stats:Y.stats||null,usage:Y.usage||null,nextCursor:Y.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 iB 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 rB 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),E=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(!E||!C.includes(E)){A.explorer.set({loading:!1,items:[],gate:"choose",error:null});return}return A.explorer.set({gate:null}),A.engine.dispatch(new SA(E))}}class w0 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 iB),A.engine.dispatch(new SA(Q.collection.id))}catch(Q){A.platform.notifications.error(`Couldn’t create collection: ${Q.message}`)}}}class T0 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 E=await B.api.list(Q.state.collectionId,{sort:Q.state.sort,order:Q.state.order,cursor:C});Q.set({items:[...Q.state.items,...E.items],nextCursor:E.nextCursor||null,loadingMore:!1})}catch(E){Q.set({loadingMore:!1}),B.notifications.error(`Couldn't load more: ${E.message}`)}}}class GB 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:E}=await B.api.trash(C);if(Q.set({trash:E}),this.op!=="list")await A.engine.dispatch(new SA(C))}catch(E){B.notifications.error(`Trash: ${E.message}`)}}}class _0 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 GB)}}class x0 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 GB)}catch(Q){A.platform.notifications.error(`Couldn’t rename: ${Q.message}`)}}}class wA 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=aB(Q,this.node),E=tK(Q,this.node);if(E&&C.some((K)=>K.id===E))return B(E);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 XB 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((E)=>this.#A(A,E,Q,B));await Promise.allSettled(C),A.engine.dispatch(new SA(Q))}async#A(A,Q,B,C){let{transfers:E,platform:K}=A,J=qE("xfer"),Y=new AbortController;E.start(J,Q.name,Q.size,Y);let I=null;try{let D=await K.api.upload(Q,{collection:B,concurrency:C,signal:Y.signal,onStart:(L)=>{I=L},onProgress:(L)=>E.progress(J,L)});if(E.finish(J,"done"),D?.name&&D.name!==Q.name)K.notifications.info(`"${Q.name}" already existed — saved as "${D.name}".`)}catch(D){if(I)K.api.abortUpload(I).catch(()=>{});if(D.code==="aborted")E.finish(J,"cancelled");else E.finish(J,"error",D.message),K.notifications.error(`Upload failed: ${Q.name} — ${D.message}`)}}}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((E)=>sK(E,this.filters));Q.set({results:C.map((E)=>({node:E})),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((E)=>({node:E})),loading:!1,ran:!0,filtered:!0,offline:!1})}catch(C){Q.set({loading:!1,error:C.message,ran:!0,filtered:!0})}}}class k0 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 E=await B.api.search(C,{mode:"keyword",limit:30});if(Q.state.paletteQuery!==C)return;Q.set({paletteFiles:E.results||[],paletteLoading:!1})}catch(E){if(Q.state.paletteQuery!==C)return;Q.set({paletteFiles:[],paletteLoading:!1,paletteError:E?.message||"Search failed"})}}}class LQ 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 E=this.mode||B.settings.get("search.mode");Q.set({query:this.query,mode:E,loading:!0,error:null,resolved:null});let K=A.offline;if(K&&!K.state.online){try{let J=await K.searchOffline(C,{limit:40});Q.set({results:J,loading:!1,ran:!0,offline:!0,resolved:null})}catch(J){Q.set({results:[],loading:!1,ran:!0,offline:!0,error:J.message})}return}try{let J=B.contributions.ofType("view").map((I)=>({id:I.id,title:I.title||I.id})),Y=await B.api.query(C,{mode:E,limit:40,views:J});Q.set({results:Y.results,resolved:Y.resolved||null,loading:!1,ran:!0,offline:!1})}catch(J){if(K){let Y=await K.searchOffline(C,{limit:40});Q.set({results:Y,loading:!1,ran:!0,offline:!0,error:Y.length?null:J.message})}else Q.set({loading:!1,error:J.message,ran:!0})}}}class g0 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 y0 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 h0 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 QJ(A,Q){try{let B=new Uint8Array(await Q.arrayBuffer());await CJ(A,WQ(B))}catch(B){A.platform.notifications.error(`Couldn't read the plugin: ${B.message}`)}}async function BJ(A,Q){try{let B=await XK(Q,(C,E)=>fetch(C,E));await CJ(A,B)}catch(B){A.platform.notifications.error(`Couldn't fetch the plugin: ${B.message}`)}}async function CJ(A,Q){let B=jA(Q.manifest);if(A.platform.plugins.plugins.has(vA(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 E=HK(Q,C);A.platform.workbench.showDialog({kind:"plugin-review",summary:E,isAdmin:!!A.social.state.admin,onInstall:async(K)=>{A.platform.workbench.closeDialog(),A.platform.workbench.setActivity("plugins");let J=A.platform.notifications.info(`Installing “${B}”…`,{sticky:!0});try{await A.platform.plugins.install(Q,{grants:K,trust:C}),A.platform.notifications.dismiss(J),A.platform.notifications.success(`Installed “${B}”`)}catch(Y){A.platform.notifications.dismiss(J),A.platform.notifications.error(`Install failed: ${Y.message}`)}}})}function EJ(A){let{platform:Q,engine:B,explorer:C}=A,{commands:E,workbench:K}=Q,J=(L)=>B.dispatch(L),Y=(L,G,X,Z={})=>E.register({id:L,title:G,handler:X,...Z});Y("workbench.showCommandPalette","Show All Commands",()=>K.openPalette("commands"),{category:"View",icon:"command"}),Y("workbench.quickOpen","Go to File…",()=>K.openPalette("files"),{category:"File",icon:"search"}),Y("workbench.view.home","Go Home (search & browse)",()=>K.showHome(),{category:"View",icon:"search"}),Y("workbench.view.plugins","Show Plugins",()=>K.setActivity("plugins"),{category:"View"}),Y("workbench.openSettings","Open Settings",()=>K.setActivity("settings"),{category:"Preferences",icon:"gear"}),Y("workbench.closeOverlays","Close",()=>K.closeOverlays(),{palette:!1}),Y("search.voice","Search by Voice",async()=>{await Q.voice.run({onText:(L,{final:G})=>{if(!L)return;if(K.setLaunchQuery(L),G)J(new LQ(L))}})},{category:"View",icon:"search"}),Y("workbench.showActivity","Show Activity (running work & problems)",()=>A.activity.togglePanel(!0),{category:"View",icon:"refresh"}),Y("workbench.rebuildIndex","Rebuild Search Index",()=>A.activity.rebuildIndex().catch(()=>{}),{category:"View",icon:"refresh"}),Y("workbench.scanCollection","Scan Collection for Outside Changes",()=>{let L=C.state.collectionId;if(!L)return Q.notifications.info("Open a collection first — a scan is per collection.");return A.activity.scanCollection(L).catch(()=>{})},{category:"Explorer",icon:"refresh"}),Y("workbench.checkStorage","Check Storage Configuration",()=>A.activity.checkStorage().catch(()=>{}),{category:"View",icon:"plug"}),Y("explorer.refresh","Refresh",()=>J(new GB),{category:"Explorer",icon:"refresh"}),Y("explorer.loadMore","Show More Items",()=>J(new T0),{palette:!1}),Y("explorer.upload","Upload Files…",()=>{GG((L)=>L.length&&J(new XB(L,C.state.collectionId)))},{category:"Explorer",icon:"upload"});let I=(L)=>{let G=L||C.selectedNodes()[0]||K.activeTab()?.node;if(!G)Q.notifications.info("Pick a file first — highlight one in the list, or open it.");return G};Y("explorer.copyLink","Copy Link to Item",async()=>{let L=I();if(!L)return;let G=dB(L);try{await navigator.clipboard.writeText(G),Q.notifications.success(`Copied ${G}`)}catch{Q.notifications.info(G,{sticky:!0})}},{category:"Explorer",icon:"link"}),Y("explorer.rename","Rename",()=>{let L=I();if(!L)return;K.showDialog({kind:"prompt",title:"Rename",label:"New name",value:L.name,confirmLabel:"Rename",onSubmit:(G)=>{if(K.closeDialog(),G?.trim()&&G!==L.name)J(new x0(L.id,G.trim()))}})},{category:"Explorer"}),Y("explorer.delete","Delete",()=>{let L=C.selectedNodes(),G=L.length?null:K.activeTab()?.node;if(G)L.push(G);if(!L.length){Q.notifications.info("Pick a file first — highlight one in the list, or open it.");return}let X=()=>J(new _0(L.map((Z)=>Z.id)));if(Q.settings.get("explorer.confirmDelete"))K.showDialog({kind:"confirm",title:`Move ${L.length} item${L.length>1?"s":""} to the trash?`,body:L.length===1?`"${L[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(),X()}});else X()},{category:"Explorer",icon:"trash"}),Y("explorer.showTrash","Show Trash",()=>{J(new RQ("list")),K.showHome()},{category:"Explorer",icon:"trash"}),Y("keys.load","Load API Keys",()=>J(new g0),{palette:!1}),Y("keys.new","New API Key",()=>A.apiKeys.startDraft(),{palette:!1}),Y("keys.cancel","Cancel API Key",()=>A.apiKeys.cancelDraft(),{palette:!1}),Y("keys.dismissMinted","Dismiss API Key",()=>A.apiKeys.clearMinted(),{palette:!1}),Y("keys.revoke","Revoke API Key",(L)=>L&&J(new h0(L)),{palette:!1}),Y("keys.mint","Create API Key",()=>{let L=A.apiKeys.state.draft,G=A.apiKeys.draftScopes();if(!L?.name?.trim()||!G)return;let X=Number(L.expiresInDays),Z=L.expiresInDays!==""&&Number.isFinite(X)&&X>0?Date.now()+X*86400000:null;return A.apiKeys.cancelDraft(),J(new y0({name:L.name.trim(),scopes:G,expiresAt:Z}))},{palette:!1}),Y("explorer.hideTrash","Hide Trash",()=>J(new RQ("hide")),{palette:!1}),Y("explorer.restore","Restore from Trash",(L)=>L&&J(new RQ("restore",L)),{palette:!1}),Y("explorer.purgeOne","Delete Forever",(L)=>L&&J(new RQ("purge",L)),{palette:!1}),Y("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(),J(new RQ("empty"))}})},{category:"Explorer",icon:"trash"}),Y("explorer.open","Open",(L)=>J(new wA(L||C.selectedNodes()[0])),{palette:!1}),Y("explorer.download","Download",async(L)=>{let G=L||C.selectedNodes()[0]||K.activeTab()?.node;if(!G?.id)return;try{let{url:X,revoke:Z}=await Q.api.download(G.id,G.name);if(HG(X,G.name),Z)setTimeout(()=>URL.revokeObjectURL(X),60000)}catch(X){Q.notifications.error(`Couldn't download ${G.name}: ${X.message}`)}},{category:"Explorer",icon:"download"}),Y("offline.pin","Make Available Offline",(L)=>{let G=L||C.selectedNodes()[0]||K.activeTab()?.node;if(G?.id)A.offline.pin(G)},{category:"Offline",icon:"download"}),Y("offline.unpin","Remove from Offline",(L)=>{let G=L||C.selectedNodes()[0]||K.activeTab()?.node;if(G)A.offline.unpin(G.id)},{palette:!1});let D=()=>{let L=C.state.collectionId,G=(C.state.collections||[]).map((X)=>({label:X.name||X.id,icon:X.id===L?"check":"files",run:()=>E.execute("collections.switch",X.id)}));if(C.state.canCreateCollection){if(G.length)G.push({sep:!0});G.push({label:"New collection…",icon:"plus",run:()=>E.execute("collections.create")})}return G};A.collectionMenu=D,Y("collections.switch","Switch Collection…",(L)=>{if(L){J(new SA(L)),K.showHome();return}let G=D();if(!G.length)return Q.notifications.info("This drive has one collection.");let X=typeof window>"u"?800:window.innerWidth;K.showContextMenu(Math.max(12,Math.round(X/2)-110),120,G)},{category:"Collections",icon:"files"}),Y("collections.create","New Collection…",()=>{K.showDialog({kind:"collection",title:"New collection",onSubmit:(L)=>{if(K.closeDialog(),L)J(new w0(L))}})},{category:"Collections",icon:"files"}),Y("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"}),Y("notifications.show","Show Notifications",()=>A.social.toggleInbox(!0),{category:"View"}),Y("notifications.enablePush","Enable Push Notifications",()=>A.social.enablePush(),{category:"Notifications"}),Y("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:(L)=>{if(K.closeDialog(),L?.trim())BJ(A,L.trim())}})},{category:"Plugins",icon:"plug"}),Y("plugins.installFromFile","Install Plugin from File…",()=>{XG((L)=>L&&QJ(A,L))},{category:"Plugins",icon:"plug"})}function KJ(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",E)},E=()=>setTimeout(()=>{if(!B.files.length)C()},300);B.addEventListener("change",()=>{A(B.files),C()},{once:!0}),window.addEventListener("focus",E),B.click()}function GG(A){KJ((Q)=>A(Q),(Q)=>{Q.multiple=!0})}function XG(A){KJ((Q)=>A(Q[0]),(Q)=>{Q.accept=".zip,application/zip"})}function HG(A,Q){let B=document.createElement("a");B.href=A,B.download=Q||"",document.body.appendChild(B),B.click(),B.remove()}function JJ(A){let Q=new $0(A.settings),B=new U0,C=new Z0,E=new j0(A),K=new W0(E),J=new R0(A),Y=new O0(A);J.offline=Y;let I={platform:A,explorer:Q,search:B,transfers:K,social:J,offline:Y,activity:E,apiKeys:C,engine:null},D=new cB({providers:{app:JQ.fromSingleton(I)}});I.engine=D,EJ(I),A.openPluginPanel=(G)=>A.workbench.openPluginPanel(G),A.context.setMany({"explorer.collectionId":null,"explorer.hasSelection":!1}),xA(Q.observe(),(G)=>{A.context.setMany({"explorer.collectionId":G.collectionId??null,"explorer.hasSelection":(G.selection?.length||0)>0})});let L=null;return xA(A.workbench.observeNav(),(G)=>{if(G.activeTabId!==L)L=G.activeTabId,J.loadSidecar(G.activeFile?G.activeFile.id:null)}),J.init(),Y.init(),E.init(),D.dispatch(new iB),{engine:D,app:I}}var{svg:$G,h:ZG}=w,v0={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 W(A,{size:Q=18,strokeWidth:B=1.6,className:C}={}){let E=Object.hasOwn(v0,A)?v0[A]:v0.file;return $G({$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}:{}}},...E.map((K)=>ZG("path",{$attrs:UG(K)})))}function UG(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 b0(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:EA,button:PA,textarea:WG,input:RG,p:oZ}=w,FG=["\uD83D\uDC4D","❤️","\uD83C\uDF89","\uD83D\uDC40","\uD83D\uDE80"];function YJ(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?w.img({src:Q.picture,alt:"",className:"avatar-img"}):EA({className:"avatar-txt"},B))}function LJ(A,Q){let B=A.so.notifications,C=Q.app.social;return k({className:"bell-wrap"},PA({className:"iconbtn bell",title:"Notifications"},W("bell",{size:19}),B.unread?EA({className:"bell-badge"},String(B.unread>9?"9+":B.unread)):null).on({click:()=>C.toggleInbox()}),A.so.inboxOpen?MG(A,Q):null)}function MG(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"},EA("Notifications"),A.so.pushSupported&&!A.so.pushEnabled?PA({className:"link"},"Enable push").on({click:()=>C.enablePush()}):A.so.pushEnabled?EA({className:"muted"},W("check",{size:13})):null),B.length?k({className:"inbox-items"},...B.slice(0,30).map((E)=>VG(E,Q))):k({className:"inbox-empty"},W("info",{size:24}),EA("You’re all caught up."))))}function VG(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"},b0(A.createdAt))).on({click:()=>{if(B?.nodeId)Q.platform.api.stat(B.nodeId).then((C)=>{Q.go(new wA(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 f0(A,Q){let B=A.nav,C=B.activeFile?{id:B.activeTabId,node:B.activeFile}:null,E=A.so.sidecar;return k({className:"infopanel"},k({className:"ip-head"},W("info",{size:15}),EA("Details"),PA({className:"iconbtn",title:"Close"},W("close",{size:14})).on({click:()=>Q.platform.workbench.toggleInfoPanel(!1)})),!C?k({className:"ip-empty"},EA("Open a file to see its tags and conversation.")):k({className:"ip-body"},PG(C.node,A,Q),NG(C.node,A,Q),zG(E,Q),OG(A,E,Q)))}function PG(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||""),PA({className:`btn small ${C?"on":""}`,$styling:{"margin-top":"10px"}},W(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 NG(A,Q,B){let C=Q.so.backlinks,E=A.collectionId?dB(A):null,K=C&&C.nodeId===A.id?C:null;return k({className:"ip-section"},k({className:"ip-label"},"Links"),E?PA({className:"ip-uri",title:"Copy this item’s link"},W("link",{size:12}),EA(E)).on({click:()=>qG(B,E)}):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((J)=>PA({className:"ip-backlink",title:J.name},W("file-text",{size:12}),EA(J.name)).on({click:()=>B.go(new wA(J))}))):k({className:"ip-muted"},"Nothing links here yet."))}async function qG(A,Q){try{await navigator.clipboard.writeText(Q),A.platform.notifications.success(`Copied ${Q}`)}catch{A.platform.notifications.info(Q,{sticky:!0})}}function zG(A,Q){let B=A?.tags||[];return k({className:"ip-section"},k({className:"ip-label"},"Tags"),k({className:"tags"},...B.map((C)=>EA({className:"tag"},C.value?`${C.name}: ${C.value}`:C.name,PA({className:"tag-x"},W("close",{size:11})).on({click:()=>Q.app.social.removeTag(C.name)}))),RG({className:"tag-input",placeholder:"+ tag",value:""}).on({keydown:(C)=>{if(C.key==="Enter"&&C.target.value.trim()){let E=C.target.value.trim(),[K,...J]=E.split(":");Q.app.social.addTag(K.trim(),J.join(":").trim()||void 0),C.target.value=""}}})))}function OG(A,Q,B){if(Q?.loading)return k({className:"ip-section"},k({className:"spinner"}));let C=Q?.comments||[],E=Q?.error?k({className:"conv-empty"},EA(`Couldn't load the conversation: ${Q.error}`),PA({className:"btn",$styling:{"margin-top":"8px"}},"Retry").on({click:()=>B.app.social.loadSidecar(Q.nodeId)})):C.length?k({className:"thread"},...C.map((K)=>IJ(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}`:""}`),E,Q?.error?null:jG(A,B))}function IJ(A,Q,B,C){let E=Q.so.me,K=B.app.social,J=E&&A.author?.id===E.id;return k({className:"comment",$styling:C?{marginLeft:"18px"}:{}},k({className:"c-head"},EA({className:"c-avatar"},(A.author?.name||"?")[0].toUpperCase()),EA({className:"c-author"},A.author?.name||A.author?.id||"Someone"),EA({className:"c-time"},b0(A.createdAt),A.edited?" · edited":"")),A.deleted?k({className:"c-body deleted"},"comment deleted"):k({className:"c-body"},SG(A.body)),!A.deleted?k({className:"c-actions"},...FG.map((Y)=>{let I=A.reactions?.[Y]||[];return PA({className:`react ${I.includes(E?.id)?"on":""}`},Y,I.length?EA({className:"rc"},String(I.length)):null).on({click:()=>K.react(A.id,Y)})}),PA({className:"c-link"},"Reply").on({click:()=>K.setReplyTo({id:A.id,author:A.author})}),J?PA({className:"c-link danger"},"Delete").on({click:()=>K.deleteComment(A.id)}):null):null,(A.replies||[]).length?k({className:"replies"},...A.replies.map((Y)=>IJ(Y,Q,B,C+1))):null).key(A.id)}function jG(A,Q){let B=Q.app.social,C=A.so.me,E=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"},EA("You’re signed out, so you can read this conversation but not add to it."),PA({className:"c-link"},"Reload to sign in").on({click:()=>window.location.reload()}))}return k({className:"composer"},E?k({className:"replying"},`Replying to ${E.author?.name||"comment"}`,PA({className:"c-link"},"cancel").on({click:()=>B.setReplyTo(null)})):null,WG({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"},EA({className:"muted"},"⌘/Ctrl + Enter"),PA({className:"btn primary",disabled:A.so.posting},"Comment").on({click:(K)=>{let J=K.target.closest(".composer").querySelector(".composer-input");B.comment(J.value),J.value=""}})))}function SG(A){let Q=[],B=/@\[([^\]]+)\]\(([^)]+)\)|(?:^|\s)@([a-zA-Z0-9._@-]{2,})/g,C=0,E;while(E=B.exec(A)){if(E.index>C)Q.push(A.slice(C,E.index+(E[3]?E[0].startsWith(" ")?1:0:0)));Q.push(EA({className:"mention"},"@"+(E[1]||E[3]))),C=B.lastIndex}if(C<A.length)Q.push(A.slice(C));return Q}var{div:DJ,button:u0,span:wG,img:TG}=w,_G=[{id:"home",icon:"search",title:"Search & files",command:"workbench.view.home"},{id:"plugins",icon:"plug",title:"Plugins",command:"workbench.view.plugins"}];function m0(A,Q){let B=A.wb.activity,C=A.plugins?.filter((E)=>E.status==="active").length||0;return DJ({className:"activitybar"},u0({className:"brand-mark",title:"Trove — home"},TG({src:"/icon.svg",alt:"Trove"})).on({click:()=>Q.exec("workbench.view.home")}),..._G.map((E)=>u0({className:`item ${B===E.id?"active":""}`,title:E.title},W(E.icon,{size:22}),E.id==="plugins"&&C?wG({className:"badge"},String(C)):null).on({click:()=>Q.exec(E.command)})),DJ({className:"spacer"}),LJ(A,Q),u0({className:`item ${B==="settings"?"active":""}`,title:"Settings"},W("gear",{size:21})).on({click:()=>Q.exec("workbench.openSettings")}),YJ(A))}var xG=new Set(["SPAN","B","STRONG","I","EM","CODE","SMALL","BR","S","U"]),kG=new Set(["class","title"]);function GJ(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 E of B.content.childNodes){let K=ZJ(E,C);if(K)Q.appendChild(K)}return Q}function XJ(A){return(GJ(A).textContent||"").trim()}function HJ(A,Q){return[...GJ(A).childNodes].map((B)=>$J(B,Q)).filter((B)=>B!=null)}function $J(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((E)=>$J(E,Q)).filter((E)=>E!=null))}function ZJ(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(!xG.has(A.tagName))return null;let B=document.createElement(A.tagName.toLowerCase());for(let C of A.attributes){let E=C.name.toLowerCase();if(!kG.has(E))continue;B.setAttribute(E,C.value.slice(0,200))}for(let C of A.childNodes){let E=ZJ(C,Q);if(E)B.appendChild(E)}return B}var{div:FQ,button:MQ,span:KA}=w;function UJ(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=HJ(A.html,w);if(!B.length)return null;let C=A.tooltip?XJ(A.tooltip):"";return A.command?MQ({className:"seg",title:C},...B).on({click:()=>Q.exec(A.command)}):KA({className:"seg",title:C},...B)}function gG(A,Q){let B=A.act||{tasks:[],issues:[]},C=B.tasks.filter((J)=>J.status==="running"),E=()=>Q.app.activity.togglePanel(!0),K=[];if(C.length){let J=C[0],I=J.total!=null&&J.total>0?Math.round((J.done||0)/J.total*100):null;K.push(MQ({className:"seg sb-activity",title:C.map((D)=>D.title).join(`
|
|
348
|
+
`)},FQ({className:"spinner",$styling:{width:"11px",height:"11px"}}),KA(C.length>1?`${C.length} running`:`${J.title}${I==null?"":` ${I}%`}`)).on({click:E}))}if(B.issues.length)K.push(MQ({className:"seg sb-attention",title:B.issues.map((J)=>J.title).join(`
|
|
349
|
+
`)},W("info",{size:12}),KA(`${B.issues.length} need${B.issues.length===1?"s":""} attention`)).on({click:E}));return K}function p0(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)),E=B<0.05?"critical":B<0.1?"low":"";return KA({className:`seg sb-usage ${E}`,title:`${QA(Q.used)} used of ${QA(Q.total)} — ${QA(Q.available)} free on this volume`},FQ({className:"usage-bar"},FQ({className:"usage-fill",$styling:{width:`${C}%`}})),KA(`${QA(Q.available)} free`))}function tB(A,Q){let B=A.ex,C=B.items||[],E=A.act||{tasks:[],issues:[]};return{collectionId:B.collectionId??null,collectionLabel:WJ(B),totalItems:B.stats?.items??C.length,totalKnown:B.stats?.items!=null,totalBytes:B.stats?.bytes??C.reduce((K,J)=>K+(J.size||0),0),shown:C.length,partial:!!B.nextCursor,usage:B.usage,uploading:A.tr.items.filter((K)=>K.status==="active"),running:E.tasks.filter((K)=>K.status==="running"),issues:E.issues,off:A.off||{online:!0,pins:[],queued:0,syncing:!1},caps:Q.platform.capabilities}}function WJ(A){if(!A?.collectionId)return"no collection";return(A.collections||[]).find((B)=>B.id===A.collectionId)?.name||A.collectionId}function c0(A,Q){let B=A.ex,C=B.items||[],E=tB(A,Q),{totalItems:K,totalBytes:J,caps:Y}=E,I=E.uploading,D=[...A.statusItems||[]].sort((Z,R)=>(Z.order??0)-(R.order??0)||Z.name.localeCompare(R.name)),L=D.filter((Z)=>Z.slot==="left").map((Z)=>UJ(Z,Q)),G=D.filter((Z)=>Z.slot!=="left").map((Z)=>UJ(Z,Q)),X=E.off;return FQ({className:"statusbar"},!X.online?KA({className:"seg offline-badge",title:"You are offline — pinned files and cached data are available"},W("info",{size:12}),KA("Offline")):X.syncing?KA({className:"seg",title:"Syncing offline changes"},FQ({className:"spinner",$styling:{width:"11px",height:"11px"}}),KA("Syncing…")):null,X.queued?KA({className:"seg",title:"Changes waiting to sync"},`${X.queued} queued`):null,X.pins.length?MQ({className:"seg",title:`${X.pins.length} file(s) available offline`},W("download",{size:12}),KA(`${X.pins.length} offline`),W("chevron-down",{size:11})).on({click:(Z)=>{let R=X.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(X.pins.length>12)R.push({label:`…and ${X.pins.length-12} more`,run:()=>{}});let F=Z.currentTarget.getBoundingClientRect();Q.platform.workbench.showContextMenu(F.left,F.top-8-R.length*34,R)}}):null,MQ({className:"seg",title:"Switch collection"},W("files",{size:13}),KA(WJ(B)),(B.collections||[]).length>1||B.canCreateCollection?W("chevron-down",{size:11}):null).on({click:(Z)=>{let R=Q.app.collectionMenu?.()||[];if(R.length>1||B.canCreateCollection){let F=Z.currentTarget.getBoundingClientRect();Q.platform.workbench.showContextMenu(F.left,F.top-8-R.length*34,R)}else Q.exec("workbench.view.home")}}),I.length?MQ({className:"seg",title:"Active uploads — click to cancel"},FQ({className:"spinner",$styling:{width:"11px",height:"11px"}}),KA(`${I.length} uploading`)).on({click:(Z)=>Q.platform.workbench.showContextMenu(Z.clientX,Z.clientY,I.map((R)=>({label:`Cancel ${R.name} (${Math.round((R.ratio||0)*100)}%)`,icon:"close",danger:!0,run:()=>Q.app.transfers.cancel(R.id)})))}):KA({className:"seg",title:B.nextCursor?`Showing ${C.length} of ${E.totalKnown?K:"more"}`:""},`${K.toLocaleString()}${E.totalKnown||!E.partial?"":"+"} item${K===1?"":"s"}`),...L,FQ({className:"spacer"}),...gG(A,Q),...G,KA({className:"seg",title:E.totalKnown||!E.partial?"Total size of this collection":`Size of the ${E.shown.toLocaleString()} items loaded so far — this server doesn’t report a collection total`},`${QA(J)}${E.totalKnown||!E.partial?"":"+"}`),p0(B),Y?KA({className:"seg",title:"Storage backend capabilities"},W(Y.storage?.presignDownload?"download":"files",{size:12}),KA(Y.storage?.presignDownload?"S3 direct":"proxied")):null,Y?.features?.semanticSearch?MQ({className:"seg",title:"Semantic search enabled"},W("star",{size:12}),KA("semantic")).on({click:()=>Q.exec("workbench.view.home")}):null)}var{div:RJ,span:FJ,button:yG}=w;function eB(A){return RJ({className:"launch-h"},RJ({className:"lh-title"},FJ(A.title),A.verbatim?FJ({className:"lh-verbatim"},A.verbatim):null),A.action||null)}function AC(A,Q,B){if(!A.menu)return null;return yG({className:"launch-more",title:`Actions for ${A.title}`,$attrs:{"aria-label":`Actions for ${A.title}`}},W("dots",{size:14})).on({click:(C)=>{C.stopPropagation(),VQ(C.currentTarget,A,Q,null,B)}})}function VQ(A,Q,B,C,E){let K=A?.getBoundingClientRect?.(),J=C?.clientX??(K?K.right-8:0),Y=C?.clientY??(K?K.bottom:0),I=Q.menu(B);E?.(),B.platform.workbench.showContextMenu(J,Y,I)}var{div:$B,span:l0}=w;function QC({groups:A,index:Q,handlers:B,ui:C}){let E=-1;return $B({className:"launch-view view-list"},...A.map((K)=>$B({className:"launch-group"},eB(K),K.items.length?$B({className:"launch-list"},...K.items.map((J)=>{let Y=++E;return hG(J,Y===Q,{hover:()=>B.hover(Y),select:()=>B.select(Y)},C)})):$B({className:"launch-empty"},K.empty||"Nothing here."))))}function hG(A,Q,{hover:B,select:C},E){return $B({className:`launch-item ${Q?"active":""}`},W(A.icon,{size:15}),l0({className:"name"},A.title),A.detail?l0({className:"launch-detail"},A.detail):null,A.badge?l0({className:"launch-kind"},A.badge):null,AC(A,E,C)).on({click:A.run,mouseenter:B,...A.menu?{contextmenu:(K)=>{K.preventDefault(),VQ(K.currentTarget,A,E,K,C)}}:{}})}function uQ(A,Q,B,{op:C="media",onError:E}={}){let K=B.platform.mediaUrls,J=null,Y=!1,I=!1,D=()=>{clearTimeout(J),J=null},L=(R)=>{if(D(),!Number.isFinite(R))return;let F=Math.max(1000,(R-Date.now())*0.8);J=setTimeout(()=>G({resume:!0}),Math.min(F,2147483647))};async function G({resume:R}){if(Y)return;let F=vG(A),P=F&&R?A.currentTime:0,g=F&&R?!A.paused&&!A.ended:!1,f;try{f=await K.url(Q.id,{op:C})}catch(M){if(!Y)E?.(M.message);return}if(Y)return;if(A.src=f.url,F){if(A.load(),P>0||g){let M=()=>{if(A.removeEventListener("loadedmetadata",M),P>0&&Number.isFinite(A.duration)&&A.duration>P)A.currentTime=P;if(g)A.play().catch(()=>{})};A.addEventListener("loadedmetadata",M)}}L(f.expiresAt)}let X=()=>{I=!1};A.addEventListener("load",X),A.addEventListener("loadeddata",X);let Z=()=>{if(Y)return;if(I){E?.(null);return}I=!0,K.invalidate(Q.id,C),G({resume:!0})};return A.addEventListener("error",Z),G({resume:!1}),()=>{Y=!0,D(),A.removeEventListener("error",Z),A.removeEventListener("load",X),A.removeEventListener("loadeddata",X)}}function vG(A){return typeof A?.play==="function"&&typeof A?.load==="function"}var{div:PQ,span:bG,img:fG}=w;function MJ({groups:A,index:Q,handlers:B,ui:C}){let E=-1;return PQ({className:"launch-view view-grid"},...A.map((K)=>PQ({className:"launch-group"},eB(K),K.items.length?PQ({className:"grid-list"},...K.items.map((J)=>{let Y=++E;return mG(J,Y===Q,{hover:()=>B.hover(Y),select:()=>B.select(Y)},C)})):PQ({className:"launch-empty"},K.empty||"Nothing here."))))}function VJ({key:A,textual:Q}){if(A==="ArrowLeft")return Q?null:-1;if(A==="ArrowRight")return Q?null:1;let B=uG();if(A==="ArrowUp")return-B;if(A==="ArrowDown")return B;return null}function uG(){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 mG(A,Q,{hover:B,select:C},E){let K=A.node,J=(K?.contentType||"").startsWith("image/");return PQ({className:`grid-tile ${Q?"active":""}`,title:A.detail?`${A.title} — ${A.detail}`:A.title},PQ({className:"gt-media"},W(K?aA(K):A.icon,{size:26}),J?fG({className:"gt-img",alt:"",loading:"lazy",decoding:"async"}).on({$attach:(Y)=>{Y._detachMedia=uQ(Y,K,E,{onError:()=>{Y.style.display="none"}})},$detach:(Y)=>{Y._detachMedia?.(),Y._detachMedia=null}}).opaque():null,A.badge?bG({className:"gt-badge"},A.badge):null,AC(A,E,C)),PQ({className:"gt-name"},A.title)).on({click:A.run,mouseenter:B,...A.menu?{contextmenu:(Y)=>{Y.preventDefault(),VQ(Y.currentTarget,A,E,Y,C)}}:{}})}var{div:d0,button:pG,span:cG}=w,lG={"core.view.list":{title:"List",icon:"list",priority:50,render:QC},"core.view.grid":{title:"Grid",icon:"grid",priority:40,match:{mime:["image/*","video/*"]},render:MJ,move:VJ}};function PJ(A){for(let[Q,B]of Object.entries(lG))A.contributions.register(Q,{type:"view",...B})}var NJ="explorer.view";function qJ(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 zJ(A,Q=[],B=null){let C=qJ(A);if(!C.length)return null;let E=A.settings.get(NJ),K=E&&C.find((I)=>I.id===E);if(K)return K;let J=B&&C.find((I)=>I.id===B);if(J)return J;let Y=Q.map((I)=>I.node).filter(Boolean);if(Y.length>=3){let I=(L)=>L.match&&Object.keys(L.match).length&&Y.filter((G)=>dG(L,G)).length/Y.length>0.6,D=C.find(I);if(D)return D}return C[0]}function dG(A,Q){let B=Q.contentType||"",C=(Q.name||"").toLowerCase(),E=C.includes(".")?C.slice(C.lastIndexOf(".")):"";if((A.match.ext||[]).includes(E))return!0;return(A.match.mime||[]).some((K)=>K.endsWith("/*")?B.startsWith(K.slice(0,-1)):B===K)}function nG(A,Q){A.settings.set(NJ,Q||void 0)}function OJ(A,Q){let B=qJ(A);if(B.length<2)return null;return d0({className:"view-switch"},...B.map((C)=>pG({className:`vs-btn ${C.id===Q?.id?"on":""}`,title:`${C.title||C.name} view`,"aria-pressed":C.id===Q?.id?"true":"false"},W(C.icon||"list",{size:14})).on({click:()=>nG(A,C.id)})))}function jJ(A,Q,B){try{let C=A?.move?.({key:Q,...B});return Number.isFinite(C)&&C!==0?C:null}catch{return null}}function SJ(A,Q){try{if(typeof A?.render==="function")return A.render(Q)}catch(B){return console.error(`view "${A?.id}" failed`,B),d0({},d0({className:"view-error"},W("warn",{size:13}),cG(`The “${A?.title||A?.id}” view could not be drawn — showing the list instead.`)),QC(Q))}return QC(Q)}var{div:sA,span:mQ,input:oG,button:NQ}=w,aG=new Set(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"]);function sG(A,{compact:Q=!1,modal:B=!1}={}){let C=A.platform.capabilities?.searchPrompt,E=(Q?C?.short||C?.placeholder:C?.placeholder)||(Q?"Search files":"Search files · # filter by tag");return Q||B?E:`${E} · ! run a command`}var CC=null;function iG(A,Q){clearTimeout(CC),CC=setTimeout(()=>A.go(new LQ(Q)),240)}function wJ(A){A.platform.workbench.setLaunchQuery(""),A.go(new LQ(""))}function rG(A,Q,B){clearTimeout(CC),CC=setTimeout(()=>A.go(new HB(Q,B)),200)}function EC(A,Q,B={}){let C=Q.platform.workbench,E=!!B.modal,K=A.wb.launch.query,J=K.startsWith("!")?"command":K.includes("#")?"filter":"search",Y=AX(A,Q,K,J,E),I=Y.flatMap((M)=>M.items),D=I.length?Math.min(A.wb.launch.index,I.length-1):0,L=(M)=>{let S=M.target.value;if(C.setLaunchQuery(S),S.startsWith("!"))return;let{text:O,filters:y}=nB(S);if(y.length)rG(Q,y,O);else iG(Q,O)},G=(M)=>C.setLaunchIndex(M),X=(M)=>{C.setLaunchIndex(M),TJ(Q,I[M])},Z=(M)=>{C.moveLaunch(M,I.length),TJ(Q,I[C.state.launch.index])},R=zJ(Q.platform,I,J==="search"?A.se.resolved?.view:null),F=(M)=>{let S=aG.has(M.key)?jJ(R,M.key,{index:D,count:I.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(),I[D]?.run();else if(M.key==="Escape"&&K)M.preventDefault(),wJ(Q);else if(M.key==="ContextMenu"||M.shiftKey&&M.key==="F10"){let O=I[D];if(O?.menu)M.preventDefault(),VQ(document.querySelector(".launch-item.active, .grid-tile.active"),O,Q)}},P=J==="search"?A.se.resolved:null,g=P&&(P.source==="llm"||P.tagFilters&&P.tagFilters.length||(P.semanticText||"").trim()!==K.trim()),f=sA({className:"launcher"},sA({className:"launch-box"},W(J==="command"?"command":J==="filter"?"tag":"search",{size:18}),oG({className:"launch-input",value:K,autofocus:!0,spellcheck:!1,placeholder:sG(Q,{compact:A.vp?.mode==="phone",modal:E})}).on({input:L,keydown:F}),K?NQ({className:"launch-clear",title:"Clear"},W("close",{size:14})).on({click:()=>wJ(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"},W("mic",{size:15})).on({click:()=>Q.exec("search.voice")}):null,E?null:OJ(Q.platform,R)),g?tG(P):null,sA({className:"launch-body"},SJ(R,{groups:Y,index:D,handlers:{hover:G,select:X},state:A,ui:Q}),eG(A,Q,J)));return E?f:sA({className:"editor"},f)}function tG(A){return sA({className:"launch-resolved"},mQ({className:"rq-label"},A.source==="llm"?"Interpreted as":"Searching"),(A.semanticText||"").trim()?mQ({className:"rq-text"},`“${A.semanticText.trim()}”`):null,...(A.tagFilters||[]).map((Q)=>mQ({className:"rq-chip"},W("tag",{size:11}),S0(Q))))}function TJ(A,Q){let B=Q?.node;A.app.explorer.select(B?.id?[B.id]:[],{nodes:B?[B]:null})}function eG(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 E=Q.platform.capabilities?.searchPrompt;if(!E?.hint&&!E?.examples?.length)return null;let K=Q.platform.workbench,J=(Y)=>()=>{K.setLaunchQuery(Y);let{text:I,filters:D}=nB(Y);if(D.length)Q.go(new HB(D,I));else Q.go(new LQ(I))};return sA({className:"launch-help"},E.hint?sA({className:"lh-hint"},W("info",{size:13}),mQ(E.hint)):null,E.examples?.length?sA({className:"lh-examples"},...E.examples.map((Y)=>NQ({className:"lh-example",title:Y.label||"Try this search"},mQ({className:"lh-q"},Y.query),Y.label?mQ({className:"lh-label"},Y.label):null).on({click:J(Y.query)}))):null)}function AX(A,Q,B,C,E){let K=()=>{if(E)Q.platform.workbench.closeSearchModal()};if(C==="command"){let M=B.slice(1).trim().toLowerCase();return[{title:"Commands",items:Q.platform.commands.paletteCommands().map((O)=>({hay:`${O.category||""} ${O.title}`.toLowerCase(),c:O})).map(({hay:O,c:y})=>({s:EX(O,M),c:y})).filter((O)=>M===""||O.s>0).sort((O,y)=>y.s-O.s).slice(0,40).map(({c:O})=>({icon:"command",title:O.title,detail:O.category,badge:"command",run:()=>{Q.exec(O.id),K()}})),empty:"No matching commands."}]}let{text:J,filters:Y}=nB(B),I=(A.se.results||[]).map((M)=>M.node),D=A.se.error,L=(M)=>NQ({className:"launch-up",title:"Retry"},W("refresh",{size:13}),"Retry").on({click:()=>Q.go(M)});if(Y.length){let M=Y.map(S0).join(" ")+(J.trim()?` · "${J.trim()}"`:"");return[{title:A.se.loading?"Filtering…":D?"Filter failed":"Filtered",verbatim:A.se.loading||D?null:M,action:D?L(new HB(Y,J)):null,items:I.map((S)=>BC(S,Q,E)),empty:A.se.loading?"Filtering…":D?`Couldn’t filter: ${D}`:"No files match those filters."}]}if(J.trim())return[{title:A.se.loading?"Searching…":D?"Search failed":"Results",action:D?L(new LQ(B)):null,items:I.map((M)=>BC(M,Q,E)),empty:A.se.loading?"Searching…":D?`Couldn’t search: ${D}`:"No files match."}];let G=[],X=(A.nav.recents||[]).map((M)=>BC(M,Q,E));if(X.length)G.push({title:"Recent",items:X});let Z=A.ex,R=(Z.items||[]).length,F=Z.stats?.items??null,P=F??R,g=F!=null?F.toLocaleString():`${R.toLocaleString()}+`,f=(Z.items||[]).map((M)=>BC(M,Q,E));if(Z.nextCursor)f.push({icon:"refresh",title:Z.loadingMore?"Loading…":F!=null?`Show more (${(F-R).toLocaleString()} more)`:"Show more",detail:"or search to jump straight to something",run:()=>Q.exec("explorer.loadMore")});if(Z.trash)G.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"},W("trash",{size:13}),"Empty trash").on({click:()=>Q.exec("explorer.emptyTrash")}):null,NQ({className:"launch-up",title:"Hide the trash"},W("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:()=>BX(M,Q)})):[],empty:"The trash is empty."});return G.push({title:Z.nextCursor?`All items · showing ${R.toLocaleString()} of ${g}`:"All items",action:E?null:NQ({className:"launch-up",title:"Upload files to this collection"},W("upload",{size:13}),"Upload").on({click:()=>Q.exec("explorer.upload")}),items:f,empty:Z.loading?"Loading…":Z.error?`Couldn’t load this collection: ${Z.error}`:"Nothing here yet — upload a file to get started."}),G}function BC(A,Q,B){return{icon:CX(A),title:A.name,detail:A.contentType||"",node:A,run:()=>{if(Q.go(new wA(A,{reset:!!B})),B)Q.platform.workbench.closeSearchModal()},menu:()=>QX(A,Q)}}function QX(A,Q){let B=(Q.app.offline?.state?.pins||[]).some((E)=>E.id===A.id),C=(E)=>Q.platform.keybindings.labelFor(E)||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 BX(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 CX(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 EX(A,Q){if(!Q)return 1;let B=A.indexOf(Q);if(B>=0)return 1000-B;let C=0;for(let E=0;E<A.length&&C<Q.length;E++)if(A[E]===Q[C])C++;return C===Q.length?1:0}var{div:V,h2:KX,h3:cQ,p:qQ,span:JA,select:JX,option:YX,input:pQ,label:kJ,button:mA,ul:g4,li:y4,code:LX}=w;function o0(A,Q){let B=Q.platform.settings.grouped();return V({className:"editor"},V({className:"stage"},V({className:"settings"},KX("Settings"),qQ({className:"sub"},"Preferences are stored in this browser. Plugins contribute their own settings here too."),...B.map((C)=>IX(C,Q)),XX(Q),$X(A,Q),MX(Q),VX(Q))))}function IX(A,Q){return V({className:"group"},cQ(A.category),...A.items.map((B)=>DX(B,Q)))}function DX(A,Q){return V({className:"setting"},V({className:"info"},V({className:"t"},A.title||A.key),A.description?V({className:"d"},A.description):null),V({className:"control"},GX(A,Q)))}function GX(A,Q){let B=(C)=>Q.platform.settings.set(A.key,C);if(A.type==="boolean")return kJ({className:"switch"},pQ({type:"checkbox",checked:!!A.value}).on({change:(C)=>B(C.target.checked)}),JA({className:"track"}));if(A.type==="enum")return JX({className:"input"},...A.enum.map((C,E)=>YX({value:C,selected:A.value===C},A.enumLabels&&A.enumLabels[E]||C))).on({change:(C)=>B(C.target.value)});if(A.type==="number"){let C=(E)=>{let K=Number(E.target.value);if(E.target.value===""||Number.isNaN(K)){E.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);E.target.value=K,B(K)};return pQ({className:"input",type:"number",value:A.value,$attrs:{min:A.minimum??"",max:A.maximum??""}}).on({change:C})}return pQ({className:"input",value:A.value??""}).on({change:(C)=>B(C.target.value)})}function XX(A){let Q=A.platform.capabilities;if(!Q)return null;let B=Q.mcp,C=Q.auth||{authorizationServers:[],source:"none"};if(!B?.enabled)return V({className:"group"},cQ("AI agents (MCP)"),qQ({className:"sub"},"MCP is switched off on this server. Set TROVE_MCP=on to enable it."));let E=(Y)=>()=>{navigator.clipboard?.writeText(Y).then(()=>A.platform.notifications.success("Copied")).catch(()=>A.platform.notifications.info(Y,{sticky:!0}))},K=C.authorizationServers||[],J=C.source==="jwt-issuer"?"from TROVE_JWT_ISSUER":C.source==="configured"?"from TROVE_AUTH_SERVER":null;return V({className:"group"},cQ("AI agents (MCP)"),qQ({className:"sub"},"Point an AI assistant at this drive. It signs in as you and sees exactly the collections you can see."),V({className:"setting"},V({className:"info"},V({className:"t"},"Server URL"),V({className:"d"},"Paste this into your assistant’s MCP settings.")),V({className:"control mcp-url"},JA({className:"mono"},B.endpoint),mA({className:"btn small",title:"Copy"},W("link",{size:13})).on({click:E(B.endpoint)}))),V({className:"setting"},V({className:"info"},V({className:"t"},"Sign-in required"),V({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.")),V({className:"control"},JA({className:"mono"},B.requiresAuth?"Yes":"No"))),B.needsAuthorizationServer?V({className:"mcp-warn"},W("warn",{size:15}),JA("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,V({className:"setting"},V({className:"info"},V({className:"t"},"Authorization server"),V({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.")),V({className:"control"},K.length?JA({className:"mono"},K.join(", ")+(J?` (${J})`:"")):JA({className:"mono muted"},"not set"))),V({className:"setting"},V({className:"info"},V({className:"t"},"Discovery document"),V({className:"d"},"What a client reads to find out how to authenticate (RFC 9728).")),V({className:"control mcp-url"},JA({className:"mono small"},C.metadataUrl))))}var HX=[{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"}],gJ="*",_J=!1;function $X(A,Q){let B=A.keys||{};if(!_J&&!B.loaded&&!B.loading)_J=!0,Q.exec("keys.load");if(B.error&&!B.keys?.length)return null;if(!B.loaded)return null;let C=A.ex?.collections||[];return V({className:"group"},cQ("API keys"),qQ({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?ZX(B.minted,Q):null,B.draft?UX(B,C,Q):null,!B.draft&&!B.minted?V({className:"keys-actions"},mA({className:"btn"},W("plus",{size:14}),"New key").on({click:()=>Q.exec("keys.new")})):null,B.keys?.length?V({className:"keys-list"},...B.keys.map((E)=>WX(E,B,C,Q))):V({className:"keys-empty"},"No keys yet."))}function ZX(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 V({className:"key-minted"},V({className:"key-minted-head"},W("warn",{size:15}),JA(`“${A.key.name}” is ready — copy it now.`)),qQ({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."),V({className:"key-secret"},LX({className:"mono"},A.secret),mA({className:"btn small",title:"Copy"},W("link",{size:13})).on({click:B})),V({className:"keys-actions"},mA({className:"btn"},"Done").on({click:()=>Q.exec("keys.dismissMinted")})))}function UX(A,Q,B){let C=A.draft,E=B.app.apiKeys.draftScopes(),K=!!C.name.trim()&&!!E;return V({className:"key-form"},V({className:"setting"},V({className:"info"},V({className:"t"},"Name"),V({className:"d"},"What it is for. This is what the list shows, so make it recognisable.")),V({className:"control"},pQ({className:"input",value:C.name,$attrs:{placeholder:"CI uploader"}}).on({input:(J)=>B.app.apiKeys.patchDraft({name:J.target.value})}))),V({className:"setting"},V({className:"info"},V({className:"t"},"Expires after"),V({className:"d"},"Days from now. Leave blank and it never expires.")),V({className:"control"},pQ({className:"input",type:"number",value:C.expiresInDays,$attrs:{min:"1",max:"3650",placeholder:"never"}}).on({input:(J)=>B.app.apiKeys.patchDraft({expiresInDays:J.target.value})}))),V({className:"key-scopes"},V({className:"key-scopes-head"},V({className:"t"},"What it may do"),V({className:"d"},"Per collection. A key with nothing ticked grants nothing and cannot be created.")),xJ({id:gJ,name:"All collections",wildcard:!0},C,B),...Q.map((J)=>xJ(J,C,B))),V({className:"keys-actions"},mA({className:"btn primary",$attrs:K?{}:{disabled:"true"}},A.busy==="mint"?"Creating…":"Create key").on({click:()=>K&&B.exec("keys.mint")}),mA({className:"btn"},"Cancel").on({click:()=>B.exec("keys.cancel")})))}function xJ(A,Q,B){let C=new Set(Q.caps[A.id]||[]);return V({className:`key-scope ${A.wildcard?"wildcard":""}`},V({className:"key-scope-name"},W(A.wildcard?"grid":"files",{size:14}),JA(A.name||A.id)),V({className:"key-scope-caps"},...HX.map((E)=>kJ({className:`cap ${C.has(E.id)?"on":""}`,title:E.hint},pQ({type:"checkbox",checked:C.has(E.id)}).on({change:()=>B.app.apiKeys.toggleCap(A.id,E.id)}),JA(E.label)))))}function WX(A,Q,B,C){let E=!!A.revokedAt,K=A.expiresAt!=null&&A.expiresAt<=Date.now(),J=E||K;return V({className:`key-row ${J?"dead":""}`},V({className:"key-row-main"},V({className:"key-row-name"},JA({className:"t"},A.name),E?JA({className:"key-tag"},"revoked"):K?JA({className:"key-tag"},"expired"):null),V({className:"key-row-scopes"},...RX(A,B)),V({className:"key-row-meta"},FX(A))),!J?mA({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 RX(A,Q){let B=(C)=>Q.find((E)=>E.id===C)?.name||C;return(A.scopes||[]).map((C)=>JA({className:"key-chip"},JA({className:"where"},C.collectionId===gJ?"all collections":B(C.collectionId)),JA({className:"what"},C.capabilities.join(" · "))))}function FX(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 MX(A){let Q=eK(A.platform);return V({className:"group"},cQ("Default Openers"),Q.length?V({},...Q.map((B)=>V({className:"setting"},V({className:"info"},V({className:"t"},B.typeKey),V({className:"d"},B.missing?`${B.openerTitle} (no longer installed)`:`Opens with ${B.openerTitle}`)),V({className:"control"},mA({className:"iconbtn",title:"Forget this default"},W("close",{size:14})).on({click:()=>sB(A.platform,B.typeKey,null)}))))):qQ({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 n0=null;function VX(A){let Q=A.platform.keybindings,B=Q.resolved(),C=A.platform.contributions,E=Q.overrides(),K=()=>{n0=null,A.rerender?.()},J=new Map;for(let Y of B)J.set(Y.key,(J.get(Y.key)||0)+1);return V({className:"group"},cQ("Keyboard Shortcuts"),qQ({className:"sub"},"Click a shortcut to record a new one. Esc cancels; Backspace clears it."),...B.map((Y)=>{let I=C.get(Y.command),D=n0===Y.bindingId,L=!!E[Y.bindingId],G=J.get(Y.key)>1;return V({className:"setting"},V({className:"info"},V({className:"t"},I?.title||Y.command),V({className:"d"},Y.command)),V({className:"control"},G&&!D?JA({className:"kbd-clash",title:"Another command answers to this shortcut too — the one registered last wins"},W("warn",{size:12})):null,mA({className:`kbd-edit ${D?"listening":""} ${G?"clash":""}`,title:D?"Press the new shortcut":"Click to rebind"},D?JA("Press keys…"):w.h("kbd",QB(Y.key))).on({click:()=>{n0=D?null:Y.bindingId,A.rerender?.()},blur:()=>{if(D)K()},keydown:(X)=>{if(!D)return;if(X.preventDefault(),X.stopPropagation(),X.key==="Escape")return K();if(X.key==="Backspace")return Q.rebind(Y,null),K();if(["Control","Meta","Alt","Shift"].includes(X.key))return;Q.rebind(Y,MC(X)),K()},$attach:(X)=>{if(D)queueMicrotask(()=>X.focus())}}),L?mA({className:"c-link",title:"Back to the default"},"reset").on({click:()=>{Q.rebind(Y,null),A.rerender?.()}}):null))}))}var{div:gA,h2:yJ,p:hJ,button:s0,span:a0}=w;function i0(A,Q){let B=A.ex||{};return gA({className:"editor"},gA({className:"stage"},gA({className:"gate"},B.gate==="create"?PX(Q):NX(B,Q))))}function PX(A){return gA({className:"gate-card"},gA({className:"gate-icon"},W("files",{size:26})),yJ("Make your first collection"),hJ({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."),gA({className:"gate-actions"},s0({className:"btn primary"},W("plus",{size:14}),"New collection").on({click:()=>A.exec("collections.create")})))}function NX(A,Q){let B=A.collections||[];return gA({className:"gate-card"},gA({className:"gate-icon"},W("grid",{size:26})),yJ(B.length===1?"Open your collection":"Choose a collection"),hJ({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."),gA({className:"gate-list"},...B.map((C)=>s0({className:"gate-choice"},gA({className:"gate-choice-main"},a0({className:"n"},C.name||C.id),a0({className:"d"},C.driver?`${C.driver}${C.description?` · ${C.description}`:""}`:C.description||"")),a0({className:"gate-caps"},(C.capabilities||[]).join(" · "))).on({click:()=>Q.exec("collections.switch",C.id)}))),A.canCreateCollection?gA({className:"gate-actions"},s0({className:"btn"},W("plus",{size:14}),"New collection").on({click:()=>Q.exec("collections.create")})):null)}var{div:l,span:UA,p:qX,button:ZB,h2:zX,input:r0,label:OX}=w;function t0(A,Q){let B=A.plugins||[];return l({className:"editor"},l({className:"stage"},l({className:"plugins"},zX("Plugins"),qX({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"},ZB({className:"btn primary"},W("upload",{size:15}),"Install from file…").on({click:()=>Q.exec("plugins.installFromFile")}),ZB({className:"btn"},W("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)=>jX(C,A,Q))):l({className:"empty",$styling:{padding:"48px"}},W("plug",{size:30}),UA("No plugins installed yet.")))))}function jX(A,Q,B){let C=!A.responsive?"not responding":A.manifest?.online===!1?"offline":"connected",E=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?UA({$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)),TX(A.trust),UA({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)=>UA({className:"cap"},K))),(A.endpoints||[]).length?l({className:"plugin-endpoints",$styling:{"font-size":"11px",color:"var(--text-faint)","margin-top":"2px"}},W("plug",{size:11})," Network: ",(A.endpoints||[]).map((K)=>K.host).join(", ")):null,A.status==="active"?l({className:"plugin-features"},l({className:"pf-head"},UA(`Features · ${C}`),UA({className:"muted"},`${E.filter((K)=>K.available).length}/${E.length} available`)),E.length?l({className:"pf-list"},...E.map(xX)):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?SX(A,B):null,l({className:"actions"},A.hasUi?ZB({className:"btn"},W("command",{size:14}),"Open panel").on({click:()=>B.platform.workbench.openPluginPanel(A.id)}):null,ZB({className:"btn"},W("refresh",{size:14}),"Refresh").on({click:()=>B.platform.plugins.refresh(A.id)}),ZB({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 SX(A,Q){return l({className:"plugin-features"},l({className:"pf-head"},UA("Settings")),l({$styling:{display:"flex","flex-direction":"column",gap:"8px"}},...A.settingsSchema.map((B)=>wX(A,B,Q))))}function wX(A,Q,B){let C=`${A.id}.${Q.key}`,E=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?r0({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"?OX({className:"switch"},r0({type:"checkbox",checked:!!E}).on({change:(K)=>B.platform.settings.set(C,K.target.checked)}),UA({className:"track"})):r0({className:"input",value:E}).on({change:(K)=>B.platform.settings.set(C,K.target.value)})))}function TX(A){if(!A)return null;if(A.status==="verified")return UA({className:"trust verified",title:"Signed by "+A.domain},W("check",{size:12}),A.domain);if(A.status==="signed")return UA({className:"trust signed"},W("info",{size:12}),"signed");if(A.status==="invalid")return UA({className:"trust invalid",title:A.reason||"The signature did not verify — this package may have been altered"},W("warn",{size:12}),"invalid signature");return UA({className:"trust unverified"},W("warn",{size:12}),"unverified")}var _X={command:"command",opener:"file",indexer:"search",statusItem:"info"};function xX(A){return l({className:`pf-row ${A.available?"":"off"}`},W(_X[A.kind]||"command",{size:13}),UA({className:"pf-title"},A.title),UA({className:"pf-kind"},A.kind),A.offline?UA({className:"pf-badge offline-ok",title:"Works offline"},"offline ✓"):null,UA({className:`pf-dot ${A.available?"on":"no"}`,title:A.available?"Available now":"Unavailable now"}))}async function vJ(A,Q,{from:B}={}){let C=lB(Q),E=A.platform.notifications;if(!C)return E.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 wA(K.node)),K.node}catch(K){return E.warn(kX(C,K,B)),null}}function kX(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:zQ,span:AE,h1:gX,h2:yX,h3:hX,p:cJ,ul:vX,ol:bX,li:fX,pre:uX,code:lJ,a:bJ,em:mX,strong:pX,blockquote:cX,hr:lX,br:dX}=w;function dJ(A,Q){let B=eQ(()=>Q.platform.api.readTextCapped(A.id,{maxBytes:e0,size:A.size}).then((C)=>C.text));return w.alias(()=>Q.platform.reactive.watch(B,(C)=>{try{return zQ({className:"viewer markdown"},zQ({className:"md"},...nJ(C,A,Q)))}catch(E){return console.error("markdown render failed",E),fJ(`This document couldn’t be displayed: ${E.message}`)}},{placeholder:()=>zQ({className:"viewer"},zQ({className:"loading"},zQ({className:"spinner"}),AE("Loading…"))),error:(C)=>fJ(C.message)}))()}function fJ(A){return zQ({className:"viewer"},zQ({className:"fallback"},W("warn",{size:40}),AE(A)))}var e0=524288,nX=5000,oX=2000;function nJ(A,Q,B){let C=String(A??""),E=C.length>e0,K=(E?C.slice(0,e0):C).split(/\r?\n/),J=[],Y=0;while(Y<K.length){if(J.length>=nX)return[...J,uJ()];let I=K[Y],D=/^\s*(```+|~~~+)(.*)$/.exec(I);if(D){let F=D[1][0].repeat(3),P=[];Y++;while(Y<K.length&&!K[Y].trimStart().startsWith(F))P.push(K[Y++]);Y++,J.push(uX({className:"md-code"},lJ(P.join(`
|
|
350
|
+
`))));continue}if(!I.trim()){Y++;continue}let L=/^(#{1,6})\s+(.*)$/.exec(I);if(L){let F=L[1].length,P=F===1?gX:F===2?yX:hX;J.push(P({className:`md-h md-h${F}`},...UB(L[2],Q,B))),Y++;continue}if(/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(I)){J.push(lX({className:"md-hr"})),Y++;continue}if(/^\s*>/.test(I)){let F=[];while(Y<K.length&&/^\s*>/.test(K[Y]))F.push(K[Y++].replace(/^\s*>\s?/,""));J.push(cX({className:"md-quote"},...nJ(F.join(`
|
|
351
|
+
`),Q,B)));continue}let G=/^\s*([-*+]|\d+[.)])\s+/.exec(I);if(G){let F=/\d/.test(G[1]),P=[];while(Y<K.length){let g=/^\s*([-*+]|\d+[.)])\s+(.*)$/.exec(K[Y]);if(!g||/\d/.test(g[1])!==F)break;P.push(fX({className:"md-li"},...UB(g[2],Q,B))),Y++}J.push((F?bX:vX)({className:"md-list"},...P));continue}let X=[];while(Y<K.length&&K[Y].trim()&&!aX(K[Y]))X.push(K[Y++]);let Z=X.join(`
|
|
352
|
+
`),R=[];Z.split(`
|
|
353
|
+
`).forEach((F,P)=>{if(P)R.push(dX());R.push(...UB(F,Q,B))}),J.push(cJ({className:"md-p"},...R))}return E?[...J,uJ()]:J}function uJ(){return cJ({className:"md-truncated"},"This document is too large to display in full. Download it to read the rest.")}function aX(A){return/^(#{1,6}\s|\s*>|\s*([-*+]|\d+[.)])\s|\s*(```|~~~))/.test(A)||/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(A)}var sX=[{re:/`([^`]+)`/,node:(A)=>lJ({className:"md-inline-code"},A[1])},{re:/\[([^\]]*)\]\(([^)\s]+)(?:\s+"[^"]*")?\)/,node:(A,Q,B)=>pJ(A[2],A[1]||A[2],Q,B)},{re:/(\*\*|__)(.+?)\1/,node:(A,Q,B,C)=>pX(...UB(A[2],Q,B,C+1))},{re:/(\*|_)(.+?)\1/,node:(A,Q,B,C)=>mX(...UB(A[2],Q,B,C+1))},{re:/(trove:[^\s<>"'`)\]}]+|https?:\/\/[^\s<>"'`)\]}]+)/,node:(A,Q,B)=>pJ(mJ(A[1]),mJ(A[1]),Q,B)}];function UB(A,Q,B,C=0){if(!A)return[];if(C>12)return[A];let E=[],K=A;while(K){if(E.length>=oX){E.push(K);break}let J=null;for(let D of sX){let L=D.re.exec(K);if(L&&(J===null||L.index<J.m.index))J={m:L,rule:D}}if(!J){E.push(K);break}let{m:Y,rule:I}=J;if(Y.index)E.push(K.slice(0,Y.index));E.push(I.node(Y,Q,B,C)),K=K.slice(Y.index+Y[0].length)}return E}function mJ(A){return A.replace(/[.,;:!?]+$/,"")}function pJ(A,Q,B,C){if(lB(A))return bJ({className:"md-link md-trove",href:"#",title:A},Q).on({click:(K)=>{K.preventDefault(),vJ(C,A,{from:B})}});if(/^https?:\/\//i.test(A))return bJ({className:"md-link",href:A,target:"_blank",rel:"noopener noreferrer",title:A},Q);return AE({className:"md-deadlink",title:`Unsupported link: ${A}`},Q)}var{div:FA,pre:iX,img:rX,span:OQ,button:tX,video:eX,audio:AH}=w,QH={"core.audio":{title:"Audio Player",priority:20,match:{mime:["audio/*"],ext:[".mp3",".flac",".wav",".opus",".ogg",".m4a",".m4b"]},component:JH},"core.video":{title:"Video Player",priority:20,match:{mime:["video/*"],ext:[".mp4",".webm",".mkv",".mov"]},component:YH},"core.image":{title:"Image Viewer",priority:20,match:{mime:["image/*"],ext:[".png",".jpg",".jpeg",".gif",".webp",".svg",".avif"]},component:KH},"core.markdown":{title:"Markdown",priority:30,match:{ext:[".md",".markdown"],mime:["text/markdown"]},component:dJ},"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:CH}};function oJ(A){for(let[Q,B]of Object.entries(QH))A.contributions.register(Q,{type:"opener",...B})}function aJ(A,Q,B){let C=B.platform.contributions.get(Q);if(C?.component)try{return C.component(A,B)}catch(E){return iJ(E.message)}if(C?.pluginId)return LH(C,A,B);return sJ(A,B)}var BH=524288;function CH(A,Q){let B=eQ(()=>Q.platform.api.readTextCapped(A.id,{maxBytes:BH,size:A.size}));return w.alias(()=>Q.platform.reactive.watch(B,({text:C,truncated:E,total:K})=>FA({className:"viewer text"},iX(C),E?FA({className:"md-truncated"},`Showing the first ${Math.round(C.length/1024)} KB${K?` of ${(K/1048576).toFixed(1)} MB`:""}. `,OQ("Download the file to read all of it.")):null),{placeholder:()=>FA({className:"viewer"},FA({className:"loading"},FA({className:"spinner"}),OQ("Loading…"))),error:(C)=>iJ(C.message)}))()}var EH="This file couldn't be loaded — it may be missing or in an unsupported format.";function QE(A,Q,B){let C=b({error:null}),K=B((J)=>C.setValue({error:J||EH}));return w.alias(()=>qB(C,(J)=>J.error?sJ(A,Q,J.error):K))()}var BE=(A,Q,B,C)=>A.on({$attach:(E)=>{E._detachMedia=uQ(E,Q,B,{onError:C})},$detach:(E)=>{E._detachMedia?.(),E._detachMedia=null}}).opaque();function KH(A,Q){return QE(A,Q,(B)=>FA({className:"viewer image"},BE(rX({alt:A.name}),A,Q,B)))}function JH(A,Q){return QE(A,Q,(B)=>FA({className:"viewer",$styling:{display:"grid","place-items":"center",gap:"16px",padding:"40px"}},W("file-audio",{size:48}),OQ({$styling:{color:"var(--text-dim)"}},A.name),BE(AH({controls:!0,$styling:{width:"min(520px, 90%)"}}),A,Q,B)))}function YH(A,Q){return QE(A,Q,(B)=>FA({className:"viewer",$styling:{display:"grid","place-items":"center",background:"#000"}},BE(eX({controls:!0,$styling:{"max-width":"100%","max-height":"100%"}}),A,Q,B)))}function sJ(A,Q,B){return FA({className:"viewer"},FA({className:"fallback"},W(B?"warn":"file",{size:44}),OQ({$styling:{"font-weight":600}},A.name),OQ(`${A.contentType||"Unknown type"} · ${QA(A.size)}`),OQ({$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."),tX({className:"btn primary"},W("download",{size:15}),"Download").on({click:()=>Q.exec("explorer.download",A)})))}function LH(A,Q,B){return FA({className:"viewer plugin-viewer"},FA({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=(E)=>{C.style.display="grid",C.innerHTML="",C.appendChild(IH(E))}}}).opaque(),FA({className:"pv-host"}).on({$attach:(C)=>{let E=C.parentElement?.querySelector(".pv-status");C._detach=B.platform.plugins.mountViewer(A.pluginId,C,Q,A.id,{onReady:()=>E?._ready?.(),onError:(K)=>E?._error?.(K||"This viewer failed to load")})},$detach:(C)=>{C._detach?.(),C._detach=null}}).opaque())}function IH(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 iJ(A){return FA({className:"viewer"},FA({className:"fallback"},W("warn",{size:40}),OQ(A||"Failed to open")))}var{div:dQ,span:rJ,button:lQ}=w,KC=new Map;function JC(A,Q){let B=A.wb,C=A.nav.stack.filter((K)=>K.kind==="file");HH(C);let E=C[C.length-1];if(!E)return dQ({className:"editor"});return dQ({className:"editor"},DH(C,E,Q),dQ({className:"stage"},XH(E,Q)))}function DH(A,Q,B){let C=B.platform.workbench;return dQ({className:"viewer-nav"},lQ({className:"vn-back",title:"Back (Esc)"},W("chevron-left",{size:16})).on({click:()=>C.back()}),dQ({className:"vn-trail"},lQ({className:"vn-crumb"},W("search",{size:13}),rJ("Search")).on({click:()=>C.showHome()}),...A.map((E)=>lQ({className:`vn-crumb ${E.id===Q.id?"active":""}`,title:E.node.name},W(aA(E.node),{size:13}),rJ({className:"label"},E.node.name)).on({click:()=>C.openFile(E.node,E.openerId)}))),dQ({className:"vn-actions"},GH(Q,B),lQ({className:"iconbtn",title:"Details & comments"},W("info",{size:15})).on({click:()=>C.toggleInfoPanel()}),lQ({className:"iconbtn",title:"Close (Esc)"},W("close",{size:15})).on({click:()=>C.showHome()})))}function GH(A,Q){let B=aB(Q.platform,A.node);if(B.length<=1)return null;return lQ({className:"iconbtn",title:"Open with…"},W("dots",{size:15})).on({click:()=>Q.platform.workbench.showDialog({kind:"opener-chooser",node:A.node,openers:B,current:A.openerId})})}function XH(A,Q){let B=`${A.id}:${A.openerId}`,C=KC.get(B);if(!C)C=()=>aJ(A.node,A.openerId,Q),KC.set(B,C);return w.alias(C)().key(A.id)}function HH(A){let Q=new Set(A.map((B)=>`${B.id}:${B.openerId}`));for(let B of KC.keys())if(!Q.has(B))KC.delete(B)}var{div:TA,input:$H,span:IQ}=w;function CE(A,Q){let B=A.overlay.palette;if(!B)return null;let C=Q.platform.workbench,E=B.mode==="files"?B.query.trim()?A.se.paletteFiles||[]:[]:FH(A,Q,B.query),K=Math.min(B.index,Math.max(0,E.length-1)),J=(Y)=>{if(!Y)return;if(C.closePalette(),B.mode==="files")Q.go(new wA(Y.node));else Q.exec(Y.id)};return TA({},TA({className:"scrim"}).on({click:()=>C.closePalette()}),TA({className:"palette"},TA({className:"search"},W(B.mode==="files"?"search":"command",{size:18}),$H({type:"text",value:B.query,autofocus:!0,placeholder:B.mode==="files"?"Search files by name…":"Type a command…"}).on({input:(Y)=>PH(Q,Y.target.value),keydown:(Y)=>VH(Y,Q,E,K,J),$attach:(Y)=>{if(queueMicrotask(()=>Y.focus()),Y.value!==B.query)Y.value=B.query}})),TA({className:"results"},E.length?E.map((Y,I)=>{let D=()=>C.setPaletteIndex(I);return B.mode==="files"?RH(Y,I===K,J,D):UH(Y,I===K,Q,J,D)}):ZH(B,A))))}function ZH(A,Q){if(A.mode!=="files")return TA({className:"none"},"No matching commands");if(Q.se.paletteError)return TA({className:"none error"},W("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 UH(A,Q,B,C,E){let K=B.platform.keybindings.labelFor(A.id),J=B.platform.commands.isAvailable(A);return TA({className:`opt ${Q?"active":""} ${J?"":"unavailable"}`},IQ({className:"ico"},W(A.icon||"command",{size:16})),A.category?IQ({className:"cat"},A.category+" ›"):null,IQ({className:"title"},A.title),!J?IQ({className:"offline-tag"},"offline"):null,K?IQ({className:"kbd"},w.h("kbd",QB(WH(B,A.id)))):null).on({click:()=>C(A),mouseenter:E})}function WH(A,Q){let B=A.platform.keybindings.resolved().find((C)=>C.command===Q);return B?B.key:""}function RH(A,Q,B,C){return TA({className:`opt ${Q?"active":""}`},IQ({className:"ico"},W(aA(A.node),{size:16})),IQ({className:"title"},A.node.name),IQ({className:"sub"},A.node.contentType||"")).on({click:()=>B(A),mouseenter:C})}function FH(A,Q,B){let C=Q.platform.commands.paletteCommands(),E=B.trim().toLowerCase();if(!E)return C.slice(0,60);let K=[];for(let J of C){let Y=`${J.category||""} ${J.title}`.toLowerCase(),I=MH(Y,E);if(I>0)K.push([I,J])}return K.sort((J,Y)=>Y[0]-J[0]).slice(0,60).map((J)=>J[1])}function MH(A,Q){let B=0,C=0;for(let E of Q){let K=A.indexOf(E,C);if(K<0)return 0;B+=K===C?3:1,C=K+1}if(A.includes(Q))B+=10;return B}function VH(A,Q,B,C,E){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(),E(B[C]);else if(A.key==="Escape")A.preventDefault(),K.closePalette()}var tJ=null;function PH(A,Q){let B=A.platform.workbench;if(B.setPaletteQuery(Q),clearTimeout(tJ),B.overlay.state.palette?.mode!=="files")return;tJ=setTimeout(()=>A.go(new k0(Q)),200)}var{div:d,span:i,button:eJ,h3:U5,p:NH,label:qH,input:zH}=w,jQ={ref:null,grants:null};function QY(A,Q){let B=Q.platform.workbench,C=A.summary;if(jQ.ref!==A)jQ={ref:A,grants:new Set(C.capabilities.filter((K)=>!K.adminOnly||A.isAdmin).map((K)=>K.id))};let E=(K)=>{jQ.grants.has(K)?jQ.grants.delete(K):jQ.grants.add(K),Q.rerender?.()};return d({},d({className:"scrim"}).on({click:()=>B.closeDialog()}),d({className:"dialog review",$styling:{width:"min(560px, 96vw)"}},OH(C),d({className:"review-body"},C.description?NH({className:"review-desc"},C.description):null,nQ("Capabilities it requests",C.capabilities.length?d({className:"cap-list"},...C.capabilities.map((K)=>SH(K,A.isAdmin,jQ.grants.has(K.id),()=>E(K.id)))):gH("None — this plugin only runs in its sandbox.")),(C.network||[]).length?nQ("Network access",d({className:"contrib-list"},...C.network.map(_H))):null,(C.commands||[]).length?nQ("Commands it can run",d({className:"contrib-list"},...C.commands.map((K)=>TH(K,Q)))):null,C.storage?nQ("Storage",xH(C.storage)):null,C.contributions.length?nQ("What it adds",d({className:"contrib-list"},...C.contributions.map(wH))):null,C.settings.length?nQ("Settings",d({className:"contrib-list"},...C.settings.map(kH))):null,d({className:"review-meta"},`${C.fileCount} files · ${QA(C.sizeBytes)} · id ${C.id}`)),d({className:"row-actions"},eJ({className:"btn"},"Cancel").on({click:()=>B.closeDialog()}),eJ({className:"btn primary"},W("plug",{size:15}),"Install").on({click:()=>A.onInstall([...jQ.grants])}))))}function OH(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,i({className:"rh-ver"},"v"+A.version)),d({className:"rh-author"},"by "+A.author)),jH(Q))}function jH(A){if(A.status==="verified")return i({className:"trust verified",title:`Signed by a key published at ${A.domain}`},W("check",{size:13}),"Verified · "+A.domain);if(A.status==="signed")return i({className:"trust signed",title:A.reason||"Signed, but the domain does not vouch for the key"},W("info",{size:13}),"Signed");if(A.status==="invalid")return i({className:"trust invalid",title:A.reason||"Invalid signature — the package may have been tampered with"},W("warn",{size:13}),"Invalid signature");return i({className:"trust unverified",title:A.reason||"This plugin is not signed"},W("warn",{size:13}),"Unverified")}function SH(A,Q,B,C){let E=A.adminOnly&&!Q;return qH({className:`cap-row ${E?"blocked":""}`},zH({type:"checkbox",checked:B&&!E,disabled:E}).on({change:()=>!E&&C()}),d({className:"cap-info"},d({className:"cap-name"},A.id,A.adminOnly?i({className:"pf-badge",$styling:{color:"var(--warn)","margin-left":"6px"}},"admin only"):null),d({className:"cap-desc"},A.description+(E?" — requires an administrator":""))))}function wH(A){let Q={command:"command",opener:"file",indexer:"search",statusItem:"info",register:"info",keymap:"command"}[A.kind]||"command";return d({className:"contrib-row"},W(Q,{size:13}),i({className:"cr-title"},A.title),A.detail?i({className:"cr-detail"},A.detail):null,A.offline?i({className:"pf-badge offline-ok"},"offline"):null,i({className:"pf-kind"},A.kind))}function TH(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"}`},W("command",{size:13}),i({className:"cr-title"},B?.title||A),i({className:"cr-detail"},A),i({className:"pf-kind"},C))}function _H(A){return d({className:"contrib-row"},W("plug",{size:13}),i({className:"cr-title"},A.host),A.path?i({className:"cr-detail"},A.path):null,i({className:"pf-kind"},A.scheme))}function xH(A){let Q=[];if(A.plugin)Q.push(AY("Private database","A SQLite store just for this plugin (server + this device).",!1));if(A.domain)Q.push(AY("Shared database","Shared with other plugins from its domain (SQLite).",A.domainBlocked));return d({className:"contrib-list"},...Q)}function AY(A,Q,B){return d({className:`contrib-row ${B?"blocked":""}`},W("plug",{size:13}),i({className:"cr-title"},A),i({className:"cr-detail"},B?Q+" — needs a verified domain":Q),B?i({className:"pf-badge",$styling:{color:"var(--warn)"}},"unavailable"):null)}function kH(A){return d({className:"contrib-row"},W("gear",{size:13}),i({className:"cr-title"},A.title),A.secret?i({className:"pf-badge",$styling:{color:"var(--warn)"}},"secret"):i({className:"pf-kind"},A.type))}function nQ(A,Q){return d({className:"review-section"},d({className:"rs-title"},A),Q)}function gH(A){return d({className:"muted",$styling:{"font-size":"12.5px"}},A)}var{div:_,span:pA,button:yA,input:oQ,h3:KE,p:N5,select:yH,option:hH,label:aQ,textarea:q5}=w;function BY(A,Q){let B=A.overlay.dialog;if(!B)return null;if(B.kind==="collection")return bH(B,Q);if(B.kind==="plugin-review")return QY(B,Q);if(B.kind==="opener-chooser")return vH(B,Q);let C=Q.platform.workbench,E=B.value??"",K=()=>B.kind==="confirm"?B.onConfirm?.():B.onSubmit?.(E);return _({},_({className:"scrim"}).on({click:()=>C.closeDialog()}),_({className:"dialog"},KE(B.title),B.body?_({className:"body"},B.body):null,B.kind==="prompt"?_({className:"field"},B.label?pA({$styling:{"font-size":"12px",color:"var(--text-dim)"}},B.label):null,oQ({className:"input",value:B.value??"",placeholder:B.placeholder||"",autofocus:!0}).on({input:(J)=>{E=J.target.value},keydown:(J)=>{if(J.key==="Enter")K();if(J.key==="Escape")C.closeDialog()},$attach:(J)=>queueMicrotask(()=>{J.focus(),J.select()})})):null,_({className:"row-actions"},yA({className:"btn"},"Cancel").on({click:()=>C.closeDialog()}),yA({className:`btn ${B.danger?"danger":"primary"}`},B.confirmLabel||"OK").on({click:K}))))}function vH(A,Q){let B=Q.platform.workbench,C=Q.platform,E=A.openerId||A.current||A.openers[0]?.id,K=!!A.remember,J=()=>{if(K&&E)sB(C,iK(A.node),E);B.closeDialog(),B.openFile(A.node,E,{reset:!!A.reset})};return _({},_({className:"scrim"}).on({click:()=>B.closeDialog()}),_({className:"dialog opener-chooser"},KE(`Open “${A.node.name}” with…`),_({className:"opener-list"},...A.openers.map((Y)=>aQ({className:`opener-opt ${Y.id===E?"sel":""}`},oQ({type:"radio",name:"opener-choice",checked:Y.id===E}).on({change:()=>B.updateDialog({openerId:Y.id})}),W(Y.icon||aA(A.node),{size:18}),_({className:"oo-main"},pA({className:"oo-title"},Y.title||Y.id),pA({className:"oo-src"},AJ(C,Y)))).on({click:()=>B.updateDialog({openerId:Y.id})}))),aQ({className:"opener-remember"},oQ({type:"checkbox",checked:K}).on({change:(Y)=>B.updateDialog({remember:Y.target.checked})}),pA(`Always use this for ${rK(A.node)}`)),_({className:"row-actions"},yA({className:"btn"},"Cancel").on({click:()=>B.closeDialog()}),yA({className:"btn primary"},"Open").on({click:J}))))}var EE={ref:null,form:null};function bH(A,Q){let B=Q.platform.workbench,C=Q.platform.capabilities?.storageDrivers||[];if(EE.ref!==A)EE={ref:A,form:{name:"",description:"",driver:C[0]?.key||""}};let E=EE.form,K=C.find((L)=>L.key===E.driver)||C[0],J=(L)=>(G)=>{if(E[L]=G.target.type==="checkbox"?G.target.checked:G.target.value,L==="driver")Q.rerender?.()},Y=()=>{let L={driver:E.driver};for(let G of K?.fields||[]){let X=E[G.name];if(X!==void 0&&X!=="")L[G.name]=G.type==="number"?Number(X):X}A.onSubmit?.({name:E.name,description:E.description,store:L})},I=(L,G,X="")=>_({className:"field",$styling:{"margin-bottom":"10px"}},aQ(L),oQ({className:"input",placeholder:X}).on({input:J(G)})),D=!!E.name.trim()&&!!E.driver&&(K?.fields||[]).every((L)=>!L.required||String(E[L.name]??"").trim());return _({},_({className:"scrim"}).on({click:()=>B.closeDialog()}),_({className:"dialog",$styling:{width:"min(480px, 94vw)"}},KE("New collection"),_({className:"body"},"A collection is a backing store you own. Configure where its files live."),I("Name","name","Team Vault"),C.length?_({className:"field",$styling:{"margin-bottom":"10px"}},aQ("Backing store"),yH({className:"input"},...C.map((L)=>hH({value:L.key,selected:E.driver===L.key},L.label))).on({change:J("driver")})):_({className:"body"},"This server has no storage drivers registered, so a collection cannot be created."),K?fH(K,E,J):null,_({className:"row-actions"},yA({className:"btn"},"Cancel").on({click:()=>B.closeDialog()}),yA({className:"btn primary",$attrs:D?{}:{disabled:"true"}},"Create collection").on({click:()=>D&&Y()}))))}function fH(A,Q,B){if(!A.fields.length)return _({className:"body",$styling:{"font-size":"12px"}},A.description||"This store needs no configuration.");return _({},A.description?_({className:"body",$styling:{"font-size":"12px","margin-bottom":"10px"}},A.description):null,...A.fields.map((C)=>C.type==="boolean"?_({className:"field",$styling:{"margin-bottom":"10px"}},aQ({},oQ({type:"checkbox"}).on({change:B(C.name)}),` ${C.label}`),C.help?_({className:"body",$styling:{"font-size":"11.5px"}},C.help):null):_({className:"field",$styling:{"margin-bottom":"10px"}},aQ(C.label+(C.required?"":" (optional)")),oQ({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?_({className:"body",$styling:{"font-size":"11.5px"}},C.help):null)))}function CY(A,Q){let B=A.overlay.contextMenu;if(!B||!B.items?.length)return null;let C=Q.platform.workbench,E=Math.min(B.items.length*34+20,window.innerHeight-24),K=Math.max(8,Math.min(B.x,window.innerWidth-220)),J=Math.max(8,Math.min(B.y,window.innerHeight-E));return _({},_({className:"scrim",$styling:{background:"transparent"}}).on({click:()=>C.closeContextMenu(),contextmenu:(Y)=>{Y.preventDefault(),C.closeContextMenu()}}),_({className:"menu",$styling:{left:K+"px",top:J+"px"}},...B.items.map((Y,I)=>Y.sep?_({className:"sep"}):yA({className:`mi ${Y.danger?"danger":""}`,autofocus:I===0},Y.icon?W(Y.icon,{size:15}):null,pA(Y.label),Y.kbd?pA({className:"kbd"},Y.kbd):null).on({click:()=>{C.closeContextMenu(),Y.run?.()},keydown:(D)=>{if(D.key==="Escape")D.preventDefault(),C.closeContextMenu()},$attach:(D)=>{if(I===0)queueMicrotask(()=>D.focus())}}))))}function EY(A,Q){let B=A.notif||[];if(!B.length)return null;return _({className:"toasts"},...B.slice(-5).map((C)=>_({className:`toast ${C.level}`},_({className:"bar"}),_({className:"msg"},C.message),yA({className:"x"},W("close",{size:14})).on({click:()=>Q.platform.notifications.dismiss(C.id)})).key(C.id)))}function KY(A,Q){let B=A.tr.items;if(!B.length)return null;return _({className:"tray"},_({className:"head"},W("upload",{size:14}),pA({$styling:{"margin-left":"6px"}},"Transfers"),_({className:"actions"},yA({className:"iconbtn",title:"Clear finished"},W("check",{size:14})).on({click:()=>Q.app.transfers.clearDone()}))),_({className:"items"},...B.map((C)=>_({className:`xfer ${C.status}`},_({className:"top"},W(C.status==="error"?"warn":C.status==="done"?"check":"upload",{size:14}),pA({className:"name"},C.name),C.status==="active"?yA({className:"iconbtn",title:"Cancel"},W("close",{size:13})).on({click:()=>Q.app.transfers.cancel(C.id)}):pA({className:"pct"},C.status==="done"?QA(C.total):C.status)),C.status==="active"?_({className:"progress"},_({$styling:{width:`${Math.round(C.ratio*100)}%`}})):C.error?_({$styling:{"font-size":"11px",color:"var(--danger)","margin-top":"4px"}},C.error):null,C.status==="active"?_({className:"pct",$styling:{"margin-top":"4px"}},`${QA(C.loaded)} / ${QA(C.total)}`):null).key(C.id))))}function JY(A,Q){let B=A.overlay.pluginPanel;if(!B)return null;let C=(A.plugins||[]).find((E)=>E.id===B);return _({className:"plugin-panel",$styling:{width:"380px"}},_({className:"head"},W("plug",{size:14}),pA(C?.name||B),yA({className:"iconbtn x"},W("close",{size:14})).on({click:()=>Q.platform.workbench.closePluginPanel()})),_({className:"host"}).on({$attach:(E)=>{E._detach=Q.platform.plugins.mountPanel(B,E,{width:380,height:460})},$detach:(E)=>E._detach?.()}))}var{div:u,button:iA,span:WB,h3:uH,p:YY,pre:mH}=w,pH={running:"refresh",done:"check",failed:"close",cancelled:"close"};function cH(A,Q){navigator.clipboard?.writeText(A).then(()=>Q.platform.notifications.success("Copied")).catch(()=>Q.platform.notifications.info(A,{sticky:!0}))}function LY(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 IY(A,Q){let B=A.status==="running",C=B&&A.total!=null&&A.total>0,E=C?Math.min(100,Math.round((A.done||0)/A.total*100)):0;return u({className:`act-task act-${A.status}`,"data-task-id":A.id},u({className:"act-row"},B?u({className:"spinner",$styling:{width:"12px",height:"12px"}}):W(pH[A.status]||"info",{size:13}),u({className:"act-body"},u({className:"act-title"},A.title),A.detail?u({className:"act-detail"},A.detail):null,A.error?u({className:"act-error"},A.error):null),B&&A.cancellable?iA({className:"act-action",title:"Cancel"},W("close",{size:12})).on({click:()=>Q.app.activity.cancel(A.id)}):!B?iA({className:"act-action",title:"Dismiss"},W("close",{size:12})).on({click:()=>Q.app.activity.dismiss(A.id)}):null),B?u({className:`act-bar ${C?"":"indeterminate"}`},u({className:"act-fill",$styling:C?{width:`${E}%`}:{}})):null,B&&LY(A)?u({className:"act-amount"},LY(A)):null)}function lH(A,Q){let B=new Date(A.firstAt||A.lastAt).toLocaleString();return u({className:`act-issue act-sev-${A.severity||"error"}`,"data-issue-id":A.id},u({className:"act-row"},W(A.severity==="warning"?"info":"close",{size:13}),u({className:"act-body"},u({className:"act-title"},A.title),A.detail?u({className:"act-detail"},A.detail):null,A.remedy?mH({className:"act-remedy"},A.remedy):null,u({className:"act-meta"},A.count>1?`${A.count} times, since ${B}`:`since ${B}`))),u({className:"act-actions"},A.remedy?iA({className:"btn small ghost"},"Copy fix").on({click:()=>cH(A.remedy,Q)}):null,A.retryable?iA({className:"btn small act-retry"},W("refresh",{size:12}),WB("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 JE(A,Q){let B=A.act||{tasks:[],issues:[]};if(!B.open)return null;let C=B.tasks.filter((K)=>K.status==="running"),E=B.tasks.filter((K)=>K.status!=="running");return u({className:"activity-panel"},u({className:"act-head"},uH("Activity"),iA({className:"act-action",title:"Close"},W("close",{size:13})).on({click:()=>Q.app.activity.togglePanel(!1)})),B.tasksError||B.issuesError?u({className:"act-offline"},W("info",{size:12}),WB(`Couldn't reach the server — this list may be out of date (${B.issuesError||B.tasksError})`)):null,u({className:"act-section"},u({className:"act-section-title"},"Running"),C.length?u(...C.map((K)=>IY(K,Q))):YY({className:"act-empty"},"Nothing running.")),B.issues.length?u({className:"act-section"},u({className:"act-section-title"},`Needs attention (${B.issues.length})`),u(...B.issues.map((K)=>lH(K,Q)))):u({className:"act-section"},u({className:"act-section-title"},"Needs attention"),YY({className:"act-empty"},B.issuesError?"Could not load the list of problems.":B.issuesLoading?"Checking…":"No standing problems.")),E.length?u({className:"act-section"},u({className:"act-section-title"},"Recently finished"),u(...E.map((K)=>IY(K,Q)))):null,u({className:"act-foot act-actions"},iA({className:"btn small ghost act-rebuild"},W("refresh",{size:12}),WB("Rebuild search index")).on({click:()=>Q.exec("workbench.rebuildIndex")}),iA({className:"btn small ghost act-scan"},W("refresh",{size:12}),WB("Scan for outside changes")).on({click:()=>Q.exec("workbench.scanCollection")}),iA({className:"btn small ghost act-storage"},W("plug",{size:12}),WB("Check storage")).on({click:()=>Q.exec("workbench.checkStorage")})))}var{div:YA,button:SQ,span:cA,img:GY}=w,DY=[{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 dH(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 XY(A,Q){let B=tB(A,Q),C=dH(B),E=A.wb.activity==="settings"?"Settings":A.wb.activity==="plugins"?"Plugins":B.collectionLabel;return YA({className:"phonebar top"},SQ({className:"pb-brand",title:"Trove — home"},GY({src:"/icon.svg",alt:"Trove"})).on({click:()=>Q.exec("workbench.view.home")}),YA({className:"pb-title"},E),SQ({className:`pb-status ${C.tone}`,title:C.label,$attrs:{"aria-label":C.label}},C.spinner?YA({className:"spinner",$styling:{width:"15px",height:"15px"}}):W(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 HY(A,Q){let B=A.wb.activity,C=A.wb.sheet,E=A.so.notifications.unread;return YA({className:"phonebar bottom"},...DY.map((K)=>SQ({className:`pb-tab ${!C&&B===K.id?"active":""}`,$attrs:{"aria-label":K.label}},W(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&&!DY.some((K)=>K.id===B)?"active":""}`,$attrs:{"aria-label":"More"}},W("dots",{size:21}),E?cA({className:"pb-badge"},String(E>9?"9+":E)):null,cA({className:"pb-label"},"More")).on({click:()=>Q.platform.workbench.openSheet("more")}))}function MA({icon:A,label:Q,value:B,danger:C,onClick:E}){let K=[W(A,{size:18}),cA({className:"sr-label"},Q),B!=null?cA({className:"sr-value"},B):null,E?W("chevron-right",{size:16,className:"sr-go"}):null];return E?SQ({className:`sheet-row ${C?"danger":""}`},...K).on({click:E}):YA({className:"sheet-row static"},...K)}function $Y(A,Q){let B=A.wb.sheet;if(!B)return null;let C=Q.platform.workbench;return YA({className:"sheet-wrap"},YA({className:"scrim"}).on({click:()=>C.closeSheet()}),YA({className:"sheet"},YA({className:"sheet-grip"}).on({click:()=>C.closeSheet()}),B==="status"?nH(A,Q):oH(A,Q)))}function nH(A,Q){let B=tB(A,Q),C=Q.platform.workbench,E=(K)=>()=>{C.closeSheet(),Q.exec(K)};return YA({className:"sheet-body"},YA({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?YA({className:"sheet-row static usage"},W("download",{size:18}),cA({className:"sr-label"},"Free space"),p0({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,YA({className:"sheet-actions"},SQ({className:"btn small ghost"},W("refresh",{size:13}),cA("Scan for changes")).on({click:E("workbench.scanCollection")}),SQ({className:"btn small ghost"},W("refresh",{size:13}),cA("Activity")).on({click:()=>{Q.platform.workbench.closeSheet(),Q.app.activity.togglePanel(!0)}})))}function oH(A,Q){let B=Q.platform.workbench,C=(J)=>()=>{B.closeSheet(),Q.exec(J)},E=A.so.me,K=A.so.notifications.unread;return YA({className:"sheet-body"},E&&!E.anonymous?YA({className:"sheet-me"},E.picture?GY({src:E.picture,alt:"",className:"avatar-img"}):cA({className:"avatar-txt"},(E.name||E.id||"?")[0].toUpperCase()),YA({},YA({className:"sm-name"},E.name||E.id),E.email?YA({className:"sm-sub"},E.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:aH,div:wQ}=w;function YE({engine:A,app:Q,platform:B,plugins:C}){let E=b(0),K={engine:A,app:Q,platform:B,go:(I)=>A.dispatch(I),exec:(I,...D)=>B.commands.execute(I,...D),rerender:()=>E.update((I)=>I+1),uninstallPlugin:(I)=>C?.uninstall(I)},{watch:J}=B.reactive,Y=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(),E],(I,D,L,G,X,Z,R,F,P,g,f,M,S,O,y,p,T,x)=>({wb:I,overlay:D,nav:L,ex:G,se:X,keys:Z,tr:R,notif:F,ctx:P,settings:g,plugins:f,statusItems:M,so:S,off:O,act:y,vp:p,voice:T,_bump:x}));return aH(()=>J(Y,(I)=>sH(I,K)))}function sH(A,Q){let B=A.vp?.mode||"desktop",C=B==="phone";return wQ({className:`shell ${B} ${A.settings["workbench.density"]==="compact"?"compact":""}`},C?XY(A,Q):null,wQ({className:"body"},C?null:m0(A,Q),iH(A,Q)),C?HY(A,Q):c0(A,Q),C?$Y(A,Q):null,rH(A,Q),CE(A,Q),BY(A,Q),CY(A,Q),JY(A,Q),EY(A,Q),KY(A,Q),JE(A,Q))}function iH(A,Q){if(A.ex?.gate&&A.wb.activity!=="settings")return i0(A,Q);switch(A.wb.activity){case"settings":return o0(A,Q);case"plugins":return t0(A,Q);default:{if(!A.nav.activeTabId)return EC(A,Q);if(!A.wb.infoPanel)return JC(A,Q);return A.vp?.mode==="phone"?f0(A,Q):wQ({className:"editor-split"},JC(A,Q),f0(A,Q))}}}function rH(A,Q){if(!A.wb.searchModal)return wQ();return wQ({className:"search-modal"},wQ({className:"scrim"}).on({click:()=>Q.platform.workbench.closeSearchModal()}),wQ({className:"search-modal-panel"},EC(A,Q,{modal:!0})))}function UY({root:A=document.querySelector(".workbench"),baseUrl:Q="",openers:B=[],views:C=[],settings:E=[],serviceWorker:K=!0}={}){let J=hK({baseUrl:Q}),{engine:Y,app:I}=JJ(J);if(oJ(J),PJ(J),ZY(J,"opener",B),ZY(J,"view",C),E.length)J.settings.register(E);J.plugins.restore();let L=YE({engine:Y,app:I,platform:J,plugins:{uninstall:(X)=>J.plugins.uninstall(X)}});w.reconcile(A,[L()]);let G=()=>{document.documentElement.dataset.theme=J.settings.get("workbench.theme")||"dark"};if(G(),xA(J.settings.observe(),()=>G()),J.viewport.install(),J.voice.refresh().catch(()=>{}),J.spatialNav.install(),J.keybindings.install(window),window.addEventListener("popstate",(X)=>J.workbench.onPopState(X)),tH(J),K&&"serviceWorker"in navigator)window.addEventListener("load",()=>navigator.serviceWorker.register("/sw.js").catch(()=>{}));return eH(Y,I),(async()=>{try{J.capabilities=await J.api.capabilities(),J.workbench.touch()}catch(X){J.notifications.error(`Cannot reach the Trove server: ${X.message}`)}Y.dispatch(new rB)})(),window.__trove={platform:J,engine:Y,app:I,test:{parsePackage:WQ,assessTrust:(X)=>J.plugins.assessTrust(X),install:(X,Z)=>J.plugins.install(X,Z),NavigateAction:SA,attachMedia:uQ}},{platform:J,engine:Y,app:I}}function ZY(A,Q,B){for(let C of B){if(!C?.id)throw Error(`A ${Q} passed to createWorkbench needs an "id"`);let{id:E,...K}=C;A.contributions.register(E,{type:Q,...K})}}function tH(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 eH(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 XB(C.dataTransfer.files,Q.explorer.state.collectionId))})}UY();
|
|
354
|
+
|
|
355
|
+
//# debugId=B4E40DB6D02BBBB864756E2164756E21
|
|
356
|
+
//# sourceMappingURL=main-f0f2tfhp.js.map
|