@ai4b-team/fsaos-gateway-sdk 3.16.0 → 3.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
- /* @fsaos/gateway v2.0.0 — Unified FSAOS Edge Runtime — 2026-08-08T17:46:32.268Z */
2
- "use strict";var __FSAOS_GATEWAY__=(()=>{var va=Object.create;var Wt=Object.defineProperty;var ba=Object.getOwnPropertyDescriptor;var wa=Object.getOwnPropertyNames;var Sa=Object.getPrototypeOf,Ra=Object.prototype.hasOwnProperty;var bs=e=>{throw TypeError(e)};var Ca=(e,t,n)=>t in e?Wt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Bt=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),xa=(e,t)=>{for(var n in t)Wt(e,n,{get:t[n],enumerable:!0})},ws=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of wa(t))!Ra.call(e,s)&&s!==n&&Wt(e,s,{get:()=>t[s],enumerable:!(r=ba(t,s))||r.enumerable});return e};var j=(e,t,n)=>(n=e!=null?va(Sa(e)):{},ws(t||!e||!e.__esModule?Wt(n,"default",{value:e,enumerable:!0}):n,e)),Pa=e=>ws(Wt({},"__esModule",{value:!0}),e);var $t=(e,t,n)=>Ca(e,typeof t!="symbol"?t+"":t,n),Sr=(e,t,n)=>t.has(e)||bs("Cannot "+n);var o=(e,t,n)=>(Sr(e,t,"read from private field"),n?n.call(e):t.get(e)),b=(e,t,n)=>t.has(e)?bs("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),_=(e,t,n,r)=>(Sr(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n),x=(e,t,n)=>(Sr(e,t,"access private method"),n);var Gt=(e,t,n,r)=>({set _(s){_(e,t,s,n)},get _(){return o(e,t,r)}});var Rs=Bt((xc,Ss)=>{Ss.exports={createClient:window.supabase.createClient}});var ie=Bt((Al,hi)=>{hi.exports=React});var Gn=Bt((Ml,mi)=>{mi.exports={jsx:React.createElement,jsxs:React.createElement,Fragment:React.Fragment}});var $i=Bt((Cd,Bi)=>{Bi.exports=ReactDOM});var ao=Bt((Od,oo)=>{oo.exports=ReactDOM});var vs={};xa(vs,{ComponentRenderer:()=>Ho,EnforcementDeniedError:()=>ft,KernelProvider:()=>Wo,QueryClientProvider:()=>hn,auth:()=>ro,awaitAnchorReady:()=>Xt,awaitScopeReady:()=>ks,callTool:()=>eo,clearCachedToken:()=>Er,clearSession:()=>kr,createItem:()=>Yi,disconnectSSE:()=>cs,disposeVfsRealtimeWs:()=>mr,electHomeAnchor:()=>Zt,emitEvent:()=>ji,fetchChannelMessages:()=>Ii,fetchChannelMessagesPage:()=>bn,fetchChannelMessagesWithCards:()=>ur,fetchEdgesForItem:()=>rr,fetchItemHistory:()=>or,fetchItemVersions:()=>_n,fetchItems:()=>vn,fetchMemberFocus:()=>ar,fetchOpenEnvelope:()=>cr,fetchRecentActivity:()=>ir,fetchResolvedItems:()=>ys,fetchTimelineHistory:()=>_s,fetchTypeDefinitions:()=>nr,fetchVfsChildren:()=>er,fetchVfsChildrenPage:()=>tr,fetchVfsItem:()=>Zn,fetchVfsItemById:()=>Xn,fetchVfsTree:()=>sr,gatewayCall:()=>R,getAccessToken:()=>xe,getAnchor:()=>Yt,getAnchorRef:()=>Xe,getAnchorVersion:()=>Mr,getAssetUrl:()=>no,getDefaultSort:()=>ca,getHomeAnchor:()=>Ue,getMountVersion:()=>tn,getMounts:()=>mt,getQueryClient:()=>P,getRequiredFormFields:()=>ua,getScope:()=>le,getScopeVersion:()=>_e,getSessionEntry:()=>Qn,initSession:()=>Dn,initVfsRealtimeWs:()=>xn,interpretSchema:()=>gs,invalidateAllVfs:()=>qi,invalidateChannelMessages:()=>Qi,invalidateChildren:()=>Yn,invalidateItem:()=>os,invalidateOpenEnvelope:()=>Ui,invalidatePathAndParent:()=>Fi,invalidateSubtree:()=>ki,invalidateTypes:()=>Di,isAnchorReady:()=>Ir,isScopeReady:()=>Un,listChildren:()=>Ji,mount:()=>so,mountRealtimeScope:()=>Pn,normalizeItem:()=>pe,ping:()=>Vi,pushChanges:()=>Zi,queryClient:()=>Ti,readItem:()=>zi,registerCleanup:()=>Pe,resetAllSdkState:()=>gt,resolvePrincipalId:()=>Lo,setAnchor:()=>Qe,setCachedToken:()=>Ps,setQueryClient:()=>Ei,setScope:()=>Fs,setupRequireShim:()=>io,signal:()=>to,subscribeAnchor:()=>Or,subscribeArtifactStream:()=>vr,subscribeMounts:()=>qn,subscribeScope:()=>Ze,subscribeToEvents:()=>J,subscribeToPath:()=>dr,subscribeToScope:()=>fr,unmountRealtimeScope:()=>Wi,updateItem:()=>Xi,uploadFile:()=>la,useAccounts:()=>Io,useAgentTimeline:()=>ga,useAllChannels:()=>_r,useArrangement:()=>oa,useArtifactStream:()=>ma,useAsset:()=>ko,useAuth:()=>yr,useChannelMessages:()=>Bo,useChannels:()=>Go,useChildren:()=>go,useComponent:()=>hs,useCreate:()=>Yo,useDelete:()=>ea,useDmChannels:()=>zo,useEdges:()=>Ro,useEventStream:()=>sa,useFileUpload:()=>fa,useInfiniteChannelMessages:()=>$o,useInfiniteChildren:()=>So,useInfiniteItems:()=>wo,useItem:()=>ho,useItemById:()=>mo,useItemHistory:()=>Ao,useItemVersions:()=>To,useItems:()=>bo,useLink:()=>na,useList:()=>ps,useMemberFocus:()=>Eo,useMounts:()=>Fo,useMove:()=>ta,useMutation:()=>ra,useNotifications:()=>ms,useOpen:()=>xo,usePermission:()=>Uo,usePermissions:()=>No,usePrincipal:()=>jo,useRealtimeQuery:()=>ia,useRecentActivity:()=>Mo,useResolve:()=>vo,useResolvedItems:()=>ha,useScope:()=>Oo,useScopeReady:()=>po,useSearch:()=>_o,useTheme:()=>Qo,useTimelineHistory:()=>ya,useTool:()=>Vo,useTree:()=>yo,useType:()=>Co,useTypeHelpers:()=>Po,useTypes:()=>gr,useUnreadCounts:()=>Jo,useUpdate:()=>Xo,useUpdatePrincipal:()=>Zo,vfsKeys:()=>w});var ft=class e extends Error{constructor(n){let r=n.message||e.fallbackMessage(n);super(r);$t(this,"name","EnforcementDeniedError");$t(this,"deniedBy");$t(this,"ruleKey");$t(this,"displayName");this.deniedBy=n.denied_by||n.error_type||n.error||"unknown";let s=n.enforcement;this.ruleKey=s?.rule_key??void 0,this.displayName=s?.display_name??void 0}static fallbackMessage(n){let r=n.error||"",s=n.denied_by||"";return s==="rule"||r==="RULE_DENIED"?"This feature is not enabled for this workspace.":s==="entitlement"||r==="ENTITLEMENT_REQUIRED"?"This feature requires a plan upgrade.":s==="access"||r==="ACCESS_DENIED"||r==="PERMISSION_DENIED"?"You don't have permission to do this.":"This action is not allowed."}get isRuleDenial(){return this.deniedBy==="rule"||this.deniedBy==="RULE_DENIED"}get isAccessDenial(){return this.deniedBy==="access"||this.deniedBy==="ACCESS_DENIED"}get isEntitlementDenial(){return this.deniedBy==="entitlement"||this.deniedBy==="ENTITLEMENT_REQUIRED"}};var Cs=j(Rs(),1),Rr=typeof window<"u"&&window.__FSAOS_CONFIG__||{},Ea=Rr.supabaseUrl||"https://vahbmsslxuustnlvsrkg.supabase.co",Ta=Rr.supabaseAnonKey||"sb_publishable_ZjosozAjfpZ4InMNElTr6Q_hHB-f5nc",De=Rr.gatewayUrl||"https://fsaos-mcp-gw-rust.fly.dev",F=(0,Cs.createClient)(Ea,Ta,{auth:{persistSession:!0,autoRefreshToken:!0,detectSessionInUrl:!1}});var Jt=null,Mn=0,xs,Pr,On=!1;xs=new Promise(e=>{Pr=e});F.auth.onAuthStateChange((e,t)=>{t?.access_token?(Jt=t.access_token,Mn=t.expires_at??Math.floor(Date.now()/1e3)+3600):(Jt=null,Mn=0),On||(On=!0,Pr())});setTimeout(()=>{On||(On=!0,Pr())},5e3);function Ps(e,t){Jt=e,Mn=t??Math.floor(Date.now()/1e3)+3600}function Er(){Jt=null,Mn=0}async function xe(){let e=typeof window<"u"&&window.__FSAOS_CONFIG__||{};if(e.embedToken){if(typeof e.embedToken=="function")try{return await e.embedToken()??null}catch{return null}return e.embedToken}return await xs,Jt}var In=null,kn=null,Es=0,Cr=new Set,Tr,Ar,Fn=!1;Tr=new Promise(e=>{Ar=e});function Ts(){Es++,Cr.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Anchor listener error:",t)}})}function Qe(e){let t=typeof e=="string"?e:e.path,n=In!==t;In=t,kn=typeof e=="string"?null:e,typeof e!="string"&&!ae.some(r=>r.id===e.id)&&(ae=[...ae,e],en()),Fn||(Fn=!0,Ar()),n&&Ts()}function Yt(){return In}function Xe(){return kn}function Mr(){return Es}function Or(e){return Cr.add(e),()=>{Cr.delete(e)}}function Xt(){return Tr}function Ir(){return Fn}var ht=null;function Zt(e){if(ht){console.warn("[SDK] electHomeAnchor called twice; ignoring (logout to re-elect).");return}ht=e,Qe(e)}function Ue(){return ht}var ae=[],xr=new Set,As=0;function en(){As++,xr.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Mount listener error:",t)}})}function mt(){return ae}function tn(){return As}function qn(e){return xr.add(e),()=>{xr.delete(e)}}function Fr(e){ae=e,en()}function Ms(e){ae.some(t=>t.id===e.id)||(ae=[...ae,e],en())}function Os(e){ae.find(n=>n.id===e)&&(ae=ae.filter(n=>n.id!==e),en(),kn?.id===e&&ht&&Qe(ht))}var pt=null,zt=null;async function Dn(){return pt||zt||(zt=(async()=>{let e=qr(),t=await xe(),n={};t&&(n.Authorization=`Bearer ${t}`);let r=await fetch(`${De}/d/${e}/init`,{method:"GET",headers:n});if(!r.ok)throw new Error(`Session init failed: ${r.status} ${r.statusText}`);let s=await r.json(),i=s.entry||s;return pt={scope_id:i.scope_id,scope_path:i.scope_path,instance_path:i.instance_path||"/root",fractal_id:i.fractal_id||null,instance_name:i.instance_name||null,display_name:i.scope_display_name||i.display_name||null},pt})(),zt)}function Qn(){return pt}function kr(){pt=null,zt=null,In=null,kn=null,ht=null,ae=[]}var Is=[];function Pe(e){Is.push(e)}function gt(){kr(),Er(),Fn=!1,Tr=new Promise(e=>{Ar=e}),Ts(),en();for(let e of Is)try{e()}catch(t){console.warn("[SDK] Cleanup function failed:",t)}}function qr(){if(typeof window<"u"){let e=window.__FSAOS_CONFIG__;return e?.hostname?e.hostname:window.location.hostname}return"localhost"}var Fs=Qe,le=Yt,_e=Mr,Ze=Or,ks=Xt,Un=Ir;var Aa=new Set(["list-memberships","init"]);async function R(e,t={}){let n=qr(),r=`${De}/d/${n}`,s={"Content-Type":"application/json"},i=await xe();i&&(s.Authorization=`Bearer ${i}`),!Aa.has(e)&&!t._scope_path&&await Xt();let a={...t},c=Qn();!a.domain_scope_id&&c?.scope_id&&(a.domain_scope_id=c.scope_id);let u=Yt();!a._scope_path&&u&&(a._scope_path=u);let d=await fetch(r,{method:"POST",headers:s,body:JSON.stringify({method:e,params:a})});if(!d.ok)throw new Error(`Gateway HTTP error: ${d.status} ${d.statusText}`);let l=await d.json();if(l.success===!1){let p=l.error||"",f=l.denied_by||l.error_type||"";throw f==="rule"||f==="access"||f==="entitlement"||p==="RULE_DENIED"||p==="ACCESS_DENIED"||p==="PERMISSION_DENIED"||p==="ENTITLEMENT_REQUIRED"?new ft(l):new Error(l.message||l.error||`Gateway call ${e} failed`)}return l}var ce=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}};var et,Ne,yt,qs,Ma=(qs=class extends ce{constructor(){super();b(this,et);b(this,Ne);b(this,yt);_(this,yt,t=>{if(typeof window<"u"&&window.addEventListener){let n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){o(this,Ne)||this.setEventListener(o(this,yt))}onUnsubscribe(){var t;this.hasListeners()||((t=o(this,Ne))==null||t.call(this),_(this,Ne,void 0))}setEventListener(t){var n;_(this,yt,t),(n=o(this,Ne))==null||n.call(this),_(this,Ne,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){o(this,et)!==t&&(_(this,et,t),this.onFocus())}onFocus(){let t=this.isFocused();this.listeners.forEach(n=>{n(t)})}isFocused(){return typeof o(this,et)=="boolean"?o(this,et):globalThis.document?.visibilityState!=="hidden"}},et=new WeakMap,Ne=new WeakMap,yt=new WeakMap,qs),_t=new Ma;var Oa={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},Ke,Dr,Ds,Ia=(Ds=class{constructor(){b(this,Ke,Oa);b(this,Dr,!1)}setTimeoutProvider(e){_(this,Ke,e)}setTimeout(e,t){return o(this,Ke).setTimeout(e,t)}clearTimeout(e){o(this,Ke).clearTimeout(e)}setInterval(e,t){return o(this,Ke).setInterval(e,t)}clearInterval(e){o(this,Ke).clearInterval(e)}},Ke=new WeakMap,Dr=new WeakMap,Ds),ve=new Ia;function Qs(e){setTimeout(e,0)}var Ur=typeof window>"u"||"Deno"in globalThis;function q(){}function Ks(e,t){return typeof e=="function"?e(t):e}function nn(e){return typeof e=="number"&&e>=0&&e!==1/0}function Nn(e,t){return Math.max(e+(t||0)-Date.now(),0)}function de(e,t){return typeof e=="function"?e(t):e}function X(e,t){return typeof e=="function"?e(t):e}function Kn(e,t){let{type:n="all",exact:r,fetchStatus:s,predicate:i,queryKey:a,stale:c}=e;if(a){if(r){if(t.queryHash!==rn(a,t.options))return!1}else if(!tt(t.queryKey,a))return!1}if(n!=="all"){let u=t.isActive();if(n==="active"&&!u||n==="inactive"&&u)return!1}return!(typeof c=="boolean"&&t.isStale()!==c||s&&s!==t.state.fetchStatus||i&&!i(t))}function Ln(e,t){let{exact:n,status:r,predicate:s,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(be(t.options.mutationKey)!==be(i))return!1}else if(!tt(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||s&&!s(t))}function rn(e,t){return(t?.queryKeyHashFn||be)(e)}function be(e){return JSON.stringify(e,(t,n)=>Qr(n)?Object.keys(n).sort().reduce((r,s)=>(r[s]=n[s],r),{}):n)}function tt(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>tt(e[n],t[n])):!1}var Fa=Object.prototype.hasOwnProperty;function Nr(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=Us(e)&&Us(t);if(!r&&!(Qr(e)&&Qr(t)))return t;let i=(r?e:Object.keys(e)).length,a=r?t:Object.keys(t),c=a.length,u=r?new Array(c):{},d=0;for(let l=0;l<c;l++){let p=r?l:a[l],f=e[p],h=t[p];if(f===h){u[p]=f,(r?l<i:Fa.call(e,p))&&d++;continue}if(f===null||h===null||typeof f!="object"||typeof h!="object"){u[p]=h;continue}let v=Nr(f,h,n+1);u[p]=v,v===f&&d++}return i===c&&d===i?e:u}function vt(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(let n in e)if(e[n]!==t[n])return!1;return!0}function Us(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Qr(e){if(!Ns(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!Ns(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function Ns(e){return Object.prototype.toString.call(e)==="[object Object]"}function Ls(e){return new Promise(t=>{ve.setTimeout(t,e)})}function sn(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?Nr(e,t):t}function js(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function Vs(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var bt=Symbol();function jn(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===bt?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function wt(e,t){return typeof e=="function"?e(...t):!!e}function Hs(e,t,n){let r=!1,s;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(s??(s=t()),r||(r=!0,s.aborted?n():s.addEventListener("abort",n,{once:!0})),s)}),e}var we=(()=>{let e=()=>Ur;return{isServer(){return e()},setIsServer(t){e=t}}})();function on(){let e,t,n=new Promise((s,i)=>{e=s,t=i});n.status="pending",n.catch(()=>{});function r(s){Object.assign(n,s),delete n.resolve,delete n.reject}return n.resolve=s=>{r({status:"fulfilled",value:s}),e(s)},n.reject=s=>{r({status:"rejected",reason:s}),t(s)},n}var Ws=Qs;function ka(){let e=[],t=0,n=c=>{c()},r=c=>{c()},s=Ws,i=c=>{t?e.push(c):s(()=>{n(c)})},a=()=>{let c=e;e=[],c.length&&s(()=>{r(()=>{c.forEach(u=>{n(u)})})})};return{batch:c=>{let u;t++;try{u=c()}finally{t--,t||a()}return u},batchCalls:c=>(...u)=>{i(()=>{c(...u)})},schedule:i,setNotifyFunction:c=>{n=c},setBatchNotifyFunction:c=>{r=c},setScheduler:c=>{s=c}}}var I=ka();var St,Le,Rt,Bs,qa=(Bs=class extends ce{constructor(){super();b(this,St,!0);b(this,Le);b(this,Rt);_(this,Rt,t=>{if(typeof window<"u"&&window.addEventListener){let n=()=>t(!0),r=()=>t(!1);return window.addEventListener("online",n,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}}})}onSubscribe(){o(this,Le)||this.setEventListener(o(this,Rt))}onUnsubscribe(){var t;this.hasListeners()||((t=o(this,Le))==null||t.call(this),_(this,Le,void 0))}setEventListener(t){var n;_(this,Rt,t),(n=o(this,Le))==null||n.call(this),_(this,Le,t(this.setOnline.bind(this)))}setOnline(t){o(this,St)!==t&&(_(this,St,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return o(this,St)}},St=new WeakMap,Le=new WeakMap,Rt=new WeakMap,Bs),Ct=new qa;function Da(e){return Math.min(1e3*2**e,3e4)}function Kr(e){return(e??"online")==="online"?Ct.isOnline():!0}var Vn=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function Hn(e){let t=!1,n=0,r,s=on(),i=()=>s.status!=="pending",a=m=>{if(!i()){let g=new Vn(m);f(g),e.onCancel?.(g)}},c=()=>{t=!0},u=()=>{t=!1},d=()=>_t.isFocused()&&(e.networkMode==="always"||Ct.isOnline())&&e.canRun(),l=()=>Kr(e.networkMode)&&e.canRun(),p=m=>{i()||(r?.(),s.resolve(m))},f=m=>{i()||(r?.(),s.reject(m))},h=()=>new Promise(m=>{r=g=>{(i()||d())&&m(g)},e.onPause?.()}).then(()=>{r=void 0,i()||e.onContinue?.()}),v=()=>{if(i())return;let m,g=n===0?e.initialPromise:void 0;try{m=g??e.fn()}catch(S){m=Promise.reject(S)}Promise.resolve(m).then(p).catch(S=>{if(i())return;let C=e.retry??(we.isServer()?0:3),E=e.retryDelay??Da,Q=typeof E=="function"?E(n,S):E,L=C===!0||typeof C=="number"&&n<C||typeof C=="function"&&C(n,S);if(t||!L){f(S);return}n++,e.onFail?.(n,S),Ls(Q).then(()=>d()?void 0:h()).then(()=>{t?f(S):v()})})};return{promise:s,status:()=>s.status,cancel:a,continue:()=>(r?.(),s),cancelRetry:c,continueRetry:u,canStart:l,start:()=>(l()?v():h().then(v),s)}}var nt,$s,Wn=($s=class{constructor(){b(this,nt)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),nn(this.gcTime)&&_(this,nt,ve.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(we.isServer()?1/0:5*60*1e3))}clearGcTimeout(){o(this,nt)!==void 0&&(ve.clearTimeout(o(this,nt)),_(this,nt,void 0))}},nt=new WeakMap,$s);var rt,xt,ue,st,V,an,it,se,Xs,Ee,Js,Ys=(Js=class extends Wn{constructor(t){super();b(this,se);b(this,rt);b(this,xt);b(this,ue);b(this,st);b(this,V);b(this,an);b(this,it);_(this,it,!1),_(this,an,t.defaultOptions),this.setOptions(t.options),this.observers=[],_(this,st,t.client),_(this,ue,o(this,st).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,_(this,rt,zs(this.options)),this.state=t.state??o(this,rt),this.scheduleGc()}get meta(){return this.options.meta}get promise(){return o(this,V)?.promise}setOptions(t){if(this.options={...o(this,an),...t},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let n=zs(this.options);n.data!==void 0&&(this.setState(Gs(n.data,n.dataUpdatedAt)),_(this,rt,n))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&o(this,ue).remove(this)}setData(t,n){let r=sn(this.state.data,t,this.options);return x(this,se,Ee).call(this,{data:r,type:"success",dataUpdatedAt:n?.updatedAt,manual:n?.manual}),r}setState(t,n){x(this,se,Ee).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){let n=o(this,V)?.promise;return o(this,V)?.cancel(t),n?n.then(q).catch(q):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return o(this,rt)}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(t=>X(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===bt||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>de(t.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(t=>t.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(t=0){return this.state.data===void 0?!0:t==="static"?!1:this.state.isInvalidated?!0:!Nn(this.state.dataUpdatedAt,t)}onFocus(){this.observers.find(n=>n.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),o(this,V)?.continue()}onOnline(){this.observers.find(n=>n.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),o(this,V)?.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),o(this,ue).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(n=>n!==t),this.observers.length||(o(this,V)&&(o(this,it)||x(this,se,Xs).call(this)?o(this,V).cancel({revert:!0}):o(this,V).cancelRetry()),this.scheduleGc()),o(this,ue).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||x(this,se,Ee).call(this,{type:"invalidate"})}async fetch(t,n){if(this.state.fetchStatus!=="idle"&&o(this,V)?.status()!=="rejected"){if(this.state.data!==void 0&&n?.cancelRefetch)this.cancel({silent:!0});else if(o(this,V))return o(this,V).continueRetry(),o(this,V).promise}if(t&&this.setOptions(t),!this.options.queryFn){let u=this.observers.find(d=>d.options.queryFn);u&&this.setOptions(u.options)}let r=new AbortController,s=u=>{Object.defineProperty(u,"signal",{enumerable:!0,get:()=>(_(this,it,!0),r.signal)})},i=()=>{let u=jn(this.options,n),l=(()=>{let p={client:o(this,st),queryKey:this.queryKey,meta:this.meta};return s(p),p})();return _(this,it,!1),this.options.persister?this.options.persister(u,l,this):u(l)},c=(()=>{let u={fetchOptions:n,options:this.options,queryKey:this.queryKey,client:o(this,st),state:this.state,fetchFn:i};return s(u),u})();this.options.behavior?.onFetch(c,this),_(this,xt,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==c.fetchOptions?.meta)&&x(this,se,Ee).call(this,{type:"fetch",meta:c.fetchOptions?.meta}),_(this,V,Hn({initialPromise:n?.initialPromise,fn:c.fetchFn,onCancel:u=>{u instanceof Vn&&u.revert&&this.setState({...o(this,xt),fetchStatus:"idle"}),r.abort()},onFail:(u,d)=>{x(this,se,Ee).call(this,{type:"failed",failureCount:u,error:d})},onPause:()=>{x(this,se,Ee).call(this,{type:"pause"})},onContinue:()=>{x(this,se,Ee).call(this,{type:"continue"})},retry:c.options.retry,retryDelay:c.options.retryDelay,networkMode:c.options.networkMode,canRun:()=>!0}));try{let u=await o(this,V).start();if(u===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(u),o(this,ue).config.onSuccess?.(u,this),o(this,ue).config.onSettled?.(u,this.state.error,this),u}catch(u){if(u instanceof Vn){if(u.silent)return o(this,V).promise;if(u.revert){if(this.state.data===void 0)throw u;return this.state.data}}throw x(this,se,Ee).call(this,{type:"error",error:u}),o(this,ue).config.onError?.(u,this),o(this,ue).config.onSettled?.(this.state.data,u,this),u}finally{this.scheduleGc()}}},rt=new WeakMap,xt=new WeakMap,ue=new WeakMap,st=new WeakMap,V=new WeakMap,an=new WeakMap,it=new WeakMap,se=new WeakSet,Xs=function(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"},Ee=function(t){let n=r=>{switch(t.type){case"failed":return{...r,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,...Lr(r.data,this.options),fetchMeta:t.meta??null};case"success":let s={...r,...Gs(t.data,t.dataUpdatedAt),dataUpdateCount:r.dataUpdateCount+1,...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return _(this,xt,t.manual?s:void 0),s;case"error":let i=t.error;return{...r,error:i,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...t.state}}};this.state=n(this.state),I.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),o(this,ue).notify({query:this,type:"updated",action:t})})},Js);function Lr(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Kr(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function Gs(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function zs(e){let t=typeof e.initialData=="function"?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var Z,T,un,z,ot,Pt,Te,je,ln,Et,Tt,at,ct,Ve,At,M,cn,jr,Vr,Hr,Wr,Br,$r,Gr,ni,ti,dn=(ti=class extends ce{constructor(t,n){super();b(this,M);b(this,Z);b(this,T);b(this,un);b(this,z);b(this,ot);b(this,Pt);b(this,Te);b(this,je);b(this,ln);b(this,Et);b(this,Tt);b(this,at);b(this,ct);b(this,Ve);b(this,At,new Set);this.options=n,_(this,Z,t),_(this,je,null),_(this,Te,on()),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(o(this,T).addObserver(this),Zs(o(this,T),this.options)?x(this,M,cn).call(this):this.updateResult(),x(this,M,Wr).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return zr(o(this,T),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return zr(o(this,T),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,x(this,M,Br).call(this),x(this,M,$r).call(this),o(this,T).removeObserver(this)}setOptions(t){let n=this.options,r=o(this,T);if(this.options=o(this,Z).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof X(this.options.enabled,o(this,T))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");x(this,M,Gr).call(this),o(this,T).setOptions(this.options),n._defaulted&&!vt(this.options,n)&&o(this,Z).getQueryCache().notify({type:"observerOptionsUpdated",query:o(this,T),observer:this});let s=this.hasListeners();s&&ei(o(this,T),r,this.options,n)&&x(this,M,cn).call(this),this.updateResult(),s&&(o(this,T)!==r||X(this.options.enabled,o(this,T))!==X(n.enabled,o(this,T))||de(this.options.staleTime,o(this,T))!==de(n.staleTime,o(this,T)))&&x(this,M,jr).call(this);let i=x(this,M,Vr).call(this);s&&(o(this,T)!==r||X(this.options.enabled,o(this,T))!==X(n.enabled,o(this,T))||i!==o(this,Ve))&&x(this,M,Hr).call(this,i)}getOptimisticResult(t){let n=o(this,Z).getQueryCache().build(o(this,Z),t),r=this.createResult(n,t);return Ua(this,r)&&(_(this,z,r),_(this,Pt,this.options),_(this,ot,o(this,T).state)),r}getCurrentResult(){return o(this,z)}trackResult(t,n){return new Proxy(t,{get:(r,s)=>(this.trackProp(s),n?.(s),s==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&o(this,Te).status==="pending"&&o(this,Te).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(r,s))})}trackProp(t){o(this,At).add(t)}getCurrentQuery(){return o(this,T)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){let n=o(this,Z).defaultQueryOptions(t),r=o(this,Z).getQueryCache().build(o(this,Z),n);return r.fetch().then(()=>this.createResult(r,n))}fetch(t){return x(this,M,cn).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),o(this,z)))}createResult(t,n){let r=o(this,T),s=this.options,i=o(this,z),a=o(this,ot),c=o(this,Pt),d=t!==r?t.state:o(this,un),{state:l}=t,p={...l},f=!1,h;if(n._optimisticResults){let N=this.hasListeners(),Y=!N&&Zs(t,n),me=N&&ei(t,r,n,s);(Y||me)&&(p={...p,...Lr(l.data,t.options)}),n._optimisticResults==="isRestoring"&&(p.fetchStatus="idle")}let{error:v,errorUpdatedAt:m,status:g}=p;h=p.data;let S=!1;if(n.placeholderData!==void 0&&h===void 0&&g==="pending"){let N;i?.isPlaceholderData&&n.placeholderData===c?.placeholderData?(N=i.data,S=!0):N=typeof n.placeholderData=="function"?n.placeholderData(o(this,Tt)?.state.data,o(this,Tt)):n.placeholderData,N!==void 0&&(g="success",h=sn(i?.data,N,n),f=!0)}if(n.select&&h!==void 0&&!S)if(i&&h===a?.data&&n.select===o(this,ln))h=o(this,Et);else try{_(this,ln,n.select),h=n.select(h),h=sn(i?.data,h,n),_(this,Et,h),_(this,je,null)}catch(N){_(this,je,N)}o(this,je)&&(v=o(this,je),h=o(this,Et),m=Date.now(),g="error");let C=p.fetchStatus==="fetching",E=g==="pending",Q=g==="error",L=E&&C,W=h!==void 0,re={status:g,fetchStatus:p.fetchStatus,isPending:E,isSuccess:g==="success",isError:Q,isInitialLoading:L,isLoading:L,data:h,dataUpdatedAt:p.dataUpdatedAt,error:v,errorUpdatedAt:m,failureCount:p.fetchFailureCount,failureReason:p.fetchFailureReason,errorUpdateCount:p.errorUpdateCount,isFetched:t.isFetched(),isFetchedAfterMount:p.dataUpdateCount>d.dataUpdateCount||p.errorUpdateCount>d.errorUpdateCount,isFetching:C,isRefetching:C&&!E,isLoadingError:Q&&!W,isPaused:p.fetchStatus==="paused",isPlaceholderData:f,isRefetchError:Q&&W,isStale:Jr(t,n),refetch:this.refetch,promise:o(this,Te),isEnabled:X(n.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){let N=re.data!==void 0,Y=re.status==="error"&&!N,me=A=>{Y?A.reject(re.error):N&&A.resolve(re.data)},ge=()=>{let A=_(this,Te,re.promise=on());me(A)},ye=o(this,Te);switch(ye.status){case"pending":t.queryHash===r.queryHash&&me(ye);break;case"fulfilled":(Y||re.data!==ye.value)&&ge();break;case"rejected":(!Y||re.error!==ye.reason)&&ge();break}}return re}updateResult(){let t=o(this,z),n=this.createResult(o(this,T),this.options);if(_(this,ot,o(this,T).state),_(this,Pt,this.options),o(this,ot).data!==void 0&&_(this,Tt,o(this,T)),vt(n,t))return;_(this,z,n);let r=()=>{if(!t)return!0;let{notifyOnChangeProps:s}=this.options,i=typeof s=="function"?s():s;if(i==="all"||!i&&!o(this,At).size)return!0;let a=new Set(i??o(this,At));return this.options.throwOnError&&a.add("error"),Object.keys(o(this,z)).some(c=>{let u=c;return o(this,z)[u]!==t[u]&&a.has(u)})};x(this,M,ni).call(this,{listeners:r()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&x(this,M,Wr).call(this)}},Z=new WeakMap,T=new WeakMap,un=new WeakMap,z=new WeakMap,ot=new WeakMap,Pt=new WeakMap,Te=new WeakMap,je=new WeakMap,ln=new WeakMap,Et=new WeakMap,Tt=new WeakMap,at=new WeakMap,ct=new WeakMap,Ve=new WeakMap,At=new WeakMap,M=new WeakSet,cn=function(t){x(this,M,Gr).call(this);let n=o(this,T).fetch(this.options,t);return t?.throwOnError||(n=n.catch(q)),n},jr=function(){x(this,M,Br).call(this);let t=de(this.options.staleTime,o(this,T));if(we.isServer()||o(this,z).isStale||!nn(t))return;let r=Nn(o(this,z).dataUpdatedAt,t)+1;_(this,at,ve.setTimeout(()=>{o(this,z).isStale||this.updateResult()},r))},Vr=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(o(this,T)):this.options.refetchInterval)??!1},Hr=function(t){x(this,M,$r).call(this),_(this,Ve,t),!(we.isServer()||X(this.options.enabled,o(this,T))===!1||!nn(o(this,Ve))||o(this,Ve)===0)&&_(this,ct,ve.setInterval(()=>{(this.options.refetchIntervalInBackground||_t.isFocused())&&x(this,M,cn).call(this)},o(this,Ve)))},Wr=function(){x(this,M,jr).call(this),x(this,M,Hr).call(this,x(this,M,Vr).call(this))},Br=function(){o(this,at)!==void 0&&(ve.clearTimeout(o(this,at)),_(this,at,void 0))},$r=function(){o(this,ct)!==void 0&&(ve.clearInterval(o(this,ct)),_(this,ct,void 0))},Gr=function(){let t=o(this,Z).getQueryCache().build(o(this,Z),this.options);if(t===o(this,T))return;let n=o(this,T);_(this,T,t),_(this,un,t.state),this.hasListeners()&&(n?.removeObserver(this),t.addObserver(this))},ni=function(t){I.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(o(this,z))}),o(this,Z).getQueryCache().notify({query:o(this,T),type:"observerResultsUpdated"})})},ti);function Qa(e,t){return X(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function Zs(e,t){return Qa(e,t)||e.state.data!==void 0&&zr(e,t,t.refetchOnMount)}function zr(e,t,n){if(X(t.enabled,e)!==!1&&de(t.staleTime,e)!=="static"){let r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&Jr(e,t)}return!1}function ei(e,t,n,r){return(e!==t||X(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&Jr(e,n)}function Jr(e,t){return X(t.enabled,e)!==!1&&e.isStaleByTime(de(t.staleTime,e))}function Ua(e,t){return!vt(e.getCurrentResult(),t)}function Mt(e){return{onFetch:(t,n)=>{let r=t.options,s=t.fetchOptions?.meta?.fetchMore?.direction,i=t.state.data?.pages||[],a=t.state.data?.pageParams||[],c={pages:[],pageParams:[]},u=0,d=async()=>{let l=!1,p=v=>{Hs(v,()=>t.signal,()=>l=!0)},f=jn(t.options,t.fetchOptions),h=async(v,m,g)=>{if(l)return Promise.reject();if(m==null&&v.pages.length)return Promise.resolve(v);let C=(()=>{let W={client:t.client,queryKey:t.queryKey,pageParam:m,direction:g?"backward":"forward",meta:t.options.meta};return p(W),W})(),E=await f(C),{maxPages:Q}=t.options,L=g?Vs:js;return{pages:L(v.pages,E,Q),pageParams:L(v.pageParams,m,Q)}};if(s&&i.length){let v=s==="backward",m=v?ri:Yr,g={pages:i,pageParams:a},S=m(r,g);c=await h(g,S,v)}else{let v=e??i.length;do{let m=u===0?a[0]??r.initialPageParam:Yr(r,c);if(u>0&&m==null)break;c=await h(c,m),u++}while(u<v)}return c};t.options.persister?t.fetchFn=()=>t.options.persister?.(d,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=d}}}function Yr(e,{pages:t,pageParams:n}){let r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function ri(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function si(e,t){return t?Yr(e,t)!=null:!1}function ii(e,t){return!t||!e.getPreviousPageParam?!1:ri(e,t)!=null}var Xr=class extends dn{constructor(e,t){super(e,t)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(e){super.setOptions({...e,behavior:Mt()})}getOptimisticResult(e){return e.behavior=Mt(),super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"backward"}}})}createResult(e,t){let{state:n}=e,r=super.createResult(e,t),{isFetching:s,isRefetching:i,isError:a,isRefetchError:c}=r,u=n.fetchMeta?.fetchMore?.direction,d=a&&u==="forward",l=s&&u==="forward",p=a&&u==="backward",f=s&&u==="backward";return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:si(t,n.data),hasPreviousPage:ii(t,n.data),isFetchNextPageError:d,isFetchingNextPage:l,isFetchPreviousPageError:p,isFetchingPreviousPage:f,isRefetchError:c&&!d&&!p,isRefetching:i&&!l&&!f}}};var fn,Se,G,ut,Re,He,oi,ai=(oi=class extends Wn{constructor(t){super();b(this,Re);b(this,fn);b(this,Se);b(this,G);b(this,ut);_(this,fn,t.client),this.mutationId=t.mutationId,_(this,G,t.mutationCache),_(this,Se,[]),this.state=t.state||Zr(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){o(this,Se).includes(t)||(o(this,Se).push(t),this.clearGcTimeout(),o(this,G).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){_(this,Se,o(this,Se).filter(n=>n!==t)),this.scheduleGc(),o(this,G).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){o(this,Se).length||(this.state.status==="pending"?this.scheduleGc():o(this,G).remove(this))}continue(){return o(this,ut)?.continue()??this.execute(this.state.variables)}async execute(t){let n=()=>{x(this,Re,He).call(this,{type:"continue"})},r={client:o(this,fn),meta:this.options.meta,mutationKey:this.options.mutationKey};_(this,ut,Hn({fn:()=>this.options.mutationFn?this.options.mutationFn(t,r):Promise.reject(new Error("No mutationFn found")),onFail:(a,c)=>{x(this,Re,He).call(this,{type:"failed",failureCount:a,error:c})},onPause:()=>{x(this,Re,He).call(this,{type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>o(this,G).canRun(this)}));let s=this.state.status==="pending",i=!o(this,ut).canStart();try{if(s)n();else{x(this,Re,He).call(this,{type:"pending",variables:t,isPaused:i}),o(this,G).config.onMutate&&await o(this,G).config.onMutate(t,this,r);let c=await this.options.onMutate?.(t,r);c!==this.state.context&&x(this,Re,He).call(this,{type:"pending",context:c,variables:t,isPaused:i})}let a=await o(this,ut).start();return await o(this,G).config.onSuccess?.(a,t,this.state.context,this,r),await this.options.onSuccess?.(a,t,this.state.context,r),await o(this,G).config.onSettled?.(a,null,this.state.variables,this.state.context,this,r),await this.options.onSettled?.(a,null,t,this.state.context,r),x(this,Re,He).call(this,{type:"success",data:a}),a}catch(a){try{await o(this,G).config.onError?.(a,t,this.state.context,this,r)}catch(c){Promise.reject(c)}try{await this.options.onError?.(a,t,this.state.context,r)}catch(c){Promise.reject(c)}try{await o(this,G).config.onSettled?.(void 0,a,this.state.variables,this.state.context,this,r)}catch(c){Promise.reject(c)}try{await this.options.onSettled?.(void 0,a,t,this.state.context,r)}catch(c){Promise.reject(c)}throw x(this,Re,He).call(this,{type:"error",error:a}),a}finally{o(this,G).runNext(this)}}},fn=new WeakMap,Se=new WeakMap,G=new WeakMap,ut=new WeakMap,Re=new WeakSet,He=function(t){let n=r=>{switch(t.type){case"failed":return{...r,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:t.isPaused,status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...r,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:t.error,failureCount:r.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=n(this.state),I.batch(()=>{o(this,Se).forEach(r=>{r.onMutationUpdate(t)}),o(this,G).notify({mutation:this,type:"updated",action:t})})},oi);function Zr(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Ae,fe,pn,ci,ui=(ci=class extends ce{constructor(t={}){super();b(this,Ae);b(this,fe);b(this,pn);this.config=t,_(this,Ae,new Set),_(this,fe,new Map),_(this,pn,0)}build(t,n,r){let s=new ai({client:t,mutationCache:this,mutationId:++Gt(this,pn)._,options:t.defaultMutationOptions(n),state:r});return this.add(s),s}add(t){o(this,Ae).add(t);let n=Bn(t);if(typeof n=="string"){let r=o(this,fe).get(n);r?r.push(t):o(this,fe).set(n,[t])}this.notify({type:"added",mutation:t})}remove(t){if(o(this,Ae).delete(t)){let n=Bn(t);if(typeof n=="string"){let r=o(this,fe).get(n);if(r)if(r.length>1){let s=r.indexOf(t);s!==-1&&r.splice(s,1)}else r[0]===t&&o(this,fe).delete(n)}}this.notify({type:"removed",mutation:t})}canRun(t){let n=Bn(t);if(typeof n=="string"){let s=o(this,fe).get(n)?.find(i=>i.state.status==="pending");return!s||s===t}else return!0}runNext(t){let n=Bn(t);return typeof n=="string"?o(this,fe).get(n)?.find(s=>s!==t&&s.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){I.batch(()=>{o(this,Ae).forEach(t=>{this.notify({type:"removed",mutation:t})}),o(this,Ae).clear(),o(this,fe).clear()})}getAll(){return Array.from(o(this,Ae))}find(t){let n={exact:!0,...t};return this.getAll().find(r=>Ln(n,r))}findAll(t={}){return this.getAll().filter(n=>Ln(t,n))}notify(t){I.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){let t=this.getAll().filter(n=>n.state.isPaused);return I.batch(()=>Promise.all(t.map(n=>n.continue().catch(q))))}},Ae=new WeakMap,fe=new WeakMap,pn=new WeakMap,ci);function Bn(e){return e.options.scope?.id}var Me,We,ee,Oe,Ie,$n,es,li,ts=(li=class extends ce{constructor(t,n){super();b(this,Ie);b(this,Me);b(this,We);b(this,ee);b(this,Oe);_(this,Me,t),this.setOptions(n),this.bindMethods(),x(this,Ie,$n).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(t){let n=this.options;this.options=o(this,Me).defaultMutationOptions(t),vt(this.options,n)||o(this,Me).getMutationCache().notify({type:"observerOptionsUpdated",mutation:o(this,ee),observer:this}),n?.mutationKey&&this.options.mutationKey&&be(n.mutationKey)!==be(this.options.mutationKey)?this.reset():o(this,ee)?.state.status==="pending"&&o(this,ee).setOptions(this.options)}onUnsubscribe(){this.hasListeners()||o(this,ee)?.removeObserver(this)}onMutationUpdate(t){x(this,Ie,$n).call(this),x(this,Ie,es).call(this,t)}getCurrentResult(){return o(this,We)}reset(){o(this,ee)?.removeObserver(this),_(this,ee,void 0),x(this,Ie,$n).call(this),x(this,Ie,es).call(this)}mutate(t,n){return _(this,Oe,n),o(this,ee)?.removeObserver(this),_(this,ee,o(this,Me).getMutationCache().build(o(this,Me),this.options)),o(this,ee).addObserver(this),o(this,ee).execute(t)}},Me=new WeakMap,We=new WeakMap,ee=new WeakMap,Oe=new WeakMap,Ie=new WeakSet,$n=function(){let t=o(this,ee)?.state??Zr();_(this,We,{...t,isPending:t.status==="pending",isSuccess:t.status==="success",isError:t.status==="error",isIdle:t.status==="idle",mutate:this.mutate,reset:this.reset})},es=function(t){I.batch(()=>{if(o(this,Oe)&&this.hasListeners()){let n=o(this,We).variables,r=o(this,We).context,s={client:o(this,Me),meta:this.options.meta,mutationKey:this.options.mutationKey};if(t?.type==="success"){try{o(this,Oe).onSuccess?.(t.data,n,r,s)}catch(i){Promise.reject(i)}try{o(this,Oe).onSettled?.(t.data,null,n,r,s)}catch(i){Promise.reject(i)}}else if(t?.type==="error"){try{o(this,Oe).onError?.(t.error,n,r,s)}catch(i){Promise.reject(i)}try{o(this,Oe).onSettled?.(void 0,t.error,n,r,s)}catch(i){Promise.reject(i)}}}this.listeners.forEach(n=>{n(o(this,We))})})},li);var Ce,di,fi=(di=class extends ce{constructor(t={}){super();b(this,Ce);this.config=t,_(this,Ce,new Map)}build(t,n,r){let s=n.queryKey,i=n.queryHash??rn(s,n),a=this.get(i);return a||(a=new Ys({client:t,queryKey:s,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(s)}),this.add(a)),a}add(t){o(this,Ce).has(t.queryHash)||(o(this,Ce).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){let n=o(this,Ce).get(t.queryHash);n&&(t.destroy(),n===t&&o(this,Ce).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){I.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return o(this,Ce).get(t)}getAll(){return[...o(this,Ce).values()]}find(t){let n={exact:!0,...t};return this.getAll().find(r=>Kn(n,r))}findAll(t={}){let n=this.getAll();return Object.keys(t).length>0?n.filter(r=>Kn(t,r)):n}notify(t){I.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){I.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){I.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},Ce=new WeakMap,di);var D,Be,$e,Ot,It,Ge,Ft,kt,pi,ns=(pi=class{constructor(e={}){b(this,D);b(this,Be);b(this,$e);b(this,Ot);b(this,It);b(this,Ge);b(this,Ft);b(this,kt);_(this,D,e.queryCache||new fi),_(this,Be,e.mutationCache||new ui),_(this,$e,e.defaultOptions||{}),_(this,Ot,new Map),_(this,It,new Map),_(this,Ge,0)}mount(){Gt(this,Ge)._++,o(this,Ge)===1&&(_(this,Ft,_t.subscribe(async e=>{e&&(await this.resumePausedMutations(),o(this,D).onFocus())})),_(this,kt,Ct.subscribe(async e=>{e&&(await this.resumePausedMutations(),o(this,D).onOnline())})))}unmount(){var e,t;Gt(this,Ge)._--,o(this,Ge)===0&&((e=o(this,Ft))==null||e.call(this),_(this,Ft,void 0),(t=o(this,kt))==null||t.call(this),_(this,kt,void 0))}isFetching(e){return o(this,D).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return o(this,Be).findAll({...e,status:"pending"}).length}getQueryData(e){let t=this.defaultQueryOptions({queryKey:e});return o(this,D).get(t.queryHash)?.state.data}ensureQueryData(e){let t=this.defaultQueryOptions(e),n=o(this,D).build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(de(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return o(this,D).findAll(e).map(({queryKey:t,state:n})=>{let r=n.data;return[t,r]})}setQueryData(e,t,n){let r=this.defaultQueryOptions({queryKey:e}),i=o(this,D).get(r.queryHash)?.state.data,a=Ks(t,i);if(a!==void 0)return o(this,D).build(this,r).setData(a,{...n,manual:!0})}setQueriesData(e,t,n){return I.batch(()=>o(this,D).findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){let t=this.defaultQueryOptions({queryKey:e});return o(this,D).get(t.queryHash)?.state}removeQueries(e){let t=o(this,D);I.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){let n=o(this,D);return I.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){let n={revert:!0,...t},r=I.batch(()=>o(this,D).findAll(e).map(s=>s.cancel(n)));return Promise.all(r).then(q).catch(q)}invalidateQueries(e,t={}){return I.batch(()=>(o(this,D).findAll(e).forEach(n=>{n.invalidate()}),e?.refetchType==="none"?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??"active"},t)))}refetchQueries(e,t={}){let n={...t,cancelRefetch:t.cancelRefetch??!0},r=I.batch(()=>o(this,D).findAll(e).filter(s=>!s.isDisabled()&&!s.isStatic()).map(s=>{let i=s.fetch(void 0,n);return n.throwOnError||(i=i.catch(q)),s.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(q)}fetchQuery(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=o(this,D).build(this,t);return n.isStaleByTime(de(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(q).catch(q)}fetchInfiniteQuery(e){return e.behavior=Mt(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(q).catch(q)}ensureInfiniteQueryData(e){return e.behavior=Mt(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return Ct.isOnline()?o(this,Be).resumePausedMutations():Promise.resolve()}getQueryCache(){return o(this,D)}getMutationCache(){return o(this,Be)}getDefaultOptions(){return o(this,$e)}setDefaultOptions(e){_(this,$e,e)}setQueryDefaults(e,t){o(this,Ot).set(be(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){let t=[...o(this,Ot).values()],n={};return t.forEach(r=>{tt(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){o(this,It).set(be(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){let t=[...o(this,It).values()],n={};return t.forEach(r=>{tt(e,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;let t={...o(this,$e).queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=rn(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===bt&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...o(this,$e).mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){o(this,D).clear(),o(this,Be).clear()}},D=new WeakMap,Be=new WeakMap,$e=new WeakMap,Ot=new WeakMap,It=new WeakMap,Ge=new WeakMap,Ft=new WeakMap,kt=new WeakMap,pi);var qt=j(ie(),1),gi=j(Gn(),1),rs=qt.createContext(void 0),U=e=>{let t=qt.useContext(rs);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},hn=({client:e,children:t})=>(qt.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,gi.jsx)(rs.Provider,{value:e,children:t}));var zn=j(ie(),1),yi=zn.createContext(!1),_i=()=>zn.useContext(yi),Il=yi.Provider;var mn=j(ie(),1),Na=j(Gn(),1);function Ka(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var La=mn.createContext(Ka()),vi=()=>mn.useContext(La);var bi=j(ie(),1);var wi=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError=="function"?wt(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},Si=e=>{bi.useEffect(()=>{e.clearReset()},[e])},Ri=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:s})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(s&&e.data===void 0||wt(n,[e.error,r]));var Ci=e=>{if(e.suspense){let n=s=>s==="static"?s:Math.max(s??1e3,1e3),r=e.staleTime;e.staleTime=typeof r=="function"?(...s)=>n(r(...s)):n(r),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},xi=(e,t)=>e.isLoading&&e.isFetching&&!t,Pi=(e,t)=>e?.suspense&&t.isPending,ss=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});var ze=j(ie(),1);function Jn(e,t,n){let r=_i(),s=vi(),i=U(n),a=i.defaultQueryOptions(e);i.getDefaultOptions().queries?._experimental_beforeQuery?.(a);let c=i.getQueryCache().get(a.queryHash);a._optimisticResults=r?"isRestoring":"optimistic",Ci(a),wi(a,s,c),Si(s);let u=!i.getQueryCache().get(a.queryHash),[d]=ze.useState(()=>new t(i,a)),l=d.getOptimisticResult(a),p=!r&&e.subscribed!==!1;if(ze.useSyncExternalStore(ze.useCallback(f=>{let h=p?d.subscribe(I.batchCalls(f)):q;return d.updateResult(),h},[d,p]),()=>d.getCurrentResult(),()=>d.getCurrentResult()),ze.useEffect(()=>{d.setOptions(a)},[a,d]),Pi(a,l))throw ss(a,d,s);if(Ri({result:l,errorResetBoundary:s,throwOnError:a.throwOnError,query:c,suspense:a.suspense}))throw l.error;return i.getDefaultOptions().queries?._experimental_afterQuery?.(a,l),a.experimental_prefetchInRender&&!we.isServer()&&xi(l,r)&&(u?ss(a,d,s):c?.promise)?.catch(q).finally(()=>{d.updateResult()}),a.notifyOnChangeProps?l:d.trackResult(l)}function k(e,t){return Jn(e,dn,t)}var Fe=j(ie(),1);function ke(e,t){let n=U(t),[r]=Fe.useState(()=>new ts(n,e));Fe.useEffect(()=>{r.setOptions(e)},[r,e]);let s=Fe.useSyncExternalStore(Fe.useCallback(a=>r.subscribe(I.batchCalls(a)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),i=Fe.useCallback((a,c)=>{r.mutate(a,c).catch(q)},[r]);if(s.error&&wt(r.options.throwOnError,[s.error]))throw s.error;return{...s,mutate:i,mutateAsync:s.mutate}}function gn(e,t){return Jn(e,Xr,t)}var Dt=null;function Ei(e){if(Dt&&Dt!==e)throw new Error("[fsaos-gateway-sdk] setQueryClient() called after a QueryClient was already in use. Inject the host client before rendering or starting realtime subscriptions.");Dt=e}function P(){return Dt||(Dt=new ns({defaultOptions:{queries:{staleTime:1e3*60*2,gcTime:1e3*60*10,refetchOnWindowFocus:!1,retry:1}}})),Dt}var Ti=new Proxy({},{get(e,t,n){let r=P(),s=r[t];return typeof s=="function"?s.bind(r):s}});function H(){return le()??"__unscoped__"}var w={all:()=>["vfs",H()],item:e=>["vfs",H(),"item",e],itemById:e=>["vfs","item-by-id",e],children:e=>["vfs",H(),"children",e],allChildren:()=>["vfs",H(),"children"],types:e=>["vfs","types",e??"default"],edges:e=>["vfs","edges",e],search:(e,t)=>["vfs",H(),"search",e,...t??[]],items:(e,t)=>["vfs",H(),"items",e,JSON.stringify(t??{})],allItems:()=>["vfs",H(),"items"],tree:(e,t)=>["vfs",H(),"tree",e,t??1],openEnvelope:(e,t)=>["vfs",H(),"open",e,t??"__default__"],allOpenEnvelopes:()=>["vfs",H(),"open"],memberFocus:e=>["vfs","member-focus",e],fractalInstances:()=>["vfs","fractal-instances"],recentActivity:(e,t,n)=>["vfs",H(),"get-activity-feed",e,t,n],itemVersions:(e,t,n,r)=>["vfs","item-versions",e,t,n,r],itemHistory:(e,t,n)=>["vfs","item-history",e,t,n],channelMessages:(e,t)=>["vfs",H(),"channel-messages",e,t??"__top__"],allChannelMessages:()=>["vfs",H(),"channel-messages"],channels:e=>["vfs",H(),"channels",e??"all"],allChannels:()=>["vfs",H(),"channels"],notifications:(e,t)=>["vfs",H(),"notifications",e??"all",t??200],allNotifications:()=>["vfs",H(),"notifications"],unreadCounts:()=>["vfs",H(),"unread-counts"],memberships:e=>["memberships",e]};function Ai(){return new Date().toISOString()}function Mi(){return crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function pe(e){let t=e.path||e.item_path||"",n=t.split("/");n.pop();let r=n.join("/"),s=e.type_data||{};return s.allowed_parent_types&&!s.accepts&&(s.accepts=s.allowed_parent_types),delete s.allowed_parent_types,{id:e.id||e.item_id||"",name:e.name||e.item_name||"",item_type:e.item_type||"unknown",path:t,parent_path:r,is_active:e.is_active!==!1,has_children:e.has_children??!1,created_at:e.created_at||Ai(),updated_at:e.updated_at||Ai(),visibility:e.visibility,type_data:s,scope_item_id:e.scope_item_id,fractal_id:e.fractal_id,parent_instance_id:e.parent_instance_id,owner_principal_id:e.owner_principal_id,created_by_principal_id:e.created_by_principal_id,parent_id:e.parent_id,space_item_id:e.space_item_id,account_item_id:e.account_item_id}}function yn(e){return(e.content?.items||e.items||[]).map(pe)}async function Xn(e){try{let t=await R("read",{id:e});if(t.item_name||t.item_path){let r=pe(t);return r.path&&P().setQueryData(w.item(r.path),r),r}let n=t.item;if(n){let r=pe(n);return r.path&&P().setQueryData(w.item(r.path),r),r}return null}catch{return null}}async function Zn(e){try{let t=await R("read",{path:e});if(t.item_name||t.item_path)return pe(t);let n=t.item;return n?pe(n):null}catch{return null}}async function er(e){try{let t=await R("list",{path:e,limit:200}),n=yn(t);for(let r of n)P().setQueryData(w.item(r.path),r);return n}catch(t){return console.error(`[gateway] Failed to fetch children of ${e}:`,t),[]}}async function tr(e,t,n){try{let r=await R("list",{path:e,limit:t,offset:n}),s=yn(r);for(let i of s)P().setQueryData(w.item(i.path),i);return{items:s,total_hint:r.total??r.content?.total??s.length}}catch(r){return console.error(`[gateway] Failed to fetch children page of ${e}:`,r),{items:[],total_hint:0}}}async function nr(e){let n=await R("types-list",e?{scope_id:e}:{}),r=n.content?.items||n.items||[],s=new Map;for(let i of r){let a=i.name,c=i.type_data;!a||!c||s.set(a,{type_key:a,display_name:c.display_name||a,display_name_plural:c.display_name_plural||a+"s",icon:c.icon||"File",color:c.color||"gray",description:c.description||"",input_schema:c.input_schema||{},system_schema:c.system_schema||{},json_schema:c.input_schema||c.json_schema||{},default_data:c.default_data||{},field_defaults:c.field_defaults||{},renderer_config:c.renderer_config||{},is_system:c.is_system??!1,is_active:c.is_active??!0,is_container:c.is_container??!1,is_scope:c.is_scope??!1,render_mode:c.render_mode||"none",placement_mode:c.placement_mode,direct_parent_types:c.direct_parent_types,allowed_parent_types:c.allowed_parent_types,governed_create:c.governed_create,create_method:c.create_method,dedup:c.dedup,edges:c.edges,events:c.events})}return s}async function rr(e){try{let t=await R("edges",{item_id:e}),n=t.outgoing||[],r=t.incoming||[],s=[];for(let i of n)s.push({id:i.edge_id||Mi(),source_item_id:e,target_item_id:i.target_id||"",edge_type:i.edge_type||"",weight:i.weight??1,context:i.context||{},is_active:!0,is_bidirectional:i.is_bidirectional});for(let i of r)s.push({id:i.edge_id||Mi(),source_item_id:i.source_id||"",target_item_id:e,edge_type:i.edge_type||"",weight:i.weight??1,context:i.context||{},is_active:!0,is_bidirectional:i.is_bidirectional});return s}catch(t){return console.warn(`[gateway] Failed to fetch edges for ${e}:`,t),[]}}async function sr(e,t=1,n,r){try{let s={path:e,max_depth:t>0?t:999};n?.length&&(s.item_types=n),r&&(s.limit=r);let i=await R("tree",s),a=yn(i);for(let c of a)P().setQueryData(w.item(c.path),c);return a}catch(s){return console.error(`[gateway] Failed to fetch tree at ${e}:`,s),[]}}async function ir(e,t=50,n=0){try{let r=await R("get-activity-feed",{scope_path:e,limit:t,offset:n});return r.content?.items||r.items||r.entries||[]}catch(r){return console.error(`[gateway] Failed to fetch recent activity for ${e}:`,r),[]}}async function _n(e,t={}){let{limit:n=50,offset:r=0,include_snapshots:s=!1}=t;try{let i=await R("item-versions",{id:e,limit:n,offset:r,include_snapshots:s});return{versions:i.content?.items||i.versions||[],total:i.total??0}}catch(i){return console.error(`[gateway] Failed to fetch item versions for ${e}:`,i),{versions:[],total:0}}}async function or(e,t=50,n=0){return _n(e,{limit:t,offset:n})}async function ar(e,t,n){try{let r={scope_id:e};t?.length&&(r.item_types=t),n&&(r.limit=n);let s=await R("member-focus",r),i=yn(s);for(let a of i)P().setQueryData(w.item(a.path),a);return i}catch(r){return console.error(`[gateway] Failed to fetch member focus for scope ${e}:`,r),[]}}async function cr(e,t){let n={path:e};t?.mode&&(n.mode=t.mode),t?.strategy&&(n.strategy=t.strategy),t?.arguments&&(n.arguments=t.arguments);let s=await R("open",n);return{item_id:s.item_id,item_path:s.item_path,item_name:s.item_name,item_type:s.item_type,render:s.render,compatible_components:s.compatible_components??[],content:s.content,metadata:s.metadata,instructions:s.instructions}}async function vn(e){let t={item_type:e.type};e.scope&&(t.scope_path=e.scope);let n={};if(e.name&&(n.name=e.name),e.tag&&(n.tag=e.tag),e.parent_id&&(n.parent_id=e.parent_id),e.sort_by&&(n.sort_by=e.sort_by),e.sort_dir&&(n.sort_dir=e.sort_dir),e.offset!=null&&(n.offset=e.offset),e.fields)for(let[r,s]of Object.entries(e.fields))n[`field.${r}`]=String(s);Object.keys(n).length>0&&(t.filters=n),e.limit!=null&&(t.limit=e.limit);try{let r=await R("query",t),s=yn(r);for(let i of s)P().setQueryData(w.item(i.path),i);return{items:s,total_hint:r.total??r.content?.total??s.length}}catch(r){return console.error(`[gateway] Failed to fetch items of type ${e.type}:`,r),{items:[],total_hint:0}}}function Oi(e){return e.filter(t=>t.item_type==="card").map(t=>{let n=t.type_data||{},r=n.payload||{};return{id:t.id||"",path:t.path||"",name:t.name||(t.path||"").split("/").pop()||"",createdAt:t.created_at||"",action:n.action||"created",targetId:n.target_id||void 0,targetPath:n.target_path||"",targetDisplayName:n.target_display_name||"",targetDescription:n.target_description||"",targetItemType:n.target_item_type||"",toolId:(t.name||"").startsWith("card-")?(t.name||"").substring(5):void 0,parentMessagePath:t.parent_message_path||void 0,visibility:n.visibility||"private",openWith:r.open_with||void 0,hostBundled:r.host_bundled===!0?!0:void 0,bundleExport:r.bundle_export||void 0,launchArguments:r.launch_arguments||void 0,requiresUserAttention:r.requires_user_attention===!0?!0:void 0}}).sort((t,n)=>t.createdAt.localeCompare(n.createdAt))}function is(e){return e.filter(t=>t.item_type==="message").map(t=>{let n=t.type_data||{},r="user";n.role==="assistant"?r="assistant":n.role==="system"&&(r="system");let s=n.metadata||{};return{id:t.id||"",path:t.path||"",content:n.message||n.content||"",created_at:t.created_at||"",role:r,seq:n.seq||0,principal_id:n.principal_id,reply_count:n.reply_count||0,parent_message_id:n.parent_message_id,intent_card:s.intent_card,metadata:Object.keys(s).length>0?s:void 0,thread_summary:Array.isArray(n.thread_summary)&&n.thread_summary.length>0?n.thread_summary:void 0}}).sort((t,n)=>t.seq-n.seq)}async function Ii(e,t){try{let n={channel_path:e};t&&(n.parent_message_id=t);let s=await R("get-channel-messages",n),i=s.messages||s.content?.items||s.items||[];return is(i)}catch(n){return console.error(`[gateway] Failed to fetch channel messages for ${e}:`,n),[]}}async function ur(e,t){try{let n={channel_path:e};t&&(n.parent_message_id=t);let s=await R("get-channel-messages",n),i=s.messages||[],a=is(i),c=Oi(i),u=new Map,d=[];for(let l of c)if(l.parentMessagePath){let p=u.get(l.parentMessagePath)||[];p.push(l),u.set(l.parentMessagePath,p)}else d.push(l);return{messages:a,messageCards:u,siblingCards:d,mode:s.mode||"top_level"}}catch(n){return console.error(`[gateway] Failed to fetch channel messages with cards for ${e}:`,n),{messages:[],messageCards:new Map,siblingCards:[],mode:"top_level"}}}async function bn(e,t){try{let n={channel_path:e};t?.parentMessageId&&(n.parent_message_id=t.parentMessageId),t?.limit&&(n.limit=t.limit),t?.before_seq!=null&&(n.before_seq=t.before_seq),t?.after_seq!=null&&(n.after_seq=t.after_seq);let s=await R("get-channel-messages",n),i=s.messages||[],a=Oi(i),c=new Map,u=[];for(let d of a)if(d.parentMessagePath){let l=c.get(d.parentMessagePath)||[];l.push(d),c.set(d.parentMessagePath,l)}else u.push(d);return{messages:is(i),messageCards:c,siblingCards:u,mode:s.mode||"top_level"}}catch(n){return console.error(`[gateway] Failed to fetch channel messages page for ${e}:`,n),{messages:[],messageCards:new Map,siblingCards:[],mode:"top_level"}}}function Yn(e){P().invalidateQueries({queryKey:w.children(e)})}function os(e){P().invalidateQueries({queryKey:w.item(e)})}function Fi(e,t){os(e),Yn(e);let n=e.split("/");n.pop();let r=n.join("/")||t;r&&Yn(r)}function ki(e){let t=e+"/";P().invalidateQueries({predicate:n=>{let r=n.queryKey;return r[0]!=="vfs"?!1:r.some(s=>typeof s=="string"&&(s===e||s.startsWith(t)))}})}function qi(){P().invalidateQueries({queryKey:w.all()})}function Di(e){P().invalidateQueries({queryKey:w.types(e)})}function Qi(e,t){e?P().invalidateQueries({queryKey:w.channelMessages(e,t)}):P().invalidateQueries({queryKey:w.allChannelMessages()})}function Ui(e,t){e&&t?P().invalidateQueries({queryKey:w.openEnvelope(e,t)}):e?P().invalidateQueries({predicate:n=>{let r=n.queryKey;return r[0]==="vfs"&&r[2]==="open"&&r[3]===e}}):P().invalidateQueries({queryKey:w.allOpenEnvelopes()})}var ja=typeof window<"u"&&(window.location?.hostname==="localhost"||window.location?.hostname==="127.0.0.1"||window.__FSAOS_WS_DEBUG__);function B(...e){ja&&console.log("[WS]",...e)}var O=null,Qt=null,Ut=null,wn=0,Va=3e4,Ni=1e4,Kt=!1,Ha=3e4,lr=null,Ki=!1;function Wa(){Rn(),lr=setInterval(()=>{qe({type:"ping"})},Ha)}function Rn(){lr&&(clearInterval(lr),lr=null)}function Ba(){typeof document>"u"||(document.hidden?Rn():Sn()&&(B("Tab visible, reconnecting..."),Cn()))}function $a(){Ki||typeof document>"u"||(document.addEventListener("visibilitychange",Ba),Ki=!0)}var te={},Nt=[],Lt=new Map,lt=new Map;function Ga(){return Object.keys(te).some(t=>te[t]&&te[t].length>0)||Nt.length>0}function Sn(){return Lt.size>0||lt.size>0}async function Cn(){if(!Sn()){B("ensureConnection: no active subscriptions, skipping");return}if(O&&O.readyState===WebSocket.OPEN){B("ensureConnection: already open");return}if(Qt)return B("ensureConnection: connection already in flight, waiting..."),Qt;if(O){B("ensureConnection: killing stale WS in state",O.readyState);try{O.close()}catch{}O=null}return Kt=!1,Qt=(async()=>{try{let e=typeof window<"u"&&window.__FSAOS_CONFIG__||{},t=De,n=await xe();if(!n){B("ensureConnection: no token available, will retry"),Li();return}let r=t.startsWith("https")?"wss":"ws",s=t.replace(/^https?:\/\//,""),i=`${r}://${s}/ws`;i+=`?token=${encodeURIComponent(n)}`,B("ensureConnection: opening WS to",i.substring(0,50)+"..."),O=new WebSocket(i),await new Promise((a,c)=>{if(!O)return c(new Error("WebSocket not created"));let u=setTimeout(()=>{if(B("ensureConnection: TIMEOUT after",Ni,"ms"),O&&O.readyState!==WebSocket.OPEN){try{O.close()}catch{}O=null}c(new Error("WebSocket connection timeout"))},Ni);O.onopen=()=>{clearTimeout(u),B("ensureConnection: CONNECTED"),wn=0,za(),(typeof document>"u"||!document.hidden)&&Wa(),$a(),a()},O.onmessage=d=>{Ja(d.data)},O.onerror=()=>{B("ensureConnection: WS error event")},O.onclose=d=>{clearTimeout(u),B("ensureConnection: WS closed, code:",d.code,"reason:",d.reason),O=null,Rn(),!Kt&&Sn()&&Li(),c(new Error(`WebSocket closed: ${d.code}`))}})}catch(e){B("ensureConnection: failed -",e?.message||e)}finally{Qt=null}})(),Qt}function Li(){if(Ut||typeof document<"u"&&document.hidden)return;let e=Math.min(1e3*Math.pow(2,wn)+Math.random()*1e3,Va);wn++,B("scheduleReconnect: attempt",wn,"in",Math.round(e),"ms"),Ut=setTimeout(()=>{Ut=null,Sn()&&Cn()},e)}function za(){for(let e of Lt.values())B("resubscribeAll: scope",e.scope_id),qe({type:"subscribe",scope_id:e.scope_id,event_types:e.event_types});for(let e of lt.values())B("resubscribeAll: path",e.path),qe({type:"subscribe_path",path:e.path,event_types:e.event_types})}function qe(e){O&&O.readyState===WebSocket.OPEN&&O.send(JSON.stringify(e))}function Ja(e){try{let t=JSON.parse(e);if(t.type==="subscribed"||t.type==="subscribed_path"||t.type==="unsubscribed"||t.type==="unsubscribed_path"||t.type==="pong")return;if(t.type==="error"){console.warn("[WS] Server error:",t.message);return}if(t.type==="event"||t.event_type){let n=t.event_type||"message",r=t.data||t;r.path&&te[r.path]&&te[r.path].forEach(s=>s(r)),te["*"]&&te["*"].forEach(s=>s(r));for(let s of Nt)s.eventType!=="*"&&s.eventType!==n||s.filter&&!s.filter(r)||s.callback(r)}}catch{}}function as(){!Ga()&&Lt.size===0&&lt.size===0&&O&&(Kt=!0,Rn(),O.close(),O=null,Kt=!1)}function dr(e,t){return te[e]||(te[e]=[]),te[e].push(t),lt.has(e)||(lt.set(e,{path:e,event_types:["token_stream"]}),O&&O.readyState===WebSocket.OPEN&&qe({type:"subscribe_path",path:e,event_types:["token_stream"]})),Cn(),()=>{let n=te[e];if(n){let r=n.indexOf(t);r!==-1&&n.splice(r,1),n.length===0&&(delete te[e],lt.delete(e),qe({type:"unsubscribe_path",path:e}))}as()}}function J(e,t,n){let s=(Array.isArray(e)?e:[e]).map(i=>({eventType:i,callback:t,filter:n}));return Nt.push(...s),Sn()&&Cn(),()=>{for(let i of s){let a=Nt.indexOf(i);a!==-1&&Nt.splice(a,1)}as()}}function fr(e,t=["vfs_change","ccm_change"]){return B("subscribeToScope:",e,t),Lt.set(e,{scope_id:e,event_types:t}),O&&O.readyState===WebSocket.OPEN&&qe({type:"subscribe",scope_id:e,event_types:t}),Cn(),()=>{Lt.delete(e),qe({type:"unsubscribe",scope_id:e}),as()}}function ji(e,t,n={}){qe({type:"emit",scope_id:e,event_type:t,payload:n})}function cs(){B("disconnectSSE: tearing down"),Kt=!0,Rn(),O&&(O.close(),O=null),Ut&&(clearTimeout(Ut),Ut=null),Qt=null,Kt=!1,wn=0;for(let e of Object.keys(te))delete te[e];Nt.length=0,Lt.clear(),lt.clear()}function Vi(){qe({type:"ping"})}Pe(cs);var jt=new Map,pr=null,hr=null,Je=new Map,Hi=250;function xn(e){mr(),Pn(e),pr=J("vfs_change",t=>Ya(t)),hr=J("ccm_change",t=>Xa(t))}function Pn(e){if(jt.has(e))return;let t=fr(e,["vfs_change","ccm_change"]);jt.set(e,t)}function Wi(e){let t=jt.get(e);t&&(t(),jt.delete(e))}function mr(){for(let[,e]of jt)e();jt.clear(),pr&&(pr(),pr=null),hr&&(hr(),hr=null),Je.forEach(e=>clearTimeout(e)),Je.clear()}Pe(mr);function Ya(e){let t=e.path,n=e.action;if(!t)return;let r=t.split("/");r.pop();let s=r.join("/")||"/root",i=Je.get(s);i&&clearTimeout(i);let a=setTimeout(()=>{Je.delete(s),Za(n,t,e,s)},Hi);Je.set(s,a)}function Xa(e){if(!e||typeof e!="object")return;let t=e.source_item_id||e.source_id,n=e.target_item_id||e.target_id;if(!(e.edge_type!=null||t!=null||n!=null))return;let s=`ccm:${t??""}:${n??""}`,i=Je.get(s);i&&clearTimeout(i);let a=setTimeout(()=>{Je.delete(s),t&&P().invalidateQueries({queryKey:w.edges(t)}),n&&P().invalidateQueries({queryKey:w.edges(n)}),!t&&!n&&P().invalidateQueries({predicate:c=>c.queryKey[0]==="vfs"&&c.queryKey[1]==="edges"})},Hi);Je.set(s,a)}function Za(e,t,n,r){if((e||"").toUpperCase()==="DELETE")P().removeQueries({queryKey:w.item(t)}),P().removeQueries({queryKey:w.children(t)}),P().removeQueries({queryKey:w.tree(t)});else if(n.item_id)try{let i={id:n.item_id,path:n.path,name:n.name,item_type:n.item_type,parent_id:n.parent_id,scope_item_id:n.scope_item_id},a=pe(i);a&&a.id&&P().setQueryData(w.item(t),a)}catch{}P().invalidateQueries({queryKey:w.children(r)}),P().invalidateQueries({predicate:i=>{let a=i.queryKey;if(a[0]!=="vfs"||a[1]!=="tree")return!1;let c=a[2];return t.startsWith(c+"/")||t===c}}),n.item_id&&P().invalidateQueries({queryKey:w.itemById(n.item_id)})}var us=j(ie(),1),Gi=j($i(),1);function zi(e){return R("read",{path:e})}function Ji(e,t){return R("list",{path:e,...t})}function Yi(e){return R("create",e)}function Xi(e){return R("update",e)}function Zi(e){return R("create",e)}function eo(e,t){let r=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).scopePath||"";return R("tools/call",{name:e,instance_path:r,...t||{}})}function to(e,t,n){return R("signal",{target_id:e,event_name:t,payload:n||{}})}function no(e){return((typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"")+e}var ro={signIn:e=>e.provider?F.auth.signInWithOAuth({provider:e.provider,options:{redirectTo:e.redirectTo||window.location.href}}):F.auth.signInWithPassword({email:e.email,password:e.password}),signUp:e=>F.auth.signUp({email:e.email,password:e.password,options:{data:e.metadata||{}}}),signOut:async()=>{await F.auth.signOut(),gt(),P().clear()},getSession:()=>F.auth.getSession().then(e=>e.data.session),getUser:()=>F.auth.getUser().then(e=>e.data.user),onAuthStateChange:e=>{let{data:{subscription:t}}=F.auth.onAuthStateChange((n,r)=>{e({event:n,session:r,user:r?.user??null})});return()=>t?.unsubscribe()},resetPassword:e=>F.auth.resetPasswordForEmail(e),signInWithMagicLink:(e,t)=>F.auth.signInWithOtp({email:e,options:{emailRedirectTo:t||window.location.href}})};function so(){let e=document.getElementById("root");if(e)try{let t=window.__FSAOS_COMPONENT__;if(!t){e.innerHTML='<div style="padding:2rem;color:#ef4444;font-family:system-ui"><h2>Component Error</h2><pre>No component found. The bundle may have failed to load.</pre></div>';return}let n=t.default||t,r=window.__FSAOS_ITEM_DATA__||null,s=r?{item:r,...r}:{};(0,Gi.createRoot)(e).render((0,us.createElement)(hn,{client:P()},(0,us.createElement)(n,s)))}catch(t){console.error("[FSAOS] Failed to mount root component:",t),e.innerHTML='<div style="padding:2rem;color:#ef4444;font-family:system-ui"><h2>Component Error</h2><pre>'+(t.message||t)+"</pre></div>"}}function io(){let e=window.React,t=window.ReactDOM,n=window.__FSAOS_GATEWAY__,r=window.__FSAOS_UI__;if(!n){console.error("[FSAOS] Cannot set up require shim: __FSAOS_GATEWAY__ not found");return}let s={react:e,"react-dom":t,"react-dom/client":t,"react/jsx-runtime":{jsx:e?.createElement,jsxs:e?.createElement,Fragment:e?.Fragment},"@fsaos/react":n,"@fsaos/gateway":n,"@fsaos/ui":r||{}};window.require=function(a){if(s[a])return s[a];throw new Error("[FSAOS] Module not found: "+a)},window.__FSAOS_MOUNT__=n.mount}var y=j(ie(),1),tc=j(ao(),1),nc=j(Gn(),1);function ec(e){return`${e}/settings/mounts`}var En=null;async function ls(e,t){En=ec(e);try{let s=((await R("read",{path:En}))?.item?.type_data?.mounts??[]).map(t).filter(a=>a!==null),i=Ue();return i&&!s.some(a=>a.id===i.id)&&s.unshift(i),Fr(s),s}catch{let n=Ue(),r=n?[n]:[];return Fr(r),r}}async function co(){if(!En)return;let e=mt().map(n=>n.id),t=Xe()?.id??null;try{await R("update",{path:En,type_data:{mounts:e,last_anchor:t}})}catch{try{let r=En.split("/").slice(0,-1).join("/");await R("create",{parent_path:r,name:"mounts",item_type:"file",type_data:{mounts:e,last_anchor:t}})}catch(r){console.warn("[SDK] mount declaration persist failed:",r)}}}async function ds(e){Ms(e),await co()}async function uo(e){Os(e),await co()}function K(){return(0,y.useSyncExternalStore)(Ze,_e,_e)}function po(){return K(),Un()}function ho(e){return K(),k({queryKey:w.item(e),queryFn:()=>Zn(e),enabled:!!e})}function mo(e){return K(),k({queryKey:w.itemById(e),queryFn:()=>Xn(e),enabled:!!e})}function ps(e){return K(),k({queryKey:w.children(e),queryFn:()=>er(e),enabled:!!e})}function go(e){let t=ps(e);return{...t,children:t.data??[]}}function yo(e,t=1){return K(),k({queryKey:w.tree(e,t),queryFn:()=>sr(e,t),enabled:!!e})}function _o(e,t){return K(),k({queryKey:w.search(e,t),queryFn:async()=>{let n={query:e};t?.length&&(n.item_types=t);let r=await R("search",n);return(r.content?.items||r.items||[]).map(pe)},enabled:!!e&&e.length>0})}function vo(e){K();let t=(0,y.useMemo)(()=>e,[JSON.stringify(e)]);return k({queryKey:["vfs",le()??"__unscoped__","resolve",JSON.stringify(t??{})],queryFn:async()=>await R("resolve",t),enabled:!!t?.query&&t.query.length>0})}function bo(e){K();let t=(0,y.useMemo)(()=>e,[JSON.stringify(e)]);return k({queryKey:w.items(t?.type??"",t),queryFn:()=>vn(t),enabled:!!t?.type,select:n=>n.items})}function wo(e){K();let t=e?.limit??20,n=(0,y.useMemo)(()=>e,[JSON.stringify(e)]),r=gn({queryKey:["vfs",le()??"__unscoped__","infinite-items",n?.type??"",JSON.stringify(n??{})],queryFn:async({pageParam:i=0})=>vn({...n,limit:t,offset:i}),initialPageParam:0,getNextPageParam:(i,a,c)=>{if(!(i.items.length<t))return c+i.items.length},enabled:!!n?.type});return{allItems:(0,y.useMemo)(()=>{if(!r.data?.pages)return[];let i=new Set,a=[];for(let c of r.data.pages)for(let u of c.items)u.id&&!i.has(u.id)&&(i.add(u.id),a.push(u));return a},[r.data?.pages]),fetchNextPage:r.fetchNextPage,isFetchingNextPage:r.isFetchingNextPage,isExhausted:!r.hasNextPage,isLoading:r.isLoading,isFetching:r.isFetching,error:r.error,totalHint:r.data?.pages?.[0]?.total_hint}}function So(e){K();let t=20,n=gn({queryKey:["vfs",le()??"__unscoped__","infinite-children",e??""],queryFn:async({pageParam:s=0})=>tr(e,t,s),initialPageParam:0,getNextPageParam:(s,i,a)=>{if(!(s.items.length<t))return a+s.items.length},enabled:!!e});return{allItems:(0,y.useMemo)(()=>{if(!n.data?.pages)return[];let s=new Set,i=[];for(let a of n.data.pages)for(let c of a.items)c.id&&!s.has(c.id)&&(s.add(c.id),i.push(c));return i},[n.data?.pages]),fetchNextPage:n.fetchNextPage,isFetchingNextPage:n.isFetchingNextPage,isExhausted:!n.hasNextPage,isLoading:n.isLoading,isFetching:n.isFetching,error:n.error,totalHint:n.data?.pages?.[0]?.total_hint}}function Ro(e){return K(),k({queryKey:w.edges(e),queryFn:()=>rr(e),enabled:!!e})}function gr(e){return K(),k({queryKey:w.types(e),queryFn:()=>nr(e)})}function Co(e,t){let n=gr(t);return{...n,data:n.data?.get(e)??void 0}}function xo(e,t){K();let n=(0,y.useMemo)(()=>t?.arguments,[JSON.stringify(t?.arguments)]),r=t?.mode,s=t?.strategy,i=t?.width;return k({queryKey:[...w.openEnvelope(e,s),i],queryFn:async()=>{let a=await cr(e,{mode:r,strategy:s,arguments:n});if(i&&a.render?.props?.url){let c=a.render.props.url,u=c.includes("?")?"&":"?";a.render.props.url=`${c}${u}w=${i}`}return a},enabled:!!e})}var lo={related_to:"Related To",depends_on:"Depends On",blocks:"Blocks",parent_of:"Parent Of",child_of:"Child Of",references:"References",implements:"Implements",extends:"Extends",contains:"Contains",belongs_to:"Belongs To",created_by:"Created By",assigned_to:"Assigned To",tagged_with:"Tagged With",linked_to:"Linked To"};function Po(e){let t=gr(e),n=t.data??new Map;return(0,y.useMemo)(()=>({canHaveChildren:h=>n.get(h.item_type)?.is_container??!1,isScope:h=>n.get(h.item_type)?.is_scope??!1,isScopeType:h=>n.get(h)?.is_scope??!1,isContainerType:h=>n.get(h)?.is_container??!1,getTypeDefinition:h=>n.get(h),getTypeColor:h=>n.get(h)?.color??"gray",getTypeIcon:h=>n.get(h)?.icon??"File",getTypeDisplayName:h=>n.get(h)?.display_name??h,getKnownEdgeTypes:()=>Object.entries(lo).map(([h,v])=>({key:h,label:v})),getEdgeTypeLabel:h=>lo[h]??h.replace(/_/g," "),allTypes:n,loading:t.isLoading}),[n,t.isLoading])}function Eo(e,t,n){return K(),k({queryKey:w.memberFocus(e),queryFn:()=>ar(e,t,n),enabled:!!e})}function To(e,t={}){let{limit:n=50,offset:r=0,include_snapshots:s=!1}=t;return k({queryKey:w.itemVersions(e,String(n),String(r),String(s)),queryFn:()=>_n(e,{limit:n,offset:r,include_snapshots:s}),enabled:!!e})}function Ao(e,t=50,n=0){return k({queryKey:w.itemHistory(e,String(t),String(n)),queryFn:()=>or(e,t,n),enabled:!!e})}function Mo(e,t=50,n=0){return K(),k({queryKey:w.recentActivity(e,String(t),String(n)),queryFn:()=>ir(e,t,n),enabled:!!e})}function Oo(){let[e,t]=(0,y.useState)(null),[n,r]=(0,y.useState)(!0),[s,i]=(0,y.useState)(null);return(0,y.useEffect)(()=>{let a=!1;return Dn().then(c=>{if(!a){let u=typeof window<"u"&&window.__FSAOS_CONFIG__||{};t({path:c.scope_path,scope_id:c.scope_id,fractal_id:c.fractal_id,instance_name:c.instance_name,display_name:c.display_name,componentPath:u.componentPath||"",isEmbed:!!u.embedToken}),r(!1)}}).catch(c=>{a||(i(c instanceof Error?c:new Error(String(c))),r(!1))}),()=>{a=!0}},[]),{data:e,loading:n,error:s}}var rc=[];function Tn(e){return{id:e.accountId,path:e.path,kind:e.isSpace?"space":"account",name:e.name,grantedUnderAccountId:e.grantedUnderAccountId??void 0}}function Io(){let{user:e}=yr(),t=(0,y.useRef)(!1),n=k({queryKey:w.memberships(e?.id??"anonymous"),queryFn:async()=>((await R("list-memberships",{})).memberships||[]).map(f=>({accountId:f.account_id,path:f.account_path,name:f.account_name,role:f.role||"member",typeData:f.account_type_data||{},joinedAt:f.joined_at,via:f.via,placement:f.placement,subordinateTo:f.subordinate_to??null,cascadeAnchorId:f.cascade_anchor_id??null,isAccount:f.is_account??void 0,isSpace:f.is_space??void 0,isOwner:f.is_owner??void 0,billingResponsible:f.billing_responsible??void 0,grantedVia:f.granted_via??null,grantedUnderAccountId:f.granted_under_account_id??null,personalSpaceId:f.personal_space_id??null,personalSpacePath:f.personal_space_path??null})),enabled:!!e?.id,staleTime:1e3*60*2}),r=n.data??rc,s=(0,y.useMemo)(()=>r.filter(l=>l.isAccount!==!1&&!l.isSpace),[r]),i=(0,y.useMemo)(()=>{let l=new Set(s.map(f=>f.accountId)),p=f=>!f.subordinateTo||!l.has(f.subordinateTo);return[...s].sort((f,h)=>Number(p(h))-Number(p(f)))},[s]),a=(0,y.useSyncExternalStore)(Ze,_e,_e),c=(0,y.useMemo)(()=>{let l=Xe();return l?r.find(p=>p.accountId===l.id)??null:null},[a,r]);(0,y.useEffect)(()=>{if(!e?.id){t.current=!1;return}if(!t.current)if(i.length===1){let l=i[0];Zt(Tn(l)),xn(l.accountId),l.personalSpacePath&&ls(l.personalSpacePath,p=>{let f=r.find(h=>h.accountId===p);return f?Tn(f):null}).catch(()=>{}),t.current=!0}else i.length>1&&(t.current=!0)},[e?.id,i,r]);let u=(0,y.useCallback)(l=>{let p=r.find(h=>h.path===l);if(!p)return;let f=Tn(p);Ue()?Qe(f):(Zt(f),p.personalSpacePath&&ls(p.personalSpacePath,h=>{let v=r.find(m=>m.accountId===h);return v?Tn(v):null}).catch(()=>{})),xn(p.accountId)},[r]),d=(0,y.useCallback)(l=>{let p=r.find(f=>f.path===l);p&&(ds(Tn(p)).catch(()=>{}),Pn(l))},[r]);return{accounts:i,allMemberships:r,currentAccount:c,mountedScope:null,switchAccount:u,mountScope:d,loading:n.isLoading,error:n.error}}function Fo(){let e=(0,y.useSyncExternalStore)(qn,tn,tn);return{mounts:(0,y.useMemo)(()=>mt(),[e]),homeAnchor:Ue(),anchor:Xe(),setAnchor:Qe,mount:ds,unmount:uo}}function yr(){let[e,t]=(0,y.useState)(null),[n,r]=(0,y.useState)(null),[s,i]=(0,y.useState)(!0),a=(0,y.useRef)(null);(0,y.useEffect)(()=>{F.auth.getSession().then(({data:h,error:v})=>{if(v){console.warn("[useAuth] getSession error, clearing stale session:",v.message),F.auth.signOut().catch(()=>{}),r(null),t(null),i(!1);return}r(h?.session??null),t(h?.session?.user??null),i(!1)}).catch(h=>{console.warn("[useAuth] getSession threw, clearing stale session:",h?.message),F.auth.signOut().catch(()=>{}),r(null),t(null),i(!1)});let{data:{subscription:f}}=F.auth.onAuthStateChange((h,v)=>{if(h==="TOKEN_REFRESHED"&&!v){console.warn("[useAuth] TOKEN_REFRESHED with null session \u2014 signing out"),F.auth.signOut().catch(()=>{}),r(null),t(null),i(!1);return}r(v),t(v?.user??null),i(!1)});return a.current=f,()=>{f?.unsubscribe()}},[]);let c=(0,y.useCallback)(async f=>f.provider?F.auth.signInWithOAuth({provider:f.provider,options:f.redirectTo?{redirectTo:f.redirectTo}:{redirectTo:window.location.href}}):F.auth.signInWithPassword({email:f.email,password:f.password}),[]),u=(0,y.useCallback)(async f=>F.auth.signUp({email:f.email,password:f.password,options:{data:f.metadata||{}}}),[]),d=(0,y.useCallback)(async()=>{await F.auth.signOut(),gt(),P().clear()},[]),l=(0,y.useCallback)(async f=>{let{error:h}=await F.auth.resetPasswordForEmail(f);if(h)throw h},[]),p=(0,y.useCallback)(async(f,h)=>{let{error:v}=await F.auth.signInWithOtp({email:f,options:h?{emailRedirectTo:h}:{emailRedirectTo:window.location.href}});if(v)throw v},[]);return{user:e,session:n,loading:s,signIn:c,signUp:u,signOut:d,resetPassword:l,signInWithMagicLink:p}}function ko(e){let[t,n]=(0,y.useState)(null),[r,s]=(0,y.useState)(!1),[i,a]=(0,y.useState)(null);return(0,y.useEffect)(()=>{if(!e){n(null),s(!1);return}if(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e))s(!0),R("resolve-asset",{asset_id:e}).then(u=>{u.success&&u.public_url?n({url:u.public_url,id:u.asset_id,name:u.name,mimeType:u.mime_type,width:u.width,height:u.height,sizeBytes:u.size_bytes}):a(new Error(u.error||"Asset not found")),s(!1)}).catch(u=>{a(u instanceof Error?u:new Error(String(u))),s(!1)});else{let d=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"";n({url:d+e}),s(!1)}},[e]),{data:t,loading:r,error:i}}var An={},fo={};Pe(()=>{for(let e of Object.keys(An))delete An[e]});var qo=null;function Do(e){qo=e,typeof window<"u"&&!window.__FSAOS_GATEWAY__&&(window.__FSAOS_GATEWAY__=e)}function sc(e){switch(e){case"react":return typeof window<"u"&&window.React||y.default;case"react-dom":case"react-dom/client":return typeof window<"u"&&window.ReactDOM||tc;case"react/jsx-runtime":case"react/jsx-dev-runtime":return typeof window<"u"&&window.React?{jsx:window.React.createElement,jsxs:window.React.createElement,Fragment:window.React.Fragment}:nc;case"@fsaos/gateway":case"@fsaos/react":return typeof window<"u"&&window.__FSAOS_GATEWAY__||qo||{};case"@fsaos/ui":return typeof window<"u"&&window.__FSAOS_UI__||{};case"@fsaos/theme":return{};default:return console.warn(`[useComponent] Unknown module requested: ${e}`),{}}}function ic(e,t){return e.replace(/^(\s*)(:root|body)(\s*[{,])/gm,(n,r,s,i)=>`${r}.${t}${i}`)}async function oc(e,t){if(!fo[e])try{let n=await fetch(e);if(!n.ok)return;let r=await n.text();if(!r.trim()||r.includes("No CSS bundle for this component"))return;t&&!r.includes(`.fsaos-c-${t}`)&&(r=ic(r,`fsaos-c-${t}`));let s=document.createElement("style");s.setAttribute("data-fsaos-component-css",e),t&&s.setAttribute("data-fsaos-component-id",t),s.textContent=r,document.head.appendChild(s),fo[e]=s}catch{}}function ac(e){let t=null,n=window.__FSAOS_REGISTER__;window.__FSAOS_REGISTER__=r=>{t=r};try{let r=["var require = arguments[0];",e,"return window.__FSAOS_COMPONENT__;"].join(`
3
- `),i=new Function(r)(sc),a=t??i;return a?a.default||a:null}finally{n!==void 0?window.__FSAOS_REGISTER__=n:delete window.__FSAOS_REGISTER__}}function hs(e){let[t,n]=(0,y.useState)(null),[r,s]=(0,y.useState)(!0),[i,a]=(0,y.useState)(null);return(0,y.useEffect)(()=>{if(!e)return;let c=!1;s(!0),a(null);let d=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"";return(async()=>{try{let l=1,p=e+"@v1",f=d+e+"/__bundle.js";try{let S=await fetch(d+e+"/__meta",{cache:"no-store"});S.ok&&(l=(await S.json()).version||1,p=e+"@v"+l,f=d+e+"/__bundle.v"+l+".js")}catch{f=d+e+"/__bundle.js?v="+Date.now()}if(c)return;if(An[p]){n(()=>An[p]),s(!1);return}let h=await fetch(f);if(!h.ok)throw new Error(`Failed to fetch bundle: ${h.status} ${h.statusText} (${f})`);let v=await h.text();if(c)return;let m=f.replace(/__bundle(\.v\d+)?\.js(\?.*)?$/,"__bundle$1.css");oc(m).catch(()=>{});let g=ac(v);if(!g)throw new Error("Bundle did not export a component. Expected window.__FSAOS_COMPONENT__ (FSAOS build) or a __FSAOS_REGISTER__(Component) call.");if(typeof g!="function")throw new Error(`Bundle export is not a React component (got ${typeof g})`);An[p]=g,c||(n(()=>g),s(!1))}catch(l){c||(a(l instanceof Error?l:new Error(String(l))),s(!1))}})(),()=>{c=!0}},[e]),{Component:t,loading:r,error:i}}var cc=["--color-primary","--color-secondary","--color-background","--color-surface","--color-text","--color-text-secondary","--color-border","--color-accent","--color-success","--color-warning","--color-error","--font-family-heading","--font-family-body","--border-radius","--spacing-unit"];function Qo(){return{data:(0,y.useMemo)(()=>{if(typeof document>"u")return{tokens:{}};let t={},n=getComputedStyle(document.documentElement);return cc.forEach(r=>{t[r]=n.getPropertyValue(r).trim()}),{tokens:t}},[]),loading:!1,error:null}}function Uo(e,t){return{data:{allowed:!0},loading:!1,error:null}}function No(e,t){let n={};return(t||[]).forEach(r=>{n[r]=!0}),{data:n,loading:!1,error:null}}var oe=null,Vt=null,fs=new Set;function uc(){fs.forEach(e=>e())}Pe(()=>{oe=null,Vt=null});async function Ko(e){let t=e;if(!t){let{data:r}=await F.auth.getSession();t=r?.session?.user?.id}let n={principalId:null,displayName:null,createdAt:null,metadata:null,vfsPath:null};if(!t)return n;if(oe&&oe.authUserId===t){let{principalId:r,displayName:s,createdAt:i,metadata:a,vfsPath:c}=oe;return{principalId:r,displayName:s,createdAt:i,metadata:a,vfsPath:c}}return Vt||(Vt=(async()=>{try{let{data:r,error:s}=await F.from("os_principals").select("id, display_name, created_at, metadata").eq("auth_user_id",t).eq("principal_type","user").maybeSingle();if(s)return console.warn("[SDK] Could not resolve principal:",s.message),n;let i=r?.id??null,a=null;if(i){let{data:u}=await F.from("os_items").select("path").eq("owner_principal_id",i).eq("item_type","principal").eq("is_active",!0).like("path","/root/principals/%"),d=(u??[]).map(l=>l.path);a=d.find(l=>l.split("/").length===4)??d[0]??null}let c={principalId:i,displayName:r?.display_name??null,createdAt:r?.created_at??null,metadata:r?.metadata??null,vfsPath:a};return oe={authUserId:t,...c},c}finally{Vt=null}})(),Vt)}async function Lo(e){return(await Ko(e)).principalId}function jo(){let e=yr(),t=e.user,n=oe?.authUserId===t?.id?oe:null,[r,s]=(0,y.useState)(n),i=(0,y.useRef)(null);return(0,y.useEffect)(()=>{let a=()=>{let c=oe;c&&c.authUserId===t?.id&&s({principalId:c.principalId,displayName:c.displayName,createdAt:c.createdAt,metadata:c.metadata,vfsPath:c.vfsPath})};return fs.add(a),()=>{fs.delete(a)}},[t?.id]),(0,y.useEffect)(()=>{if(!t?.id){s(null),i.current=null;return}i.current===t.id&&r?.principalId!=null||(i.current=t.id,Ko(t.id).then(a=>{s(a)}))},[t?.id]),e.loading?{data:null,loading:!0,error:null}:t?{data:{id:t.id,principalId:r?.principalId??null,email:t.email,display_name:r?.displayName??void 0,created_at:r?.createdAt??void 0,vfs_path:r?.vfsPath??void 0,role:t.role||t.app_metadata?.role||"user",authenticated:!0,metadata:r?.metadata??t.user_metadata??{}},loading:!1,error:null}:{data:{id:"anonymous",principalId:null,role:"viewer",authenticated:!1},loading:!1,error:null}}function Vo(){return{data:null,loading:!1,error:null}}function Ho(e){let{path:t,...n}=e,r=hs(t),s=r.Component,{loading:i,error:a}=r;return i?(0,y.createElement)("div",{className:"fsaos-loading"},""):a?(0,y.createElement)("div",{className:"fsaos-error"},"Failed to load component"):s?(0,y.createElement)(s,n):null}function Wo(e){return e.children}function Bo(e){let t=K(),{channelPath:n,parentMessageId:r,realtime:s=!0,enabled:i}=e,a=i!==void 0?i&&!!n:!!n,c=(0,y.useMemo)(()=>w.channelMessages(n??"",r),[n,r,t]),u=U(),d=(0,y.useRef)(null),l=k({queryKey:c,queryFn:()=>ur(n,r),enabled:a});(0,y.useEffect)(()=>{if(!s||!a)return;let m=J("vfs_change",()=>{d.current&&clearTimeout(d.current),d.current=setTimeout(()=>{u.invalidateQueries({queryKey:c})},500)},g=>(g.item_type==="message"||g.item_type==="card")&&typeof g.path=="string"&&g.path.startsWith(n));return()=>{m(),d.current&&clearTimeout(d.current)}},[s,a,n,c,u]);let p=l.data,f=p?.messages??[],h=p?.messageCards??new Map,v=p?.siblingCards??[];return{messages:f,messageCards:h,siblingCards:v,threads:(0,y.useMemo)(()=>f.filter(m=>m.reply_count>0),[f]),isLoading:l.isLoading,isFetching:l.isFetching,error:l.error,refetch:l.refetch}}function $o(e){K();let{channelPath:t,parentMessageId:n,limit:r=50,realtime:s=!0,enabled:i=!0}=e,a=!!n,c=i&&!!t,u=gn({queryKey:[...w.channelMessages(t||"",n),"infinite",r],queryFn:async({pageParam:m})=>bn(t,{parentMessageId:n,limit:r,before_seq:a?void 0:m,after_seq:a?m:void 0}),initialPageParam:void 0,getNextPageParam:m=>!a||m.messages.length<r?void 0:m.messages[m.messages.length-1]?.seq,getPreviousPageParam:m=>a||m.messages.length<r?void 0:m.messages[0]?.seq,enabled:c}),d=(0,y.useMemo)(()=>{if(!u.data?.pages)return[];let m=new Set,g=[];for(let S of u.data.pages)for(let C of S.messages)m.has(C.id)||(m.add(C.id),g.push(C));return g.sort((S,C)=>S.seq-C.seq)},[u.data?.pages]),{messageCards:l,siblingCards:p}=(0,y.useMemo)(()=>{let m=new Map,g=[];if(!u.data?.pages)return{messageCards:m,siblingCards:g};let S=new Set;for(let C of u.data.pages){for(let[E,Q]of C.messageCards)for(let L of Q){if(S.has(L.id))continue;S.add(L.id);let W=m.get(E)||[];W.push(L),m.set(E,W)}for(let E of C.siblingCards)S.has(E.id)||(S.add(E.id),g.push(E))}return{messageCards:m,siblingCards:g}},[u.data?.pages]),f=U(),h=(0,y.useRef)(null),v=(0,y.useMemo)(()=>[...w.channelMessages(t||"",n),"infinite",r],[t,n,r]);return(0,y.useEffect)(()=>{if(!s||!t||!c)return;let m=J("vfs_change",()=>{h.current&&clearTimeout(h.current),h.current=setTimeout(async()=>{let g=f.getQueryData(v);if(!g?.pages?.length){f.invalidateQueries({queryKey:v});return}let S=0;for(let C of g.pages)for(let E of C.messages)E.seq>S&&(S=E.seq);if(S===0){f.invalidateQueries({queryKey:v});return}try{let C=await bn(t,{parentMessageId:n,limit:r,after_seq:S});if(C.messages.length===0&&C.siblingCards.length===0){f.invalidateQueries({queryKey:v});return}if(C.messages.length>0){let E=Math.min(...C.messages.map(Q=>Q.seq));if(E>S+1){console.warn(`[useInfiniteChannelMessages] sequence gap detected: maxSeq=${S}, minNewSeq=${E}. Triggering full refetch.`),f.invalidateQueries({queryKey:v});return}}f.setQueryData(v,E=>{if(!E)return E;let Q=[...E.pages],L=Q.length-1,W=Q[L],dt=new Set(W.messages.map(A=>A.id)),re=C.messages.filter(A=>!dt.has(A.id)),N=[...W.messages,...re].sort((A,Ye)=>A.seq-Ye.seq),Y=new Map(W.messageCards);for(let[A,Ye]of C.messageCards){let $=Y.get(A)||[],Ht=new Set($.map(wr=>wr.id)),_a=Ye.filter(wr=>!Ht.has(wr.id));Y.set(A,[...$,..._a])}let me=new Set(W.siblingCards.map(A=>A.id)),ge=C.siblingCards.filter(A=>!me.has(A.id)),ye=[...W.siblingCards,...ge];return Q[L]={...W,messages:N,messageCards:Y,siblingCards:ye},{...E,pages:Q}})}catch(C){console.warn("[useInfiniteChannelMessages] live tail fetch failed, falling back to full invalidation:",C),f.invalidateQueries({queryKey:v})}},500)},g=>(g.item_type==="message"||g.item_type==="card")&&typeof g.path=="string"&&g.path.startsWith(t));return()=>{m(),h.current&&clearTimeout(h.current)}},[s,t,c,v,f,n,r]),{messages:d,messageCards:l,siblingCards:p,threads:d.filter(m=>m.reply_count>0),isLoading:u.isLoading,isFetching:u.isFetching,error:u.error,refetch:u.refetch,hasPreviousPage:u.hasPreviousPage??!1,fetchPreviousPage:u.fetchPreviousPage,isFetchingPreviousPage:u.isFetchingPreviousPage??!1,hasNextPage:u.hasNextPage??!1,fetchNextPage:u.fetchNextPage,isFetchingNextPage:u.isFetchingNextPage??!1}}function lc(e){return e==="on"||e==="auto"?"on":"off"}function dc(e){let t=e.type_data||{},n=e._reader||{},r=n.context_lineage||{};return{id:e.id||"",path:e.path||"",name:e.name||"",displayName:t.display_name||e.name||"",aiMode:lc(t.ai_mode),isPrivate:t.is_private||!1,isDm:t.is_dm||!1,messageCount:t.message_count||0,updatedAt:e.updated_at||"",chatScopePath:r.context_path||"",contextId:e.scope_item_id||"",contextPath:r.context_path||"",contextType:r.context_type||"",contextName:r.context_name||"",contextDisplayName:r.context_name||"",contextPrincipalId:void 0,accountId:e.account_item_id||"",accountPath:"",accountDisplayName:"",memberRole:n.member_role||"member",memberPath:"",modePath:"",autoPilot:t.auto_pilot||!1}}function _r(e={}){let t=K(),{realtime:n=!0,enabled:r=!0}=e,s=U(),i=(0,y.useRef)(null),a=(0,y.useMemo)(()=>w.channels("all"),[t]),c=k({queryKey:a,queryFn:async()=>((await R("query",{item_type:"channel",include_reader:!0,limit:500})).items||[]).map(dc),enabled:r});return(0,y.useEffect)(()=>{if(!n||!r)return;let d=J("vfs_change",()=>{i.current&&clearTimeout(i.current),i.current=setTimeout(()=>{s.invalidateQueries({queryKey:a})},1e3)},p=>p.item_type==="channel"||p.item_type==="message"),l=J("ccm_change",()=>{i.current&&clearTimeout(i.current),i.current=setTimeout(()=>{s.invalidateQueries({queryKey:a})},1e3)},p=>p.item_type==="channel"||p.item_type==="message");return()=>{d(),l(),i.current&&clearTimeout(i.current)}},[n,r,a,s]),{channels:c.data??[],isLoading:c.isLoading,isFetching:c.isFetching,error:c.error,refetch:c.refetch}}function Go(e={}){let t=_r(e),n=(0,y.useMemo)(()=>t.channels.filter(r=>!r.isDm),[t.channels]);return{...t,channels:n}}function zo(e={}){let t=_r(e),n=(0,y.useMemo)(()=>t.channels.filter(r=>r.isDm),[t.channels]);return{...t,channels:n}}function ms(e={}){let t=K(),{filter:n="all",limit:r=200,realtime:s=!0,enabled:i=!0}=e,a=U(),c=(0,y.useRef)(null),u=(0,y.useMemo)(()=>w.notifications(n,r),[n,r,t]),d=k({queryKey:u,queryFn:async()=>{let p={limit:r};return n==="unread"&&(p.filter="unread"),(await R("get-notifications",p)).notifications||[]},enabled:i});return(0,y.useEffect)(()=>{if(!s||!i)return;let p=["vfs_change","ccm_change"].map(f=>J(f,()=>{c.current&&clearTimeout(c.current),c.current=setTimeout(()=>{a.invalidateQueries({queryKey:u})},2e3)},h=>h.item_type==="notification"||h.item_type==="message"));return()=>{p.forEach(f=>f()),c.current&&clearTimeout(c.current)}},[s,i,u,a]),{notifications:d.data??[],isLoading:d.isLoading,isFetching:d.isFetching,error:d.error,refetch:d.refetch}}function Jo(e={}){let{channels:t,realtime:n=!0,enabled:r=!0}=e,{notifications:s,isLoading:i,isFetching:a,error:c,refetch:u}=ms({filter:"unread",limit:200,realtime:n,enabled:r}),d=(0,y.useMemo)(()=>{let h=new Map;for(let v of s)v.is_unread&&v.channel_id&&h.set(v.channel_id,(h.get(v.channel_id)||0)+1);return h},[s]),l=(0,y.useMemo)(()=>{let h=0;return d.forEach(v=>{h+=v}),h},[d]),{dmUnread:p,channelUnread:f}=(0,y.useMemo)(()=>{if(!t)return{dmUnread:0,channelUnread:0};let h=new Set(t.filter(g=>g.isDm).map(g=>g.id)),v=0,m=0;return d.forEach((g,S)=>{h.has(S)?v+=g:m+=g}),{dmUnread:v,channelUnread:m}},[t,d]);return{unreadByChannel:d,totalUnread:l,dmUnread:p,channelUnread:f,isLoading:i,isFetching:a,error:c,refetch:u}}function Yo(){let e=U();return ke({mutationFn:t=>R("create",t),onSuccess:(t,n)=>{let r=n.parent_path;r&&e.invalidateQueries({queryKey:w.children(r)})}})}function Xo(){let e=U();return ke({mutationFn:t=>R("update",t),onSuccess:(t,n)=>{let r=n.path;if(r){e.invalidateQueries({queryKey:w.item(r)});let s=r.split("/");s.pop();let i=s.join("/");i&&e.invalidateQueries({queryKey:w.children(i)})}}})}function Zo(){return ke({mutationFn:e=>R("update-principal",e),onSuccess:(e,t)=>{if(!oe)return;let n=e&&typeof e=="object"&&e.metadata?e.metadata:{...oe.metadata??{},...typeof t.language=="string"?{language:t.language}:{},...typeof t.timezone=="string"?{timezone:t.timezone}:{},..."avatar_file_id"in t?{avatar_file_id:t.avatar_file_id}:{}};oe={...oe,displayName:typeof t.display_name=="string"?t.display_name:oe.displayName,metadata:n},uc()}})}function ea(){let e=U();return ke({mutationFn:t=>R("delete",t),onSuccess:(t,n)=>{let r=n.path;if(r){e.removeQueries({queryKey:w.item(r)});let s=r.split("/");s.pop();let i=s.join("/");i&&e.invalidateQueries({queryKey:w.children(i)})}}})}function ta(){let e=U();return ke({mutationFn:t=>R("move",t),onSuccess:(t,n)=>{let r=n.path,s=n.new_parent_path;if(r){e.invalidateQueries({queryKey:w.item(r)});let i=r.split("/");i.pop();let a=i.join("/");a&&e.invalidateQueries({queryKey:w.children(a)})}s&&e.invalidateQueries({queryKey:w.children(s)})}})}function na(){let e=U();return ke({mutationFn:t=>R("link",t),onSuccess:(t,n)=>{let r=n.source_id,s=n.target_id;r&&e.invalidateQueries({queryKey:w.edges(r)}),s&&e.invalidateQueries({queryKey:w.edges(s)})}})}function ra(e,t){let n=U(),{optimistic:r,...s}=t??{};return ke({mutationFn:i=>R(e,i),onMutate:r?async i=>{await n.cancelQueries({queryKey:r.queryKey});let a=n.getQueryData(r.queryKey);return n.setQueryData(r.queryKey,c=>r.update(c,i)),{previous:a}}:void 0,onError:(i,a,c)=>{r&&c?.previous!==void 0&&n.setQueryData(r.queryKey,c.previous),s.onError?.(i)},onSuccess:s.onSuccess,onSettled:r?()=>{n.invalidateQueries({queryKey:r.queryKey})}:void 0})}function sa(e,t,n){let r,s,i,a=!0;if(typeof e=="string")r=e,s=t,i=n;else{s=e;let d=t;r=d.eventType,i=d.filter,a=d.enabled??!0}let c=(0,y.useRef)(s),u=(0,y.useRef)(i);(0,y.useEffect)(()=>{c.current=s,u.current=i},[s,i]),(0,y.useEffect)(()=>a?J(r,l=>c.current(l),u.current?l=>u.current(l):void 0):void 0,[r,a])}function ia(e){let{queryKey:t,queryFn:n,eventType:r,filter:s,enabled:i=!0,debounceMs:a=500}=e,c=U(),u=(0,y.useRef)(null),d=k({queryKey:t,queryFn:n,enabled:i});return(0,y.useEffect)(()=>{if(!i)return;let l=J(r,()=>{u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{c.invalidateQueries({queryKey:t})},a)},s);return()=>{l(),u.current&&clearTimeout(u.current)}},[r,i,a,c,JSON.stringify(t)]),d}function oa(e){K();let t=(0,y.useMemo)(()=>e?typeof e=="string"?{path:e}:e:null,[typeof e=="string"?e:JSON.stringify(e)]),n=!!t&&!!(t.key||t.path||t.item_id),r=t?.key??t?.path??t?.item_id??"",s=k({queryKey:["vfs",le()??"__unscoped__","arrangement",r],queryFn:async()=>{if(!t)return null;let l=await R("resolve-arrangement",t);return l?.success===!1?(console.warn("[useArrangement] resolve-arrangement failed:",l?.error),null):l??null},enabled:n}),i=s.data??null,a=(0,y.useMemo)(()=>i?.resolved_children??[],[i]),c=i?.resolution_level??null,u=(0,y.useMemo)(()=>{let p=(i?.type_data??null)?.order;return Array.isArray(p)?p:null},[i]),d=(0,y.useCallback)(l=>{if(!u||!l?.length)return l??[];let p=m=>m.id??m.name??"",f=new Map(u.map((m,g)=>[m,g])),h=[],v=[];for(let m of l)(f.has(p(m))?h:v).push(m);return h.sort((m,g)=>f.get(p(m))-f.get(p(g))),[...h,...v]},[u]);return{...s,arrangement:i,resolvedChildren:a,resolutionLevel:c,order:u,sourceScopeId:i?.scope_item_id??null,applyTo:d}}function fc(e){return e.split("_").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function pc(e,t){return t&&t.length>0?"select":e==="boolean"?"toggle":e==="integer"||e==="number"?"range":e==="string"?"text":"none"}function hc(e,t){return!(e==="object"||e==="array")}function mc(e){return["string","number","integer","boolean"].includes(e)}function gc(e){return e!=="object"&&e!=="array"}function aa(e,t,n,r){let s=e?.properties;if(!s||typeof s!="object")return[];let i=[];for(let[a,c]of Object.entries(s)){let u=c.type||"string",d=c.enum,l=hc(u,d),p=mc(u),f=pc(u,d);i.push({key:a,label:c.title||fc(a),type:u,description:c.description,enum_values:d,default_value:n[a]??r[a]??c.default,editable:t,filterable:l,sortable:p,filter_widget:f})}return i}function gs(e){let t=e.default_data||{},n=e.field_defaults||{},r=aa(e.input_schema,!0,t,n),s=aa(e.system_schema,!1,t,n),i=[...r,...s],a=i.filter(d=>gc(d.type)),c=i.filter(d=>d.filterable),u=i.filter(d=>d.sortable);return{fields:i,columns:a,filterable:c,sortable:u,form_fields:r,system_fields:s}}function ca(e){return{field:"updated_at",direction:"desc"}}function ua(e){let t=gs(e),n=new Set(e.input_schema?.required||[]);return t.form_fields.filter(r=>n.has(r.key)||r.default_value===void 0)}var ne=j(ie(),1);var yc=0;function _c(){return`upload_${Date.now()}_${++yc}`}async function la(e,t,n,r){let s=t.name||(e instanceof File?e.name:`file-${Date.now()}`),i=e.type||"application/octet-stream",a=t.itemType||"file",u=await R("create",{parent_path:t.parentPath,item_type:a,name:s,type_data:{...t.typeData||{},file_source:{type:"upload",content_type:i}}});if(!u.id)throw new Error(u.error||u.message||"Failed to create file item");let d=u.id,l=u.path;if(u.storage_completed&&u.file_ref)return{itemId:d,itemPath:l,fileRef:u.file_ref};let p=u.storage_key,f=u.upload_token,h=u.storage_worker_url||"https://fsaos-storage.radns.workers.dev";if(!p)throw new Error("Gateway returned no storage_key \u2014 file_source may not be supported for this item type");await vc(h,p,f,e,i,n,r);let v=await da(d,p,i);return{itemId:d,itemPath:l,fileRef:v}}function vc(e,t,n,r,s,i,a){return new Promise((c,u)=>{let d=new XMLHttpRequest;if(d.open("PUT",`${e}/upload`),d.setRequestHeader("X-Storage-Key",t),d.setRequestHeader("Content-Type",s),n&&d.setRequestHeader("X-Upload-Token",n),d.upload.onprogress=l=>{l.lengthComputable&&i&&i(Math.round(l.loaded/l.total*100))},d.onload=()=>{d.status>=200&&d.status<300?c():u(new Error(`Storage upload failed: HTTP ${d.status} \u2014 ${d.responseText?.slice(0,300)}`))},d.onerror=()=>u(new Error("Storage upload network error")),d.ontimeout=()=>u(new Error("Storage upload timed out")),a){if(a.aborted){u(new Error("Upload cancelled"));return}a.addEventListener("abort",()=>{d.abort(),u(new Error("Upload cancelled"))})}d.send(r)})}async function da(e,t,n){let r=await xe(),s=await fetch(`${De}/storage/upload-complete`,{method:"POST",headers:{"Content-Type":"application/json",...r?{Authorization:`Bearer ${r}`}:{}},body:JSON.stringify({item_id:e,storage_key:t,content_type:n})});if(!s.ok){let a=await s.text().catch(()=>"");throw new Error(`Upload confirmation failed: HTTP ${s.status} \u2014 ${a.slice(0,300)}`)}let i=await s.json();if(!i.success)throw new Error(i.error||i.message||"Upload confirmation rejected");return i.file_ref}function fa(){let[e,t]=(0,ne.useState)([]),n=U(),r=(0,ne.useRef)(e);r.current=e;let s=(0,ne.useCallback)((m,g)=>{t(S=>S.map(C=>C.id===m?{...C,...g}:C))},[]),i=(0,ne.useCallback)(m=>{t(g=>[...g,m])},[]),a=(0,ne.useCallback)(async(m,g,S,C,E)=>{let Q=S.name||g.name,L=g.type||"application/octet-stream",W=S.itemType||"file",dt=E?.itemId||null,re=E?.itemPath||null,N=E?.storageKey||null,Y=E?.uploadToken||null,me=E?.storageWorkerUrl||null;try{if(!C||C==="create"){s(m,{status:"creating",error:null,_failedAt:null});let A=await R("create",{parent_path:S.parentPath,item_type:W,name:Q,type_data:{...S.typeData||{},file_source:{type:"upload",content_type:L}}});if(!A.id)throw Object.assign(new Error(A.error||A.message||"Failed to create file item"),{_step:"create"});if(dt=A.id,re=A.path,s(m,{itemId:dt,itemPath:re}),A.storage_completed&&A.file_ref){s(m,{status:"complete",progress:100,fileRef:A.file_ref}),n.invalidateQueries({queryKey:w.children(S.parentPath)});return}if(N=A.storage_key,Y=A.upload_token||"",me=A.storage_worker_url||"https://fsaos-storage.radns.workers.dev",s(m,{_storageKey:N,_uploadToken:Y,_storageWorkerUrl:me}),!N)throw Object.assign(new Error("Gateway returned no storage_key"),{_step:"create"})}(!C||C==="create"||C==="upload")&&(s(m,{status:"uploading",progress:0,error:null,_failedAt:null}),await new Promise((A,Ye)=>{let $=new XMLHttpRequest;s(m,{_xhr:$}),$.open("PUT",`${me}/upload`),$.setRequestHeader("X-Storage-Key",N),$.setRequestHeader("Content-Type",L),Y&&$.setRequestHeader("X-Upload-Token",Y),$.upload.onprogress=Ht=>{Ht.lengthComputable&&s(m,{progress:Math.round(Ht.loaded/Ht.total*100)})},$.onload=()=>{$.status>=200&&$.status<300?A():Ye(Object.assign(new Error(`Storage upload failed: HTTP ${$.status}`),{_step:"upload"}))},$.onerror=()=>Ye(Object.assign(new Error("Storage upload network error"),{_step:"upload"})),$.ontimeout=()=>Ye(Object.assign(new Error("Storage upload timed out"),{_step:"upload"})),$.send(g)}),s(m,{progress:100,_xhr:null})),s(m,{status:"confirming",error:null,_failedAt:null});let ge=await da(dt,N,L);s(m,{status:"complete",fileRef:ge}),n.invalidateQueries({queryKey:w.children(S.parentPath)})}catch(ge){let ye=ge?.message||String(ge),A=ge?._step||"create";s(m,{status:"error",error:ye,_failedAt:A,_xhr:null})}},[s,n]),c=(0,ne.useCallback)((m,g)=>{let S=_c();i({id:S,file:m,status:"creating",progress:0,error:null,itemId:null,itemPath:null,fileRef:null,options:g,_storageKey:null,_uploadToken:null,_storageWorkerUrl:null,_xhr:null,_failedAt:null}),a(S,m,g)},[i,a]),u=(0,ne.useCallback)((m,g)=>{for(let S of m)c(S,g)},[c]),d=(0,ne.useCallback)(m=>{let g=r.current.find(E=>E.id===m);if(!g||g.status!=="error")return;let S=g._failedAt||"create",C=g._storageKey&&g.itemId?{storageKey:g._storageKey,uploadToken:g._uploadToken||"",storageWorkerUrl:g._storageWorkerUrl||"https://fsaos-storage.radns.workers.dev",itemId:g.itemId,itemPath:g.itemPath||""}:void 0;a(m,g.file,g.options,S,C)},[a]),l=(0,ne.useCallback)(m=>{let g=r.current.find(S=>S.id===m);g&&(g._xhr&&g._xhr.abort(),s(m,{status:"error",error:"Cancelled",_xhr:null,_failedAt:null}))},[s]),p=(0,ne.useCallback)(m=>{t(g=>g.filter(S=>S.id!==m))},[]),f=(0,ne.useCallback)(()=>{t(m=>m.filter(g=>g.status!=="complete"))},[]),h=e.some(m=>m.status==="creating"||m.status==="uploading"||m.status==="confirming"),v=e.map(({_storageKey:m,_uploadToken:g,_storageWorkerUrl:S,_xhr:C,_failedAt:E,...Q})=>Q);return{upload:c,uploadMultiple:u,uploads:v,retryUpload:d,cancelUpload:l,removeUpload:p,clearCompleted:f,isUploading:h}}var pa=j(ie(),1);async function ys(e,t){return await R("resolve-items",{context_id:e,item_type:t})}function ha(e,t){return(0,pa.useSyncExternalStore)(Ze,_e,_e),k({queryKey:["vfs",le()??"__unscoped__","resolved-items",e??"",t],queryFn:()=>ys(e,t),enabled:!!(e&&t)})}var he=j(ie(),1);function vr(e,t){let n={artifacts:new Map,timeline:[]},r=new Map;function s(a){if(!a.action?.startsWith("artifact_"))return;let u,d=a.name;if(typeof d=="string"&&d.startsWith("{"))try{u=JSON.parse(d)}catch{return}else if(a.artifact_id)u=a;else return;switch(u.type){case"artifact_opened":{let l=Date.now();if(n.artifacts.set(u.artifact_id,{artifact_id:u.artifact_id,surface_type:u.surface_type,tool_id:u.tool_id,tool_name:u.tool_name,target_uri:u.target_uri,status:"streaming",content:"",total_chars:0,delta_count:0,artifact_item_uri:null,evidence_uri:null,meta:u.meta,started_at:l,completed_at:null}),r.has(u.tool_id)){let p=r.get(u.tool_id);n.timeline[p].artifact_ids.push(u.artifact_id)}else{let p=n.timeline.length;n.timeline.push({tool_id:u.tool_id,tool_name:u.tool_name,status:"started",target_uri:u.target_uri,started_at:l,completed_at:null,artifact_ids:[u.artifact_id]}),r.set(u.tool_id,p)}break}case"artifact_delta":{let l=n.artifacts.get(u.artifact_id);l&&(l.content+=u.content_delta,l.total_chars+=u.content_delta.length,l.delta_count+=1,u.target_uri&&!l.target_uri&&(l.target_uri=u.target_uri));break}case"artifact_done":{let l=n.artifacts.get(u.artifact_id);l&&(l.status=u.status,l.total_chars=u.total_chars,l.artifact_item_uri=u.artifact_item_uri,l.evidence_uri=u.evidence_uri,u.target_uri&&(l.target_uri=u.target_uri),(u.status==="completed"||u.status==="failed")&&(l.completed_at=Date.now()));let p=r.get(u.tool_id);if(p!==void 0){let f=n.timeline[p];u.status==="executing"?f.status="executing":u.status==="completed"?(f.status="completed",f.completed_at=Date.now()):u.status==="failed"&&(f.status="failed",f.completed_at=Date.now()),u.target_uri&&!f.target_uri&&(f.target_uri=u.target_uri)}break}}t(n)}return dr(e,s)}function ma(e,t=!0){let[n,r]=(0,he.useState)(new Map),[s,i]=(0,he.useState)([]),a=(0,he.useRef)({artifacts:new Map,timeline:[]});(0,he.useEffect)(()=>!e||!t?void 0:vr(e,p=>{a.current=p,r(new Map(p.artifacts)),i([...p.timeline])}),[e,t]);let c=(0,he.useCallback)(()=>{r(new Map),i([]),a.current={artifacts:new Map,timeline:[]}},[]),u=Array.from(n.values()).find(l=>l.surface_type==="file_editor"&&l.status==="streaming")??null,d=Array.from(n.values()).filter(l=>l.surface_type==="activity"&&(l.status==="streaming"||l.status==="executing"));return{artifacts:n,timeline:s,activeEditor:u,activeActivities:d,reset:c}}function ga(e,t=!0){let[n,r]=(0,he.useState)([]);(0,he.useEffect)(()=>!e||!t?void 0:vr(e,a=>{r([...a.timeline])}),[e,t]);let s=n.length>0?n[n.length-1]:null;return{timeline:n,latestActivity:s}}var br=j(ie(),1);function bc(e,t,n,r){return["vfs","timeline-history",e,t??"__all__",n??500,r??0]}async function _s(e,t){let n=`${e}/datasets/agent-events`,r=t?.limit??500,s=t?.offset??0,i={limit:r,offset:s,sort:[{key:"seq",direction:"asc"}]};t?.turnId&&(i.filters=[{key:"turn_id",operator:"eq",value:t.turnId}]);try{let c=(await R("open",{path:n,mode:"extract",strategy:"rows",arguments:i}))?.content;return c?(c.rows??c.items??c.data??[]).map(wc).sort((d,l)=>d.seq-l.seq):[]}catch(a){if(a?.status===404||a?.message?.includes("not found"))return[];throw a}}function ya(e,t){let{turnId:n,limit:r=500,offset:s=0,enabled:i=!0,debounceMs:a=300}=t??{},c=e?`${e}/datasets/agent-events`:null,u=U(),d=(0,br.useRef)(null),l=c?bc(c,n,r,s):["vfs","timeline-history","__disabled__"],p=k({queryKey:l,queryFn:()=>_s(e,{turnId:n,limit:r,offset:s}),enabled:!!e&&i});return(0,br.useEffect)(()=>{if(!c||!i)return;let f=J("vfs_change",()=>{d.current&&clearTimeout(d.current),d.current=setTimeout(()=>{u.invalidateQueries({queryKey:l})},a)},h=>{let v=h?.path;return v?v===c||v.startsWith(c+"/"):!1});return()=>{f(),d.current&&clearTimeout(d.current)}},[c,i,a,u,JSON.stringify(l)]),{events:p.data??[],isLoading:p.isLoading,error:p.error,isFetching:p.isFetching,refetch:()=>{p.refetch()}}}function wc(e){return{turn_id:String(e.turn_id??""),seq:Number(e.seq??0),kind:String(e.kind??""),status:String(e.status??""),title:String(e.title??""),tool_name:e.tool_name!=null?String(e.tool_name):void 0,tool_id:e.tool_id!=null?String(e.tool_id):void 0,evidence_uri:e.evidence_uri!=null?String(e.evidence_uri):void 0,artifact_item_uri:e.artifact_item_uri!=null?String(e.artifact_item_uri):void 0,preview:e.preview!=null?String(e.preview):void 0,duration_ms:e.duration_ms!=null?Number(e.duration_ms):void 0,started_at:String(e.started_at??""),completed_at:e.completed_at!=null?String(e.completed_at):void 0,error_type:e.error_type!=null?String(e.error_type):void 0,meta:e.meta!=null?e.meta:void 0}}Do(vs);return Pa(vs);})();
1
+ /* @fsaos/gateway v2.0.0 — Unified FSAOS Edge Runtime — 2026-08-10T14:09:50.397Z */
2
+ "use strict";var __FSAOS_GATEWAY__=(()=>{var wa=Object.create;var Wt=Object.defineProperty;var Sa=Object.getOwnPropertyDescriptor;var Ra=Object.getOwnPropertyNames;var Ca=Object.getPrototypeOf,Pa=Object.prototype.hasOwnProperty;var ws=e=>{throw TypeError(e)};var xa=(e,t,n)=>t in e?Wt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Bt=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Ea=(e,t)=>{for(var n in t)Wt(e,n,{get:t[n],enumerable:!0})},Ss=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Ra(t))!Pa.call(e,s)&&s!==n&&Wt(e,s,{get:()=>t[s],enumerable:!(r=Sa(t,s))||r.enumerable});return e};var j=(e,t,n)=>(n=e!=null?wa(Ca(e)):{},Ss(t||!e||!e.__esModule?Wt(n,"default",{value:e,enumerable:!0}):n,e)),Ta=e=>Ss(Wt({},"__esModule",{value:!0}),e);var $t=(e,t,n)=>xa(e,typeof t!="symbol"?t+"":t,n),Rr=(e,t,n)=>t.has(e)||ws("Cannot "+n);var o=(e,t,n)=>(Rr(e,t,"read from private field"),n?n.call(e):t.get(e)),b=(e,t,n)=>t.has(e)?ws("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),_=(e,t,n,r)=>(Rr(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n),P=(e,t,n)=>(Rr(e,t,"access private method"),n);var Gt=(e,t,n,r)=>({set _(s){_(e,t,s,n)},get _(){return o(e,t,r)}});var Cs=Bt((Ec,Rs)=>{Rs.exports={createClient:window.supabase.createClient}});var ie=Bt((Ol,mi)=>{mi.exports=React});var Gn=Bt((Il,gi)=>{gi.exports={jsx:React.createElement,jsxs:React.createElement,Fragment:React.Fragment}});var zi=Bt((xd,Gi)=>{Gi.exports=ReactDOM});var uo=Bt((Fd,co)=>{co.exports=ReactDOM});var bs={};Ea(bs,{ComponentRenderer:()=>Bo,EnforcementDeniedError:()=>ft,KernelProvider:()=>$o,QueryClientProvider:()=>hn,auth:()=>io,awaitAnchorReady:()=>Xt,awaitScopeReady:()=>qs,callTool:()=>no,clearCachedToken:()=>Tr,clearSession:()=>qr,createItem:()=>Zi,disconnectSSE:()=>us,disposeVfsRealtimeWs:()=>gr,electHomeAnchor:()=>Zt,emitEvent:()=>Hi,fetchChannelMessages:()=>Fi,fetchChannelMessagesPage:()=>bn,fetchChannelMessagesWithCards:()=>ur,fetchEdgesForItem:()=>rr,fetchItemHistory:()=>or,fetchItemVersions:()=>_n,fetchItems:()=>vn,fetchMemberFocus:()=>ar,fetchOpenEnvelope:()=>cr,fetchRecentActivity:()=>ir,fetchResolvedItems:()=>_s,fetchTimelineHistory:()=>vs,fetchTypeDefinitions:()=>nr,fetchVfsChildren:()=>er,fetchVfsChildrenPage:()=>tr,fetchVfsItem:()=>Zn,fetchVfsItemById:()=>Xn,fetchVfsTree:()=>sr,gatewayCall:()=>R,getAccessToken:()=>Pe,getAnchor:()=>Yt,getAnchorRef:()=>Xe,getAnchorVersion:()=>Or,getAssetUrl:()=>so,getDefaultSort:()=>la,getHomeAnchor:()=>Ue,getMountVersion:()=>tn,getMounts:()=>mt,getQueryClient:()=>x,getRequiredFormFields:()=>da,getScope:()=>le,getScopeVersion:()=>_e,getSessionEntry:()=>Qn,initSession:()=>Dn,initVfsRealtimeWs:()=>Pn,interpretSchema:()=>ys,invalidateAllVfs:()=>Di,invalidateChannelMessages:()=>Ui,invalidateChildren:()=>Yn,invalidateItem:()=>as,invalidateOpenEnvelope:()=>Ni,invalidatePathAndParent:()=>ki,invalidateSubtree:()=>qi,invalidateTypes:()=>Qi,isAnchorReady:()=>Fr,isScopeReady:()=>Un,listChildren:()=>Xi,mount:()=>oo,mountRealtimeScope:()=>xn,normalizeItem:()=>pe,ping:()=>Wi,pushChanges:()=>to,queryClient:()=>Ai,readItem:()=>Yi,registerCleanup:()=>xe,resetAllSdkState:()=>gt,resolvePrincipalId:()=>Vo,setAnchor:()=>Qe,setCachedToken:()=>Es,setQueryClient:()=>Ti,setScope:()=>ks,setupRequireShim:()=>ao,signal:()=>ro,subscribeAnchor:()=>Ir,subscribeArtifactStream:()=>br,subscribeMounts:()=>qn,subscribeScope:()=>Ze,subscribeToEvents:()=>J,subscribeToPath:()=>fr,subscribeToScope:()=>pr,unmountRealtimeScope:()=>$i,updateItem:()=>eo,uploadFile:()=>fa,useAccounts:()=>ko,useAgentTimeline:()=>_a,useAllChannels:()=>vr,useArrangement:()=>ca,useArtifactStream:()=>ya,useAsset:()=>Do,useAuth:()=>_r,useChannelMessages:()=>Go,useChannels:()=>Jo,useChildren:()=>_o,useComponent:()=>ms,useCreate:()=>Zo,useDelete:()=>na,useDmChannels:()=>Yo,useEdges:()=>Po,useEventStream:()=>oa,useFileUpload:()=>ha,useInfiniteChannelMessages:()=>zo,useInfiniteChildren:()=>Co,useInfiniteItems:()=>Ro,useItem:()=>go,useItemById:()=>yo,useItemHistory:()=>Oo,useItemVersions:()=>Mo,useItems:()=>So,useLink:()=>sa,useList:()=>hs,useMemberFocus:()=>Ao,useMounts:()=>qo,useMove:()=>ra,useMutation:()=>ia,useNotifications:()=>gs,useOpen:()=>Eo,usePermission:()=>Ko,usePermissions:()=>Lo,usePrincipal:()=>Ho,useRealtimeQuery:()=>aa,useRecentActivity:()=>Io,useResolve:()=>wo,useResolvedItems:()=>ga,useScope:()=>Fo,useScopeReady:()=>mo,useSearch:()=>bo,useTheme:()=>No,useTimelineHistory:()=>va,useTool:()=>Wo,useTree:()=>vo,useType:()=>xo,useTypeHelpers:()=>To,useTypes:()=>yr,useUnreadCounts:()=>Xo,useUpdate:()=>ea,useUpdatePrincipal:()=>ta,vfsKeys:()=>w});var ft=class e extends Error{constructor(n){let r=n.message||e.fallbackMessage(n);super(r);$t(this,"name","EnforcementDeniedError");$t(this,"deniedBy");$t(this,"ruleKey");$t(this,"displayName");this.deniedBy=n.denied_by||n.error_type||n.error||"unknown";let s=n.enforcement;this.ruleKey=s?.rule_key??void 0,this.displayName=s?.display_name??void 0}static fallbackMessage(n){let r=n.error||"",s=n.denied_by||"";return s==="rule"||r==="RULE_DENIED"?"This feature is not enabled for this workspace.":s==="entitlement"||r==="ENTITLEMENT_REQUIRED"?"This feature requires a plan upgrade.":s==="access"||r==="ACCESS_DENIED"||r==="PERMISSION_DENIED"?"You don't have permission to do this.":"This action is not allowed."}get isRuleDenial(){return this.deniedBy==="rule"||this.deniedBy==="RULE_DENIED"}get isAccessDenial(){return this.deniedBy==="access"||this.deniedBy==="ACCESS_DENIED"}get isEntitlementDenial(){return this.deniedBy==="entitlement"||this.deniedBy==="ENTITLEMENT_REQUIRED"}};var Ps=j(Cs(),1),Cr=typeof window<"u"&&window.__FSAOS_CONFIG__||{},Aa=Cr.supabaseUrl||"https://vahbmsslxuustnlvsrkg.supabase.co",Ma=Cr.supabaseAnonKey||"sb_publishable_ZjosozAjfpZ4InMNElTr6Q_hHB-f5nc",De=Cr.gatewayUrl||"https://fsaos-mcp-gw-rust.fly.dev",F=(0,Ps.createClient)(Aa,Ma,{auth:{persistSession:!0,autoRefreshToken:!0,detectSessionInUrl:!1}});var Jt=null,Mn=0,xs,Er,On=!1;xs=new Promise(e=>{Er=e});F.auth.onAuthStateChange((e,t)=>{t?.access_token?(Jt=t.access_token,Mn=t.expires_at??Math.floor(Date.now()/1e3)+3600):(Jt=null,Mn=0),On||(On=!0,Er())});setTimeout(()=>{On||(On=!0,Er())},5e3);function Es(e,t){Jt=e,Mn=t??Math.floor(Date.now()/1e3)+3600}function Tr(){Jt=null,Mn=0}async function Pe(){let e=typeof window<"u"&&window.__FSAOS_CONFIG__||{};if(e.embedToken){if(typeof e.embedToken=="function")try{return await e.embedToken()??null}catch{return null}return e.embedToken}return await xs,Jt}var In=null,kn=null,Ts=0,Pr=new Set,Ar,Mr,Fn=!1;Ar=new Promise(e=>{Mr=e});function As(){Ts++,Pr.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Anchor listener error:",t)}})}function Qe(e){let t=typeof e=="string"?e:e.path,n=In!==t;In=t,kn=typeof e=="string"?null:e,typeof e!="string"&&!ae.some(r=>r.id===e.id)&&(ae=[...ae,e],en()),Fn||(Fn=!0,Mr()),n&&As()}function Yt(){return In}function Xe(){return kn}function Or(){return Ts}function Ir(e){return Pr.add(e),()=>{Pr.delete(e)}}function Xt(){return Ar}function Fr(){return Fn}var ht=null;function Zt(e){if(ht){console.warn("[SDK] electHomeAnchor called twice; ignoring (logout to re-elect).");return}ht=e,Qe(e)}function Ue(){return ht}var ae=[],xr=new Set,Ms=0;function en(){Ms++,xr.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Mount listener error:",t)}})}function mt(){return ae}function tn(){return Ms}function qn(e){return xr.add(e),()=>{xr.delete(e)}}function kr(e){ae=e,en()}function Os(e){ae.some(t=>t.id===e.id)||(ae=[...ae,e],en())}function Is(e){ae.find(n=>n.id===e)&&(ae=ae.filter(n=>n.id!==e),en(),kn?.id===e&&ht&&Qe(ht))}var pt=null,zt=null;async function Dn(){return pt||zt||(zt=(async()=>{let e=Dr(),t=await Pe(),n={};t&&(n.Authorization=`Bearer ${t}`);let r=await fetch(`${De}/d/${e}/init`,{method:"GET",headers:n});if(!r.ok)throw new Error(`Session init failed: ${r.status} ${r.statusText}`);let s=await r.json(),i=s.entry||s;return pt={scope_id:i.scope_id,scope_path:i.scope_path,instance_path:i.instance_path||"/root",fractal_id:i.fractal_id||null,instance_name:i.instance_name||null,display_name:i.scope_display_name||i.display_name||null},pt})(),zt)}function Qn(){return pt}function qr(){pt=null,zt=null,In=null,kn=null,ht=null,ae=[]}var Fs=[];function xe(e){Fs.push(e)}function gt(){qr(),Tr(),Fn=!1,Ar=new Promise(e=>{Mr=e}),As(),en();for(let e of Fs)try{e()}catch(t){console.warn("[SDK] Cleanup function failed:",t)}}function Dr(){if(typeof window<"u"){let e=window.__FSAOS_CONFIG__;return e?.hostname?e.hostname:window.location.hostname}return"localhost"}var ks=Qe,le=Yt,_e=Or,Ze=Ir,qs=Xt,Un=Fr;var Oa=new Set(["list-memberships","init"]);async function R(e,t={}){let n=Dr(),r=`${De}/d/${n}`,s={"Content-Type":"application/json"},i=await Pe();i&&(s.Authorization=`Bearer ${i}`),!Oa.has(e)&&!t._scope_path&&await Xt();let a={...t},c=Qn();!a.domain_scope_id&&c?.scope_id&&(a.domain_scope_id=c.scope_id);let u=Yt();!a._scope_path&&u&&(a._scope_path=u);let l=await fetch(r,{method:"POST",headers:s,body:JSON.stringify({method:e,params:a})});if(!l.ok)throw new Error(`Gateway HTTP error: ${l.status} ${l.statusText}`);let d=await l.json();if(d.success===!1){let p=d.error||"",f=d.denied_by||d.error_type||"";throw f==="rule"||f==="access"||f==="entitlement"||p==="RULE_DENIED"||p==="ACCESS_DENIED"||p==="PERMISSION_DENIED"||p==="ENTITLEMENT_REQUIRED"?new ft(d):new Error(d.message||d.error||`Gateway call ${e} failed`)}return d}var ce=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}};var et,Ne,yt,Ds,Ia=(Ds=class extends ce{constructor(){super();b(this,et);b(this,Ne);b(this,yt);_(this,yt,t=>{if(typeof window<"u"&&window.addEventListener){let n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){o(this,Ne)||this.setEventListener(o(this,yt))}onUnsubscribe(){var t;this.hasListeners()||((t=o(this,Ne))==null||t.call(this),_(this,Ne,void 0))}setEventListener(t){var n;_(this,yt,t),(n=o(this,Ne))==null||n.call(this),_(this,Ne,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){o(this,et)!==t&&(_(this,et,t),this.onFocus())}onFocus(){let t=this.isFocused();this.listeners.forEach(n=>{n(t)})}isFocused(){return typeof o(this,et)=="boolean"?o(this,et):globalThis.document?.visibilityState!=="hidden"}},et=new WeakMap,Ne=new WeakMap,yt=new WeakMap,Ds),_t=new Ia;var Fa={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},Ke,Qr,Qs,ka=(Qs=class{constructor(){b(this,Ke,Fa);b(this,Qr,!1)}setTimeoutProvider(e){_(this,Ke,e)}setTimeout(e,t){return o(this,Ke).setTimeout(e,t)}clearTimeout(e){o(this,Ke).clearTimeout(e)}setInterval(e,t){return o(this,Ke).setInterval(e,t)}clearInterval(e){o(this,Ke).clearInterval(e)}},Ke=new WeakMap,Qr=new WeakMap,Qs),ve=new ka;function Us(e){setTimeout(e,0)}var Nr=typeof window>"u"||"Deno"in globalThis;function q(){}function Ls(e,t){return typeof e=="function"?e(t):e}function nn(e){return typeof e=="number"&&e>=0&&e!==1/0}function Nn(e,t){return Math.max(e+(t||0)-Date.now(),0)}function de(e,t){return typeof e=="function"?e(t):e}function X(e,t){return typeof e=="function"?e(t):e}function Kn(e,t){let{type:n="all",exact:r,fetchStatus:s,predicate:i,queryKey:a,stale:c}=e;if(a){if(r){if(t.queryHash!==rn(a,t.options))return!1}else if(!tt(t.queryKey,a))return!1}if(n!=="all"){let u=t.isActive();if(n==="active"&&!u||n==="inactive"&&u)return!1}return!(typeof c=="boolean"&&t.isStale()!==c||s&&s!==t.state.fetchStatus||i&&!i(t))}function Ln(e,t){let{exact:n,status:r,predicate:s,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(be(t.options.mutationKey)!==be(i))return!1}else if(!tt(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||s&&!s(t))}function rn(e,t){return(t?.queryKeyHashFn||be)(e)}function be(e){return JSON.stringify(e,(t,n)=>Ur(n)?Object.keys(n).sort().reduce((r,s)=>(r[s]=n[s],r),{}):n)}function tt(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>tt(e[n],t[n])):!1}var qa=Object.prototype.hasOwnProperty;function Kr(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=Ns(e)&&Ns(t);if(!r&&!(Ur(e)&&Ur(t)))return t;let i=(r?e:Object.keys(e)).length,a=r?t:Object.keys(t),c=a.length,u=r?new Array(c):{},l=0;for(let d=0;d<c;d++){let p=r?d:a[d],f=e[p],h=t[p];if(f===h){u[p]=f,(r?d<i:qa.call(e,p))&&l++;continue}if(f===null||h===null||typeof f!="object"||typeof h!="object"){u[p]=h;continue}let v=Kr(f,h,n+1);u[p]=v,v===f&&l++}return i===c&&l===i?e:u}function vt(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(let n in e)if(e[n]!==t[n])return!1;return!0}function Ns(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Ur(e){if(!Ks(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!Ks(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function Ks(e){return Object.prototype.toString.call(e)==="[object Object]"}function js(e){return new Promise(t=>{ve.setTimeout(t,e)})}function sn(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?Kr(e,t):t}function Vs(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function Hs(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var bt=Symbol();function jn(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===bt?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function wt(e,t){return typeof e=="function"?e(...t):!!e}function Ws(e,t,n){let r=!1,s;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(s??(s=t()),r||(r=!0,s.aborted?n():s.addEventListener("abort",n,{once:!0})),s)}),e}var we=(()=>{let e=()=>Nr;return{isServer(){return e()},setIsServer(t){e=t}}})();function on(){let e,t,n=new Promise((s,i)=>{e=s,t=i});n.status="pending",n.catch(()=>{});function r(s){Object.assign(n,s),delete n.resolve,delete n.reject}return n.resolve=s=>{r({status:"fulfilled",value:s}),e(s)},n.reject=s=>{r({status:"rejected",reason:s}),t(s)},n}var Bs=Us;function Da(){let e=[],t=0,n=c=>{c()},r=c=>{c()},s=Bs,i=c=>{t?e.push(c):s(()=>{n(c)})},a=()=>{let c=e;e=[],c.length&&s(()=>{r(()=>{c.forEach(u=>{n(u)})})})};return{batch:c=>{let u;t++;try{u=c()}finally{t--,t||a()}return u},batchCalls:c=>(...u)=>{i(()=>{c(...u)})},schedule:i,setNotifyFunction:c=>{n=c},setBatchNotifyFunction:c=>{r=c},setScheduler:c=>{s=c}}}var I=Da();var St,Le,Rt,$s,Qa=($s=class extends ce{constructor(){super();b(this,St,!0);b(this,Le);b(this,Rt);_(this,Rt,t=>{if(typeof window<"u"&&window.addEventListener){let n=()=>t(!0),r=()=>t(!1);return window.addEventListener("online",n,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}}})}onSubscribe(){o(this,Le)||this.setEventListener(o(this,Rt))}onUnsubscribe(){var t;this.hasListeners()||((t=o(this,Le))==null||t.call(this),_(this,Le,void 0))}setEventListener(t){var n;_(this,Rt,t),(n=o(this,Le))==null||n.call(this),_(this,Le,t(this.setOnline.bind(this)))}setOnline(t){o(this,St)!==t&&(_(this,St,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return o(this,St)}},St=new WeakMap,Le=new WeakMap,Rt=new WeakMap,$s),Ct=new Qa;function Ua(e){return Math.min(1e3*2**e,3e4)}function Lr(e){return(e??"online")==="online"?Ct.isOnline():!0}var Vn=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function Hn(e){let t=!1,n=0,r,s=on(),i=()=>s.status!=="pending",a=m=>{if(!i()){let g=new Vn(m);f(g),e.onCancel?.(g)}},c=()=>{t=!0},u=()=>{t=!1},l=()=>_t.isFocused()&&(e.networkMode==="always"||Ct.isOnline())&&e.canRun(),d=()=>Lr(e.networkMode)&&e.canRun(),p=m=>{i()||(r?.(),s.resolve(m))},f=m=>{i()||(r?.(),s.reject(m))},h=()=>new Promise(m=>{r=g=>{(i()||l())&&m(g)},e.onPause?.()}).then(()=>{r=void 0,i()||e.onContinue?.()}),v=()=>{if(i())return;let m,g=n===0?e.initialPromise:void 0;try{m=g??e.fn()}catch(S){m=Promise.reject(S)}Promise.resolve(m).then(p).catch(S=>{if(i())return;let C=e.retry??(we.isServer()?0:3),E=e.retryDelay??Ua,Q=typeof E=="function"?E(n,S):E,L=C===!0||typeof C=="number"&&n<C||typeof C=="function"&&C(n,S);if(t||!L){f(S);return}n++,e.onFail?.(n,S),js(Q).then(()=>l()?void 0:h()).then(()=>{t?f(S):v()})})};return{promise:s,status:()=>s.status,cancel:a,continue:()=>(r?.(),s),cancelRetry:c,continueRetry:u,canStart:d,start:()=>(d()?v():h().then(v),s)}}var nt,Gs,Wn=(Gs=class{constructor(){b(this,nt)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),nn(this.gcTime)&&_(this,nt,ve.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(we.isServer()?1/0:5*60*1e3))}clearGcTimeout(){o(this,nt)!==void 0&&(ve.clearTimeout(o(this,nt)),_(this,nt,void 0))}},nt=new WeakMap,Gs);var rt,Pt,ue,st,V,an,it,se,Zs,Ee,Ys,Xs=(Ys=class extends Wn{constructor(t){super();b(this,se);b(this,rt);b(this,Pt);b(this,ue);b(this,st);b(this,V);b(this,an);b(this,it);_(this,it,!1),_(this,an,t.defaultOptions),this.setOptions(t.options),this.observers=[],_(this,st,t.client),_(this,ue,o(this,st).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,_(this,rt,Js(this.options)),this.state=t.state??o(this,rt),this.scheduleGc()}get meta(){return this.options.meta}get promise(){return o(this,V)?.promise}setOptions(t){if(this.options={...o(this,an),...t},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let n=Js(this.options);n.data!==void 0&&(this.setState(zs(n.data,n.dataUpdatedAt)),_(this,rt,n))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&o(this,ue).remove(this)}setData(t,n){let r=sn(this.state.data,t,this.options);return P(this,se,Ee).call(this,{data:r,type:"success",dataUpdatedAt:n?.updatedAt,manual:n?.manual}),r}setState(t,n){P(this,se,Ee).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){let n=o(this,V)?.promise;return o(this,V)?.cancel(t),n?n.then(q).catch(q):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return o(this,rt)}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(t=>X(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===bt||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>de(t.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(t=>t.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(t=0){return this.state.data===void 0?!0:t==="static"?!1:this.state.isInvalidated?!0:!Nn(this.state.dataUpdatedAt,t)}onFocus(){this.observers.find(n=>n.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),o(this,V)?.continue()}onOnline(){this.observers.find(n=>n.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),o(this,V)?.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),o(this,ue).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(n=>n!==t),this.observers.length||(o(this,V)&&(o(this,it)||P(this,se,Zs).call(this)?o(this,V).cancel({revert:!0}):o(this,V).cancelRetry()),this.scheduleGc()),o(this,ue).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||P(this,se,Ee).call(this,{type:"invalidate"})}async fetch(t,n){if(this.state.fetchStatus!=="idle"&&o(this,V)?.status()!=="rejected"){if(this.state.data!==void 0&&n?.cancelRefetch)this.cancel({silent:!0});else if(o(this,V))return o(this,V).continueRetry(),o(this,V).promise}if(t&&this.setOptions(t),!this.options.queryFn){let u=this.observers.find(l=>l.options.queryFn);u&&this.setOptions(u.options)}let r=new AbortController,s=u=>{Object.defineProperty(u,"signal",{enumerable:!0,get:()=>(_(this,it,!0),r.signal)})},i=()=>{let u=jn(this.options,n),d=(()=>{let p={client:o(this,st),queryKey:this.queryKey,meta:this.meta};return s(p),p})();return _(this,it,!1),this.options.persister?this.options.persister(u,d,this):u(d)},c=(()=>{let u={fetchOptions:n,options:this.options,queryKey:this.queryKey,client:o(this,st),state:this.state,fetchFn:i};return s(u),u})();this.options.behavior?.onFetch(c,this),_(this,Pt,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==c.fetchOptions?.meta)&&P(this,se,Ee).call(this,{type:"fetch",meta:c.fetchOptions?.meta}),_(this,V,Hn({initialPromise:n?.initialPromise,fn:c.fetchFn,onCancel:u=>{u instanceof Vn&&u.revert&&this.setState({...o(this,Pt),fetchStatus:"idle"}),r.abort()},onFail:(u,l)=>{P(this,se,Ee).call(this,{type:"failed",failureCount:u,error:l})},onPause:()=>{P(this,se,Ee).call(this,{type:"pause"})},onContinue:()=>{P(this,se,Ee).call(this,{type:"continue"})},retry:c.options.retry,retryDelay:c.options.retryDelay,networkMode:c.options.networkMode,canRun:()=>!0}));try{let u=await o(this,V).start();if(u===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(u),o(this,ue).config.onSuccess?.(u,this),o(this,ue).config.onSettled?.(u,this.state.error,this),u}catch(u){if(u instanceof Vn){if(u.silent)return o(this,V).promise;if(u.revert){if(this.state.data===void 0)throw u;return this.state.data}}throw P(this,se,Ee).call(this,{type:"error",error:u}),o(this,ue).config.onError?.(u,this),o(this,ue).config.onSettled?.(this.state.data,u,this),u}finally{this.scheduleGc()}}},rt=new WeakMap,Pt=new WeakMap,ue=new WeakMap,st=new WeakMap,V=new WeakMap,an=new WeakMap,it=new WeakMap,se=new WeakSet,Zs=function(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"},Ee=function(t){let n=r=>{switch(t.type){case"failed":return{...r,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,...jr(r.data,this.options),fetchMeta:t.meta??null};case"success":let s={...r,...zs(t.data,t.dataUpdatedAt),dataUpdateCount:r.dataUpdateCount+1,...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return _(this,Pt,t.manual?s:void 0),s;case"error":let i=t.error;return{...r,error:i,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...t.state}}};this.state=n(this.state),I.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),o(this,ue).notify({query:this,type:"updated",action:t})})},Ys);function jr(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Lr(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function zs(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function Js(e){let t=typeof e.initialData=="function"?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var Z,T,un,z,ot,xt,Te,je,ln,Et,Tt,at,ct,Ve,At,O,cn,Vr,Hr,Wr,Br,$r,Gr,zr,ri,ni,dn=(ni=class extends ce{constructor(t,n){super();b(this,O);b(this,Z);b(this,T);b(this,un);b(this,z);b(this,ot);b(this,xt);b(this,Te);b(this,je);b(this,ln);b(this,Et);b(this,Tt);b(this,at);b(this,ct);b(this,Ve);b(this,At,new Set);this.options=n,_(this,Z,t),_(this,je,null),_(this,Te,on()),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(o(this,T).addObserver(this),ei(o(this,T),this.options)?P(this,O,cn).call(this):this.updateResult(),P(this,O,Br).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Jr(o(this,T),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Jr(o(this,T),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,P(this,O,$r).call(this),P(this,O,Gr).call(this),o(this,T).removeObserver(this)}setOptions(t){let n=this.options,r=o(this,T);if(this.options=o(this,Z).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof X(this.options.enabled,o(this,T))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");P(this,O,zr).call(this),o(this,T).setOptions(this.options),n._defaulted&&!vt(this.options,n)&&o(this,Z).getQueryCache().notify({type:"observerOptionsUpdated",query:o(this,T),observer:this});let s=this.hasListeners();s&&ti(o(this,T),r,this.options,n)&&P(this,O,cn).call(this),this.updateResult(),s&&(o(this,T)!==r||X(this.options.enabled,o(this,T))!==X(n.enabled,o(this,T))||de(this.options.staleTime,o(this,T))!==de(n.staleTime,o(this,T)))&&P(this,O,Vr).call(this);let i=P(this,O,Hr).call(this);s&&(o(this,T)!==r||X(this.options.enabled,o(this,T))!==X(n.enabled,o(this,T))||i!==o(this,Ve))&&P(this,O,Wr).call(this,i)}getOptimisticResult(t){let n=o(this,Z).getQueryCache().build(o(this,Z),t),r=this.createResult(n,t);return Ka(this,r)&&(_(this,z,r),_(this,xt,this.options),_(this,ot,o(this,T).state)),r}getCurrentResult(){return o(this,z)}trackResult(t,n){return new Proxy(t,{get:(r,s)=>(this.trackProp(s),n?.(s),s==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&o(this,Te).status==="pending"&&o(this,Te).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(r,s))})}trackProp(t){o(this,At).add(t)}getCurrentQuery(){return o(this,T)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){let n=o(this,Z).defaultQueryOptions(t),r=o(this,Z).getQueryCache().build(o(this,Z),n);return r.fetch().then(()=>this.createResult(r,n))}fetch(t){return P(this,O,cn).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),o(this,z)))}createResult(t,n){let r=o(this,T),s=this.options,i=o(this,z),a=o(this,ot),c=o(this,xt),l=t!==r?t.state:o(this,un),{state:d}=t,p={...d},f=!1,h;if(n._optimisticResults){let N=this.hasListeners(),Y=!N&&ei(t,n),me=N&&ti(t,r,n,s);(Y||me)&&(p={...p,...jr(d.data,t.options)}),n._optimisticResults==="isRestoring"&&(p.fetchStatus="idle")}let{error:v,errorUpdatedAt:m,status:g}=p;h=p.data;let S=!1;if(n.placeholderData!==void 0&&h===void 0&&g==="pending"){let N;i?.isPlaceholderData&&n.placeholderData===c?.placeholderData?(N=i.data,S=!0):N=typeof n.placeholderData=="function"?n.placeholderData(o(this,Tt)?.state.data,o(this,Tt)):n.placeholderData,N!==void 0&&(g="success",h=sn(i?.data,N,n),f=!0)}if(n.select&&h!==void 0&&!S)if(i&&h===a?.data&&n.select===o(this,ln))h=o(this,Et);else try{_(this,ln,n.select),h=n.select(h),h=sn(i?.data,h,n),_(this,Et,h),_(this,je,null)}catch(N){_(this,je,N)}o(this,je)&&(v=o(this,je),h=o(this,Et),m=Date.now(),g="error");let C=p.fetchStatus==="fetching",E=g==="pending",Q=g==="error",L=E&&C,B=h!==void 0,re={status:g,fetchStatus:p.fetchStatus,isPending:E,isSuccess:g==="success",isError:Q,isInitialLoading:L,isLoading:L,data:h,dataUpdatedAt:p.dataUpdatedAt,error:v,errorUpdatedAt:m,failureCount:p.fetchFailureCount,failureReason:p.fetchFailureReason,errorUpdateCount:p.errorUpdateCount,isFetched:t.isFetched(),isFetchedAfterMount:p.dataUpdateCount>l.dataUpdateCount||p.errorUpdateCount>l.errorUpdateCount,isFetching:C,isRefetching:C&&!E,isLoadingError:Q&&!B,isPaused:p.fetchStatus==="paused",isPlaceholderData:f,isRefetchError:Q&&B,isStale:Yr(t,n),refetch:this.refetch,promise:o(this,Te),isEnabled:X(n.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){let N=re.data!==void 0,Y=re.status==="error"&&!N,me=A=>{Y?A.reject(re.error):N&&A.resolve(re.data)},ge=()=>{let A=_(this,Te,re.promise=on());me(A)},ye=o(this,Te);switch(ye.status){case"pending":t.queryHash===r.queryHash&&me(ye);break;case"fulfilled":(Y||re.data!==ye.value)&&ge();break;case"rejected":(!Y||re.error!==ye.reason)&&ge();break}}return re}updateResult(){let t=o(this,z),n=this.createResult(o(this,T),this.options);if(_(this,ot,o(this,T).state),_(this,xt,this.options),o(this,ot).data!==void 0&&_(this,Tt,o(this,T)),vt(n,t))return;_(this,z,n);let r=()=>{if(!t)return!0;let{notifyOnChangeProps:s}=this.options,i=typeof s=="function"?s():s;if(i==="all"||!i&&!o(this,At).size)return!0;let a=new Set(i??o(this,At));return this.options.throwOnError&&a.add("error"),Object.keys(o(this,z)).some(c=>{let u=c;return o(this,z)[u]!==t[u]&&a.has(u)})};P(this,O,ri).call(this,{listeners:r()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&P(this,O,Br).call(this)}},Z=new WeakMap,T=new WeakMap,un=new WeakMap,z=new WeakMap,ot=new WeakMap,xt=new WeakMap,Te=new WeakMap,je=new WeakMap,ln=new WeakMap,Et=new WeakMap,Tt=new WeakMap,at=new WeakMap,ct=new WeakMap,Ve=new WeakMap,At=new WeakMap,O=new WeakSet,cn=function(t){P(this,O,zr).call(this);let n=o(this,T).fetch(this.options,t);return t?.throwOnError||(n=n.catch(q)),n},Vr=function(){P(this,O,$r).call(this);let t=de(this.options.staleTime,o(this,T));if(we.isServer()||o(this,z).isStale||!nn(t))return;let r=Nn(o(this,z).dataUpdatedAt,t)+1;_(this,at,ve.setTimeout(()=>{o(this,z).isStale||this.updateResult()},r))},Hr=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(o(this,T)):this.options.refetchInterval)??!1},Wr=function(t){P(this,O,Gr).call(this),_(this,Ve,t),!(we.isServer()||X(this.options.enabled,o(this,T))===!1||!nn(o(this,Ve))||o(this,Ve)===0)&&_(this,ct,ve.setInterval(()=>{(this.options.refetchIntervalInBackground||_t.isFocused())&&P(this,O,cn).call(this)},o(this,Ve)))},Br=function(){P(this,O,Vr).call(this),P(this,O,Wr).call(this,P(this,O,Hr).call(this))},$r=function(){o(this,at)!==void 0&&(ve.clearTimeout(o(this,at)),_(this,at,void 0))},Gr=function(){o(this,ct)!==void 0&&(ve.clearInterval(o(this,ct)),_(this,ct,void 0))},zr=function(){let t=o(this,Z).getQueryCache().build(o(this,Z),this.options);if(t===o(this,T))return;let n=o(this,T);_(this,T,t),_(this,un,t.state),this.hasListeners()&&(n?.removeObserver(this),t.addObserver(this))},ri=function(t){I.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(o(this,z))}),o(this,Z).getQueryCache().notify({query:o(this,T),type:"observerResultsUpdated"})})},ni);function Na(e,t){return X(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function ei(e,t){return Na(e,t)||e.state.data!==void 0&&Jr(e,t,t.refetchOnMount)}function Jr(e,t,n){if(X(t.enabled,e)!==!1&&de(t.staleTime,e)!=="static"){let r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&Yr(e,t)}return!1}function ti(e,t,n,r){return(e!==t||X(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&Yr(e,n)}function Yr(e,t){return X(t.enabled,e)!==!1&&e.isStaleByTime(de(t.staleTime,e))}function Ka(e,t){return!vt(e.getCurrentResult(),t)}function Mt(e){return{onFetch:(t,n)=>{let r=t.options,s=t.fetchOptions?.meta?.fetchMore?.direction,i=t.state.data?.pages||[],a=t.state.data?.pageParams||[],c={pages:[],pageParams:[]},u=0,l=async()=>{let d=!1,p=v=>{Ws(v,()=>t.signal,()=>d=!0)},f=jn(t.options,t.fetchOptions),h=async(v,m,g)=>{if(d)return Promise.reject();if(m==null&&v.pages.length)return Promise.resolve(v);let C=(()=>{let B={client:t.client,queryKey:t.queryKey,pageParam:m,direction:g?"backward":"forward",meta:t.options.meta};return p(B),B})(),E=await f(C),{maxPages:Q}=t.options,L=g?Hs:Vs;return{pages:L(v.pages,E,Q),pageParams:L(v.pageParams,m,Q)}};if(s&&i.length){let v=s==="backward",m=v?si:Xr,g={pages:i,pageParams:a},S=m(r,g);c=await h(g,S,v)}else{let v=e??i.length;do{let m=u===0?a[0]??r.initialPageParam:Xr(r,c);if(u>0&&m==null)break;c=await h(c,m),u++}while(u<v)}return c};t.options.persister?t.fetchFn=()=>t.options.persister?.(l,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=l}}}function Xr(e,{pages:t,pageParams:n}){let r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function si(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function ii(e,t){return t?Xr(e,t)!=null:!1}function oi(e,t){return!t||!e.getPreviousPageParam?!1:si(e,t)!=null}var Zr=class extends dn{constructor(e,t){super(e,t)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(e){super.setOptions({...e,behavior:Mt()})}getOptimisticResult(e){return e.behavior=Mt(),super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"backward"}}})}createResult(e,t){let{state:n}=e,r=super.createResult(e,t),{isFetching:s,isRefetching:i,isError:a,isRefetchError:c}=r,u=n.fetchMeta?.fetchMore?.direction,l=a&&u==="forward",d=s&&u==="forward",p=a&&u==="backward",f=s&&u==="backward";return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:ii(t,n.data),hasPreviousPage:oi(t,n.data),isFetchNextPageError:l,isFetchingNextPage:d,isFetchPreviousPageError:p,isFetchingPreviousPage:f,isRefetchError:c&&!l&&!p,isRefetching:i&&!d&&!f}}};var fn,Se,G,ut,Re,He,ai,ci=(ai=class extends Wn{constructor(t){super();b(this,Re);b(this,fn);b(this,Se);b(this,G);b(this,ut);_(this,fn,t.client),this.mutationId=t.mutationId,_(this,G,t.mutationCache),_(this,Se,[]),this.state=t.state||es(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){o(this,Se).includes(t)||(o(this,Se).push(t),this.clearGcTimeout(),o(this,G).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){_(this,Se,o(this,Se).filter(n=>n!==t)),this.scheduleGc(),o(this,G).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){o(this,Se).length||(this.state.status==="pending"?this.scheduleGc():o(this,G).remove(this))}continue(){return o(this,ut)?.continue()??this.execute(this.state.variables)}async execute(t){let n=()=>{P(this,Re,He).call(this,{type:"continue"})},r={client:o(this,fn),meta:this.options.meta,mutationKey:this.options.mutationKey};_(this,ut,Hn({fn:()=>this.options.mutationFn?this.options.mutationFn(t,r):Promise.reject(new Error("No mutationFn found")),onFail:(a,c)=>{P(this,Re,He).call(this,{type:"failed",failureCount:a,error:c})},onPause:()=>{P(this,Re,He).call(this,{type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>o(this,G).canRun(this)}));let s=this.state.status==="pending",i=!o(this,ut).canStart();try{if(s)n();else{P(this,Re,He).call(this,{type:"pending",variables:t,isPaused:i}),o(this,G).config.onMutate&&await o(this,G).config.onMutate(t,this,r);let c=await this.options.onMutate?.(t,r);c!==this.state.context&&P(this,Re,He).call(this,{type:"pending",context:c,variables:t,isPaused:i})}let a=await o(this,ut).start();return await o(this,G).config.onSuccess?.(a,t,this.state.context,this,r),await this.options.onSuccess?.(a,t,this.state.context,r),await o(this,G).config.onSettled?.(a,null,this.state.variables,this.state.context,this,r),await this.options.onSettled?.(a,null,t,this.state.context,r),P(this,Re,He).call(this,{type:"success",data:a}),a}catch(a){try{await o(this,G).config.onError?.(a,t,this.state.context,this,r)}catch(c){Promise.reject(c)}try{await this.options.onError?.(a,t,this.state.context,r)}catch(c){Promise.reject(c)}try{await o(this,G).config.onSettled?.(void 0,a,this.state.variables,this.state.context,this,r)}catch(c){Promise.reject(c)}try{await this.options.onSettled?.(void 0,a,t,this.state.context,r)}catch(c){Promise.reject(c)}throw P(this,Re,He).call(this,{type:"error",error:a}),a}finally{o(this,G).runNext(this)}}},fn=new WeakMap,Se=new WeakMap,G=new WeakMap,ut=new WeakMap,Re=new WeakSet,He=function(t){let n=r=>{switch(t.type){case"failed":return{...r,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:t.isPaused,status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...r,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:t.error,failureCount:r.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=n(this.state),I.batch(()=>{o(this,Se).forEach(r=>{r.onMutationUpdate(t)}),o(this,G).notify({mutation:this,type:"updated",action:t})})},ai);function es(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Ae,fe,pn,ui,li=(ui=class extends ce{constructor(t={}){super();b(this,Ae);b(this,fe);b(this,pn);this.config=t,_(this,Ae,new Set),_(this,fe,new Map),_(this,pn,0)}build(t,n,r){let s=new ci({client:t,mutationCache:this,mutationId:++Gt(this,pn)._,options:t.defaultMutationOptions(n),state:r});return this.add(s),s}add(t){o(this,Ae).add(t);let n=Bn(t);if(typeof n=="string"){let r=o(this,fe).get(n);r?r.push(t):o(this,fe).set(n,[t])}this.notify({type:"added",mutation:t})}remove(t){if(o(this,Ae).delete(t)){let n=Bn(t);if(typeof n=="string"){let r=o(this,fe).get(n);if(r)if(r.length>1){let s=r.indexOf(t);s!==-1&&r.splice(s,1)}else r[0]===t&&o(this,fe).delete(n)}}this.notify({type:"removed",mutation:t})}canRun(t){let n=Bn(t);if(typeof n=="string"){let s=o(this,fe).get(n)?.find(i=>i.state.status==="pending");return!s||s===t}else return!0}runNext(t){let n=Bn(t);return typeof n=="string"?o(this,fe).get(n)?.find(s=>s!==t&&s.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){I.batch(()=>{o(this,Ae).forEach(t=>{this.notify({type:"removed",mutation:t})}),o(this,Ae).clear(),o(this,fe).clear()})}getAll(){return Array.from(o(this,Ae))}find(t){let n={exact:!0,...t};return this.getAll().find(r=>Ln(n,r))}findAll(t={}){return this.getAll().filter(n=>Ln(t,n))}notify(t){I.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){let t=this.getAll().filter(n=>n.state.isPaused);return I.batch(()=>Promise.all(t.map(n=>n.continue().catch(q))))}},Ae=new WeakMap,fe=new WeakMap,pn=new WeakMap,ui);function Bn(e){return e.options.scope?.id}var Me,We,ee,Oe,Ie,$n,ts,di,ns=(di=class extends ce{constructor(t,n){super();b(this,Ie);b(this,Me);b(this,We);b(this,ee);b(this,Oe);_(this,Me,t),this.setOptions(n),this.bindMethods(),P(this,Ie,$n).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(t){let n=this.options;this.options=o(this,Me).defaultMutationOptions(t),vt(this.options,n)||o(this,Me).getMutationCache().notify({type:"observerOptionsUpdated",mutation:o(this,ee),observer:this}),n?.mutationKey&&this.options.mutationKey&&be(n.mutationKey)!==be(this.options.mutationKey)?this.reset():o(this,ee)?.state.status==="pending"&&o(this,ee).setOptions(this.options)}onUnsubscribe(){this.hasListeners()||o(this,ee)?.removeObserver(this)}onMutationUpdate(t){P(this,Ie,$n).call(this),P(this,Ie,ts).call(this,t)}getCurrentResult(){return o(this,We)}reset(){o(this,ee)?.removeObserver(this),_(this,ee,void 0),P(this,Ie,$n).call(this),P(this,Ie,ts).call(this)}mutate(t,n){return _(this,Oe,n),o(this,ee)?.removeObserver(this),_(this,ee,o(this,Me).getMutationCache().build(o(this,Me),this.options)),o(this,ee).addObserver(this),o(this,ee).execute(t)}},Me=new WeakMap,We=new WeakMap,ee=new WeakMap,Oe=new WeakMap,Ie=new WeakSet,$n=function(){let t=o(this,ee)?.state??es();_(this,We,{...t,isPending:t.status==="pending",isSuccess:t.status==="success",isError:t.status==="error",isIdle:t.status==="idle",mutate:this.mutate,reset:this.reset})},ts=function(t){I.batch(()=>{if(o(this,Oe)&&this.hasListeners()){let n=o(this,We).variables,r=o(this,We).context,s={client:o(this,Me),meta:this.options.meta,mutationKey:this.options.mutationKey};if(t?.type==="success"){try{o(this,Oe).onSuccess?.(t.data,n,r,s)}catch(i){Promise.reject(i)}try{o(this,Oe).onSettled?.(t.data,null,n,r,s)}catch(i){Promise.reject(i)}}else if(t?.type==="error"){try{o(this,Oe).onError?.(t.error,n,r,s)}catch(i){Promise.reject(i)}try{o(this,Oe).onSettled?.(void 0,t.error,n,r,s)}catch(i){Promise.reject(i)}}}this.listeners.forEach(n=>{n(o(this,We))})})},di);var Ce,fi,pi=(fi=class extends ce{constructor(t={}){super();b(this,Ce);this.config=t,_(this,Ce,new Map)}build(t,n,r){let s=n.queryKey,i=n.queryHash??rn(s,n),a=this.get(i);return a||(a=new Xs({client:t,queryKey:s,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(s)}),this.add(a)),a}add(t){o(this,Ce).has(t.queryHash)||(o(this,Ce).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){let n=o(this,Ce).get(t.queryHash);n&&(t.destroy(),n===t&&o(this,Ce).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){I.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return o(this,Ce).get(t)}getAll(){return[...o(this,Ce).values()]}find(t){let n={exact:!0,...t};return this.getAll().find(r=>Kn(n,r))}findAll(t={}){let n=this.getAll();return Object.keys(t).length>0?n.filter(r=>Kn(t,r)):n}notify(t){I.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){I.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){I.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},Ce=new WeakMap,fi);var D,Be,$e,Ot,It,Ge,Ft,kt,hi,rs=(hi=class{constructor(e={}){b(this,D);b(this,Be);b(this,$e);b(this,Ot);b(this,It);b(this,Ge);b(this,Ft);b(this,kt);_(this,D,e.queryCache||new pi),_(this,Be,e.mutationCache||new li),_(this,$e,e.defaultOptions||{}),_(this,Ot,new Map),_(this,It,new Map),_(this,Ge,0)}mount(){Gt(this,Ge)._++,o(this,Ge)===1&&(_(this,Ft,_t.subscribe(async e=>{e&&(await this.resumePausedMutations(),o(this,D).onFocus())})),_(this,kt,Ct.subscribe(async e=>{e&&(await this.resumePausedMutations(),o(this,D).onOnline())})))}unmount(){var e,t;Gt(this,Ge)._--,o(this,Ge)===0&&((e=o(this,Ft))==null||e.call(this),_(this,Ft,void 0),(t=o(this,kt))==null||t.call(this),_(this,kt,void 0))}isFetching(e){return o(this,D).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return o(this,Be).findAll({...e,status:"pending"}).length}getQueryData(e){let t=this.defaultQueryOptions({queryKey:e});return o(this,D).get(t.queryHash)?.state.data}ensureQueryData(e){let t=this.defaultQueryOptions(e),n=o(this,D).build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(de(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return o(this,D).findAll(e).map(({queryKey:t,state:n})=>{let r=n.data;return[t,r]})}setQueryData(e,t,n){let r=this.defaultQueryOptions({queryKey:e}),i=o(this,D).get(r.queryHash)?.state.data,a=Ls(t,i);if(a!==void 0)return o(this,D).build(this,r).setData(a,{...n,manual:!0})}setQueriesData(e,t,n){return I.batch(()=>o(this,D).findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){let t=this.defaultQueryOptions({queryKey:e});return o(this,D).get(t.queryHash)?.state}removeQueries(e){let t=o(this,D);I.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){let n=o(this,D);return I.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){let n={revert:!0,...t},r=I.batch(()=>o(this,D).findAll(e).map(s=>s.cancel(n)));return Promise.all(r).then(q).catch(q)}invalidateQueries(e,t={}){return I.batch(()=>(o(this,D).findAll(e).forEach(n=>{n.invalidate()}),e?.refetchType==="none"?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??"active"},t)))}refetchQueries(e,t={}){let n={...t,cancelRefetch:t.cancelRefetch??!0},r=I.batch(()=>o(this,D).findAll(e).filter(s=>!s.isDisabled()&&!s.isStatic()).map(s=>{let i=s.fetch(void 0,n);return n.throwOnError||(i=i.catch(q)),s.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(q)}fetchQuery(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=o(this,D).build(this,t);return n.isStaleByTime(de(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(q).catch(q)}fetchInfiniteQuery(e){return e.behavior=Mt(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(q).catch(q)}ensureInfiniteQueryData(e){return e.behavior=Mt(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return Ct.isOnline()?o(this,Be).resumePausedMutations():Promise.resolve()}getQueryCache(){return o(this,D)}getMutationCache(){return o(this,Be)}getDefaultOptions(){return o(this,$e)}setDefaultOptions(e){_(this,$e,e)}setQueryDefaults(e,t){o(this,Ot).set(be(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){let t=[...o(this,Ot).values()],n={};return t.forEach(r=>{tt(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){o(this,It).set(be(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){let t=[...o(this,It).values()],n={};return t.forEach(r=>{tt(e,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;let t={...o(this,$e).queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=rn(t.queryKey,t)),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!=="always"),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode="offlineFirst"),t.queryFn===bt&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...o(this,$e).mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){o(this,D).clear(),o(this,Be).clear()}},D=new WeakMap,Be=new WeakMap,$e=new WeakMap,Ot=new WeakMap,It=new WeakMap,Ge=new WeakMap,Ft=new WeakMap,kt=new WeakMap,hi);var qt=j(ie(),1),yi=j(Gn(),1),ss=qt.createContext(void 0),U=e=>{let t=qt.useContext(ss);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},hn=({client:e,children:t})=>(qt.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,yi.jsx)(ss.Provider,{value:e,children:t}));var zn=j(ie(),1),_i=zn.createContext(!1),vi=()=>zn.useContext(_i),kl=_i.Provider;var mn=j(ie(),1),La=j(Gn(),1);function ja(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Va=mn.createContext(ja()),bi=()=>mn.useContext(Va);var wi=j(ie(),1);var Si=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError=="function"?wt(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},Ri=e=>{wi.useEffect(()=>{e.clearReset()},[e])},Ci=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:s})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(s&&e.data===void 0||wt(n,[e.error,r]));var Pi=e=>{if(e.suspense){let n=s=>s==="static"?s:Math.max(s??1e3,1e3),r=e.staleTime;e.staleTime=typeof r=="function"?(...s)=>n(r(...s)):n(r),typeof e.gcTime=="number"&&(e.gcTime=Math.max(e.gcTime,1e3))}},xi=(e,t)=>e.isLoading&&e.isFetching&&!t,Ei=(e,t)=>e?.suspense&&t.isPending,is=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});var ze=j(ie(),1);function Jn(e,t,n){let r=vi(),s=bi(),i=U(n),a=i.defaultQueryOptions(e);i.getDefaultOptions().queries?._experimental_beforeQuery?.(a);let c=i.getQueryCache().get(a.queryHash);a._optimisticResults=r?"isRestoring":"optimistic",Pi(a),Si(a,s,c),Ri(s);let u=!i.getQueryCache().get(a.queryHash),[l]=ze.useState(()=>new t(i,a)),d=l.getOptimisticResult(a),p=!r&&e.subscribed!==!1;if(ze.useSyncExternalStore(ze.useCallback(f=>{let h=p?l.subscribe(I.batchCalls(f)):q;return l.updateResult(),h},[l,p]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),ze.useEffect(()=>{l.setOptions(a)},[a,l]),Ei(a,d))throw is(a,l,s);if(Ci({result:d,errorResetBoundary:s,throwOnError:a.throwOnError,query:c,suspense:a.suspense}))throw d.error;return i.getDefaultOptions().queries?._experimental_afterQuery?.(a,d),a.experimental_prefetchInRender&&!we.isServer()&&xi(d,r)&&(u?is(a,l,s):c?.promise)?.catch(q).finally(()=>{l.updateResult()}),a.notifyOnChangeProps?d:l.trackResult(d)}function k(e,t){return Jn(e,dn,t)}var Fe=j(ie(),1);function ke(e,t){let n=U(t),[r]=Fe.useState(()=>new ns(n,e));Fe.useEffect(()=>{r.setOptions(e)},[r,e]);let s=Fe.useSyncExternalStore(Fe.useCallback(a=>r.subscribe(I.batchCalls(a)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),i=Fe.useCallback((a,c)=>{r.mutate(a,c).catch(q)},[r]);if(s.error&&wt(r.options.throwOnError,[s.error]))throw s.error;return{...s,mutate:i,mutateAsync:s.mutate}}function gn(e,t){return Jn(e,Zr,t)}var Dt=null;function Ti(e){if(Dt&&Dt!==e)throw new Error("[fsaos-gateway-sdk] setQueryClient() called after a QueryClient was already in use. Inject the host client before rendering or starting realtime subscriptions.");Dt=e}function x(){return Dt||(Dt=new rs({defaultOptions:{queries:{staleTime:1e3*60*2,gcTime:1e3*60*10,refetchOnWindowFocus:!1,retry:1}}})),Dt}var Ai=new Proxy({},{get(e,t,n){let r=x(),s=r[t];return typeof s=="function"?s.bind(r):s}});function H(){return le()??"__unscoped__"}var w={all:()=>["vfs",H()],item:e=>["vfs",H(),"item",e],itemById:e=>["vfs","item-by-id",e],children:e=>["vfs",H(),"children",e],allChildren:()=>["vfs",H(),"children"],types:e=>["vfs","types",e??"default"],edges:e=>["vfs","edges",e],search:(e,t)=>["vfs",H(),"search",e,...t??[]],items:(e,t)=>["vfs",H(),"items",e,JSON.stringify(t??{})],allItems:()=>["vfs",H(),"items"],tree:(e,t)=>["vfs",H(),"tree",e,t??1],openEnvelope:(e,t)=>["vfs",H(),"open",e,t??"__default__"],allOpenEnvelopes:()=>["vfs",H(),"open"],memberFocus:e=>["vfs","member-focus",e],fractalInstances:()=>["vfs","fractal-instances"],recentActivity:(e,t,n)=>["vfs",H(),"get-activity-feed",e,t,n],itemVersions:(e,t,n,r)=>["vfs","item-versions",e,t,n,r],itemHistory:(e,t,n)=>["vfs","item-history",e,t,n],channelMessages:(e,t)=>["vfs",H(),"channel-messages",e,t??"__top__"],allChannelMessages:()=>["vfs",H(),"channel-messages"],channels:e=>["vfs",H(),"channels",e??"all"],allChannels:()=>["vfs",H(),"channels"],notifications:(e,t)=>["vfs",H(),"notifications",e??"all",t??200],allNotifications:()=>["vfs",H(),"notifications"],unreadCounts:()=>["vfs",H(),"unread-counts"],memberships:e=>["memberships",e]};function Mi(){return new Date().toISOString()}function Oi(){return crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function pe(e){let t=e.path||e.item_path||"",n=t.split("/");n.pop();let r=n.join("/"),s=e.type_data||{};return s.allowed_parent_types&&!s.accepts&&(s.accepts=s.allowed_parent_types),delete s.allowed_parent_types,{id:e.id||e.item_id||"",name:e.name||e.item_name||"",item_type:e.item_type||"unknown",path:t,parent_path:r,is_active:e.is_active!==!1,has_children:e.has_children??!1,created_at:e.created_at||Mi(),updated_at:e.updated_at||Mi(),visibility:e.visibility,type_data:s,scope_item_id:e.scope_item_id,fractal_id:e.fractal_id,parent_instance_id:e.parent_instance_id,owner_principal_id:e.owner_principal_id,created_by_principal_id:e.created_by_principal_id,parent_id:e.parent_id,space_item_id:e.space_item_id,account_item_id:e.account_item_id}}function yn(e){return(e.content?.items||e.items||[]).map(pe)}async function Xn(e){try{let t=await R("read",{id:e});if(t.item_name||t.item_path){let r=pe(t);return r.path&&x().setQueryData(w.item(r.path),r),r}let n=t.item;if(n){let r=pe(n);return r.path&&x().setQueryData(w.item(r.path),r),r}return null}catch{return null}}async function Zn(e){try{let t=await R("read",{path:e});if(t.item_name||t.item_path)return pe(t);let n=t.item;return n?pe(n):null}catch{return null}}async function er(e){try{let t=await R("list",{path:e,limit:200}),n=yn(t);for(let r of n)x().setQueryData(w.item(r.path),r);return n}catch(t){return console.error(`[gateway] Failed to fetch children of ${e}:`,t),[]}}async function tr(e,t,n){try{let r=await R("list",{path:e,limit:t,offset:n}),s=yn(r);for(let i of s)x().setQueryData(w.item(i.path),i);return{items:s,total_hint:r.total??r.content?.total??s.length}}catch(r){return console.error(`[gateway] Failed to fetch children page of ${e}:`,r),{items:[],total_hint:0}}}async function nr(e){let n=await R("types-list",e?{scope_id:e}:{}),r=n.content?.items||n.items||[],s=new Map;for(let i of r){let a=i.name,c=i.type_data;!a||!c||s.set(a,{type_key:a,display_name:c.display_name||a,display_name_plural:c.display_name_plural||a+"s",icon:c.icon||"File",color:c.color||"gray",description:c.description||"",input_schema:c.input_schema||{},system_schema:c.system_schema||{},json_schema:c.input_schema||c.json_schema||{},default_data:c.default_data||{},field_defaults:c.field_defaults||{},renderer_config:c.renderer_config||{},is_system:c.is_system??!1,is_active:c.is_active??!0,is_container:c.is_container??!1,is_scope:c.is_scope??!1,render_mode:c.render_mode||"none",placement_mode:c.placement_mode,direct_parent_types:c.direct_parent_types,allowed_parent_types:c.allowed_parent_types,governed_create:c.governed_create,create_method:c.create_method,dedup:c.dedup,edges:c.edges,events:c.events})}return s}async function rr(e){try{let t=await R("edges",{item_id:e}),n=t.outgoing||[],r=t.incoming||[],s=[];for(let i of n)s.push({id:i.edge_id||Oi(),source_item_id:e,target_item_id:i.target_id||"",edge_type:i.edge_type||"",weight:i.weight??1,context:i.context||{},is_active:!0,is_bidirectional:i.is_bidirectional});for(let i of r)s.push({id:i.edge_id||Oi(),source_item_id:i.source_id||"",target_item_id:e,edge_type:i.edge_type||"",weight:i.weight??1,context:i.context||{},is_active:!0,is_bidirectional:i.is_bidirectional});return s}catch(t){return console.warn(`[gateway] Failed to fetch edges for ${e}:`,t),[]}}async function sr(e,t=1,n,r){try{let s={path:e,max_depth:t>0?t:999};n?.length&&(s.item_types=n),r&&(s.limit=r);let i=await R("tree",s),a=yn(i);for(let c of a)x().setQueryData(w.item(c.path),c);return a}catch(s){return console.error(`[gateway] Failed to fetch tree at ${e}:`,s),[]}}async function ir(e,t=50,n=0){try{let r=await R("get-activity-feed",{scope_path:e,limit:t,offset:n});return r.content?.items||r.items||r.entries||[]}catch(r){return console.error(`[gateway] Failed to fetch recent activity for ${e}:`,r),[]}}async function _n(e,t={}){let{limit:n=50,offset:r=0,include_snapshots:s=!1}=t;try{let i=await R("item-versions",{id:e,limit:n,offset:r,include_snapshots:s});return{versions:i.content?.items||i.versions||[],total:i.total??0}}catch(i){return console.error(`[gateway] Failed to fetch item versions for ${e}:`,i),{versions:[],total:0}}}async function or(e,t=50,n=0){return _n(e,{limit:t,offset:n})}async function ar(e,t,n){try{let r={scope_id:e};t?.length&&(r.item_types=t),n&&(r.limit=n);let s=await R("member-focus",r),i=yn(s);for(let a of i)x().setQueryData(w.item(a.path),a);return i}catch(r){return console.error(`[gateway] Failed to fetch member focus for scope ${e}:`,r),[]}}async function cr(e,t){let n={path:e};t?.mode&&(n.mode=t.mode),t?.strategy&&(n.strategy=t.strategy),t?.arguments&&(n.arguments=t.arguments);let s=await R("open",n);return{item_id:s.item_id,item_path:s.item_path,item_name:s.item_name,item_type:s.item_type,render:s.render,compatible_components:s.compatible_components??[],content:s.content,metadata:s.metadata,instructions:s.instructions}}async function vn(e){let t={item_type:e.type};e.scope&&(t.scope_path=e.scope);let n={};if(e.name&&(n.name=e.name),e.tag&&(n.tag=e.tag),e.parent_id&&(n.parent_id=e.parent_id),e.sort_by&&(n.sort_by=e.sort_by),e.sort_dir&&(n.sort_dir=e.sort_dir),e.offset!=null&&(n.offset=e.offset),e.fields)for(let[r,s]of Object.entries(e.fields))n[`field.${r}`]=String(s);Object.keys(n).length>0&&(t.filters=n),e.limit!=null&&(t.limit=e.limit);try{let r=await R("query",t),s=yn(r);for(let i of s)x().setQueryData(w.item(i.path),i);return{items:s,total_hint:r.total??r.content?.total??s.length}}catch(r){return console.error(`[gateway] Failed to fetch items of type ${e.type}:`,r),{items:[],total_hint:0}}}function Ii(e){return e.filter(t=>t.item_type==="card").map(t=>{let n=t.type_data||{},r=n.payload||{};return{id:t.id||"",path:t.path||"",name:t.name||(t.path||"").split("/").pop()||"",createdAt:t.created_at||"",action:n.action||"created",targetId:n.target_id||void 0,targetPath:n.target_path||"",targetDisplayName:n.target_display_name||"",targetDescription:n.target_description||"",targetItemType:n.target_item_type||"",toolId:(t.name||"").startsWith("card-")?(t.name||"").substring(5):void 0,parentMessagePath:t.parent_message_path||void 0,visibility:n.visibility||"private",openWith:r.open_with||void 0,hostBundled:r.host_bundled===!0?!0:void 0,bundleExport:r.bundle_export||void 0,launchArguments:r.launch_arguments||void 0,requiresUserAttention:r.requires_user_attention===!0?!0:void 0}}).sort((t,n)=>t.createdAt.localeCompare(n.createdAt))}function os(e){return e.filter(t=>t.item_type==="message").map(t=>{let n=t.type_data||{},r="user";n.role==="assistant"?r="assistant":n.role==="system"&&(r="system");let s=n.metadata||{};return{id:t.id||"",path:t.path||"",content:n.message||n.content||"",created_at:t.created_at||"",role:r,seq:n.seq||0,principal_id:n.principal_id,reply_count:n.reply_count||0,parent_message_id:n.parent_message_id,intent_card:s.intent_card,metadata:Object.keys(s).length>0?s:void 0,thread_summary:Array.isArray(n.thread_summary)&&n.thread_summary.length>0?n.thread_summary:void 0}}).sort((t,n)=>t.seq-n.seq)}async function Fi(e,t){try{let n={channel_path:e};t&&(n.parent_message_id=t);let s=await R("get-channel-messages",n),i=s.messages||s.content?.items||s.items||[];return os(i)}catch(n){return console.error(`[gateway] Failed to fetch channel messages for ${e}:`,n),[]}}async function ur(e,t){try{let n={channel_path:e};t&&(n.parent_message_id=t);let s=await R("get-channel-messages",n),i=s.messages||[],a=os(i),c=Ii(i),u=new Map,l=[];for(let d of c)if(d.parentMessagePath){let p=u.get(d.parentMessagePath)||[];p.push(d),u.set(d.parentMessagePath,p)}else l.push(d);return{messages:a,messageCards:u,siblingCards:l,mode:s.mode||"top_level"}}catch(n){return console.error(`[gateway] Failed to fetch channel messages with cards for ${e}:`,n),{messages:[],messageCards:new Map,siblingCards:[],mode:"top_level"}}}async function bn(e,t){try{let n={channel_path:e};t?.parentMessageId&&(n.parent_message_id=t.parentMessageId),t?.limit&&(n.limit=t.limit),t?.before_seq!=null&&(n.before_seq=t.before_seq),t?.after_seq!=null&&(n.after_seq=t.after_seq);let s=await R("get-channel-messages",n),i=s.messages||[],a=Ii(i),c=new Map,u=[];for(let l of a)if(l.parentMessagePath){let d=c.get(l.parentMessagePath)||[];d.push(l),c.set(l.parentMessagePath,d)}else u.push(l);return{messages:os(i),messageCards:c,siblingCards:u,mode:s.mode||"top_level"}}catch(n){return console.error(`[gateway] Failed to fetch channel messages page for ${e}:`,n),{messages:[],messageCards:new Map,siblingCards:[],mode:"top_level"}}}function Yn(e){x().invalidateQueries({queryKey:w.children(e)})}function as(e){x().invalidateQueries({queryKey:w.item(e)})}function ki(e,t){as(e),Yn(e);let n=e.split("/");n.pop();let r=n.join("/")||t;r&&Yn(r)}function qi(e){let t=e+"/";x().invalidateQueries({predicate:n=>{let r=n.queryKey;return r[0]!=="vfs"?!1:r.some(s=>typeof s=="string"&&(s===e||s.startsWith(t)))}})}function Di(){x().invalidateQueries({queryKey:w.all()})}function Qi(e){x().invalidateQueries({queryKey:w.types(e)})}function Ui(e,t){e?x().invalidateQueries({queryKey:w.channelMessages(e,t)}):x().invalidateQueries({queryKey:w.allChannelMessages()})}function Ni(e,t){e&&t?x().invalidateQueries({queryKey:w.openEnvelope(e,t)}):e?x().invalidateQueries({predicate:n=>{let r=n.queryKey;return r[0]==="vfs"&&r[2]==="open"&&r[3]===e}}):x().invalidateQueries({queryKey:w.allOpenEnvelopes()})}var Ha=typeof window<"u"&&(window.location?.hostname==="localhost"||window.location?.hostname==="127.0.0.1"||window.__FSAOS_WS_DEBUG__);function W(...e){Ha&&console.log("[WS]",...e)}var M=null,Qt=null,Ut=null,wn=0,Wa=3e4,Ki=1e4,Kt=!1,Vi=3e4,Ba=Vi*2+5e3,lr=0,dr=null,Li=!1;function $a(){Rn(),lr=Date.now(),dr=setInterval(()=>{if(M&&M.readyState===WebSocket.OPEN&&Date.now()-lr>Ba){W("ping: no inbound traffic for",Date.now()-lr,"ms \u2014 closing half-open socket");try{M.close(4e3,"liveness timeout")}catch{}return}qe({type:"ping"})},Vi)}function Rn(){dr&&(clearInterval(dr),dr=null)}function Ga(){typeof document>"u"||(document.hidden?Rn():Sn()&&(W("Tab visible, reconnecting..."),Cn()))}function za(){Li||typeof document>"u"||(document.addEventListener("visibilitychange",Ga),Li=!0)}var te={},Nt=[],Lt=new Map,lt=new Map;function Ja(){return Object.keys(te).some(t=>te[t]&&te[t].length>0)||Nt.length>0}function Sn(){return Lt.size>0||lt.size>0}async function Cn(){if(!Sn()){W("ensureConnection: no active subscriptions, skipping");return}if(M&&M.readyState===WebSocket.OPEN){W("ensureConnection: already open");return}if(Qt)return W("ensureConnection: connection already in flight, waiting..."),Qt;if(M){W("ensureConnection: killing stale WS in state",M.readyState);try{M.close()}catch{}M=null}return Kt=!1,Qt=(async()=>{try{let e=typeof window<"u"&&window.__FSAOS_CONFIG__||{},t=De,n=await Pe();if(!n){W("ensureConnection: no token available, will retry"),ji();return}let r=t.startsWith("https")?"wss":"ws",s=t.replace(/^https?:\/\//,""),i=`${r}://${s}/ws`;i+=`?token=${encodeURIComponent(n)}`,W("ensureConnection: opening WS to",i.substring(0,50)+"..."),M=new WebSocket(i),await new Promise((a,c)=>{if(!M)return c(new Error("WebSocket not created"));let u=setTimeout(()=>{if(W("ensureConnection: TIMEOUT after",Ki,"ms"),M&&M.readyState!==WebSocket.OPEN){try{M.close()}catch{}M=null}c(new Error("WebSocket connection timeout"))},Ki);M.onopen=()=>{clearTimeout(u),W("ensureConnection: CONNECTED"),wn=0,Ya(),(typeof document>"u"||!document.hidden)&&$a(),za(),a()},M.onmessage=l=>{Xa(l.data)},M.onerror=()=>{W("ensureConnection: WS error event")},M.onclose=l=>{clearTimeout(u),W("ensureConnection: WS closed, code:",l.code,"reason:",l.reason),M=null,Rn(),!Kt&&Sn()&&ji(),c(new Error(`WebSocket closed: ${l.code}`))}})}catch(e){W("ensureConnection: failed -",e?.message||e)}finally{Qt=null}})(),Qt}function ji(){if(Ut||typeof document<"u"&&document.hidden)return;let e=Math.min(1e3*Math.pow(2,wn)+Math.random()*1e3,Wa);wn++,W("scheduleReconnect: attempt",wn,"in",Math.round(e),"ms"),Ut=setTimeout(()=>{Ut=null,Sn()&&Cn()},e)}function Ya(){for(let e of Lt.values())W("resubscribeAll: scope",e.scope_id),qe({type:"subscribe",scope_id:e.scope_id,event_types:e.event_types});for(let e of lt.values())W("resubscribeAll: path",e.path),qe({type:"subscribe_path",path:e.path,event_types:e.event_types})}function qe(e){M&&M.readyState===WebSocket.OPEN&&M.send(JSON.stringify(e))}function Xa(e){lr=Date.now();try{let t=JSON.parse(e);if(t.type==="subscribed"||t.type==="subscribed_path"||t.type==="unsubscribed"||t.type==="unsubscribed_path"||t.type==="pong")return;if(t.type==="error"){console.warn("[WS] Server error:",t.message);return}if(t.type==="event"||t.event_type){let n=t.event_type||"message",r=t.data||t;r.path&&te[r.path]&&te[r.path].forEach(s=>s(r)),te["*"]&&te["*"].forEach(s=>s(r));for(let s of Nt)s.eventType!=="*"&&s.eventType!==n||s.filter&&!s.filter(r)||s.callback(r)}}catch{}}function cs(){!Ja()&&Lt.size===0&&lt.size===0&&M&&(Kt=!0,Rn(),M.close(),M=null,Kt=!1)}function fr(e,t){return te[e]||(te[e]=[]),te[e].push(t),lt.has(e)||(lt.set(e,{path:e,event_types:["token_stream"]}),M&&M.readyState===WebSocket.OPEN&&qe({type:"subscribe_path",path:e,event_types:["token_stream"]})),Cn(),()=>{let n=te[e];if(n){let r=n.indexOf(t);r!==-1&&n.splice(r,1),n.length===0&&(delete te[e],lt.delete(e),qe({type:"unsubscribe_path",path:e}))}cs()}}function J(e,t,n){let s=(Array.isArray(e)?e:[e]).map(i=>({eventType:i,callback:t,filter:n}));return Nt.push(...s),Sn()&&Cn(),()=>{for(let i of s){let a=Nt.indexOf(i);a!==-1&&Nt.splice(a,1)}cs()}}function pr(e,t=["vfs_change","ccm_change"]){return W("subscribeToScope:",e,t),Lt.set(e,{scope_id:e,event_types:t}),M&&M.readyState===WebSocket.OPEN&&qe({type:"subscribe",scope_id:e,event_types:t}),Cn(),()=>{Lt.delete(e),qe({type:"unsubscribe",scope_id:e}),cs()}}function Hi(e,t,n={}){qe({type:"emit",scope_id:e,event_type:t,payload:n})}function us(){W("disconnectSSE: tearing down"),Kt=!0,Rn(),M&&(M.close(),M=null),Ut&&(clearTimeout(Ut),Ut=null),Qt=null,Kt=!1,wn=0;for(let e of Object.keys(te))delete te[e];Nt.length=0,Lt.clear(),lt.clear()}function Wi(){qe({type:"ping"})}xe(us);var jt=new Map,hr=null,mr=null,Je=new Map,Bi=250;function Pn(e){gr(),xn(e),hr=J("vfs_change",t=>Za(t)),mr=J("ccm_change",t=>ec(t))}function xn(e){if(jt.has(e))return;let t=pr(e,["vfs_change","ccm_change"]);jt.set(e,t)}function $i(e){let t=jt.get(e);t&&(t(),jt.delete(e))}function gr(){for(let[,e]of jt)e();jt.clear(),hr&&(hr(),hr=null),mr&&(mr(),mr=null),Je.forEach(e=>clearTimeout(e)),Je.clear()}xe(gr);function Za(e){let t=e.path,n=e.action;if(!t)return;let r=t.split("/");r.pop();let s=r.join("/")||"/root",i=Je.get(s);i&&clearTimeout(i);let a=setTimeout(()=>{Je.delete(s),tc(n,t,e,s)},Bi);Je.set(s,a)}function ec(e){if(!e||typeof e!="object")return;let t=e.source_item_id||e.source_id,n=e.target_item_id||e.target_id;if(!(e.edge_type!=null||t!=null||n!=null))return;let s=`ccm:${t??""}:${n??""}`,i=Je.get(s);i&&clearTimeout(i);let a=setTimeout(()=>{Je.delete(s),t&&x().invalidateQueries({queryKey:w.edges(t)}),n&&x().invalidateQueries({queryKey:w.edges(n)}),!t&&!n&&x().invalidateQueries({predicate:c=>c.queryKey[0]==="vfs"&&c.queryKey[1]==="edges"})},Bi);Je.set(s,a)}function tc(e,t,n,r){if((e||"").toUpperCase()==="DELETE")x().removeQueries({queryKey:w.item(t)}),x().removeQueries({queryKey:w.children(t)}),x().removeQueries({queryKey:w.tree(t)});else if(n.item_id)try{let i={id:n.item_id,path:n.path,name:n.name,item_type:n.item_type,parent_id:n.parent_id,scope_item_id:n.scope_item_id},a=pe(i);a&&a.id&&x().setQueryData(w.item(t),a)}catch{}x().invalidateQueries({queryKey:w.children(r)}),x().invalidateQueries({predicate:i=>{let a=i.queryKey;if(a[0]!=="vfs"||a[1]!=="tree")return!1;let c=a[2];return t.startsWith(c+"/")||t===c}}),n.item_id&&x().invalidateQueries({queryKey:w.itemById(n.item_id)})}var ls=j(ie(),1),Ji=j(zi(),1);function Yi(e){return R("read",{path:e})}function Xi(e,t){return R("list",{path:e,...t})}function Zi(e){return R("create",e)}function eo(e){return R("update",e)}function to(e){return R("create",e)}function no(e,t){let r=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).scopePath||"";return R("tools/call",{name:e,instance_path:r,...t||{}})}function ro(e,t,n){return R("signal",{target_id:e,event_name:t,payload:n||{}})}function so(e){return((typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"")+e}var io={signIn:e=>e.provider?F.auth.signInWithOAuth({provider:e.provider,options:{redirectTo:e.redirectTo||window.location.href}}):F.auth.signInWithPassword({email:e.email,password:e.password}),signUp:e=>F.auth.signUp({email:e.email,password:e.password,options:{data:e.metadata||{}}}),signOut:async()=>{await F.auth.signOut(),gt(),x().clear()},getSession:()=>F.auth.getSession().then(e=>e.data.session),getUser:()=>F.auth.getUser().then(e=>e.data.user),onAuthStateChange:e=>{let{data:{subscription:t}}=F.auth.onAuthStateChange((n,r)=>{e({event:n,session:r,user:r?.user??null})});return()=>t?.unsubscribe()},resetPassword:e=>F.auth.resetPasswordForEmail(e),signInWithMagicLink:(e,t)=>F.auth.signInWithOtp({email:e,options:{emailRedirectTo:t||window.location.href}})};function oo(){let e=document.getElementById("root");if(e)try{let t=window.__FSAOS_COMPONENT__;if(!t){e.innerHTML='<div style="padding:2rem;color:#ef4444;font-family:system-ui"><h2>Component Error</h2><pre>No component found. The bundle may have failed to load.</pre></div>';return}let n=t.default||t,r=window.__FSAOS_ITEM_DATA__||null,s=r?{item:r,...r}:{};(0,Ji.createRoot)(e).render((0,ls.createElement)(hn,{client:x()},(0,ls.createElement)(n,s)))}catch(t){console.error("[FSAOS] Failed to mount root component:",t),e.innerHTML='<div style="padding:2rem;color:#ef4444;font-family:system-ui"><h2>Component Error</h2><pre>'+(t.message||t)+"</pre></div>"}}function ao(){let e=window.React,t=window.ReactDOM,n=window.__FSAOS_GATEWAY__,r=window.__FSAOS_UI__;if(!n){console.error("[FSAOS] Cannot set up require shim: __FSAOS_GATEWAY__ not found");return}let s={react:e,"react-dom":t,"react-dom/client":t,"react/jsx-runtime":{jsx:e?.createElement,jsxs:e?.createElement,Fragment:e?.Fragment},"@fsaos/react":n,"@fsaos/gateway":n,"@fsaos/ui":r||{}};window.require=function(a){if(s[a])return s[a];throw new Error("[FSAOS] Module not found: "+a)},window.__FSAOS_MOUNT__=n.mount}var y=j(ie(),1),rc=j(uo(),1),sc=j(Gn(),1);function nc(e){return`${e}/settings/mounts`}var En=null;async function ds(e,t){En=nc(e);try{let s=((await R("read",{path:En}))?.item?.type_data?.mounts??[]).map(t).filter(a=>a!==null),i=Ue();return i&&!s.some(a=>a.id===i.id)&&s.unshift(i),kr(s),s}catch{let n=Ue(),r=n?[n]:[];return kr(r),r}}async function lo(){if(!En)return;let e=mt().map(n=>n.id),t=Xe()?.id??null;try{await R("update",{path:En,type_data:{mounts:e,last_anchor:t}})}catch{try{let r=En.split("/").slice(0,-1).join("/");await R("create",{parent_path:r,name:"mounts",item_type:"file",type_data:{mounts:e,last_anchor:t}})}catch(r){console.warn("[SDK] mount declaration persist failed:",r)}}}async function fs(e){Os(e),await lo()}async function fo(e){Is(e),await lo()}function K(){return(0,y.useSyncExternalStore)(Ze,_e,_e)}function mo(){return K(),Un()}function go(e){return K(),k({queryKey:w.item(e),queryFn:()=>Zn(e),enabled:!!e})}function yo(e){return K(),k({queryKey:w.itemById(e),queryFn:()=>Xn(e),enabled:!!e})}function hs(e){return K(),k({queryKey:w.children(e),queryFn:()=>er(e),enabled:!!e})}function _o(e){let t=hs(e);return{...t,children:t.data??[]}}function vo(e,t=1){return K(),k({queryKey:w.tree(e,t),queryFn:()=>sr(e,t),enabled:!!e})}function bo(e,t){return K(),k({queryKey:w.search(e,t),queryFn:async()=>{let n={query:e};t?.length&&(n.item_types=t);let r=await R("search",n);return(r.content?.items||r.items||[]).map(pe)},enabled:!!e&&e.length>0})}function wo(e){K();let t=(0,y.useMemo)(()=>e,[JSON.stringify(e)]);return k({queryKey:["vfs",le()??"__unscoped__","resolve",JSON.stringify(t??{})],queryFn:async()=>await R("resolve",t),enabled:!!t?.query&&t.query.length>0})}function So(e){K();let t=(0,y.useMemo)(()=>e,[JSON.stringify(e)]);return k({queryKey:w.items(t?.type??"",t),queryFn:()=>vn(t),enabled:!!t?.type,select:n=>n.items})}function Ro(e){K();let t=e?.limit??20,n=(0,y.useMemo)(()=>e,[JSON.stringify(e)]),r=gn({queryKey:["vfs",le()??"__unscoped__","infinite-items",n?.type??"",JSON.stringify(n??{})],queryFn:async({pageParam:i=0})=>vn({...n,limit:t,offset:i}),initialPageParam:0,getNextPageParam:(i,a,c)=>{if(!(i.items.length<t))return c+i.items.length},enabled:!!n?.type});return{allItems:(0,y.useMemo)(()=>{if(!r.data?.pages)return[];let i=new Set,a=[];for(let c of r.data.pages)for(let u of c.items)u.id&&!i.has(u.id)&&(i.add(u.id),a.push(u));return a},[r.data?.pages]),fetchNextPage:r.fetchNextPage,isFetchingNextPage:r.isFetchingNextPage,isExhausted:!r.hasNextPage,isLoading:r.isLoading,isFetching:r.isFetching,error:r.error,totalHint:r.data?.pages?.[0]?.total_hint}}function Co(e){K();let t=20,n=gn({queryKey:["vfs",le()??"__unscoped__","infinite-children",e??""],queryFn:async({pageParam:s=0})=>tr(e,t,s),initialPageParam:0,getNextPageParam:(s,i,a)=>{if(!(s.items.length<t))return a+s.items.length},enabled:!!e});return{allItems:(0,y.useMemo)(()=>{if(!n.data?.pages)return[];let s=new Set,i=[];for(let a of n.data.pages)for(let c of a.items)c.id&&!s.has(c.id)&&(s.add(c.id),i.push(c));return i},[n.data?.pages]),fetchNextPage:n.fetchNextPage,isFetchingNextPage:n.isFetchingNextPage,isExhausted:!n.hasNextPage,isLoading:n.isLoading,isFetching:n.isFetching,error:n.error,totalHint:n.data?.pages?.[0]?.total_hint}}function Po(e){return K(),k({queryKey:w.edges(e),queryFn:()=>rr(e),enabled:!!e})}function yr(e){return K(),k({queryKey:w.types(e),queryFn:()=>nr(e)})}function xo(e,t){let n=yr(t);return{...n,data:n.data?.get(e)??void 0}}function Eo(e,t){K();let n=(0,y.useMemo)(()=>t?.arguments,[JSON.stringify(t?.arguments)]),r=t?.mode,s=t?.strategy,i=t?.width;return k({queryKey:[...w.openEnvelope(e,s),i],queryFn:async()=>{let a=await cr(e,{mode:r,strategy:s,arguments:n});if(i&&a.render?.props?.url){let c=a.render.props.url,u=c.includes("?")?"&":"?";a.render.props.url=`${c}${u}w=${i}`}return a},enabled:!!e})}var po={related_to:"Related To",depends_on:"Depends On",blocks:"Blocks",parent_of:"Parent Of",child_of:"Child Of",references:"References",implements:"Implements",extends:"Extends",contains:"Contains",belongs_to:"Belongs To",created_by:"Created By",assigned_to:"Assigned To",tagged_with:"Tagged With",linked_to:"Linked To"};function To(e){let t=yr(e),n=t.data??new Map;return(0,y.useMemo)(()=>({canHaveChildren:h=>n.get(h.item_type)?.is_container??!1,isScope:h=>n.get(h.item_type)?.is_scope??!1,isScopeType:h=>n.get(h)?.is_scope??!1,isContainerType:h=>n.get(h)?.is_container??!1,getTypeDefinition:h=>n.get(h),getTypeColor:h=>n.get(h)?.color??"gray",getTypeIcon:h=>n.get(h)?.icon??"File",getTypeDisplayName:h=>n.get(h)?.display_name??h,getKnownEdgeTypes:()=>Object.entries(po).map(([h,v])=>({key:h,label:v})),getEdgeTypeLabel:h=>po[h]??h.replace(/_/g," "),allTypes:n,loading:t.isLoading}),[n,t.isLoading])}function Ao(e,t,n){return K(),k({queryKey:w.memberFocus(e),queryFn:()=>ar(e,t,n),enabled:!!e})}function Mo(e,t={}){let{limit:n=50,offset:r=0,include_snapshots:s=!1}=t;return k({queryKey:w.itemVersions(e,String(n),String(r),String(s)),queryFn:()=>_n(e,{limit:n,offset:r,include_snapshots:s}),enabled:!!e})}function Oo(e,t=50,n=0){return k({queryKey:w.itemHistory(e,String(t),String(n)),queryFn:()=>or(e,t,n),enabled:!!e})}function Io(e,t=50,n=0){return K(),k({queryKey:w.recentActivity(e,String(t),String(n)),queryFn:()=>ir(e,t,n),enabled:!!e})}function Fo(){let[e,t]=(0,y.useState)(null),[n,r]=(0,y.useState)(!0),[s,i]=(0,y.useState)(null);return(0,y.useEffect)(()=>{let a=!1;return Dn().then(c=>{if(!a){let u=typeof window<"u"&&window.__FSAOS_CONFIG__||{};t({path:c.scope_path,scope_id:c.scope_id,fractal_id:c.fractal_id,instance_name:c.instance_name,display_name:c.display_name,componentPath:u.componentPath||"",isEmbed:!!u.embedToken}),r(!1)}}).catch(c=>{a||(i(c instanceof Error?c:new Error(String(c))),r(!1))}),()=>{a=!0}},[]),{data:e,loading:n,error:s}}var ic=[];function Tn(e){return{id:e.accountId,path:e.path,kind:e.isSpace?"space":"account",name:e.name,grantedUnderAccountId:e.grantedUnderAccountId??void 0}}function ko(){let{user:e}=_r(),t=(0,y.useRef)(!1),n=k({queryKey:w.memberships(e?.id??"anonymous"),queryFn:async()=>((await R("list-memberships",{})).memberships||[]).map(f=>({accountId:f.account_id,path:f.account_path,name:f.account_name,role:f.role||"member",typeData:f.account_type_data||{},joinedAt:f.joined_at,via:f.via,placement:f.placement,subordinateTo:f.subordinate_to??null,cascadeAnchorId:f.cascade_anchor_id??null,isAccount:f.is_account??void 0,isSpace:f.is_space??void 0,isOwner:f.is_owner??void 0,billingResponsible:f.billing_responsible??void 0,grantedVia:f.granted_via??null,grantedUnderAccountId:f.granted_under_account_id??null,personalSpaceId:f.personal_space_id??null,personalSpacePath:f.personal_space_path??null})),enabled:!!e?.id,staleTime:1e3*60*2}),r=n.data??ic,s=(0,y.useMemo)(()=>r.filter(d=>d.isAccount!==!1&&!d.isSpace),[r]),i=(0,y.useMemo)(()=>{let d=new Set(s.map(f=>f.accountId)),p=f=>!f.subordinateTo||!d.has(f.subordinateTo);return[...s].sort((f,h)=>Number(p(h))-Number(p(f)))},[s]),a=(0,y.useSyncExternalStore)(Ze,_e,_e),c=(0,y.useMemo)(()=>{let d=Xe();return d?r.find(p=>p.accountId===d.id)??null:null},[a,r]);(0,y.useEffect)(()=>{if(!e?.id){t.current=!1;return}if(!t.current)if(i.length===1){let d=i[0];Zt(Tn(d)),Pn(d.accountId),d.personalSpacePath&&ds(d.personalSpacePath,p=>{let f=r.find(h=>h.accountId===p);return f?Tn(f):null}).catch(()=>{}),t.current=!0}else i.length>1&&(t.current=!0)},[e?.id,i,r]);let u=(0,y.useCallback)(d=>{let p=r.find(h=>h.path===d);if(!p)return;let f=Tn(p);Ue()?Qe(f):(Zt(f),p.personalSpacePath&&ds(p.personalSpacePath,h=>{let v=r.find(m=>m.accountId===h);return v?Tn(v):null}).catch(()=>{})),Pn(p.accountId)},[r]),l=(0,y.useCallback)(d=>{let p=r.find(f=>f.path===d);p&&(fs(Tn(p)).catch(()=>{}),xn(d))},[r]);return{accounts:i,allMemberships:r,currentAccount:c,mountedScope:null,switchAccount:u,mountScope:l,loading:n.isLoading,error:n.error}}function qo(){let e=(0,y.useSyncExternalStore)(qn,tn,tn);return{mounts:(0,y.useMemo)(()=>mt(),[e]),homeAnchor:Ue(),anchor:Xe(),setAnchor:Qe,mount:fs,unmount:fo}}function _r(){let[e,t]=(0,y.useState)(null),[n,r]=(0,y.useState)(null),[s,i]=(0,y.useState)(!0),a=(0,y.useRef)(null);(0,y.useEffect)(()=>{F.auth.getSession().then(({data:h,error:v})=>{if(v){console.warn("[useAuth] getSession error, clearing stale session:",v.message),F.auth.signOut().catch(()=>{}),r(null),t(null),i(!1);return}r(h?.session??null),t(h?.session?.user??null),i(!1)}).catch(h=>{console.warn("[useAuth] getSession threw, clearing stale session:",h?.message),F.auth.signOut().catch(()=>{}),r(null),t(null),i(!1)});let{data:{subscription:f}}=F.auth.onAuthStateChange((h,v)=>{if(h==="TOKEN_REFRESHED"&&!v){console.warn("[useAuth] TOKEN_REFRESHED with null session \u2014 signing out"),F.auth.signOut().catch(()=>{}),r(null),t(null),i(!1);return}r(v),t(v?.user??null),i(!1)});return a.current=f,()=>{f?.unsubscribe()}},[]);let c=(0,y.useCallback)(async f=>f.provider?F.auth.signInWithOAuth({provider:f.provider,options:f.redirectTo?{redirectTo:f.redirectTo}:{redirectTo:window.location.href}}):F.auth.signInWithPassword({email:f.email,password:f.password}),[]),u=(0,y.useCallback)(async f=>F.auth.signUp({email:f.email,password:f.password,options:{data:f.metadata||{}}}),[]),l=(0,y.useCallback)(async()=>{await F.auth.signOut(),gt(),x().clear()},[]),d=(0,y.useCallback)(async f=>{let{error:h}=await F.auth.resetPasswordForEmail(f);if(h)throw h},[]),p=(0,y.useCallback)(async(f,h)=>{let{error:v}=await F.auth.signInWithOtp({email:f,options:h?{emailRedirectTo:h}:{emailRedirectTo:window.location.href}});if(v)throw v},[]);return{user:e,session:n,loading:s,signIn:c,signUp:u,signOut:l,resetPassword:d,signInWithMagicLink:p}}function Do(e){let[t,n]=(0,y.useState)(null),[r,s]=(0,y.useState)(!1),[i,a]=(0,y.useState)(null);return(0,y.useEffect)(()=>{if(!e){n(null),s(!1);return}if(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e))s(!0),R("resolve-asset",{asset_id:e}).then(u=>{u.success&&u.public_url?n({url:u.public_url,id:u.asset_id,name:u.name,mimeType:u.mime_type,width:u.width,height:u.height,sizeBytes:u.size_bytes}):a(new Error(u.error||"Asset not found")),s(!1)}).catch(u=>{a(u instanceof Error?u:new Error(String(u))),s(!1)});else{let l=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"";n({url:l+e}),s(!1)}},[e]),{data:t,loading:r,error:i}}var An={},ho={};xe(()=>{for(let e of Object.keys(An))delete An[e]});var Qo=null;function Uo(e){Qo=e,typeof window<"u"&&!window.__FSAOS_GATEWAY__&&(window.__FSAOS_GATEWAY__=e)}function oc(e){switch(e){case"react":return typeof window<"u"&&window.React||y.default;case"react-dom":case"react-dom/client":return typeof window<"u"&&window.ReactDOM||rc;case"react/jsx-runtime":case"react/jsx-dev-runtime":return typeof window<"u"&&window.React?{jsx:window.React.createElement,jsxs:window.React.createElement,Fragment:window.React.Fragment}:sc;case"@fsaos/gateway":case"@fsaos/react":return typeof window<"u"&&window.__FSAOS_GATEWAY__||Qo||{};case"@fsaos/ui":return typeof window<"u"&&window.__FSAOS_UI__||{};case"@fsaos/theme":return{};default:return console.warn(`[useComponent] Unknown module requested: ${e}`),{}}}function ac(e,t){return e.replace(/^(\s*)(:root|body)(\s*[{,])/gm,(n,r,s,i)=>`${r}.${t}${i}`)}async function cc(e,t){if(!ho[e])try{let n=await fetch(e);if(!n.ok)return;let r=await n.text();if(!r.trim()||r.includes("No CSS bundle for this component"))return;t&&!r.includes(`.fsaos-c-${t}`)&&(r=ac(r,`fsaos-c-${t}`));let s=document.createElement("style");s.setAttribute("data-fsaos-component-css",e),t&&s.setAttribute("data-fsaos-component-id",t),s.textContent=r,document.head.appendChild(s),ho[e]=s}catch{}}function uc(e){let t=null,n=window.__FSAOS_REGISTER__;window.__FSAOS_REGISTER__=r=>{t=r};try{let r=["var require = arguments[0];",e,"return window.__FSAOS_COMPONENT__;"].join(`
3
+ `),i=new Function(r)(oc),a=t??i;return a?a.default||a:null}finally{n!==void 0?window.__FSAOS_REGISTER__=n:delete window.__FSAOS_REGISTER__}}function ms(e){let[t,n]=(0,y.useState)(null),[r,s]=(0,y.useState)(!0),[i,a]=(0,y.useState)(null);return(0,y.useEffect)(()=>{if(!e)return;let c=!1;s(!0),a(null);let l=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"";return(async()=>{try{let d=1,p=e+"@v1",f=l+e+"/__bundle.js";try{let S=await fetch(l+e+"/__meta",{cache:"no-store"});S.ok&&(d=(await S.json()).version||1,p=e+"@v"+d,f=l+e+"/__bundle.v"+d+".js")}catch{f=l+e+"/__bundle.js?v="+Date.now()}if(c)return;if(An[p]){n(()=>An[p]),s(!1);return}let h=await fetch(f);if(!h.ok)throw new Error(`Failed to fetch bundle: ${h.status} ${h.statusText} (${f})`);let v=await h.text();if(c)return;let m=f.replace(/__bundle(\.v\d+)?\.js(\?.*)?$/,"__bundle$1.css");cc(m).catch(()=>{});let g=uc(v);if(!g)throw new Error("Bundle did not export a component. Expected window.__FSAOS_COMPONENT__ (FSAOS build) or a __FSAOS_REGISTER__(Component) call.");if(typeof g!="function")throw new Error(`Bundle export is not a React component (got ${typeof g})`);An[p]=g,c||(n(()=>g),s(!1))}catch(d){c||(a(d instanceof Error?d:new Error(String(d))),s(!1))}})(),()=>{c=!0}},[e]),{Component:t,loading:r,error:i}}var lc=["--color-primary","--color-secondary","--color-background","--color-surface","--color-text","--color-text-secondary","--color-border","--color-accent","--color-success","--color-warning","--color-error","--font-family-heading","--font-family-body","--border-radius","--spacing-unit"];function No(){return{data:(0,y.useMemo)(()=>{if(typeof document>"u")return{tokens:{}};let t={},n=getComputedStyle(document.documentElement);return lc.forEach(r=>{t[r]=n.getPropertyValue(r).trim()}),{tokens:t}},[]),loading:!1,error:null}}function Ko(e,t){return{data:{allowed:!0},loading:!1,error:null}}function Lo(e,t){let n={};return(t||[]).forEach(r=>{n[r]=!0}),{data:n,loading:!1,error:null}}var oe=null,Vt=null,ps=new Set;function dc(){ps.forEach(e=>e())}xe(()=>{oe=null,Vt=null});async function jo(e){let t=e;if(!t){let{data:r}=await F.auth.getSession();t=r?.session?.user?.id}let n={principalId:null,displayName:null,createdAt:null,metadata:null,vfsPath:null};if(!t)return n;if(oe&&oe.authUserId===t){let{principalId:r,displayName:s,createdAt:i,metadata:a,vfsPath:c}=oe;return{principalId:r,displayName:s,createdAt:i,metadata:a,vfsPath:c}}return Vt||(Vt=(async()=>{try{let{data:r,error:s}=await F.from("os_principals").select("id, display_name, created_at, metadata").eq("auth_user_id",t).eq("principal_type","user").maybeSingle();if(s)return console.warn("[SDK] Could not resolve principal:",s.message),n;let i=r?.id??null,a=null;if(i){let{data:u}=await F.from("os_items").select("path").eq("owner_principal_id",i).eq("item_type","principal").eq("is_active",!0).like("path","/root/principals/%"),l=(u??[]).map(d=>d.path);a=l.find(d=>d.split("/").length===4)??l[0]??null}let c={principalId:i,displayName:r?.display_name??null,createdAt:r?.created_at??null,metadata:r?.metadata??null,vfsPath:a};return oe={authUserId:t,...c},c}finally{Vt=null}})(),Vt)}async function Vo(e){return(await jo(e)).principalId}function Ho(){let e=_r(),t=e.user,n=oe?.authUserId===t?.id?oe:null,[r,s]=(0,y.useState)(n),i=(0,y.useRef)(null);return(0,y.useEffect)(()=>{let a=()=>{let c=oe;c&&c.authUserId===t?.id&&s({principalId:c.principalId,displayName:c.displayName,createdAt:c.createdAt,metadata:c.metadata,vfsPath:c.vfsPath})};return ps.add(a),()=>{ps.delete(a)}},[t?.id]),(0,y.useEffect)(()=>{if(!t?.id){s(null),i.current=null;return}i.current===t.id&&r?.principalId!=null||(i.current=t.id,jo(t.id).then(a=>{s(a)}))},[t?.id]),e.loading?{data:null,loading:!0,error:null}:t?{data:{id:t.id,principalId:r?.principalId??null,email:t.email,display_name:r?.displayName??void 0,created_at:r?.createdAt??void 0,vfs_path:r?.vfsPath??void 0,role:t.role||t.app_metadata?.role||"user",authenticated:!0,metadata:r?.metadata??t.user_metadata??{}},loading:!1,error:null}:{data:{id:"anonymous",principalId:null,role:"viewer",authenticated:!1},loading:!1,error:null}}function Wo(){return{data:null,loading:!1,error:null}}function Bo(e){let{path:t,...n}=e,r=ms(t),s=r.Component,{loading:i,error:a}=r;return i?(0,y.createElement)("div",{className:"fsaos-loading"},""):a?(0,y.createElement)("div",{className:"fsaos-error"},"Failed to load component"):s?(0,y.createElement)(s,n):null}function $o(e){return e.children}function Go(e){let t=K(),{channelPath:n,parentMessageId:r,realtime:s=!0,enabled:i}=e,a=i!==void 0?i&&!!n:!!n,c=(0,y.useMemo)(()=>w.channelMessages(n??"",r),[n,r,t]),u=U(),l=(0,y.useRef)(null),d=k({queryKey:c,queryFn:()=>ur(n,r),enabled:a});(0,y.useEffect)(()=>{if(!s||!a)return;let m=J("vfs_change",()=>{l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{u.invalidateQueries({queryKey:c})},500)},g=>(g.item_type==="message"||g.item_type==="card")&&typeof g.path=="string"&&g.path.startsWith(n));return()=>{m(),l.current&&clearTimeout(l.current)}},[s,a,n,c,u]);let p=d.data,f=p?.messages??[],h=p?.messageCards??new Map,v=p?.siblingCards??[];return{messages:f,messageCards:h,siblingCards:v,threads:(0,y.useMemo)(()=>f.filter(m=>m.reply_count>0),[f]),isLoading:d.isLoading,isFetching:d.isFetching,error:d.error,refetch:d.refetch}}function zo(e){K();let{channelPath:t,parentMessageId:n,limit:r=50,realtime:s=!0,enabled:i=!0}=e,a=!!n,c=i&&!!t,u=gn({queryKey:[...w.channelMessages(t||"",n),"infinite",r],queryFn:async({pageParam:m})=>bn(t,{parentMessageId:n,limit:r,before_seq:a?void 0:m,after_seq:a?m:void 0}),initialPageParam:void 0,getNextPageParam:m=>!a||m.messages.length<r?void 0:m.messages[m.messages.length-1]?.seq,getPreviousPageParam:m=>a||m.messages.length<r?void 0:m.messages[0]?.seq,enabled:c}),l=(0,y.useMemo)(()=>{if(!u.data?.pages)return[];let m=new Set,g=[];for(let S of u.data.pages)for(let C of S.messages)m.has(C.id)||(m.add(C.id),g.push(C));return g.sort((S,C)=>S.seq-C.seq)},[u.data?.pages]),{messageCards:d,siblingCards:p}=(0,y.useMemo)(()=>{let m=new Map,g=[];if(!u.data?.pages)return{messageCards:m,siblingCards:g};let S=new Set;for(let C of u.data.pages){for(let[E,Q]of C.messageCards)for(let L of Q){if(S.has(L.id))continue;S.add(L.id);let B=m.get(E)||[];B.push(L),m.set(E,B)}for(let E of C.siblingCards)S.has(E.id)||(S.add(E.id),g.push(E))}return{messageCards:m,siblingCards:g}},[u.data?.pages]),f=U(),h=(0,y.useRef)(null),v=(0,y.useMemo)(()=>[...w.channelMessages(t||"",n),"infinite",r],[t,n,r]);return(0,y.useEffect)(()=>{if(!s||!t||!c)return;let m=J("vfs_change",()=>{h.current&&clearTimeout(h.current),h.current=setTimeout(async()=>{let g=f.getQueryData(v);if(!g?.pages?.length){f.invalidateQueries({queryKey:v});return}let S=0;for(let C of g.pages)for(let E of C.messages)E.seq>S&&(S=E.seq);if(S===0){f.invalidateQueries({queryKey:v});return}try{let C=await bn(t,{parentMessageId:n,limit:r,after_seq:S});if(C.messages.length===0&&C.siblingCards.length===0){f.invalidateQueries({queryKey:v});return}if(C.messages.length>0){let E=Math.min(...C.messages.map(Q=>Q.seq));if(E>S+1){console.warn(`[useInfiniteChannelMessages] sequence gap detected: maxSeq=${S}, minNewSeq=${E}. Triggering full refetch.`),f.invalidateQueries({queryKey:v});return}}f.setQueryData(v,E=>{if(!E)return E;let Q=[...E.pages],L=Q.length-1,B=Q[L],dt=new Set(B.messages.map(A=>A.id)),re=C.messages.filter(A=>!dt.has(A.id)),N=[...B.messages,...re].sort((A,Ye)=>A.seq-Ye.seq),Y=new Map(B.messageCards);for(let[A,Ye]of C.messageCards){let $=Y.get(A)||[],Ht=new Set($.map(Sr=>Sr.id)),ba=Ye.filter(Sr=>!Ht.has(Sr.id));Y.set(A,[...$,...ba])}let me=new Set(B.siblingCards.map(A=>A.id)),ge=C.siblingCards.filter(A=>!me.has(A.id)),ye=[...B.siblingCards,...ge];return Q[L]={...B,messages:N,messageCards:Y,siblingCards:ye},{...E,pages:Q}})}catch(C){console.warn("[useInfiniteChannelMessages] live tail fetch failed, falling back to full invalidation:",C),f.invalidateQueries({queryKey:v})}},500)},g=>(g.item_type==="message"||g.item_type==="card")&&typeof g.path=="string"&&g.path.startsWith(t));return()=>{m(),h.current&&clearTimeout(h.current)}},[s,t,c,v,f,n,r]),{messages:l,messageCards:d,siblingCards:p,threads:l.filter(m=>m.reply_count>0),isLoading:u.isLoading,isFetching:u.isFetching,error:u.error,refetch:u.refetch,hasPreviousPage:u.hasPreviousPage??!1,fetchPreviousPage:u.fetchPreviousPage,isFetchingPreviousPage:u.isFetchingPreviousPage??!1,hasNextPage:u.hasNextPage??!1,fetchNextPage:u.fetchNextPage,isFetchingNextPage:u.isFetchingNextPage??!1}}function fc(e){return e==="on"||e==="auto"?"on":"off"}function pc(e){let t=e.type_data||{},n=e._reader||{},r=n.context_lineage||{};return{id:e.id||"",path:e.path||"",name:e.name||"",displayName:t.display_name||e.name||"",aiMode:fc(t.ai_mode),isPrivate:t.is_private||!1,isDm:t.is_dm||!1,messageCount:t.message_count||0,updatedAt:e.updated_at||"",chatScopePath:r.context_path||"",contextId:e.scope_item_id||"",contextPath:r.context_path||"",contextType:r.context_type||"",contextName:r.context_name||"",contextDisplayName:r.context_name||"",contextPrincipalId:void 0,accountId:e.account_item_id||"",accountPath:"",accountDisplayName:"",memberRole:n.member_role||"member",memberPath:"",modePath:"",autoPilot:t.auto_pilot||!1}}function vr(e={}){let t=K(),{realtime:n=!0,enabled:r=!0}=e,s=U(),i=(0,y.useRef)(null),a=(0,y.useMemo)(()=>w.channels("all"),[t]),c=k({queryKey:a,queryFn:async()=>((await R("query",{item_type:"channel",include_reader:!0,limit:500})).items||[]).map(pc),enabled:r});return(0,y.useEffect)(()=>{if(!n||!r)return;let l=J("vfs_change",()=>{i.current&&clearTimeout(i.current),i.current=setTimeout(()=>{s.invalidateQueries({queryKey:a})},1e3)},p=>p.item_type==="channel"||p.item_type==="message"),d=J("ccm_change",()=>{i.current&&clearTimeout(i.current),i.current=setTimeout(()=>{s.invalidateQueries({queryKey:a})},1e3)},p=>p.item_type==="channel"||p.item_type==="message");return()=>{l(),d(),i.current&&clearTimeout(i.current)}},[n,r,a,s]),{channels:c.data??[],isLoading:c.isLoading,isFetching:c.isFetching,error:c.error,refetch:c.refetch}}function Jo(e={}){let t=vr(e),n=(0,y.useMemo)(()=>t.channels.filter(r=>!r.isDm),[t.channels]);return{...t,channels:n}}function Yo(e={}){let t=vr(e),n=(0,y.useMemo)(()=>t.channels.filter(r=>r.isDm),[t.channels]);return{...t,channels:n}}function gs(e={}){let t=K(),{filter:n="all",limit:r=200,realtime:s=!0,enabled:i=!0}=e,a=U(),c=(0,y.useRef)(null),u=(0,y.useMemo)(()=>w.notifications(n,r),[n,r,t]),l=k({queryKey:u,queryFn:async()=>{let p={limit:r};return n==="unread"&&(p.filter="unread"),(await R("get-notifications",p)).notifications||[]},enabled:i});return(0,y.useEffect)(()=>{if(!s||!i)return;let p=["vfs_change","ccm_change"].map(f=>J(f,()=>{c.current&&clearTimeout(c.current),c.current=setTimeout(()=>{a.invalidateQueries({queryKey:u})},2e3)},h=>h.item_type==="notification"||h.item_type==="message"));return()=>{p.forEach(f=>f()),c.current&&clearTimeout(c.current)}},[s,i,u,a]),{notifications:l.data??[],isLoading:l.isLoading,isFetching:l.isFetching,error:l.error,refetch:l.refetch}}function Xo(e={}){let{channels:t,realtime:n=!0,enabled:r=!0}=e,{notifications:s,isLoading:i,isFetching:a,error:c,refetch:u}=gs({filter:"unread",limit:200,realtime:n,enabled:r}),l=(0,y.useMemo)(()=>{let h=new Map;for(let v of s)v.is_unread&&v.channel_id&&h.set(v.channel_id,(h.get(v.channel_id)||0)+1);return h},[s]),d=(0,y.useMemo)(()=>{let h=0;return l.forEach(v=>{h+=v}),h},[l]),{dmUnread:p,channelUnread:f}=(0,y.useMemo)(()=>{if(!t)return{dmUnread:0,channelUnread:0};let h=new Set(t.filter(g=>g.isDm).map(g=>g.id)),v=0,m=0;return l.forEach((g,S)=>{h.has(S)?v+=g:m+=g}),{dmUnread:v,channelUnread:m}},[t,l]);return{unreadByChannel:l,totalUnread:d,dmUnread:p,channelUnread:f,isLoading:i,isFetching:a,error:c,refetch:u}}function Zo(){let e=U();return ke({mutationFn:t=>R("create",t),onSuccess:(t,n)=>{let r=n.parent_path;r&&e.invalidateQueries({queryKey:w.children(r)})}})}function ea(){let e=U();return ke({mutationFn:t=>R("update",t),onSuccess:(t,n)=>{let r=n.path;if(r){e.invalidateQueries({queryKey:w.item(r)});let s=r.split("/");s.pop();let i=s.join("/");i&&e.invalidateQueries({queryKey:w.children(i)})}}})}function ta(){return ke({mutationFn:e=>R("update-principal",e),onSuccess:(e,t)=>{if(!oe)return;let n=e&&typeof e=="object"&&e.metadata?e.metadata:{...oe.metadata??{},...typeof t.language=="string"?{language:t.language}:{},...typeof t.timezone=="string"?{timezone:t.timezone}:{},..."avatar_file_id"in t?{avatar_file_id:t.avatar_file_id}:{}};oe={...oe,displayName:typeof t.display_name=="string"?t.display_name:oe.displayName,metadata:n},dc()}})}function na(){let e=U();return ke({mutationFn:t=>R("delete",t),onSuccess:(t,n)=>{let r=n.path;if(r){e.removeQueries({queryKey:w.item(r)});let s=r.split("/");s.pop();let i=s.join("/");i&&e.invalidateQueries({queryKey:w.children(i)})}}})}function ra(){let e=U();return ke({mutationFn:t=>R("move",t),onSuccess:(t,n)=>{let r=n.path,s=n.new_parent_path;if(r){e.invalidateQueries({queryKey:w.item(r)});let i=r.split("/");i.pop();let a=i.join("/");a&&e.invalidateQueries({queryKey:w.children(a)})}s&&e.invalidateQueries({queryKey:w.children(s)})}})}function sa(){let e=U();return ke({mutationFn:t=>R("link",t),onSuccess:(t,n)=>{let r=n.source_id,s=n.target_id;r&&e.invalidateQueries({queryKey:w.edges(r)}),s&&e.invalidateQueries({queryKey:w.edges(s)})}})}function ia(e,t){let n=U(),{optimistic:r,...s}=t??{};return ke({mutationFn:i=>R(e,i),onMutate:r?async i=>{await n.cancelQueries({queryKey:r.queryKey});let a=n.getQueryData(r.queryKey);return n.setQueryData(r.queryKey,c=>r.update(c,i)),{previous:a}}:void 0,onError:(i,a,c)=>{r&&c?.previous!==void 0&&n.setQueryData(r.queryKey,c.previous),s.onError?.(i)},onSuccess:s.onSuccess,onSettled:r?()=>{n.invalidateQueries({queryKey:r.queryKey})}:void 0})}function oa(e,t,n){let r,s,i,a=!0;if(typeof e=="string")r=e,s=t,i=n;else{s=e;let l=t;r=l.eventType,i=l.filter,a=l.enabled??!0}let c=(0,y.useRef)(s),u=(0,y.useRef)(i);(0,y.useEffect)(()=>{c.current=s,u.current=i},[s,i]),(0,y.useEffect)(()=>a?J(r,d=>c.current(d),u.current?d=>u.current(d):void 0):void 0,[r,a])}function aa(e){let{queryKey:t,queryFn:n,eventType:r,filter:s,enabled:i=!0,debounceMs:a=500}=e,c=U(),u=(0,y.useRef)(null),l=k({queryKey:t,queryFn:n,enabled:i});return(0,y.useEffect)(()=>{if(!i)return;let d=J(r,()=>{u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{c.invalidateQueries({queryKey:t})},a)},s);return()=>{d(),u.current&&clearTimeout(u.current)}},[r,i,a,c,JSON.stringify(t)]),l}function ca(e){K();let t=(0,y.useMemo)(()=>e?typeof e=="string"?{path:e}:e:null,[typeof e=="string"?e:JSON.stringify(e)]),n=!!t&&!!(t.key||t.path||t.item_id),r=t?.key??t?.path??t?.item_id??"",s=k({queryKey:["vfs",le()??"__unscoped__","arrangement",r],queryFn:async()=>{if(!t)return null;let d=await R("resolve-arrangement",t);return d?.success===!1?(console.warn("[useArrangement] resolve-arrangement failed:",d?.error),null):d??null},enabled:n}),i=s.data??null,a=(0,y.useMemo)(()=>i?.resolved_children??[],[i]),c=i?.resolution_level??null,u=(0,y.useMemo)(()=>{let p=(i?.type_data??null)?.order;return Array.isArray(p)?p:null},[i]),l=(0,y.useCallback)(d=>{if(!u||!d?.length)return d??[];let p=m=>m.id??m.name??"",f=new Map(u.map((m,g)=>[m,g])),h=[],v=[];for(let m of d)(f.has(p(m))?h:v).push(m);return h.sort((m,g)=>f.get(p(m))-f.get(p(g))),[...h,...v]},[u]);return{...s,arrangement:i,resolvedChildren:a,resolutionLevel:c,order:u,sourceScopeId:i?.scope_item_id??null,applyTo:l}}function hc(e){return e.split("_").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function mc(e,t){return t&&t.length>0?"select":e==="boolean"?"toggle":e==="integer"||e==="number"?"range":e==="string"?"text":"none"}function gc(e,t){return!(e==="object"||e==="array")}function yc(e){return["string","number","integer","boolean"].includes(e)}function _c(e){return e!=="object"&&e!=="array"}function ua(e,t,n,r){let s=e?.properties;if(!s||typeof s!="object")return[];let i=[];for(let[a,c]of Object.entries(s)){let u=c.type||"string",l=c.enum,d=gc(u,l),p=yc(u),f=mc(u,l);i.push({key:a,label:c.title||hc(a),type:u,description:c.description,enum_values:l,default_value:n[a]??r[a]??c.default,editable:t,filterable:d,sortable:p,filter_widget:f})}return i}function ys(e){let t=e.default_data||{},n=e.field_defaults||{},r=ua(e.input_schema,!0,t,n),s=ua(e.system_schema,!1,t,n),i=[...r,...s],a=i.filter(l=>_c(l.type)),c=i.filter(l=>l.filterable),u=i.filter(l=>l.sortable);return{fields:i,columns:a,filterable:c,sortable:u,form_fields:r,system_fields:s}}function la(e){return{field:"updated_at",direction:"desc"}}function da(e){let t=ys(e),n=new Set(e.input_schema?.required||[]);return t.form_fields.filter(r=>n.has(r.key)||r.default_value===void 0)}var ne=j(ie(),1);var vc=0;function bc(){return`upload_${Date.now()}_${++vc}`}async function fa(e,t,n,r){let s=t.name||(e instanceof File?e.name:`file-${Date.now()}`),i=e.type||"application/octet-stream",a=t.itemType||"file",c={parent_path:t.parentPath,item_type:a,name:s,type_data:{...t.typeData||{},file_source:{type:"upload",content_type:i}}};t.cardParentPath&&(c.card_parent_path=t.cardParentPath);let l=await R("create",c);if(!l.id)throw new Error(l.error||l.message||"Failed to create file item");let d=l.id,p=l.path;if(l.storage_completed&&l.file_ref)return{itemId:d,itemPath:p,fileRef:l.file_ref};let f=l.storage_key,h=l.upload_token,v=l.storage_worker_url||"https://fsaos-storage.radns.workers.dev";if(!f)throw new Error("Gateway returned no storage_key \u2014 file_source may not be supported for this item type");await wc(v,f,h,e,i,n,r);let m=await pa(d,f,i);return{itemId:d,itemPath:p,fileRef:m}}function wc(e,t,n,r,s,i,a){return new Promise((c,u)=>{let l=new XMLHttpRequest;if(l.open("PUT",`${e}/upload`),l.setRequestHeader("X-Storage-Key",t),l.setRequestHeader("Content-Type",s),n&&l.setRequestHeader("X-Upload-Token",n),l.upload.onprogress=d=>{d.lengthComputable&&i&&i(Math.round(d.loaded/d.total*100))},l.onload=()=>{l.status>=200&&l.status<300?c():u(new Error(`Storage upload failed: HTTP ${l.status} \u2014 ${l.responseText?.slice(0,300)}`))},l.onerror=()=>u(new Error("Storage upload network error")),l.ontimeout=()=>u(new Error("Storage upload timed out")),a){if(a.aborted){u(new Error("Upload cancelled"));return}a.addEventListener("abort",()=>{l.abort(),u(new Error("Upload cancelled"))})}l.send(r)})}async function pa(e,t,n){let r=await Pe(),s=await fetch(`${De}/storage/upload-complete`,{method:"POST",headers:{"Content-Type":"application/json",...r?{Authorization:`Bearer ${r}`}:{}},body:JSON.stringify({item_id:e,storage_key:t,content_type:n})});if(!s.ok){let a=await s.text().catch(()=>"");throw new Error(`Upload confirmation failed: HTTP ${s.status} \u2014 ${a.slice(0,300)}`)}let i=await s.json();if(!i.success)throw new Error(i.error||i.message||"Upload confirmation rejected");return i.file_ref}function ha(){let[e,t]=(0,ne.useState)([]),n=U(),r=(0,ne.useRef)(e);r.current=e;let s=(0,ne.useCallback)((m,g)=>{t(S=>S.map(C=>C.id===m?{...C,...g}:C))},[]),i=(0,ne.useCallback)(m=>{t(g=>[...g,m])},[]),a=(0,ne.useCallback)(async(m,g,S,C,E)=>{let Q=S.name||g.name,L=g.type||"application/octet-stream",B=S.itemType||"file",dt=E?.itemId||null,re=E?.itemPath||null,N=E?.storageKey||null,Y=E?.uploadToken||null,me=E?.storageWorkerUrl||null;try{if(!C||C==="create"){s(m,{status:"creating",error:null,_failedAt:null});let A=await R("create",{parent_path:S.parentPath,item_type:B,name:Q,type_data:{...S.typeData||{},file_source:{type:"upload",content_type:L}}});if(!A.id)throw Object.assign(new Error(A.error||A.message||"Failed to create file item"),{_step:"create"});if(dt=A.id,re=A.path,s(m,{itemId:dt,itemPath:re}),A.storage_completed&&A.file_ref){s(m,{status:"complete",progress:100,fileRef:A.file_ref}),n.invalidateQueries({queryKey:w.children(S.parentPath)});return}if(N=A.storage_key,Y=A.upload_token||"",me=A.storage_worker_url||"https://fsaos-storage.radns.workers.dev",s(m,{_storageKey:N,_uploadToken:Y,_storageWorkerUrl:me}),!N)throw Object.assign(new Error("Gateway returned no storage_key"),{_step:"create"})}(!C||C==="create"||C==="upload")&&(s(m,{status:"uploading",progress:0,error:null,_failedAt:null}),await new Promise((A,Ye)=>{let $=new XMLHttpRequest;s(m,{_xhr:$}),$.open("PUT",`${me}/upload`),$.setRequestHeader("X-Storage-Key",N),$.setRequestHeader("Content-Type",L),Y&&$.setRequestHeader("X-Upload-Token",Y),$.upload.onprogress=Ht=>{Ht.lengthComputable&&s(m,{progress:Math.round(Ht.loaded/Ht.total*100)})},$.onload=()=>{$.status>=200&&$.status<300?A():Ye(Object.assign(new Error(`Storage upload failed: HTTP ${$.status}`),{_step:"upload"}))},$.onerror=()=>Ye(Object.assign(new Error("Storage upload network error"),{_step:"upload"})),$.ontimeout=()=>Ye(Object.assign(new Error("Storage upload timed out"),{_step:"upload"})),$.send(g)}),s(m,{progress:100,_xhr:null})),s(m,{status:"confirming",error:null,_failedAt:null});let ge=await pa(dt,N,L);s(m,{status:"complete",fileRef:ge}),n.invalidateQueries({queryKey:w.children(S.parentPath)})}catch(ge){let ye=ge?.message||String(ge),A=ge?._step||"create";s(m,{status:"error",error:ye,_failedAt:A,_xhr:null})}},[s,n]),c=(0,ne.useCallback)((m,g)=>{let S=bc();i({id:S,file:m,status:"creating",progress:0,error:null,itemId:null,itemPath:null,fileRef:null,options:g,_storageKey:null,_uploadToken:null,_storageWorkerUrl:null,_xhr:null,_failedAt:null}),a(S,m,g)},[i,a]),u=(0,ne.useCallback)((m,g)=>{for(let S of m)c(S,g)},[c]),l=(0,ne.useCallback)(m=>{let g=r.current.find(E=>E.id===m);if(!g||g.status!=="error")return;let S=g._failedAt||"create",C=g._storageKey&&g.itemId?{storageKey:g._storageKey,uploadToken:g._uploadToken||"",storageWorkerUrl:g._storageWorkerUrl||"https://fsaos-storage.radns.workers.dev",itemId:g.itemId,itemPath:g.itemPath||""}:void 0;a(m,g.file,g.options,S,C)},[a]),d=(0,ne.useCallback)(m=>{let g=r.current.find(S=>S.id===m);g&&(g._xhr&&g._xhr.abort(),s(m,{status:"error",error:"Cancelled",_xhr:null,_failedAt:null}))},[s]),p=(0,ne.useCallback)(m=>{t(g=>g.filter(S=>S.id!==m))},[]),f=(0,ne.useCallback)(()=>{t(m=>m.filter(g=>g.status!=="complete"))},[]),h=e.some(m=>m.status==="creating"||m.status==="uploading"||m.status==="confirming"),v=e.map(({_storageKey:m,_uploadToken:g,_storageWorkerUrl:S,_xhr:C,_failedAt:E,...Q})=>Q);return{upload:c,uploadMultiple:u,uploads:v,retryUpload:l,cancelUpload:d,removeUpload:p,clearCompleted:f,isUploading:h}}var ma=j(ie(),1);async function _s(e,t){return await R("resolve-items",{context_id:e,item_type:t})}function ga(e,t){return(0,ma.useSyncExternalStore)(Ze,_e,_e),k({queryKey:["vfs",le()??"__unscoped__","resolved-items",e??"",t],queryFn:()=>_s(e,t),enabled:!!(e&&t)})}var he=j(ie(),1);function br(e,t){let n={artifacts:new Map,timeline:[]},r=new Map;function s(a){if(!a.action?.startsWith("artifact_"))return;let u,l=a.name;if(typeof l=="string"&&l.startsWith("{"))try{u=JSON.parse(l)}catch{return}else if(a.artifact_id)u=a;else return;switch(u.type){case"artifact_opened":{let d=Date.now();if(n.artifacts.set(u.artifact_id,{artifact_id:u.artifact_id,surface_type:u.surface_type,tool_id:u.tool_id,tool_name:u.tool_name,target_uri:u.target_uri,status:"streaming",content:"",total_chars:0,delta_count:0,artifact_item_uri:null,evidence_uri:null,meta:u.meta,started_at:d,completed_at:null}),r.has(u.tool_id)){let p=r.get(u.tool_id);n.timeline[p].artifact_ids.push(u.artifact_id)}else{let p=n.timeline.length;n.timeline.push({tool_id:u.tool_id,tool_name:u.tool_name,status:"started",target_uri:u.target_uri,started_at:d,completed_at:null,artifact_ids:[u.artifact_id]}),r.set(u.tool_id,p)}break}case"artifact_delta":{let d=n.artifacts.get(u.artifact_id);d&&(d.content+=u.content_delta,d.total_chars+=u.content_delta.length,d.delta_count+=1,u.target_uri&&!d.target_uri&&(d.target_uri=u.target_uri));break}case"artifact_done":{let d=n.artifacts.get(u.artifact_id);d&&(d.status=u.status,d.total_chars=u.total_chars,d.artifact_item_uri=u.artifact_item_uri,d.evidence_uri=u.evidence_uri,u.target_uri&&(d.target_uri=u.target_uri),(u.status==="completed"||u.status==="failed")&&(d.completed_at=Date.now()));let p=r.get(u.tool_id);if(p!==void 0){let f=n.timeline[p];u.status==="executing"?f.status="executing":u.status==="completed"?(f.status="completed",f.completed_at=Date.now()):u.status==="failed"&&(f.status="failed",f.completed_at=Date.now()),u.target_uri&&!f.target_uri&&(f.target_uri=u.target_uri)}break}}t(n)}return fr(e,s)}function ya(e,t=!0){let[n,r]=(0,he.useState)(new Map),[s,i]=(0,he.useState)([]),a=(0,he.useRef)({artifacts:new Map,timeline:[]});(0,he.useEffect)(()=>!e||!t?void 0:br(e,p=>{a.current=p,r(new Map(p.artifacts)),i([...p.timeline])}),[e,t]);let c=(0,he.useCallback)(()=>{r(new Map),i([]),a.current={artifacts:new Map,timeline:[]}},[]),u=Array.from(n.values()).find(d=>d.surface_type==="file_editor"&&d.status==="streaming")??null,l=Array.from(n.values()).filter(d=>d.surface_type==="activity"&&(d.status==="streaming"||d.status==="executing"));return{artifacts:n,timeline:s,activeEditor:u,activeActivities:l,reset:c}}function _a(e,t=!0){let[n,r]=(0,he.useState)([]);(0,he.useEffect)(()=>!e||!t?void 0:br(e,a=>{r([...a.timeline])}),[e,t]);let s=n.length>0?n[n.length-1]:null;return{timeline:n,latestActivity:s}}var wr=j(ie(),1);function Sc(e,t,n,r){return["vfs","timeline-history",e,t??"__all__",n??500,r??0]}async function vs(e,t){let n=`${e}/datasets/agent-events`,r=t?.limit??500,s=t?.offset??0,i={limit:r,offset:s,sort:[{key:"seq",direction:"asc"}]};t?.turnId&&(i.filters=[{key:"turn_id",operator:"eq",value:t.turnId}]);try{let c=(await R("open",{path:n,mode:"extract",strategy:"rows",arguments:i}))?.content;return c?(c.rows??c.items??c.data??[]).map(Rc).sort((l,d)=>l.seq-d.seq):[]}catch(a){if(a?.status===404||a?.message?.includes("not found"))return[];throw a}}function va(e,t){let{turnId:n,limit:r=500,offset:s=0,enabled:i=!0,debounceMs:a=300}=t??{},c=e?`${e}/datasets/agent-events`:null,u=U(),l=(0,wr.useRef)(null),d=c?Sc(c,n,r,s):["vfs","timeline-history","__disabled__"],p=k({queryKey:d,queryFn:()=>vs(e,{turnId:n,limit:r,offset:s}),enabled:!!e&&i});return(0,wr.useEffect)(()=>{if(!c||!i)return;let f=J("vfs_change",()=>{l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{u.invalidateQueries({queryKey:d})},a)},h=>{let v=h?.path;return v?v===c||v.startsWith(c+"/"):!1});return()=>{f(),l.current&&clearTimeout(l.current)}},[c,i,a,u,JSON.stringify(d)]),{events:p.data??[],isLoading:p.isLoading,error:p.error,isFetching:p.isFetching,refetch:()=>{p.refetch()}}}function Rc(e){return{turn_id:String(e.turn_id??""),seq:Number(e.seq??0),kind:String(e.kind??""),status:String(e.status??""),title:String(e.title??""),tool_name:e.tool_name!=null?String(e.tool_name):void 0,tool_id:e.tool_id!=null?String(e.tool_id):void 0,evidence_uri:e.evidence_uri!=null?String(e.evidence_uri):void 0,artifact_item_uri:e.artifact_item_uri!=null?String(e.artifact_item_uri):void 0,preview:e.preview!=null?String(e.preview):void 0,duration_ms:e.duration_ms!=null?Number(e.duration_ms):void 0,started_at:String(e.started_at??""),completed_at:e.completed_at!=null?String(e.completed_at):void 0,error_type:e.error_type!=null?String(e.error_type):void 0,meta:e.meta!=null?e.meta:void 0}}Uo(bs);return Ta(bs);})();
4
4
 
5
5
  /* ── Auto-setup: require shim + mount + backward compat globals ── */
6
6
  (function() {