@ai4b-team/fsaos-gateway-sdk 5.5.0 → 5.5.1

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,5 +1,5 @@
1
- /* @fsaos/gateway v2.0.0 — Unified FSAOS Edge Runtime — 2026-11-15T02:30:26.016Z */
2
- "use strict";var __FSAOS_GATEWAY__=(()=>{var ql=Object.create;var Bn=Object.defineProperty;var Nl=Object.getOwnPropertyDescriptor;var Ql=Object.getOwnPropertyNames;var Dl=Object.getPrototypeOf,Ul=Object.prototype.hasOwnProperty;var ao=e=>{throw TypeError(e)};var Kl=(e,t,n)=>t in e?Bn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var $n=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),co=(e,t)=>{for(var n in t)Bn(e,n,{get:t[n],enumerable:!0})},uo=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Ql(t))!Ul.call(e,s)&&s!==n&&Bn(e,s,{get:()=>t[s],enumerable:!(r=Nl(t,s))||r.enumerable});return e};var Y=(e,t,n)=>(n=e!=null?ql(Dl(e)):{},uo(t||!e||!e.__esModule?Bn(n,"default",{value:e,enumerable:!0}):n,e)),Ll=e=>uo(Bn({},"__esModule",{value:!0}),e);var z=(e,t,n)=>Kl(e,typeof t!="symbol"?t+"":t,n),Ds=(e,t,n)=>t.has(e)||ao("Cannot "+n);var d=(e,t,n)=>(Ds(e,t,"read from private field"),n?n.call(e):t.get(e)),I=(e,t,n)=>t.has(e)?ao("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),S=(e,t,n,r)=>(Ds(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n),F=(e,t,n)=>(Ds(e,t,"access private method"),n);var Vn=(e,t,n,r)=>({set _(s){S(e,t,s,n)},get _(){return d(e,t,r)}});var ue=$n((Qf,lo)=>{lo.exports=React});var Hr=$n((Fm,$o)=>{$o.exports={jsx:React.createElement,jsxs:React.createElement,Fragment:React.Fragment}});var sa=$n((dg,ra)=>{ra.exports={createClient:window.supabase.createClient}});var Fa=$n((Tg,Oa)=>{Oa.exports=ReactDOM});var Ju=$n((Iy,zu)=>{zu.exports=ReactDOM});var io={};co(io,{CHANNEL_AI_MODES:()=>_u,ComponentRenderer:()=>mu,EnforcementDeniedError:()=>Fe,FormSubmissionError:()=>jn,GatewayRequestError:()=>ge,HostSessionUnavailableError:()=>Ht,InteractionTrackingError:()=>Ln,KernelProvider:()=>gu,QueryClientProvider:()=>sr,acceptInvitation:()=>wf,acceptInvite:()=>Ji,answerInput:()=>Xi,assignPersonalSection:()=>El,auth:()=>ol,awaitAnchorReady:()=>ur,awaitScopeReady:()=>ha,callTool:()=>rl,cancelInvitation:()=>xf,cancelQueuedTurn:()=>Wu,cancelTurn:()=>$u,clearCachedToken:()=>fi,clearSession:()=>bi,configureGatewayReads:()=>Ia,connectHostSession:()=>_a,createAgent:()=>Zi,createInvitation:()=>vf,createItem:()=>el,disconnectSSE:()=>Mi,disposeVfsRealtimeWs:()=>Fi,electHomeAnchor:()=>Kt,emitEvent:()=>tc,fetchChannelMessages:()=>dc,fetchChannelMessagesPage:()=>wr,fetchChannelMessagesWithCards:()=>vs,fetchEdgesForItem:()=>ms,fetchItemHistory:()=>ys,fetchItemVersions:()=>vr,fetchItems:()=>Vt,fetchMemberFocus:()=>_s,fetchOpenEnvelope:()=>br,fetchRecentActivity:()=>hs,fetchResolvedItems:()=>to,fetchTimelineHistory:()=>no,fetchTurnQueueEntries:()=>cc,fetchTypeDefinitions:()=>ps,fetchVfsChildren:()=>_r,fetchVfsChildrenPage:()=>fs,fetchVfsItem:()=>yr,fetchVfsItemById:()=>hr,fetchVfsTree:()=>gs,gatewayCall:()=>x,getAccessToken:()=>tt,getAnchor:()=>_t,getAnchorRef:()=>de,getAnchorVersion:()=>gi,getAssetUrl:()=>il,getDefaultSort:()=>gl,getHomeAnchor:()=>me,getInvitation:()=>bf,getMountVersion:()=>lr,getMounts:()=>Ae,getPathSubscriptionState:()=>rc,getQueryClient:()=>N,getRequiredFormFields:()=>hl,getScope:()=>W,getScopeVersion:()=>ee,getServerClockOffsetMs:()=>xa,getServerClockSyncedAt:()=>Ra,getSessionEntry:()=>vt,hasServerClock:()=>Sa,initSession:()=>nt,initVfsRealtimeWs:()=>Wt,initializeFsaos:()=>ju,initializeWorkspace:()=>Ms,interpretSchema:()=>eo,invalidateAllVfs:()=>mc,invalidateChannelMessages:()=>hc,invalidateChildren:()=>ds,invalidateItem:()=>Oi,invalidateOpenEnvelope:()=>yc,invalidatePathAndParent:()=>fc,invalidateSubtree:()=>pc,invalidateTypes:()=>gc,inviteMember:()=>zi,isAnchorReady:()=>yi,isChannelPath:()=>he,isListableItemsFilter:()=>qn,isScopeReady:()=>zr,itemsFilterFromQueryFilter:()=>uc,listChildren:()=>Xu,listInvitations:()=>Pf,loadMounts:()=>Gt,loadPublishedBundle:()=>ou,mount:()=>al,mountRealtimeScope:()=>Qn,normalizeItem:()=>Oe,onConnectionStateChange:()=>ls,pathSubscriptionMatches:()=>Ti,personalSectionsKey:()=>Mr,ping:()=>nc,pushChanges:()=>nl,queryClient:()=>La,readItem:()=>Zu,refreshQuery:()=>be,registerCleanup:()=>se,rejectInvitation:()=>Sf,replaceMounts:()=>Rs,resendInvitation:()=>Rf,resetAllSdkState:()=>Cn,resolvePrincipalId:()=>fu,resubscribePath:()=>ic,seatMember:()=>Yi,selectMount:()=>Cr,serveHostSession:()=>Bu,serverDeadlinePassed:()=>Pa,serverMsUntil:()=>Ca,serverNow:()=>Zr,setAnchor:()=>Pn,setCachedToken:()=>aa,setQueryClient:()=>Ka,setScope:()=>ga,setupRequireShim:()=>cl,signal:()=>sl,startTracking:()=>ks,steerTurn:()=>Vu,submitForm:()=>Gu,subscribeAnchor:()=>hi,subscribeArtifactStream:()=>Os,subscribeMounts:()=>Gr,subscribeScope:()=>xe,subscribeToEvents:()=>ie,subscribeToPath:()=>us,subscribeToScope:()=>Fn,trackAction:()=>Ku,trackEvent:()=>Jt,trackPageView:()=>Uu,unmountRealtimeScope:()=>Ss,updateItem:()=>tl,uploadFile:()=>_l,useAcceptInvite:()=>ll,useAccounts:()=>Yc,useAgentTimeline:()=>Rl,useAllChannels:()=>Ts,useAnswerInput:()=>pl,useArrangement:()=>Kn,useArtifactStream:()=>xl,useAsset:()=>Xc,useAuth:()=>Is,useChannelMessages:()=>hu,useChannels:()=>vu,useChildren:()=>qc,useComponent:()=>Hi,useCreate:()=>Su,useCreateAgent:()=>fl,useDelete:()=>Pu,useDmChannels:()=>bu,useEdges:()=>Hc,useEventStream:()=>Tu,useFileUpload:()=>bl,useIncrementalItems:()=>Kc,useInfiniteChannelMessages:()=>yu,useInfiniteChildren:()=>Lc,useInfiniteItems:()=>Li,useInviteMember:()=>ul,useItem:()=>Oc,useItemById:()=>Fc,useItemHistory:()=>Gc,useItemVersions:()=>Wc,useItems:()=>Uc,useLink:()=>Eu,useList:()=>Ki,useMemberFocus:()=>Vc,useMintedAsset:()=>ku,useMounts:()=>Zc,useMove:()=>Cu,useMutation:()=>Iu,useNotifications:()=>ji,useOpen:()=>Bc,usePermission:()=>uu,usePermissions:()=>lu,usePersonalItemOrder:()=>Ou,usePersonalSections:()=>Tl,usePinnedItems:()=>Cl,usePrincipal:()=>pu,usePublishedComponent:()=>au,useRealtimeQuery:()=>Au,useRecentActivity:()=>zc,useResolve:()=>Dc,useResolvedItems:()=>Sl,useScope:()=>Jc,useScopeReady:()=>Mc,useSearch:()=>Qc,useSeatMember:()=>dl,useTheme:()=>cu,useTimelineHistory:()=>Pl,useTree:()=>Nc,useType:()=>jc,useTypeHelpers:()=>$c,useTypes:()=>Es,useUnreadCounts:()=>wu,useUpdate:()=>xu,useUpdatePrincipal:()=>Ru,vfsKeys:()=>E,waitForPathReady:()=>sc});var Fe=class e extends Error{constructor(n){let r=n.message||e.fallbackMessage(n);super(r);z(this,"name","EnforcementDeniedError");z(this,"deniedBy");z(this,"ruleKey");z(this,"displayName");z(this,"payload");this.payload=n,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 Pt=Y(ue(),1);var Ee=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 It,at,Zt,fo,Hl=(fo=class extends Ee{constructor(){super();I(this,It);I(this,at);I(this,Zt);S(this,Zt,t=>{if(typeof window<"u"&&window.addEventListener){let n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){d(this,at)||this.setEventListener(d(this,Zt))}onUnsubscribe(){var t;this.hasListeners()||((t=d(this,at))==null||t.call(this),S(this,at,void 0))}setEventListener(t){var n;S(this,Zt,t),(n=d(this,at))==null||n.call(this),S(this,at,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){d(this,It)!==t&&(S(this,It,t),this.onFocus())}onFocus(){let t=this.isFocused();this.listeners.forEach(n=>{n(t)})}isFocused(){return typeof d(this,It)=="boolean"?d(this,It):globalThis.document?.visibilityState!=="hidden"}},It=new WeakMap,at=new WeakMap,Zt=new WeakMap,fo),Xt=new Hl;var jl={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},ct,Us,po,Bl=(po=class{constructor(){I(this,ct,jl);I(this,Us,!1)}setTimeoutProvider(e){S(this,ct,e)}setTimeout(e,t){return d(this,ct).setTimeout(e,t)}clearTimeout(e){d(this,ct).clearTimeout(e)}setInterval(e,t){return d(this,ct).setInterval(e,t)}clearInterval(e){d(this,ct).clearInterval(e)}},ct=new WeakMap,Us=new WeakMap,po),De=new Bl;function mo(e){setTimeout(e,0)}var Ls=typeof window>"u"||"Deno"in globalThis;function Z(){}function yo(e,t){return typeof e=="function"?e(t):e}function Wn(e){return typeof e=="number"&&e>=0&&e!==1/0}function Or(e,t){return Math.max(e+(t||0)-Date.now(),0)}function qe(e,t){return typeof e=="function"?e(t):e}function ye(e,t){return typeof e=="function"?e(t):e}function Fr(e,t){let{type:n="all",exact:r,fetchStatus:s,predicate:i,queryKey:o,stale:a}=e;if(o){if(r){if(t.queryHash!==Gn(o,t.options))return!1}else if(!Tt(t.queryKey,o))return!1}if(n!=="all"){let c=t.isActive();if(n==="active"&&!c||n==="inactive"&&c)return!1}return!(typeof a=="boolean"&&t.isStale()!==a||s&&s!==t.state.fetchStatus||i&&!i(t))}function qr(e,t){let{exact:n,status:r,predicate:s,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(Ue(t.options.mutationKey)!==Ue(i))return!1}else if(!Tt(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||s&&!s(t))}function Gn(e,t){return(t?.queryKeyHashFn||Ue)(e)}function Ue(e){return JSON.stringify(e,(t,n)=>Ks(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 $l=Object.prototype.hasOwnProperty;function Hs(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=go(e)&&go(t);if(!r&&!(Ks(e)&&Ks(t)))return t;let i=(r?e:Object.keys(e)).length,o=r?t:Object.keys(t),a=o.length,c=r?new Array(a):{},u=0;for(let l=0;l<a;l++){let f=r?l:o[l],h=e[f],p=t[f];if(h===p){c[f]=h,(r?l<i:$l.call(e,f))&&u++;continue}if(h===null||p===null||typeof h!="object"||typeof p!="object"){c[f]=p;continue}let m=Hs(h,p,n+1);c[f]=m,m===h&&u++}return i===a&&u===i?e:c}function en(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 go(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Ks(e){if(!ho(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!ho(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function ho(e){return Object.prototype.toString.call(e)==="[object Object]"}function _o(e){return new Promise(t=>{De.setTimeout(t,e)})}function zn(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?Hs(e,t):t}function vo(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function bo(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var tn=Symbol();function Nr(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===tn?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function nn(e,t){return typeof e=="function"?e(...t):!!e}function wo(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 Ke=(()=>{let e=()=>Ls;return{isServer(){return e()},setIsServer(t){e=t}}})();function Jn(){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 So=mo;function Vl(){let e=[],t=0,n=a=>{a()},r=a=>{a()},s=So,i=a=>{t?e.push(a):s(()=>{n(a)})},o=()=>{let a=e;e=[],a.length&&s(()=>{r(()=>{a.forEach(c=>{n(c)})})})};return{batch:a=>{let c;t++;try{c=a()}finally{t--,t||o()}return c},batchCalls:a=>(...c)=>{i(()=>{a(...c)})},schedule:i,setNotifyFunction:a=>{n=a},setBatchNotifyFunction:a=>{r=a},setScheduler:a=>{s=a}}}var j=Vl();var rn,ut,sn,xo,Wl=(xo=class extends Ee{constructor(){super();I(this,rn,!0);I(this,ut);I(this,sn);S(this,sn,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(){d(this,ut)||this.setEventListener(d(this,sn))}onUnsubscribe(){var t;this.hasListeners()||((t=d(this,ut))==null||t.call(this),S(this,ut,void 0))}setEventListener(t){var n;S(this,sn,t),(n=d(this,ut))==null||n.call(this),S(this,ut,t(this.setOnline.bind(this)))}setOnline(t){d(this,rn)!==t&&(S(this,rn,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return d(this,rn)}},rn=new WeakMap,ut=new WeakMap,sn=new WeakMap,xo),on=new Wl;function Gl(e){return Math.min(1e3*2**e,3e4)}function js(e){return(e??"online")==="online"?on.isOnline():!0}var Qr=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function Dr(e){let t=!1,n=0,r,s=Jn(),i=()=>s.status!=="pending",o=y=>{if(!i()){let g=new Qr(y);h(g),e.onCancel?.(g)}},a=()=>{t=!0},c=()=>{t=!1},u=()=>Xt.isFocused()&&(e.networkMode==="always"||on.isOnline())&&e.canRun(),l=()=>js(e.networkMode)&&e.canRun(),f=y=>{i()||(r?.(),s.resolve(y))},h=y=>{i()||(r?.(),s.reject(y))},p=()=>new Promise(y=>{r=g=>{(i()||u())&&y(g)},e.onPause?.()}).then(()=>{r=void 0,i()||e.onContinue?.()}),m=()=>{if(i())return;let y,g=n===0?e.initialPromise:void 0;try{y=g??e.fn()}catch(v){y=Promise.reject(v)}Promise.resolve(y).then(f).catch(v=>{if(i())return;let _=e.retry??(Ke.isServer()?0:3),w=e.retryDelay??Gl,C=typeof w=="function"?w(n,v):w,R=_===!0||typeof _=="number"&&n<_||typeof _=="function"&&_(n,v);if(t||!R){h(v);return}n++,e.onFail?.(n,v),_o(C).then(()=>u()?void 0:p()).then(()=>{t?h(v):m()})})};return{promise:s,status:()=>s.status,cancel:o,continue:()=>(r?.(),s),cancelRetry:a,continueRetry:c,canStart:l,start:()=>(l()?m():p().then(m),s)}}var At,Ro,Ur=(Ro=class{constructor(){I(this,At)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Wn(this.gcTime)&&S(this,At,De.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Ke.isServer()?1/0:5*60*1e3))}clearGcTimeout(){d(this,At)!==void 0&&(De.clearTimeout(d(this,At)),S(this,At,void 0))}},At=new WeakMap,Ro);var kt,an,Ie,Mt,oe,Yn,Ot,Se,To,We,Eo,Io=(Eo=class extends Ur{constructor(t){super();I(this,Se);I(this,kt);I(this,an);I(this,Ie);I(this,Mt);I(this,oe);I(this,Yn);I(this,Ot);S(this,Ot,!1),S(this,Yn,t.defaultOptions),this.setOptions(t.options),this.observers=[],S(this,Mt,t.client),S(this,Ie,d(this,Mt).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,S(this,kt,Co(this.options)),this.state=t.state??d(this,kt),this.scheduleGc()}get meta(){return this.options.meta}get promise(){return d(this,oe)?.promise}setOptions(t){if(this.options={...d(this,Yn),...t},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let n=Co(this.options);n.data!==void 0&&(this.setState(Po(n.data,n.dataUpdatedAt)),S(this,kt,n))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&d(this,Ie).remove(this)}setData(t,n){let r=zn(this.state.data,t,this.options);return F(this,Se,We).call(this,{data:r,type:"success",dataUpdatedAt:n?.updatedAt,manual:n?.manual}),r}setState(t,n){F(this,Se,We).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){let n=d(this,oe)?.promise;return d(this,oe)?.cancel(t),n?n.then(Z).catch(Z):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return d(this,kt)}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(t=>ye(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===tn||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>qe(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:!Or(this.state.dataUpdatedAt,t)}onFocus(){this.observers.find(n=>n.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),d(this,oe)?.continue()}onOnline(){this.observers.find(n=>n.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),d(this,oe)?.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),d(this,Ie).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(n=>n!==t),this.observers.length||(d(this,oe)&&(d(this,Ot)||F(this,Se,To).call(this)?d(this,oe).cancel({revert:!0}):d(this,oe).cancelRetry()),this.scheduleGc()),d(this,Ie).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||F(this,Se,We).call(this,{type:"invalidate"})}async fetch(t,n){if(this.state.fetchStatus!=="idle"&&d(this,oe)?.status()!=="rejected"){if(this.state.data!==void 0&&n?.cancelRefetch)this.cancel({silent:!0});else if(d(this,oe))return d(this,oe).continueRetry(),d(this,oe).promise}if(t&&this.setOptions(t),!this.options.queryFn){let c=this.observers.find(u=>u.options.queryFn);c&&this.setOptions(c.options)}let r=new AbortController,s=c=>{Object.defineProperty(c,"signal",{enumerable:!0,get:()=>(S(this,Ot,!0),r.signal)})},i=()=>{let c=Nr(this.options,n),l=(()=>{let f={client:d(this,Mt),queryKey:this.queryKey,meta:this.meta};return s(f),f})();return S(this,Ot,!1),this.options.persister?this.options.persister(c,l,this):c(l)},a=(()=>{let c={fetchOptions:n,options:this.options,queryKey:this.queryKey,client:d(this,Mt),state:this.state,fetchFn:i};return s(c),c})();this.options.behavior?.onFetch(a,this),S(this,an,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==a.fetchOptions?.meta)&&F(this,Se,We).call(this,{type:"fetch",meta:a.fetchOptions?.meta}),S(this,oe,Dr({initialPromise:n?.initialPromise,fn:a.fetchFn,onCancel:c=>{c instanceof Qr&&c.revert&&this.setState({...d(this,an),fetchStatus:"idle"}),r.abort()},onFail:(c,u)=>{F(this,Se,We).call(this,{type:"failed",failureCount:c,error:u})},onPause:()=>{F(this,Se,We).call(this,{type:"pause"})},onContinue:()=>{F(this,Se,We).call(this,{type:"continue"})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0}));try{let c=await d(this,oe).start();if(c===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(c),d(this,Ie).config.onSuccess?.(c,this),d(this,Ie).config.onSettled?.(c,this.state.error,this),c}catch(c){if(c instanceof Qr){if(c.silent)return d(this,oe).promise;if(c.revert){if(this.state.data===void 0)throw c;return this.state.data}}throw F(this,Se,We).call(this,{type:"error",error:c}),d(this,Ie).config.onError?.(c,this),d(this,Ie).config.onSettled?.(this.state.data,c,this),c}finally{this.scheduleGc()}}},kt=new WeakMap,an=new WeakMap,Ie=new WeakMap,Mt=new WeakMap,oe=new WeakMap,Yn=new WeakMap,Ot=new WeakMap,Se=new WeakSet,To=function(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"},We=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,...Bs(r.data,this.options),fetchMeta:t.meta??null};case"success":let s={...r,...Po(t.data,t.dataUpdatedAt),dataUpdateCount:r.dataUpdateCount+1,...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return S(this,an,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),j.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),d(this,Ie).notify({query:this,type:"updated",action:t})})},Eo);function Bs(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:js(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function Po(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function Co(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 _e,U,Xn,pe,Ft,cn,Ge,lt,er,un,ln,qt,Nt,dt,dn,H,Zn,$s,Vs,Ws,Gs,zs,Js,Ys,Oo,Mo,tr=(Mo=class extends Ee{constructor(t,n){super();I(this,H);I(this,_e);I(this,U);I(this,Xn);I(this,pe);I(this,Ft);I(this,cn);I(this,Ge);I(this,lt);I(this,er);I(this,un);I(this,ln);I(this,qt);I(this,Nt);I(this,dt);I(this,dn,new Set);this.options=n,S(this,_e,t),S(this,lt,null),S(this,Ge,Jn()),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(d(this,U).addObserver(this),Ao(d(this,U),this.options)?F(this,H,Zn).call(this):this.updateResult(),F(this,H,Gs).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Zs(d(this,U),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Zs(d(this,U),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,F(this,H,zs).call(this),F(this,H,Js).call(this),d(this,U).removeObserver(this)}setOptions(t){let n=this.options,r=d(this,U);if(this.options=d(this,_e).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof ye(this.options.enabled,d(this,U))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");F(this,H,Ys).call(this),d(this,U).setOptions(this.options),n._defaulted&&!en(this.options,n)&&d(this,_e).getQueryCache().notify({type:"observerOptionsUpdated",query:d(this,U),observer:this});let s=this.hasListeners();s&&ko(d(this,U),r,this.options,n)&&F(this,H,Zn).call(this),this.updateResult(),s&&(d(this,U)!==r||ye(this.options.enabled,d(this,U))!==ye(n.enabled,d(this,U))||qe(this.options.staleTime,d(this,U))!==qe(n.staleTime,d(this,U)))&&F(this,H,$s).call(this);let i=F(this,H,Vs).call(this);s&&(d(this,U)!==r||ye(this.options.enabled,d(this,U))!==ye(n.enabled,d(this,U))||i!==d(this,dt))&&F(this,H,Ws).call(this,i)}getOptimisticResult(t){let n=d(this,_e).getQueryCache().build(d(this,_e),t),r=this.createResult(n,t);return Jl(this,r)&&(S(this,pe,r),S(this,cn,this.options),S(this,Ft,d(this,U).state)),r}getCurrentResult(){return d(this,pe)}trackResult(t,n){return new Proxy(t,{get:(r,s)=>(this.trackProp(s),n?.(s),s==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&d(this,Ge).status==="pending"&&d(this,Ge).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(r,s))})}trackProp(t){d(this,dn).add(t)}getCurrentQuery(){return d(this,U)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){let n=d(this,_e).defaultQueryOptions(t),r=d(this,_e).getQueryCache().build(d(this,_e),n);return r.fetch().then(()=>this.createResult(r,n))}fetch(t){return F(this,H,Zn).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),d(this,pe)))}createResult(t,n){let r=d(this,U),s=this.options,i=d(this,pe),o=d(this,Ft),a=d(this,cn),u=t!==r?t.state:d(this,Xn),{state:l}=t,f={...l},h=!1,p;if(n._optimisticResults){let k=this.hasListeners(),T=!k&&Ao(t,n),A=k&&ko(t,r,n,s);(T||A)&&(f={...f,...Bs(l.data,t.options)}),n._optimisticResults==="isRestoring"&&(f.fetchStatus="idle")}let{error:m,errorUpdatedAt:y,status:g}=f;p=f.data;let v=!1;if(n.placeholderData!==void 0&&p===void 0&&g==="pending"){let k;i?.isPlaceholderData&&n.placeholderData===a?.placeholderData?(k=i.data,v=!0):k=typeof n.placeholderData=="function"?n.placeholderData(d(this,ln)?.state.data,d(this,ln)):n.placeholderData,k!==void 0&&(g="success",p=zn(i?.data,k,n),h=!0)}if(n.select&&p!==void 0&&!v)if(i&&p===o?.data&&n.select===d(this,er))p=d(this,un);else try{S(this,er,n.select),p=n.select(p),p=zn(i?.data,p,n),S(this,un,p),S(this,lt,null)}catch(k){S(this,lt,k)}d(this,lt)&&(m=d(this,lt),p=d(this,un),y=Date.now(),g="error");let _=f.fetchStatus==="fetching",w=g==="pending",C=g==="error",R=w&&_,M=p!==void 0,P={status:g,fetchStatus:f.fetchStatus,isPending:w,isSuccess:g==="success",isError:C,isInitialLoading:R,isLoading:R,data:p,dataUpdatedAt:f.dataUpdatedAt,error:m,errorUpdatedAt:y,failureCount:f.fetchFailureCount,failureReason:f.fetchFailureReason,errorUpdateCount:f.errorUpdateCount,isFetched:t.isFetched(),isFetchedAfterMount:f.dataUpdateCount>u.dataUpdateCount||f.errorUpdateCount>u.errorUpdateCount,isFetching:_,isRefetching:_&&!w,isLoadingError:C&&!M,isPaused:f.fetchStatus==="paused",isPlaceholderData:h,isRefetchError:C&&M,isStale:Xs(t,n),refetch:this.refetch,promise:d(this,Ge),isEnabled:ye(n.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){let k=P.data!==void 0,T=P.status==="error"&&!k,A=K=>{T?K.reject(P.error):k&&K.resolve(P.data)},O=()=>{let K=S(this,Ge,P.promise=Jn());A(K)},q=d(this,Ge);switch(q.status){case"pending":t.queryHash===r.queryHash&&A(q);break;case"fulfilled":(T||P.data!==q.value)&&O();break;case"rejected":(!T||P.error!==q.reason)&&O();break}}return P}updateResult(){let t=d(this,pe),n=this.createResult(d(this,U),this.options);if(S(this,Ft,d(this,U).state),S(this,cn,this.options),d(this,Ft).data!==void 0&&S(this,ln,d(this,U)),en(n,t))return;S(this,pe,n);let r=()=>{if(!t)return!0;let{notifyOnChangeProps:s}=this.options,i=typeof s=="function"?s():s;if(i==="all"||!i&&!d(this,dn).size)return!0;let o=new Set(i??d(this,dn));return this.options.throwOnError&&o.add("error"),Object.keys(d(this,pe)).some(a=>{let c=a;return d(this,pe)[c]!==t[c]&&o.has(c)})};F(this,H,Oo).call(this,{listeners:r()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&F(this,H,Gs).call(this)}},_e=new WeakMap,U=new WeakMap,Xn=new WeakMap,pe=new WeakMap,Ft=new WeakMap,cn=new WeakMap,Ge=new WeakMap,lt=new WeakMap,er=new WeakMap,un=new WeakMap,ln=new WeakMap,qt=new WeakMap,Nt=new WeakMap,dt=new WeakMap,dn=new WeakMap,H=new WeakSet,Zn=function(t){F(this,H,Ys).call(this);let n=d(this,U).fetch(this.options,t);return t?.throwOnError||(n=n.catch(Z)),n},$s=function(){F(this,H,zs).call(this);let t=qe(this.options.staleTime,d(this,U));if(Ke.isServer()||d(this,pe).isStale||!Wn(t))return;let r=Or(d(this,pe).dataUpdatedAt,t)+1;S(this,qt,De.setTimeout(()=>{d(this,pe).isStale||this.updateResult()},r))},Vs=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(d(this,U)):this.options.refetchInterval)??!1},Ws=function(t){F(this,H,Js).call(this),S(this,dt,t),!(Ke.isServer()||ye(this.options.enabled,d(this,U))===!1||!Wn(d(this,dt))||d(this,dt)===0)&&S(this,Nt,De.setInterval(()=>{(this.options.refetchIntervalInBackground||Xt.isFocused())&&F(this,H,Zn).call(this)},d(this,dt)))},Gs=function(){F(this,H,$s).call(this),F(this,H,Ws).call(this,F(this,H,Vs).call(this))},zs=function(){d(this,qt)!==void 0&&(De.clearTimeout(d(this,qt)),S(this,qt,void 0))},Js=function(){d(this,Nt)!==void 0&&(De.clearInterval(d(this,Nt)),S(this,Nt,void 0))},Ys=function(){let t=d(this,_e).getQueryCache().build(d(this,_e),this.options);if(t===d(this,U))return;let n=d(this,U);S(this,U,t),S(this,Xn,t.state),this.hasListeners()&&(n?.removeObserver(this),t.addObserver(this))},Oo=function(t){j.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(d(this,pe))}),d(this,_e).getQueryCache().notify({query:d(this,U),type:"observerResultsUpdated"})})},Mo);function zl(e,t){return ye(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function Ao(e,t){return zl(e,t)||e.state.data!==void 0&&Zs(e,t,t.refetchOnMount)}function Zs(e,t,n){if(ye(t.enabled,e)!==!1&&qe(t.staleTime,e)!=="static"){let r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&Xs(e,t)}return!1}function ko(e,t,n,r){return(e!==t||ye(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&Xs(e,n)}function Xs(e,t){return ye(t.enabled,e)!==!1&&e.isStaleByTime(qe(t.staleTime,e))}function Jl(e,t){return!en(e.getCurrentResult(),t)}function fn(e){return{onFetch:(t,n)=>{let r=t.options,s=t.fetchOptions?.meta?.fetchMore?.direction,i=t.state.data?.pages||[],o=t.state.data?.pageParams||[],a={pages:[],pageParams:[]},c=0,u=async()=>{let l=!1,f=m=>{wo(m,()=>t.signal,()=>l=!0)},h=Nr(t.options,t.fetchOptions),p=async(m,y,g)=>{if(l)return Promise.reject();if(y==null&&m.pages.length)return Promise.resolve(m);let _=(()=>{let M={client:t.client,queryKey:t.queryKey,pageParam:y,direction:g?"backward":"forward",meta:t.options.meta};return f(M),M})(),w=await h(_),{maxPages:C}=t.options,R=g?bo:vo;return{pages:R(m.pages,w,C),pageParams:R(m.pageParams,y,C)}};if(s&&i.length){let m=s==="backward",y=m?Fo:ei,g={pages:i,pageParams:o},v=y(r,g);a=await p(g,v,m)}else{let m=e??i.length;do{let y=c===0?o[0]??r.initialPageParam:ei(r,a);if(c>0&&y==null)break;a=await p(a,y),c++}while(c<m)}return a};t.options.persister?t.fetchFn=()=>t.options.persister?.(u,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=u}}}function ei(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 Fo(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function qo(e,t){return t?ei(e,t)!=null:!1}function No(e,t){return!t||!e.getPreviousPageParam?!1:Fo(e,t)!=null}var ti=class extends tr{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:fn()})}getOptimisticResult(e){return e.behavior=fn(),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:o,isRefetchError:a}=r,c=n.fetchMeta?.fetchMore?.direction,u=o&&c==="forward",l=s&&c==="forward",f=o&&c==="backward",h=s&&c==="backward";return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:qo(t,n.data),hasPreviousPage:No(t,n.data),isFetchNextPageError:u,isFetchingNextPage:l,isFetchPreviousPageError:f,isFetchingPreviousPage:h,isRefetchError:a&&!u&&!f,isRefetching:i&&!l&&!h}}};var nr,Le,le,Qt,He,ft,Qo,Do=(Qo=class extends Ur{constructor(t){super();I(this,He);I(this,nr);I(this,Le);I(this,le);I(this,Qt);S(this,nr,t.client),this.mutationId=t.mutationId,S(this,le,t.mutationCache),S(this,Le,[]),this.state=t.state||ni(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){d(this,Le).includes(t)||(d(this,Le).push(t),this.clearGcTimeout(),d(this,le).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){S(this,Le,d(this,Le).filter(n=>n!==t)),this.scheduleGc(),d(this,le).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){d(this,Le).length||(this.state.status==="pending"?this.scheduleGc():d(this,le).remove(this))}continue(){return d(this,Qt)?.continue()??this.execute(this.state.variables)}async execute(t){let n=()=>{F(this,He,ft).call(this,{type:"continue"})},r={client:d(this,nr),meta:this.options.meta,mutationKey:this.options.mutationKey};S(this,Qt,Dr({fn:()=>this.options.mutationFn?this.options.mutationFn(t,r):Promise.reject(new Error("No mutationFn found")),onFail:(o,a)=>{F(this,He,ft).call(this,{type:"failed",failureCount:o,error:a})},onPause:()=>{F(this,He,ft).call(this,{type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>d(this,le).canRun(this)}));let s=this.state.status==="pending",i=!d(this,Qt).canStart();try{if(s)n();else{F(this,He,ft).call(this,{type:"pending",variables:t,isPaused:i}),d(this,le).config.onMutate&&await d(this,le).config.onMutate(t,this,r);let a=await this.options.onMutate?.(t,r);a!==this.state.context&&F(this,He,ft).call(this,{type:"pending",context:a,variables:t,isPaused:i})}let o=await d(this,Qt).start();return await d(this,le).config.onSuccess?.(o,t,this.state.context,this,r),await this.options.onSuccess?.(o,t,this.state.context,r),await d(this,le).config.onSettled?.(o,null,this.state.variables,this.state.context,this,r),await this.options.onSettled?.(o,null,t,this.state.context,r),F(this,He,ft).call(this,{type:"success",data:o}),o}catch(o){try{await d(this,le).config.onError?.(o,t,this.state.context,this,r)}catch(a){Promise.reject(a)}try{await this.options.onError?.(o,t,this.state.context,r)}catch(a){Promise.reject(a)}try{await d(this,le).config.onSettled?.(void 0,o,this.state.variables,this.state.context,this,r)}catch(a){Promise.reject(a)}try{await this.options.onSettled?.(void 0,o,t,this.state.context,r)}catch(a){Promise.reject(a)}throw F(this,He,ft).call(this,{type:"error",error:o}),o}finally{d(this,le).runNext(this)}}},nr=new WeakMap,Le=new WeakMap,le=new WeakMap,Qt=new WeakMap,He=new WeakSet,ft=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),j.batch(()=>{d(this,Le).forEach(r=>{r.onMutationUpdate(t)}),d(this,le).notify({mutation:this,type:"updated",action:t})})},Qo);function ni(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var ze,Ne,rr,Uo,Ko=(Uo=class extends Ee{constructor(t={}){super();I(this,ze);I(this,Ne);I(this,rr);this.config=t,S(this,ze,new Set),S(this,Ne,new Map),S(this,rr,0)}build(t,n,r){let s=new Do({client:t,mutationCache:this,mutationId:++Vn(this,rr)._,options:t.defaultMutationOptions(n),state:r});return this.add(s),s}add(t){d(this,ze).add(t);let n=Kr(t);if(typeof n=="string"){let r=d(this,Ne).get(n);r?r.push(t):d(this,Ne).set(n,[t])}this.notify({type:"added",mutation:t})}remove(t){if(d(this,ze).delete(t)){let n=Kr(t);if(typeof n=="string"){let r=d(this,Ne).get(n);if(r)if(r.length>1){let s=r.indexOf(t);s!==-1&&r.splice(s,1)}else r[0]===t&&d(this,Ne).delete(n)}}this.notify({type:"removed",mutation:t})}canRun(t){let n=Kr(t);if(typeof n=="string"){let s=d(this,Ne).get(n)?.find(i=>i.state.status==="pending");return!s||s===t}else return!0}runNext(t){let n=Kr(t);return typeof n=="string"?d(this,Ne).get(n)?.find(s=>s!==t&&s.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){j.batch(()=>{d(this,ze).forEach(t=>{this.notify({type:"removed",mutation:t})}),d(this,ze).clear(),d(this,Ne).clear()})}getAll(){return Array.from(d(this,ze))}find(t){let n={exact:!0,...t};return this.getAll().find(r=>qr(n,r))}findAll(t={}){return this.getAll().filter(n=>qr(t,n))}notify(t){j.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){let t=this.getAll().filter(n=>n.state.isPaused);return j.batch(()=>Promise.all(t.map(n=>n.continue().catch(Z))))}},ze=new WeakMap,Ne=new WeakMap,rr=new WeakMap,Uo);function Kr(e){return e.options.scope?.id}var Je,pt,ve,Ye,Ze,Lr,ri,Lo,si=(Lo=class extends Ee{constructor(t,n){super();I(this,Ze);I(this,Je);I(this,pt);I(this,ve);I(this,Ye);S(this,Je,t),this.setOptions(n),this.bindMethods(),F(this,Ze,Lr).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(t){let n=this.options;this.options=d(this,Je).defaultMutationOptions(t),en(this.options,n)||d(this,Je).getMutationCache().notify({type:"observerOptionsUpdated",mutation:d(this,ve),observer:this}),n?.mutationKey&&this.options.mutationKey&&Ue(n.mutationKey)!==Ue(this.options.mutationKey)?this.reset():d(this,ve)?.state.status==="pending"&&d(this,ve).setOptions(this.options)}onUnsubscribe(){this.hasListeners()||d(this,ve)?.removeObserver(this)}onMutationUpdate(t){F(this,Ze,Lr).call(this),F(this,Ze,ri).call(this,t)}getCurrentResult(){return d(this,pt)}reset(){d(this,ve)?.removeObserver(this),S(this,ve,void 0),F(this,Ze,Lr).call(this),F(this,Ze,ri).call(this)}mutate(t,n){return S(this,Ye,n),d(this,ve)?.removeObserver(this),S(this,ve,d(this,Je).getMutationCache().build(d(this,Je),this.options)),d(this,ve).addObserver(this),d(this,ve).execute(t)}},Je=new WeakMap,pt=new WeakMap,ve=new WeakMap,Ye=new WeakMap,Ze=new WeakSet,Lr=function(){let t=d(this,ve)?.state??ni();S(this,pt,{...t,isPending:t.status==="pending",isSuccess:t.status==="success",isError:t.status==="error",isIdle:t.status==="idle",mutate:this.mutate,reset:this.reset})},ri=function(t){j.batch(()=>{if(d(this,Ye)&&this.hasListeners()){let n=d(this,pt).variables,r=d(this,pt).context,s={client:d(this,Je),meta:this.options.meta,mutationKey:this.options.mutationKey};if(t?.type==="success"){try{d(this,Ye).onSuccess?.(t.data,n,r,s)}catch(i){Promise.reject(i)}try{d(this,Ye).onSettled?.(t.data,null,n,r,s)}catch(i){Promise.reject(i)}}else if(t?.type==="error"){try{d(this,Ye).onError?.(t.error,n,r,s)}catch(i){Promise.reject(i)}try{d(this,Ye).onSettled?.(void 0,t.error,n,r,s)}catch(i){Promise.reject(i)}}}this.listeners.forEach(n=>{n(d(this,pt))})})},Lo);var je,Ho,jo=(Ho=class extends Ee{constructor(t={}){super();I(this,je);this.config=t,S(this,je,new Map)}build(t,n,r){let s=n.queryKey,i=n.queryHash??Gn(s,n),o=this.get(i);return o||(o=new Io({client:t,queryKey:s,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(s)}),this.add(o)),o}add(t){d(this,je).has(t.queryHash)||(d(this,je).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){let n=d(this,je).get(t.queryHash);n&&(t.destroy(),n===t&&d(this,je).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){j.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return d(this,je).get(t)}getAll(){return[...d(this,je).values()]}find(t){let n={exact:!0,...t};return this.getAll().find(r=>Fr(n,r))}findAll(t={}){let n=this.getAll();return Object.keys(t).length>0?n.filter(r=>Fr(t,r)):n}notify(t){j.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){j.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){j.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},je=new WeakMap,Ho);var X,mt,gt,pn,mn,ht,gn,hn,Bo,ii=(Bo=class{constructor(e={}){I(this,X);I(this,mt);I(this,gt);I(this,pn);I(this,mn);I(this,ht);I(this,gn);I(this,hn);S(this,X,e.queryCache||new jo),S(this,mt,e.mutationCache||new Ko),S(this,gt,e.defaultOptions||{}),S(this,pn,new Map),S(this,mn,new Map),S(this,ht,0)}mount(){Vn(this,ht)._++,d(this,ht)===1&&(S(this,gn,Xt.subscribe(async e=>{e&&(await this.resumePausedMutations(),d(this,X).onFocus())})),S(this,hn,on.subscribe(async e=>{e&&(await this.resumePausedMutations(),d(this,X).onOnline())})))}unmount(){var e,t;Vn(this,ht)._--,d(this,ht)===0&&((e=d(this,gn))==null||e.call(this),S(this,gn,void 0),(t=d(this,hn))==null||t.call(this),S(this,hn,void 0))}isFetching(e){return d(this,X).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return d(this,mt).findAll({...e,status:"pending"}).length}getQueryData(e){let t=this.defaultQueryOptions({queryKey:e});return d(this,X).get(t.queryHash)?.state.data}ensureQueryData(e){let t=this.defaultQueryOptions(e),n=d(this,X).build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(qe(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return d(this,X).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=d(this,X).get(r.queryHash)?.state.data,o=yo(t,i);if(o!==void 0)return d(this,X).build(this,r).setData(o,{...n,manual:!0})}setQueriesData(e,t,n){return j.batch(()=>d(this,X).findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){let t=this.defaultQueryOptions({queryKey:e});return d(this,X).get(t.queryHash)?.state}removeQueries(e){let t=d(this,X);j.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){let n=d(this,X);return j.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){let n={revert:!0,...t},r=j.batch(()=>d(this,X).findAll(e).map(s=>s.cancel(n)));return Promise.all(r).then(Z).catch(Z)}invalidateQueries(e,t={}){return j.batch(()=>(d(this,X).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=j.batch(()=>d(this,X).findAll(e).filter(s=>!s.isDisabled()&&!s.isStatic()).map(s=>{let i=s.fetch(void 0,n);return n.throwOnError||(i=i.catch(Z)),s.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(Z)}fetchQuery(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=d(this,X).build(this,t);return n.isStaleByTime(qe(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Z).catch(Z)}fetchInfiniteQuery(e){return e.behavior=fn(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Z).catch(Z)}ensureInfiniteQueryData(e){return e.behavior=fn(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return on.isOnline()?d(this,mt).resumePausedMutations():Promise.resolve()}getQueryCache(){return d(this,X)}getMutationCache(){return d(this,mt)}getDefaultOptions(){return d(this,gt)}setDefaultOptions(e){S(this,gt,e)}setQueryDefaults(e,t){d(this,pn).set(Ue(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){let t=[...d(this,pn).values()],n={};return t.forEach(r=>{Tt(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){d(this,mn).set(Ue(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){let t=[...d(this,mn).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={...d(this,gt).queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Gn(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===tn&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...d(this,gt).mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){d(this,X).clear(),d(this,mt).clear()}},X=new WeakMap,mt=new WeakMap,gt=new WeakMap,pn=new WeakMap,mn=new WeakMap,ht=new WeakMap,gn=new WeakMap,hn=new WeakMap,Bo);var yn=Y(ue(),1),Vo=Y(Hr(),1),oi=yn.createContext(void 0),L=e=>{let t=yn.useContext(oi);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},sr=({client:e,children:t})=>(yn.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,Vo.jsx)(oi.Provider,{value:e,children:t}));var jr=Y(ue(),1),Wo=jr.createContext(!1),Go=()=>jr.useContext(Wo),Nm=Wo.Provider;var ir=Y(ue(),1),Yl=Y(Hr(),1);function Zl(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Xl=ir.createContext(Zl()),zo=()=>ir.useContext(Xl);var Jo=Y(ue(),1);var Yo=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError=="function"?nn(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},Zo=e=>{Jo.useEffect(()=>{e.clearReset()},[e])},Xo=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:s})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(s&&e.data===void 0||nn(n,[e.error,r]));var ea=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))}},ta=(e,t)=>e.isLoading&&e.isFetching&&!t,na=(e,t)=>e?.suspense&&t.isPending,ai=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});var yt=Y(ue(),1);function Br(e,t,n){let r=Go(),s=zo(),i=L(n),o=i.defaultQueryOptions(e);i.getDefaultOptions().queries?._experimental_beforeQuery?.(o);let a=i.getQueryCache().get(o.queryHash);o._optimisticResults=r?"isRestoring":"optimistic",ea(o),Yo(o,s,a),Zo(s);let c=!i.getQueryCache().get(o.queryHash),[u]=yt.useState(()=>new t(i,o)),l=u.getOptimisticResult(o),f=!r&&e.subscribed!==!1;if(yt.useSyncExternalStore(yt.useCallback(h=>{let p=f?u.subscribe(j.batchCalls(h)):Z;return u.updateResult(),p},[u,f]),()=>u.getCurrentResult(),()=>u.getCurrentResult()),yt.useEffect(()=>{u.setOptions(o)},[o,u]),na(o,l))throw ai(o,u,s);if(Xo({result:l,errorResetBoundary:s,throwOnError:o.throwOnError,query:a,suspense:o.suspense}))throw l.error;return i.getDefaultOptions().queries?._experimental_afterQuery?.(o,l),o.experimental_prefetchInRender&&!Ke.isServer()&&ta(l,r)&&(c?ai(o,u,s):a?.promise)?.catch(Z).finally(()=>{u.updateResult()}),o.notifyOnChangeProps?l:u.trackResult(l)}function B(e,t){return Br(e,tr,t)}var Xe=Y(ue(),1);function ne(e,t){let n=L(t),[r]=Xe.useState(()=>new si(n,e));Xe.useEffect(()=>{r.setOptions(e)},[r,e]);let s=Xe.useSyncExternalStore(Xe.useCallback(o=>r.subscribe(j.batchCalls(o)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),i=Xe.useCallback((o,a)=>{r.mutate(o,a).catch(Z)},[r]);if(s.error&&nn(r.options.throwOnError,[s.error]))throw s.error;return{...s,mutate:i,mutateAsync:s.mutate}}function or(e,t){return Br(e,ti,t)}var ia=Y(sa(),1),_n=typeof window<"u"&&window.__FSAOS_CONFIG__||{},Dt=Array.isArray(_n.sources)?_n.sources:[],et=_n.hostSession===!0,ed=_n.supabaseUrl||"https://vahbmsslxuustnlvsrkg.supabase.co",td=_n.supabaseAnonKey||"sb_publishable_ZjosozAjfpZ4InMNElTr6Q_hHB-f5nc",Te=_n.gatewayUrl||"https://fsaos-mcp-gw-rust.fly.dev",V=(0,ia.createClient)(ed,td,{auth:{persistSession:!0,autoRefreshToken:!0,detectSessionInUrl:!1}});var ar=null,$r=0,oa,di,Vr=!1;oa=new Promise(e=>{di=e});V.auth.onAuthStateChange((e,t)=>{t?.access_token?(ar=t.access_token,$r=t.expires_at??Math.floor(Date.now()/1e3)+3600):(ar=null,$r=0),Vr||(Vr=!0,di())});setTimeout(()=>{Vr||(Vr=!0,di())},5e3);function aa(e,t){ar=e,$r=t??Math.floor(Date.now()/1e3)+3600}function fi(){ar=null,$r=0}async function tt(){let e=typeof window<"u"&&window.__FSAOS_CONFIG__||{};if(et)return null;if(e.embedToken){if(typeof e.embedToken=="function")try{return await e.embedToken()??null}catch{return null}return e.embedToken}return await oa,ar}var Sn=null,xn=null,ca=0,ci=new Set,pi,cr,Rn=!1;pi=new Promise(e=>{cr=e});function mi(){ca++,ci.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Anchor listener error:",t)}})}function Pn(e){let t=typeof e=="string"?e:e.path,n=Sn!==t||xn?.id!==(typeof e=="string"?void 0:e.id);Sn=t,xn=typeof e=="string"?null:e,typeof e!="string"&&!Ut.some(r=>r.id===e.id)&&(Ut=[...Ut,e],_i()),Rn||(Rn=!0,cr()),n&&mi()}function _t(){return Sn}function de(){return xn}function gi(){return ca}function hi(e){return ci.add(e),()=>{ci.delete(e)}}function ur(){return pi}function yi(){return Rn}var Wr=null;function Kt(e,t={}){if(Wr){console.warn("[SDK] electHomeAnchor called twice; ignoring (logout to re-elect).");return}Wr=e,t.activate!==!1&&Pn(e)}function me(){return Wr}var Ut=[],ui=new Set,ua=0;function _i(){ua++,ui.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Mount listener error:",t)}})}function Ae(){return Ut}function lr(){return ua}function Gr(e){return ui.add(e),()=>{ui.delete(e)}}function la(e,t){let n=JSON.stringify(Ut)!==JSON.stringify(e),r=Sn!==t.path||xn?.id!==t.id;Ut=e,Sn=t.path,xn=t,Rn||(Rn=!0,cr()),n&&_i(),r&&mi()}var bn=null,vn=null,wn=0,li=new Set,da=0;function fa(){da++,li.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Session listener error:",t)}})}function ae(){return wn}function vi(){return da}function pa(e){return li.add(e),()=>{li.delete(e)}}async function nt(){if(bn)return bn;if(vn)return vn;let e=wn;return vn=(async()=>{let t=Lt(),n=await tt();if(e!==wn)throw new Error("Session changed during initialization");let r={};n&&(r.Authorization=`Bearer ${n}`);let s=await fetch(`${Te}/d/${t}/init`,{method:"GET",headers:r});if(!s.ok)throw new Error(`Session init failed: ${s.status} ${s.statusText}`);let i=await s.json();if(e!==wn)throw new Error("Session changed during initialization");let o=i.entry||i;return bn={scope_id:o.scope_id,scope_path:o.scope_path,instance_path:o.instance_path||"/root",fractal_id:o.fractal_id||null,instance_name:o.instance_name||null,display_name:o.scope_display_name||o.display_name||null,principal_id:o.principal_id||null},fa(),bn})().catch(t=>{throw e===wn&&(vn=null),t}),vn}function vt(){return bn}function bi(){wn++,bn=null,vn=null,Sn=null,xn=null,Wr=null,Ut=[],fa()}var ma=[];function se(e){ma.push(e)}function Cn(){bi(),fi(),cr(),Rn=!1,pi=new Promise(e=>{cr=e}),mi(),_i();for(let e of ma)try{e()}catch(t){console.warn("[SDK] Cleanup function failed:",t)}}function Lt(){if(typeof window<"u"){let e=window.__FSAOS_CONFIG__;return e?.hostname?e.hostname:window.location.hostname}return"localhost"}var ga=Pn,W=_t,ee=gi,xe=hi,ha=ur,zr=yi;var jt="host-session",nd=5e3;function wi(e){return typeof e=="object"&&e!==null&&e.fsaos===jt&&typeof e.kind=="string"}var Ht=class extends Error{constructor(){super(...arguments);z(this,"name","HostSessionUnavailableError")}},Jr=null,rd=0,Yr=new Map;function ya(){return Jr||(Jr=new Promise((e,t)=>{if(!et){t(new Ht("This page was not started with hostSession."));return}if(typeof window>"u"||!window.parent||window.parent===window){t(new Ht("This page is signed in only inside the app that frames it. Open it from there."));return}let n=window.parent,r=null,s=setTimeout(()=>{r===null&&(window.removeEventListener("message",i),t(new Ht("The window around this page did not sign it in. Open it from the app that owns it.")))},nd);function i(o){if(o.source!==n||!wi(o.data))return;let a=o.data;if(r===null){if(a.kind!=="welcome")return;r=o.origin,clearTimeout(s),a.anchor&&Pn(a.anchor),e({host:n,origin:r,item:a.item??null});return}if(o.origin!==r||a.kind!=="result")return;let c=Yr.get(a.id);c&&(Yr.delete(a.id),c.resolve(a.ok?{ok:!0,response:a.response}:{ok:!1,error:a.error}))}window.addEventListener("message",i),n.postMessage({fsaos:jt,kind:"hello"},"*")}),Jr)}async function _a(){let{item:e}=await ya();return{item:e}}async function va(e,t,n){if(n?.aborted)throw new DOMException("Read cancelled","AbortError");let{host:r,origin:s}=await ya();if(n?.aborted)throw new DOMException("Read cancelled","AbortError");let i=JSON.parse(JSON.stringify(t??{}));return new Promise((o,a)=>{let c=`${Date.now().toString(36)}-${(++rd).toString(36)}`,u=()=>{Yr.delete(c),a(new DOMException("Read cancelled","AbortError"))};Yr.set(c,{resolve:l=>{n?.removeEventListener("abort",u),o(l)}}),n?.addEventListener("abort",u,{once:!0}),r.postMessage({fsaos:jt,kind:"call",id:c,method:e,params:i},s)})}var Si=0,ba=!1,wa=0;function xi(e){if(typeof e!="string")return;let t=Date.parse(e);Number.isNaN(t)||(Si=t-Date.now(),ba=!0,wa=Date.now())}function Zr(){return Date.now()+Si}function Sa(){return ba}function xa(){return Si}function Ra(){return wa}function Pa(e){if(typeof e!="string")return null;let t=Date.parse(e);return Number.isNaN(t)?null:Zr()>=t}function Ca(e){if(typeof e!="string")return null;let t=Date.parse(e);return Number.isNaN(t)?null:Math.max(0,t-Zr())}var En,ke=new Map,Bt=[],Ri=0,Pi={foreground:0,normal:1,background:2},Xr=()=>performance.now(),Ci=()=>new DOMException("Read cancelled","AbortError");function Ia(e={}){En={concurrency:Math.max(1,Math.min(16,Math.floor(e.concurrency??6))),timeoutMs:Math.max(1e3,e.timeoutMs??15e3),onTiming:e.onTiming},ts()}function Ta(){for(let e of ke.values()){e.controller.abort();for(let t of e.consumers)t.detach(),t.reject(Ci());e.consumers.clear(),e.timer&&clearTimeout(e.timer)}ke.clear(),Bt.length=0}function Aa(e,t){return e==="query"?!("materialize"in t):["read","list","search","resolve","resolve-items","get-channel-messages","list-memberships"].includes(e)}function es(e){return Array.isArray(e)?`[${e.map(es).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>`${JSON.stringify(t)}:${es(n)}`).join(",")}}`:JSON.stringify(e)}function ka(e,t,n,r){if(n.signal?.aborted)return Promise.reject(Ci());if(!En)return r(n.signal);let s=ke.get(e);if(s)Pi[n.priority??"normal"]<Pi[s.priority]&&(s.priority=n.priority??"normal");else{s={key:e,method:t,priority:n.priority??"normal",queuedAt:Xr(),controller:new AbortController,consumers:new Set,run:r},ke.set(e,s),Bt.push(s);let a=s;s.timer=setTimeout(()=>{a.controller.abort();let c=new Error("The read timed out. Please retry.");c.name="TimeoutError";for(let u of a.consumers)u.detach(),u.reject(c);a.consumers.clear(),ke.get(a.key)===a&&ke.delete(a.key),Ea(a)},En.timeoutMs)}let i=s,o=new Promise((a,c)=>{let u=()=>{l.detach(),i.consumers.delete(l),c(Ci()),i.consumers.size||(i.controller.abort(),ke.get(i.key)===i&&ke.delete(i.key),Ea(i))},l={resolve:f=>a(structuredClone(f)),reject:c,detach:()=>n.signal?.removeEventListener("abort",u)};i.consumers.add(l),n.signal?.addEventListener("abort",u,{once:!0})});return ts(),o}function Ea(e){let t=Bt.indexOf(e);t>=0&&(Bt.splice(t,1),ke.get(e.key)===e&&ke.delete(e.key),e.timer&&clearTimeout(e.timer)),ts()}function ts(){if(En)for(;Ri<En.concurrency&&Bt.length;){let e=r=>Pi[r.priority]-Math.floor((Xr()-r.queuedAt)/2e3);Bt.sort((r,s)=>e(r)-e(s)||r.queuedAt-s.queuedAt);let t=Bt.shift();if(!t.consumers.size)continue;Ri++,t.startedAt=Xr();let n="success";Promise.resolve().then(()=>t.run(t.controller.signal)).then(r=>{for(let s of t.consumers)s.detach(),s.resolve(r)},r=>{n=t.controller.signal.aborted?"aborted":"error";for(let s of t.consumers)s.detach(),s.reject(r)}).finally(()=>{t.timer&&clearTimeout(t.timer),t.consumers.clear(),ke.get(t.key)===t&&ke.delete(t.key),Ri--;try{En?.onTiming?.({method:t.method,priority:t.priority,queueMs:Math.round(t.startedAt-t.queuedAt),requestMs:Math.round(Xr()-t.startedAt),outcome:n})}catch{}ts()})}}se(Ta);var sd=new Set(["list-memberships","init"]),ge=class extends Error{constructor(n){let r=typeof n.payload?.error=="string"?n.payload.error.trim():"",s=typeof n.payload?.message=="string"?n.payload.message.trim():"",i=n.responseBody.trim()||`Gateway HTTP error: ${n.status} ${n.statusText}`.trim(),o=r&&s?`${r}: ${s}`:s||r||i;super(o);z(this,"name","GatewayRequestError");z(this,"method");z(this,"status");z(this,"statusText");z(this,"payload");z(this,"responseBody");this.method=n.method,this.status=n.status,this.statusText=n.statusText,this.payload=n.payload,this.responseBody=n.responseBody}};async function x(e,t={},n={}){if(et)return id(e,t,n);let r=ae(),s=_t(),i=Lt(),o=`${Te}/d/${i}`,a={"Content-Type":"application/json"},c=await Ma(tt(),n.signal);if(r!==ae())throw new Error("Session changed before gateway request");if(c&&(a.Authorization=`Bearer ${c}`),!sd.has(e)&&!t._scope_path&&await Ma(ur(),n.signal),r!==ae())throw new Error("Session changed before gateway request");let u={...t},l=vt();!u.domain_scope_id&&l?.scope_id&&(u.domain_scope_id=l.scope_id);let f=s??_t();!u._scope_path&&f&&(u._scope_path=f);let h=async p=>{if(r!==ae())throw new Error("Session changed before queued gateway request");let m=await fetch(o,{method:"POST",signal:p,headers:a,body:JSON.stringify({method:e,params:u})}),y=await m.text();if(r!==ae())throw new Error("Session changed during gateway request");let g=null;if(y)try{g=JSON.parse(y)}catch{}if(!m.ok||!g)throw new ge({method:e,status:m.status,statusText:m.statusText,payload:g,responseBody:y});if(g.success===!1){let v=g.error||"",_=g.denied_by||g.error_type||"";throw _==="rule"||_==="access"||_==="entitlement"||v==="RULE_DENIED"||v==="ACCESS_DENIED"||v==="PERMISSION_DENIED"||v==="ENTITLEMENT_REQUIRED"?new Fe(g):new ge({method:e,status:m.status,statusText:m.statusText,payload:g,responseBody:y})}return g&&g.server_now!==void 0&&xi(g.server_now),g};return Aa(e,u)?ka(es([r,i,c,e,u]),e,n,h):h(n.signal)}async function id(e,t,n){let r=await va(e,t,n.signal);if(r.ok){let o=r.response?.server_now;return o!==void 0&&xi(o),r.response}let s=r.error;if(s.kind==="denied")throw new Fe(s.payload);if(s.kind==="gateway")throw new ge({method:s.method,status:s.status,statusText:s.statusText,payload:s.payload,responseBody:s.responseBody});let i=new Error(s.message);throw i.name=s.name,i}function Ma(e,t){return t?t.aborted?Promise.reject(new DOMException("Read cancelled","AbortError")):new Promise((n,r)=>{let s=()=>r(new DOMException("Read cancelled","AbortError"));t.addEventListener("abort",s,{once:!0}),e.then(n,r).finally(()=>t.removeEventListener("abort",s))}):e}var b=Y(ue(),1),Gd=Y(Fa(),1),zd=Y(Hr(),1);var qa=new WeakMap;function be(e,t,n={}){let r=n.exact===!0,s=()=>e.invalidateQueries({queryKey:t,exact:r},{cancelRefetch:!1}),i=e.getQueryCache().findAll({queryKey:t,exact:r,fetchStatus:"fetching"}).flatMap(f=>f.promise?[f.promise]:[]);if(i.length===0)return s();let o=`${r?"=":"^"}${JSON.stringify(t)}`,a=qa.get(e);a||(a=new Map,qa.set(e,a));let c=a.get(o);if(c)return c;let u=a,l=Promise.allSettled(i).then(()=>(u.delete(o),s()));return u.set(o,l),l}function he(e,t){return typeof e=="string"&&(e===t||e.startsWith(`${t}/`))}var ns=new WeakMap,Na=e=>e.meta?.arrangementRealtime===!0;function rt(e,t){let n=e.getQueryCache().find({queryKey:t,exact:!0});if(!n)return;let r=ns.get(e);r||(r=new Map,ns.set(e,r));let s=r.get(n.queryHash);s&&clearTimeout(s),r.set(n.queryHash,setTimeout(()=>{r.delete(n.queryHash),e.getQueryCache().get(n.queryHash)===n&&be(e,t,{exact:!0})},250))}function Qa(e,t){if(!(!t||typeof t!="object"))for(let n of e.getQueryCache().getAll()){if(!Na(n))continue;let r=n.state.data;if(n.meta?.personalSections===!0){(r?.item_path&&[t.path,t.old_path].some(i=>typeof i=="string"&&(i===r.item_path||i.startsWith(r.item_path+"/")))||r?.sections?.some(i=>i.entries?.some(o=>o.target?.id===t.item_id))||!r?.item_id&&t.item_type==="item_arrangement"&&t.name==="sidebar-sections")&&rt(e,n.queryKey);continue}if(!r?.item_id)continue;let s=(i,o)=>!!(i&&t.item_id===i||o&&(t.path===o||t.old_path===o));(s(r.item_id,r.item_path)||t.parent_id===r.item_id||t.old_parent_id===r.item_id||[t.path,t.old_path].some(i=>typeof i=="string"&&i.slice(0,i.lastIndexOf("/"))===r.item_path)||r.resolved_children?.some(i=>s(i.id,i.symlink_path||i.path)||i.target&&s(i.target.id,i.target.path)))&&rt(e,n.queryKey)}}function Da(e){for(let t of e.getQueryCache().getAll())Na(t)&&t.state.data!==void 0&&rt(e,t.queryKey)}function Ua(e){ns.get(e)?.forEach(clearTimeout),ns.delete(e)}var st=null;se(()=>{st&&(st.cancelQueries({queryKey:["vfs"]}),st.removeQueries({queryKey:["vfs"]}))});function Ka(e){if(st&&st!==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.");st=e}function N(){return st||(st=new ii({defaultOptions:{queries:{staleTime:1e3*60*2,gcTime:1e3*60*10,refetchOnWindowFocus:!1,retry:1}}})),st}var La=new Proxy({},{get(e,t,n){let r=N(),s=r[t];return typeof s=="function"?s.bind(r):s}});var rs=new WeakMap;function Ei(e){return e.meta?.infiniteItemsRealtime?.filter}function od(e,t){return e.state.data?.pages?.some(r=>r.items?.some(s=>t.item_id&&s.id===t.item_id||t.path&&s.path===t.path||t.old_path&&s.path===t.old_path))??!1}function ad(e){if(e.type)return new Set([e.type]);if(!e.any_of?.length)return null;let t=new Set;for(let n of e.any_of){if(!n.item_type)return null;t.add(n.item_type)}return t}function cd(e,t,n){if(od(e,n))return!0;if(t.spaceIds!==void 0&&(!t.spaceIds.length||n.space_item_id!==void 0&&!t.spaceIds.includes(n.space_item_id)&&!t.spaceIds.includes(n.old_space_item_id)))return!1;let r=t.scope,s=typeof r=="string"&&r!=="__unscoped__",i=typeof n.path=="string"||typeof n.old_path=="string";if(s&&i&&!he(n.path,r)&&!he(n.old_path,r))return!1;if(n.item_type==="symlink"&&s&&i)return!0;let o=ad(t);return n.item_type&&o&&!o.has(n.item_type)||t.parent_id&&n.parent_id!==void 0&&n.parent_id!==t.parent_id&&n.old_parent_id!==t.parent_id?!1:i||!!(t.parent_id&&n.parent_id===t.parent_id)}function Ha(e,t){let n=rs.get(e);n||(n=new Map,rs.set(e,n));let r=n.get(t.queryHash);r&&clearTimeout(r),n.set(t.queryHash,setTimeout(()=>{n.delete(t.queryHash),!(e.getQueryCache().get(t.queryHash)!==t||!Ei(t))&&be(e,t.queryKey,{exact:!0})},500))}function ja(e,t){if(!(!t||typeof t!="object"))for(let n of e.getQueryCache().getAll()){let r=Ei(n);r&&cd(n,r,t)&&Ha(e,n)}}function Ba(e){for(let t of e.getQueryCache().getAll())Ei(t)&&t.state.data!==void 0&&Ha(e,t)}function $a(e){rs.get(e)?.forEach(clearTimeout),rs.delete(e)}var ss=class extends Error{constructor(){super("The server did not confirm the selected-Space listing contract")}};function Va(e,t){if(!Array.isArray(t)||t.some(n=>typeof n!="string")||JSON.stringify([...new Set(t)].sort())!==JSON.stringify(e))throw new ss}function bt(e){return!e||e.spaceIds===void 0?e:{...e,spaceIds:[...new Set(e.spaceIds.map(t=>t.toLowerCase()))].sort(),...e.limit!==void 0?{limit:Math.max(1,Math.min(e.limit,500))}:{}}}function In(e){return e instanceof ss||e instanceof Fe||e instanceof ge&&(e.payload?.error==="SPACE_SELECTION_UNAVAILABLE"||e.payload?.error==="QUERY_PARAMS_INVALID"||e.status===401||e.status===403)}function ce(){return W()??"__unscoped__"}var E={all:()=>["vfs",ce()],item:e=>["vfs",ce(),"item",e],itemById:e=>["vfs","item-by-id",e],children:e=>["vfs",ce(),"children",e],allChildren:()=>["vfs",ce(),"children"],types:e=>["vfs","types",e??"default"],edges:e=>["vfs","edges",e],search:(e,t)=>["vfs",ce(),"search",e,...t??[]],items:(e,t)=>["vfs",ce(),"items",e,JSON.stringify(bt(t??{}))],allItems:()=>["vfs",ce(),"items"],tree:(e,t)=>["vfs",ce(),"tree",e,t??1],openEnvelope:(e,t)=>["vfs",ce(),"open",e,t??"__default__"],allOpenEnvelopes:()=>["vfs",ce(),"open"],memberFocus:e=>["vfs","member-focus",e],fractalInstances:()=>["vfs","fractal-instances"],recentActivity:(e,t,n)=>["vfs",ce(),"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",ce(),"channel-messages",e,t??"__top__"],allChannelMessages:()=>["vfs",ce(),"channel-messages"],channels:e=>["vfs",ce(),"channels",e??"all"],allChannels:()=>["vfs",ce(),"channels"],notifications:(e,t)=>["vfs",ce(),"notifications",e??"all",t??200],allNotifications:()=>["vfs",ce(),"notifications"],unreadCounts:()=>["vfs",ce(),"unread-counts"],memberships:e=>["memberships",e]};var ud=typeof window<"u"&&(window.location?.hostname==="localhost"||window.location?.hostname==="127.0.0.1"||window.__FSAOS_WS_DEBUG__);function J(...e){ud&&console.log("[WS]",...e)}var Q=null,Tn=null,kn=null,dr=0,ld=3e4,Wa=1e4,On=!1,Ga=!1,Xa=3e4,dd=Xa*2+5e3,is=0,os=null,za=!1;function fd(){pr(),is=Date.now(),os=setInterval(()=>{if(Q&&Q.readyState===WebSocket.OPEN&&Date.now()-is>dd){J("ping: no inbound traffic for",Date.now()-is,"ms \u2014 closing half-open socket");try{Q.close(4e3,"liveness timeout")}catch{}return}ot({type:"ping"})},Xa)}function pr(){os&&(clearInterval(os),os=null)}function pd(){typeof document>"u"||(document.hidden?pr():fr()&&(J("Tab visible, reconnecting..."),$t()))}function md(){za||typeof document>"u"||(document.addEventListener("visibilitychange",pd),za=!0)}var Re={};function Ti(e,t){let n=e.replace(/\/+$/,""),r=t.replace(/\/+$/,"");return!n||!r?n===r:r===n||r.startsWith(`${n}/`)}var Mn=[],it=new Map,An=new Map,Me=new Map;function gd(e){let t=An.get(e);return t?Array.from(new Set(Array.from(t.values()).flatMap(n=>n.event_types))).sort():[]}function Ja(e,t){return e?e.length===t.length&&e.every((n,r)=>n===t[r]):!1}function Ya(e){let t=gd(e);if(t.length===0)return it.delete(e),null;let n={scope_id:e,event_types:t};return it.set(e,n),n}var Be=new Map,wt=new Map,Ii="disconnected",as=[];function cs(e){if(Ii!==e){Ii=e;for(let t of[...as])try{t(e)}catch{}}}function hd(e){Be.set(e,"ready");let t=wt.get(e);if(t){wt.delete(e);for(let n of t)n()}}function yd(){for(let e of Be.keys())Be.set(e,"disconnected")}function Ai(e,t){Be.set(e,"pending"),ot({type:"subscribe_path",path:e,event_types:t})}function _d(){return Object.keys(Re).some(t=>Re[t]&&Re[t].length>0)||Mn.length>0}function fr(){return it.size>0||Me.size>0}async function $t(){if(et){J("ensureConnection: the host holds the session, no realtime connection");return}if(!fr()){J("ensureConnection: no active subscriptions, skipping");return}if(Q&&Q.readyState===WebSocket.OPEN){J("ensureConnection: already open");return}if(Tn)return J("ensureConnection: connection already in flight, waiting..."),Tn;if(Q){J("ensureConnection: killing stale WS in state",Q.readyState);try{Q.close()}catch{}Q=null}return On=!1,Tn=(async()=>{try{let e=typeof window<"u"&&window.__FSAOS_CONFIG__||{},t=Te,n=await tt();if(!n){J("ensureConnection: no token available, will retry"),Za();return}let r=t.startsWith("https")?"wss":"ws",s=t.replace(/^https?:\/\//,""),i=`${r}://${s}/ws`;i+=`?token=${encodeURIComponent(n)}`,J("ensureConnection: opening WS to",i.substring(0,50)+"..."),cs("connecting"),Q=new WebSocket(i);let o=Q;await new Promise((a,c)=>{if(!Q)return c(new Error("WebSocket not created"));let u=setTimeout(()=>{if(Q===o){if(J("ensureConnection: TIMEOUT after",Wa,"ms"),Q&&Q.readyState!==WebSocket.OPEN){try{Q.close()}catch{}Q=null}c(new Error("WebSocket connection timeout"))}},Wa);o.onopen=()=>{if(Q!==o)return;clearTimeout(u),J("ensureConnection: CONNECTED");let l=Ga;Ga=!0,dr=0,cs("connected"),vd(l),(typeof document>"u"||!document.hidden)&&fd(),md(),a()},o.onmessage=l=>{Q===o&&bd(l.data)},o.onerror=()=>{J("ensureConnection: WS error event")},o.onclose=l=>{clearTimeout(u),Q===o&&(J("ensureConnection: WS closed, code:",l.code,"reason:",l.reason),Q=null,pr(),yd(),cs("disconnected"),!On&&fr()&&Za(),c(new Error(`WebSocket closed: ${l.code}`)))}})}catch(e){J("ensureConnection: failed -",e?.message||e)}finally{Tn=null}})(),Tn}function Za(){if(kn||typeof document<"u"&&document.hidden)return;let e=Math.min(1e3*Math.pow(2,dr)+Math.random()*1e3,ld);dr++,J("scheduleReconnect: attempt",dr,"in",Math.round(e),"ms"),kn=setTimeout(()=>{kn=null,fr()&&$t()},e)}function vd(e=!1){for(let t of it.values())J("resubscribeAll: scope",t.scope_id),ot({type:"subscribe",scope_id:t.scope_id,event_types:t.event_types});for(let t of Me.values())J("resubscribeAll: path",t.path),Ai(t.path,t.event_types);e&&ec("reconnect")}function ec(e){try{let t=N();Ba(t),Da(t);for(let n of Me.values())t.invalidateQueries({queryKey:E.item(n.path)}),t.invalidateQueries({queryKey:E.children(n.path)});t.invalidateQueries({queryKey:E.allChannelMessages()}),J("catchUpAfterGap:",e,"- invalidated",Me.size,"paths and the transcripts on screen")}catch(t){J("catchUpAfterGap: cache invalidation skipped",t)}}function ot(e){Q&&Q.readyState===WebSocket.OPEN&&Q.send(JSON.stringify(e))}function bd(e){is=Date.now();try{let t=JSON.parse(e);if(t.type==="subscribed_path"){typeof t.path=="string"&&hd(t.path);return}if(t.type==="subscribed"||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==="resync"){ec(typeof t.reason=="string"?t.reason:"resync");return}if(t.type==="event"||t.event_type){let n=t.event_type||"message",r=t.data||t;if(n==="vfs_change"&&(ja(N(),r),Qa(N(),r)),typeof r.path=="string")for(let[s,i]of Object.entries(Re))s!=="*"&&Ti(s,r.path)&&i.forEach(o=>o(r));Re["*"]&&Re["*"].forEach(s=>s(r));for(let s of Mn)s.eventType!=="*"&&s.eventType!==n||s.filter&&!s.filter(r)||s.callback(r)}}catch{}}function ki(){!_d()&&it.size===0&&Me.size===0&&Q&&(On=!0,pr(),Q.close(),Q=null,On=!1)}function us(e,t){return Re[e]||(Re[e]=[]),Re[e].push(t),Me.has(e)||(Me.set(e,{path:e,event_types:["token_stream"]}),Q&&Q.readyState===WebSocket.OPEN?Ai(e,["token_stream"]):Be.set(e,"pending")),$t(),()=>{let n=Re[e];if(n){let r=n.indexOf(t);r!==-1&&n.splice(r,1),n.length===0&&(delete Re[e],Me.delete(e),Be.delete(e),wt.delete(e),ot({type:"unsubscribe_path",path:e}))}ki()}}function ie(e,t,n){let s=(Array.isArray(e)?e:[e]).map(i=>({eventType:i,callback:t,filter:n}));return Mn.push(...s),fr()&&$t(),()=>{for(let i of s){let o=Mn.indexOf(i);o!==-1&&Mn.splice(o,1)}ki()}}function Fn(e,t=["vfs_change","ccm_change"]){let n=Symbol(e),r=Array.from(new Set(t)).sort();if(r.length===0)return()=>{};let s=An.get(e)??new Map,i=it.get(e)?.event_types;s.set(n,{event_types:r}),An.set(e,s);let o=Ya(e);if(!o)return()=>{};J("subscribeToScope:",e,o.event_types),Q&&Q.readyState===WebSocket.OPEN&&!Ja(i,o.event_types)&&ot({type:"subscribe",scope_id:e,event_types:o.event_types}),$t();let a=!0;return()=>{if(!a)return;a=!1;let c=An.get(e);if(!c?.delete(n))return;let u=it.get(e)?.event_types;if(c.size===0)An.delete(e),it.delete(e),ot({type:"unsubscribe",scope_id:e});else{let l=Ya(e);l&&Q&&Q.readyState===WebSocket.OPEN&&!Ja(u,l.event_types)&&ot({type:"subscribe",scope_id:e,event_types:l.event_types})}ki()}}function tc(e,t,n={}){ot({type:"emit",scope_id:e,event_type:t,payload:n})}function Mi(){J("disconnectSSE: tearing down"),$a(N()),Ua(N()),On=!0,pr(),Q&&(Q.close(),Q=null),kn&&(clearTimeout(kn),kn=null),Tn=null,On=!1,dr=0;for(let e of Object.keys(Re))delete Re[e];Mn.length=0,it.clear(),An.clear(),Me.clear(),Be.clear(),wt.clear(),cs("disconnected")}function nc(){ot({type:"ping"})}function rc(e){return Me.has(e)?Be.get(e)??"pending":"unsubscribed"}function sc(e,t=5e3){return!Me.has(e)||et?Promise.resolve(!1):Be.get(e)==="ready"&&Q&&Q.readyState===WebSocket.OPEN?Promise.resolve(!0):($t(),new Promise(n=>{let r=!1,s=wt.get(e)??[],i=()=>{r||(r=!0,clearTimeout(o),n(!0))};s.push(i),wt.set(e,s);let o=setTimeout(()=>{if(r)return;r=!0;let a=wt.get(e);if(a){let c=a.indexOf(i);c!==-1&&a.splice(c,1),a.length===0&&wt.delete(e)}n(!1)},t)}))}function ic(e){let t=Me.get(e);if(!t){J("resubscribePath: no active subscription for",e);return}Q&&Q.readyState===WebSocket.OPEN?(J("resubscribePath: re-sending frame for",e),Ai(t.path,t.event_types)):(Be.set(e,"pending"),$t())}function ls(e){as.push(e);try{e(Ii)}catch{}return()=>{let t=as.indexOf(e);t!==-1&&as.splice(t,1)}}se(Mi);function oc(){return new Date().toISOString()}function ac(){return crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function Oe(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||oc(),updated_at:e.updated_at||oc(),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 gr(e){return(e.content?.items||e.items||[]).map(Oe)}async function hr(e){try{let t=await x("read",{id:e});if(t.item_name||t.item_path){let r=Oe(t);return r.path&&N().setQueryData(E.item(r.path),r),r}let n=t.item;if(n){let r=Oe(n);return r.path&&N().setQueryData(E.item(r.path),r),r}return null}catch{return null}}async function yr(e){try{let t=await x("read",{path:e});if(t.item_name||t.item_path)return Oe(t);let n=t.item;return n?Oe(n):null}catch{return null}}async function _r(e){try{let t=await x("list",{path:e,limit:200}),n=gr(t);for(let r of n)N().setQueryData(E.item(r.path),r);return n}catch(t){return console.error(`[gateway] Failed to fetch children of ${e}:`,t),[]}}async function cc(e,t){let{items:n}=await Vt({type:"turn_queue_entry",scope:e,parent_id:t,fields:{state:"queued"},sort_by:"created_at",sort_dir:"asc",limit:100});return n.map(r=>{let s=String(r.type_data?.conversation_anchor_item_id??r.type_data?.conversation_root_id??t);return{id:r.id,path:r.path,content:String(r.type_data?.content??""),state:String(r.type_data?.state??"queued"),queue_seq:Number(r.type_data?.queue_seq??0),created_at:r.created_at,conversation_anchor_item_id:s,conversation_root_id:s,client_request_id:typeof r.type_data?.client_request_id=="string"?r.type_data.client_request_id:void 0,promoted_message_id:typeof r.type_data?.promoted_message_id=="string"?r.type_data.promoted_message_id:void 0,promoted_event_id:typeof r.type_data?.promoted_event_id=="string"?r.type_data.promoted_event_id:void 0}}).sort((r,s)=>r.queue_seq-s.queue_seq||r.created_at.localeCompare(s.created_at))}async function fs(e,t,n){try{let r=await x("list",{path:e,limit:t,offset:n}),s=gr(r);for(let i of s)N().setQueryData(E.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 ps(e){let n=await x("types-list",e?{scope_id:e}:{}),r=n.content?.items||n.items||[],s=new Map;for(let i of r){let o=i.name,a=i.type_data;!o||!a||s.set(o,{type_key:o,display_name:a.display_name||o,display_name_plural:a.display_name_plural||o+"s",icon:a.icon||"File",color:a.color||"gray",description:a.description||"",input_schema:a.input_schema||{},system_schema:a.system_schema||{},json_schema:a.input_schema||a.json_schema||{},default_data:a.default_data||{},field_defaults:a.field_defaults||{},renderer_config:a.renderer_config||{},is_system:a.is_system??!1,is_active:a.is_active??!0,is_container:a.is_container??!1,is_scope:a.is_scope??!1,render_mode:a.render_mode||"none",placement_mode:a.placement_mode,direct_parent_types:a.direct_parent_types,allowed_parent_types:a.allowed_parent_types,governed_create:a.governed_create,create_method:a.create_method,dedup:a.dedup,edges:a.edges,events:a.events})}return s}async function ms(e){try{let t=await x("edges",{item_id:e}),n=t.outgoing||[],r=t.incoming||[],s=[];for(let i of n)s.push({id:i.edge_id||ac(),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||ac(),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 gs(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 x("tree",s),o=gr(i);for(let a of o)N().setQueryData(E.item(a.path),a);return o}catch(s){return console.error(`[gateway] Failed to fetch tree at ${e}:`,s),[]}}async function hs(e,t=50,n=0){try{let r=await x("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 vr(e,t={}){let{limit:n=50,offset:r=0,include_snapshots:s=!1}=t;try{let i=await x("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 ys(e,t=50,n=0){return vr(e,{limit:t,offset:n})}async function _s(e,t,n){try{let r={scope_id:e};t?.length&&(r.item_types=t),n&&(r.limit=n);let s=await x("member-focus",r),i=gr(s);for(let o of i)N().setQueryData(E.item(o.path),o);return i}catch(r){return console.error(`[gateway] Failed to fetch member focus for scope ${e}:`,r),[]}}async function br(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 x("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}}function qn(e){return!!e&&(!!e.type||Array.isArray(e.any_of)&&e.any_of.length>0)}function wd(e){let t={};e.item_type&&(t.item_type=e.item_type);for(let[n,r]of Object.entries(e.fields??{}))t[`field.${n}`]=String(r);for(let[n,r]of Object.entries(e.field_in??{}))t[`field_in.${n}`]=r.map(String);return t}var Sd=["catalog","parent_only","internal"];function uc(e,t={}){if(!e||typeof e!="object")return null;let n=o=>typeof o=="string"||typeof o=="number"||typeof o=="boolean",r=o=>{let a={},c={};for(let[u,l]of Object.entries(o))u.startsWith("field.")&&u.length>6&&n(l)?a[u.slice(6)]=l:u.startsWith("field_in.")&&u.length>9&&Array.isArray(l)&&(c[u.slice(9)]=l.filter(n));return{fields:a,field_in:c}},s={};typeof e.type=="string"&&e.type&&(s.type=e.type),typeof e.sort_by=="string"&&(s.sort_by=e.sort_by),(e.sort_dir==="asc"||e.sort_dir==="desc")&&(s.sort_dir=e.sort_dir),typeof e.name=="string"&&e.name&&(s.name=e.name),typeof e.tag=="string"&&e.tag&&(s.tag=e.tag),typeof e.discovery=="string"&&Sd.includes(e.discovery)&&(s.discovery=e.discovery);let i=r(e);if(Object.keys(i.fields).length&&(s.fields=i.fields),Object.keys(i.field_in).length&&(s.field_in=i.field_in),Array.isArray(e.any_of)){let o=[];for(let a of e.any_of){if(!a||typeof a!="object"||Array.isArray(a))continue;let c=a,u={};typeof c.item_type=="string"&&c.item_type&&(u.item_type=c.item_type);let l=r(c);Object.keys(l.fields).length&&(u.fields=l.fields),Object.keys(l.field_in).length&&(u.field_in=l.field_in),Object.keys(u).length&&o.push(u)}o.length&&(s.any_of=o)}return qn(s)?{...s,...t}:null}async function Vt(e,t={}){if(e=bt(e),e.spaceIds?.length===0)return{items:[],total_hint:0};let n={};e.type&&(n.item_type=e.type),e.scope&&(n.scope_path=e.scope);let r={};if(e.spaceIds!==void 0&&(r.space_ids=e.spaceIds),e.name&&(r.name=e.name),e.tag&&(r.tag=e.tag),e.parent_id&&(r.parent_id=e.parent_id),e.sort_by&&(r.sort_by=e.sort_by),e.sort_dir&&(r.sort_dir=e.sort_dir),e.offset!=null&&(r.offset=e.offset),e.fields)for(let[s,i]of Object.entries(e.fields))r[`field.${s}`]=String(i);if(e.field_in)for(let[s,i]of Object.entries(e.field_in))r[`field_in.${s}`]=i.map(String);e.discovery&&(r.discovery=e.discovery),e.any_of?.length&&(r.any_of=e.any_of.map(wd)),Object.keys(r).length>0&&(n.filters=r),e.limit!=null&&(n.limit=e.limit);try{let s=await x("query",n,t);e.spaceIds!==void 0&&Va(e.spaceIds,s.selected_space_ids??s.content?.selected_space_ids);let i=gr(s);for(let o of i)N().setQueryData(E.item(o.path),o);return{items:i,total_hint:s.total??s.content?.total??i.length}}catch(s){if(t.signal?.aborted||s instanceof Error&&s.name==="AbortError"||(console.error(`[gateway] Failed to fetch items of type ${e.type??"(any_of)"}:`,s),t.throwOnError||e.spaceIds!==void 0))throw s;return{items:[],total_hint:0}}}function xd(e){if(!e||typeof e!="object")return;let t=e;if(t.version!==1||typeof t.work_id!="string"||!t.work_id)return;let n=r=>{let s=t[r];return typeof s=="string"&&s?s:void 0};return{version:1,workId:t.work_id,threadRootId:n("thread_root_id"),requestMessageId:n("request_message_id"),replyMessageId:n("reply_message_id"),replyMessagePath:n("reply_message_path"),todoListId:n("todo_list_id"),todoListPath:n("todo_list_path"),stepId:n("step_id"),stepPath:n("step_path"),runId:n("run_id"),parentRunId:n("parent_run_id"),toolCallId:n("tool_call_id"),traceId:n("trace_id")}}function lc(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,origin:xd(n.origin),presentationRole:r.presentation_role==="user-request"?"user-request":r.presentation_role==="output"?"output":void 0}}).sort((t,n)=>t.createdAt.localeCompare(n.createdAt))}function mr(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,status:typeof n.status=="string"?n.status:void 0,delivery_state:typeof n.delivery_state=="string"?n.delivery_state:void 0,cognition_event_id:typeof n.cognition_event_id=="string"?n.cognition_event_id:void 0,seq:n.seq||0,principal_id:n.principal_id,member_id:typeof n.member_id=="string"?n.member_id:void 0,reply_count:n.reply_count||0,member_count:n.member_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 dc(e,t){try{let n={channel_path:e};t&&(n.parent_message_id=t);let s=await x("get-channel-messages",n),i=s.messages||s.content?.items||s.items||[];return mr(i)}catch(n){throw console.error(`[gateway] Failed to fetch channel messages for ${e}:`,n),n}}async function vs(e,t){try{let n={channel_path:e};t&&(n.parent_message_id=t);let s=await x("get-channel-messages",n),i=s.messages||[],o=mr(i),a=lc(i),c=new Map,u=[];for(let l of a)if(l.parentMessagePath){let f=c.get(l.parentMessagePath)||[];f.push(l),c.set(l.parentMessagePath,f)}else u.push(l);return{messages:o,activityMessages:mr(s.activity_messages||[]),messageCards:c,siblingCards:u,mode:s.mode||"top_level"}}catch(n){throw console.error(`[gateway] Failed to fetch channel messages with cards for ${e}:`,n),n}}async function wr(e,t){try{let n={channel_path:e};t?.parentMessageId&&(n.parent_message_id=t.parentMessageId),t?.conversationsOnly&&(n.conversations_only=!0),t?.transcriptOnly&&(n.transcript_only=!0),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 x("get-channel-messages",n);if(t?.conversationsOnly&&s.conversations_only!==!0)throw new Error("This server does not support conversation history lists yet. Update the message reader.");if(t?.transcriptOnly&&s.transcript_only!==!0)throw new Error("This server does not support channel transcript pages yet. Update the message reader.");let i=s.messages||[],o=lc(i),a=new Map,c=[];for(let u of o)if(u.parentMessagePath){let l=a.get(u.parentMessagePath)||[];l.push(u),a.set(u.parentMessagePath,l)}else c.push(u);return{messages:mr(i),activityMessages:mr(s.activity_messages||[]),messageCards:a,siblingCards:c,mode:s.mode||"top_level"}}catch(n){throw console.error(`[gateway] Failed to fetch channel messages page for ${e}:`,n),n}}function ds(e){N().invalidateQueries({queryKey:E.children(e)})}function Oi(e){N().invalidateQueries({queryKey:E.item(e)})}function fc(e,t){Oi(e),ds(e);let n=e.split("/");n.pop();let r=n.join("/")||t;r&&ds(r)}function pc(e){let t=e+"/";N().invalidateQueries({predicate:n=>{let r=n.queryKey;return r[0]!=="vfs"?!1:r.some(s=>typeof s=="string"&&(s===e||s.startsWith(t)))}})}function mc(){N().invalidateQueries({queryKey:E.all()})}function gc(e){N().invalidateQueries({queryKey:E.types(e)})}function hc(e,t){e?N().invalidateQueries({queryKey:E.channelMessages(e,t)}):N().invalidateQueries({queryKey:E.allChannelMessages()})}function yc(e,t){e&&t?N().invalidateQueries({queryKey:E.openEnvelope(e,t)}):e?N().invalidateQueries({predicate:n=>{let r=n.queryKey;return r[0]==="vfs"&&r[2]==="open"&&r[3]===e}}):N().invalidateQueries({queryKey:E.allOpenEnvelopes()})}function $e(e){return{id:e.accountId,path:e.path,kind:e.isSpace?"space":"account",name:e.name,grantedUnderAccountId:e.grantedUnderAccountId??void 0}}async function bs(){return((await x("list-memberships",{})).memberships||[]).map(n=>({accountId:n.account_id,path:n.account_path,name:n.account_name,role:n.role||"member",typeData:n.account_type_data||{},joinedAt:n.joined_at,via:n.via,placement:n.placement,subordinateTo:n.subordinate_to??null,cascadeAnchorId:n.cascade_anchor_id??null,isAccount:n.is_account??void 0,isSpace:n.is_space??void 0,isOwner:n.is_owner??void 0,billingResponsible:n.billing_responsible??void 0,grantedVia:n.granted_via??null,invitationAccepted:n.invitation_accepted===!0,grantedUnderAccountId:n.granted_under_account_id??null,membershipPath:n.membership_path??null,personalSpaceId:n.personal_space_id??null,personalSpacePath:n.personal_space_path??null}))}var Nn=new Map,xr=null,ws=null,St=new Map,_c=250,Sr=new Map;function Wt(e){if(xr){Qn(e);return}Qn(e),xr=ie("vfs_change",t=>Rd(t)),ws=ie("ccm_change",t=>Pd(t))}function Qn(e){if(Nn.has(e))return;let t=Fn(e,["vfs_change","ccm_change"]);Nn.set(e,t)}function Ss(e){let t=Nn.get(e);t&&(t(),Nn.delete(e))}function Fi(){for(let[,e]of Nn)e();Nn.clear(),xr&&(xr(),xr=null),ws&&(ws(),ws=null),St.forEach(e=>clearTimeout(e)),St.clear(),Sr.clear()}se(Fi);function Rd(e){let t=e.path,n=e.action;if(!t)return;let r=t.split("/");r.pop();let s=r.join("/")||"/root",i=Sr.get(s);i||(i=new Map,Sr.set(s,i)),i.set(t,{action:n,itemId:typeof e.item_id=="string"?e.item_id:void 0});let o=St.get(s);o&&clearTimeout(o);let a=setTimeout(()=>{St.delete(s);let c=Sr.get(s);Sr.delete(s),c&&Cd(s,c)},_c);St.set(s,a)}function Pd(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)||!t&&!n||e.item_type==="message")return;let s=`ccm:${t??""}:${n??""}`,i=St.get(s);i&&clearTimeout(i);let o=setTimeout(()=>{St.delete(s),t&&N().invalidateQueries({queryKey:E.edges(t)}),n&&N().invalidateQueries({queryKey:E.edges(n)})},_c);St.set(s,o)}function Cd(e,t){let n=N();for(let[s,i]of t)(i.action||"").toUpperCase()==="DELETE"?(n.removeQueries({queryKey:E.item(s)}),n.removeQueries({queryKey:E.children(s)}),n.removeQueries({queryKey:E.tree(s)})):be(n,E.item(s),{exact:!0}),i.itemId&&n.invalidateQueries({queryKey:E.itemById(i.itemId)});n.invalidateQueries({queryKey:E.children(e)});let r=[...t.keys()];n.invalidateQueries({predicate:s=>{let i=s.queryKey;if(i[0]!=="vfs"||i[1]!=="tree")return!1;let o=i[2];return r.some(a=>a.startsWith(o+"/")||a===o)}})}var Dn=null;se(()=>{Dn=null});function xt(e){if(e!==Dn||e.generation!==ae())throw new Error("Workspace session changed")}function Ed(e){return e instanceof ge&&e.payload?.error==="item_not_found"}function Rr(e,t){let n=e.resolve(t.id);if(!n||n.path!==t.path||n.kind!==t.kind)throw new Error("Mount is not an available membership");return n}function Pr(e){let t=me();if(!t)throw new Error("Elect a home account before loading mounts");return[t,...e.filter((n,r)=>n.id!==t.id&&e.findIndex(s=>s.id===n.id)===r)]}function vc(e,t){return JSON.stringify({mounts:e.map(n=>n.id),last_anchor:t.id})}async function bc(e,t,n){xt(e);let r=vc(t,n);if(e.saved===r)return;let s=JSON.parse(r);await x(e.exists?"update":"create",e.exists?{_scope_path:e.scope,path:e.path,type_data:s}:{_scope_path:e.scope,parent_path:e.path.slice(0,e.path.lastIndexOf("/")),name:"mounts",item_type:"file",type_data:s}),xt(e),e.exists=!0,e.saved=r}function wc(e,t){let n=Ae();Wt(me().id);for(let r of n)e.some(s=>s.id===r.id)||Ss(r.id);for(let r of e)Qn(r.id);la(e,t)}async function Gt(e,t,n={}){let r=me();if(!r)throw new Error("Elect a home account before loading mounts");let s=`${e}/settings/mounts`;if(Dn&&Dn.path!==s)throw new Error("Reset the session before changing the mount declaration owner");let i=Dn??(Dn={generation:ae(),path:s,scope:r.path,resolve:t,exists:!1,ready:!1,saved:null,queue:Promise.resolve()});return xt(i),i.resolve=t,i.loading?i.loading:i.ready?Ae():(i.loading=(async()=>{let o=null;try{let l=await x("read",{path:s,_scope_path:i.scope});if(xt(i),o=l.type_data??l.item?.type_data,!o||!Array.isArray(o.mounts)||!o.mounts.every(f=>typeof f=="string"))throw new Error("Invalid saved mount declaration");i.exists=!0}catch(l){if(xt(i),!Ed(l))throw l;i.exists=!1}let a=n.initialAnchor?Rr(i,n.initialAnchor):r,c=Pr(o?o.mounts.map(l=>i.resolve(l)).filter(l=>l!==null):[a]),u=o?c.find(l=>l.id===o.last_anchor)??c.find(l=>l.kind==="space")??r:a;return o?i.saved=vc(c,u):n.initialAnchor&&await bc(i,c,u),xt(i),i.ready=!0,wc(c,u),c})().finally(()=>{i.loading=void 0}),i.loading)}function xs(e){let t=Dn;if(!t?.ready)return Promise.reject(new Error("Workspace mounts are not loaded"));let n=t.queue.then(async()=>{xt(t);let{refs:r,anchor:s}=e(t);await bc(t,r,s),xt(t),wc(r,s)});return t.queue=n.catch(()=>{}),n}function qi(e){return xs(t=>({refs:Pr([...Ae(),Rr(t,e)]),anchor:de()}))}function Sc(e){return xs(()=>{if(e===me().id)throw new Error("The home account cannot be unmounted");let t=Pr(Ae().filter(r=>r.id!==e)),n=t.find(r=>r.id===de()?.id)??t.find(r=>r.kind==="space")??me();return{refs:t,anchor:n}})}function Cr(e){return xs(t=>{let n=Rr(t,e);return{refs:Pr([...Ae(),n]),anchor:n}})}function Rs(e,t){return xs(n=>{let r=Pr(e.map(i=>Rr(n,i))),s=Rr(n,t);if(!r.some(i=>i.id===s.id))throw new Error("Selected mount must be in the working set");return{refs:r,anchor:s}})}var Ni={};co(Ni,{Badge:()=>Od,Breadcrumbs:()=>Bd,Button:()=>qd,Card:()=>Md,DataView:()=>Qd,Detail:()=>Kd,Empty:()=>Nd,FilePreview:()=>Wd,Form:()=>Ud,Grid:()=>Ad,Image:()=>$d,Link:()=>Hd,Page:()=>Id,Router:()=>Ld,Sidebar:()=>kd,Spinner:()=>Fd,Stack:()=>Td,Table:()=>Dd,Tabs:()=>jd,Video:()=>Vd});var G=Y(ue(),1);function xc(){return(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||""}function Id(e){return(0,G.createElement)("div",{style:{minHeight:"100vh",display:"flex",flexDirection:"column"},className:e.className||""},e.children)}function Td(e){let t=e.direction||"vertical";return(0,G.createElement)("div",{style:{display:"flex",flexDirection:t==="horizontal"?"row":"column",gap:e.gap||"0.5rem",padding:e.padding||"0",alignItems:e.align||"stretch",justifyContent:e.justify||"flex-start",flex:e.flex||"initial"},className:e.className||""},e.children)}function Ad(e){return(0,G.createElement)("div",{style:{display:"grid",gridTemplateColumns:"repeat("+(e.columns||3)+", 1fr)",gap:e.gap||"1rem",padding:e.padding||"0"},className:e.className||""},e.children)}function kd(e){return(0,G.createElement)("div",{style:{display:"flex",flexDirection:"row",minHeight:"100vh"},className:e.className||""},e.children)}function Md(e){return(0,G.createElement)("div",{style:{border:"1px solid var(--color-border, #e5e7eb)",borderRadius:"var(--border-radius, 0.5rem)",padding:e.padding||"1rem",background:"var(--color-surface, #fff)"},className:e.className||"",onClick:e.onClick},e.children)}function Od(e){return(0,G.createElement)("span",{style:{display:"inline-flex",alignItems:"center",padding:"0.125rem 0.5rem",fontSize:"0.75rem",fontWeight:"500",borderRadius:"9999px",background:e.color||"#e5e7eb",color:e.textColor||"#374151"},className:e.className||""},e.children||e.label)}function Fd(e){let t=e.size||"1.5rem";return(0,G.createElement)("div",{style:{width:t,height:t,border:"2px solid #e5e7eb",borderTopColor:"var(--color-primary, #3b82f6)",borderRadius:"50%",animation:"fsaos-spin 0.6s linear infinite"}})}function qd(e){return(0,G.createElement)("button",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",padding:"0.5rem 1rem",fontSize:"0.875rem",fontWeight:"500",borderRadius:"var(--border-radius, 0.375rem)",border:e.variant==="outline"?"1px solid var(--color-border, #d1d5db)":"none",background:e.variant==="outline"||e.variant==="ghost"?"transparent":"var(--color-primary, #3b82f6)",color:e.variant==="outline"||e.variant==="ghost"?"var(--color-text, #1a1a1a)":"#fff",cursor:e.disabled?"not-allowed":"pointer",opacity:e.disabled?"0.5":"1",gap:"0.5rem"},className:e.className||"",onClick:e.onClick,disabled:e.disabled},e.children||e.label)}function Nd(e){return(0,G.createElement)("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:"3rem",color:"var(--color-text-secondary, #6b7280)",textAlign:"center"}},e.icon?(0,G.createElement)("div",{style:{fontSize:"2rem",marginBottom:"0.5rem"}},e.icon):null,(0,G.createElement)("div",{style:{fontWeight:500,marginBottom:"0.25rem"}},e.title||e.message||e.children||"No items"),e.description?(0,G.createElement)("div",{style:{fontSize:"0.875rem",opacity:.7}},e.description):null)}function Qd(e){return(0,G.createElement)("div",{className:e.className||""},e.children)}function Dd(e){return(0,G.createElement)("table",{className:e.className||""},e.children)}function Ud(e){return(0,G.createElement)("form",{className:e.className||"",onSubmit:e.onSubmit},e.children)}function Kd(e){return(0,G.createElement)("div",{className:e.className||""},e.children)}function Ld(e){return(0,G.createElement)("div",null,e.children)}function Hd(e){return(0,G.createElement)("a",{href:e.href||e.to,className:e.className||"",onClick:e.onClick},e.children)}function jd(e){return(0,G.createElement)("div",{className:e.className||""},e.children)}function Bd(e){return(0,G.createElement)("nav",{className:e.className||""},e.children)}function $d(e){return(0,G.createElement)("img",{src:e.src||(e.path?xc()+e.path:""),alt:e.alt||"",className:e.className||"",style:e.style})}function Vd(e){return(0,G.createElement)("video",{src:e.src||(e.path?xc()+e.path:""),controls:!0,className:e.className||""})}function Wd(e){return(0,G.createElement)("div",{className:e.className||""},e.children||"File preview")}function Ps(e){if(typeof e.path!="string")return!1;let t=[...Ae().map(n=>n.path),de()?.path].filter(n=>!!n);return!t.length&&W()&&t.push(W()),t.some(n=>he(e.path,n))}function Qi(e,t,n,r){if(!["message","card"].includes(e?.item_type)||!he(e.path,t))return!1;if(!n){let s=e.path.slice(t.length).replace(/^\//,""),i=s?s.split("/").length:0;return e.item_type==="message"?i===1:i===1||i===2}return e.item_id===n||e.parent_id===n?!0:r.some(s=>{if(e.item_id===s.id||e.parent_id===s.id)return!0;let i=s.id===n?s.path:s.parent_message_id===n?s.path.slice(0,s.path.lastIndexOf("/")):void 0;return!!i&&he(e.path,i)})}var Rc=new WeakMap;function Pc(e,t,n){let r=Rc.get(e);r||(r=new Map,Rc.set(e,r));let s=JSON.stringify(t),i=r.get(s);if(!i){let a=!1,c,u=!1,l=!1,f=new Set,h=new Set,p=()=>e.getQueryData(t)??[],m=()=>{a||u||c||(c=setTimeout(()=>{c=void 0,y()},250))},y=async()=>{if(a)return;u=!0;let C=l;l=!1;let R=[...f],M=new Set(h);h.clear(),f.clear();try{if(C)await be(e,t,{exact:!0});else{let P=(await Promise.allSettled(R.map(async k=>{let T=e.getQueryCache().find({queryKey:t,exact:!0});if(!T)return;let A=await x("read",{id:k});if(A.success===!1)throw new Error("Channel refresh failed");if(a||!T||e.getQueryCache().find({queryKey:t,exact:!0})!==T)return;let O=Oe(A.item??A);if(O.id!==k||O.item_type!=="channel")return;let q=p().find(Pe=>Pe.id===k);if(!q)return;let K=n({...O}),$={...q,path:K.path,name:K.name,displayName:K.displayName,messageCount:K.messageCount,aiMode:K.aiMode,activeAgentIds:K.activeAgentIds,isPrivate:K.isPrivate,isDm:K.isDm,autoPilot:K.autoPilot,isArchived:K.isArchived,updatedAt:K.updatedAt};M.has(k)&&(q.name!==$.name||q.displayName!==$.displayName||q.path!==$.path)&&(l=!0),e.setQueryData(t,Pe=>Pe?.map(re=>re.id===k?$:re))}))).find(k=>k.status==="rejected");if(P?.status==="rejected")throw P.reason}}catch(D){console.warn("[channels] refresh failed",D)}finally{u=!1,(l||f.size)&&m()}},g=C=>p().some(R=>R.id===C.item_id||R.path===C.path)?!0:Ps(C),v=C=>{if(!g(C))return;let R=String(C.action??"").toLowerCase();if(["insert","delete","rename","move"].includes(R))l=!0;else if(R==="update"){let M=p().find(D=>D.id===C.item_id||D.path===C.path);M&&(f.add(M.id),h.add(M.id))}(l||f.size)&&m()},_=C=>{let R=p().find(M=>M.id===C.parent_id);R&&(f.add(R.id),m())},w=["vfs_change","ccm_change"].flatMap(C=>[ie(C,v,R=>R.item_type==="channel"),ie(C,_,R=>R.item_type==="message")]);i={users:0,stop:()=>{a=!0,c&&clearTimeout(c),w.forEach(C=>C())}},r.set(s,i)}i.users++;let o=!1;return()=>{o||(o=!0,--i.users===0&&(i.stop(),r.delete(s)))}}function te(){return(0,b.useSyncExternalStore)(xe,ee,ee)}function Mc(){return te(),zr()}function Oc(e){return te(),B({queryKey:E.item(e),queryFn:()=>yr(e),enabled:!!e,staleTime:1/0})}function Fc(e){return te(),B({queryKey:E.itemById(e),queryFn:()=>hr(e),enabled:!!e,staleTime:1/0})}function Ki(e){return te(),B({queryKey:E.children(e),queryFn:()=>_r(e),enabled:!!e})}function qc(e){let t=Ki(e);return{...t,children:t.data??[]}}function Nc(e,t=1){return te(),B({queryKey:E.tree(e,t),queryFn:()=>gs(e,t),enabled:!!e})}function Qc(e,t){return te(),B({queryKey:E.search(e,t),queryFn:async()=>{let n={query:e};t?.length&&(n.item_types=t);let r=await x("search",n);return(r.content?.items||r.items||r.results||[]).map(Oe)},enabled:!!e&&e.length>0})}function Dc(e){te();let t=(0,b.useMemo)(()=>e,[JSON.stringify(e)]);return B({queryKey:["vfs",W()??"__unscoped__","resolve",JSON.stringify(t??{})],queryFn:async()=>await x("resolve",t),enabled:!!t?.query&&t.query.length>0})}function Uc(e){te();let t=bt(e),n=(0,b.useMemo)(()=>t,[JSON.stringify(t)]),r=B({queryKey:E.items(n?.type??"",n),queryFn:({signal:s})=>Vt(n,{signal:s,throwOnError:!0}),enabled:qn(n),...n?.spaceIds!==void 0?{retry:(s,i)=>!In(i)&&Mu(s,i)}:{},select:s=>s.items});return n?.spaceIds!==void 0&&In(r.error)?{...r,data:void 0}:r}function Li(e,t={}){let n=te(),{realtime:r=!1}=t,s=bt(e),i=s?.limit??20,o=(0,b.useMemo)(()=>s,[JSON.stringify(s)]),a=(0,b.useMemo)(()=>["vfs",W()??"__unscoped__","infinite-items",o?.type??"",JSON.stringify(o??{})],[n,o]),c=or({queryKey:a,queryFn:async({pageParam:f=0,signal:h})=>Vt({...o,limit:i,offset:f},{throwOnError:!0,signal:h,priority:t.priority}),initialPageParam:0,getNextPageParam:(f,h,p)=>{if(!(o?.spaceIds!==void 0&&f.total_hint!==void 0&&p+f.items.length>=f.total_hint)&&!(f.items.length<i))return p+f.items.length},enabled:qn(o),...o?.spaceIds!==void 0?{retry:(f,h)=>!In(h)&&Mu(f,h)}:{},staleTime:r?1/0:t.staleTime,meta:r&&o?{infiniteItemsRealtime:{filter:o}}:{}}),u=(0,b.useMemo)(()=>{if(o?.spaceIds!==void 0&&In(c.error))return[];if(!c.data?.pages)return[];let f=new Set,h=[];for(let p of c.data.pages)for(let m of p.items)m.id&&!f.has(m.id)&&(f.add(m.id),h.push(m));return h},[c.data?.pages,c.error,o]),l=o?.spaceIds!==void 0&&In(c.error);return{allItems:u,refetch:c.refetch,fetchNextPage:c.fetchNextPage,isFetchingNextPage:c.isFetchingNextPage,isExhausted:l||!c.hasNextPage,isLoading:c.isLoading,isFetching:c.isFetching,error:c.error,totalHint:l?void 0:c.data?.pages?.[0]?.total_hint}}function Cc(e){return!!e?.type&&!!e.scope&&e.sort_by==="created_at"&&!e.offset&&!e.spaceIds&&!e.any_of&&!e.name&&!e.tag&&!e.discovery}function Jd(e,t){if(e.is_active===!1||e.item_type!==t.type||!he(e.path,t.scope)||t.parent_id&&e.parent_id!==t.parent_id)return!1;let n=e.type_data??{};for(let[r,s]of Object.entries(t.fields??{})){let i=n[r];if(typeof s=="string"&&s.endsWith("*")){if(typeof i!="string"||!i.startsWith(s.slice(0,-1)))return!1}else if(i!==s)return!1}for(let[r,s]of Object.entries(t.field_in??{}))if(!s.includes(n[r]))return!1;return!0}function Kc(e,t={}){let n=Cc(e),r=Li(e,n?{realtime:!1,staleTime:3e4}:{realtime:!0}),s=L(),i=JSON.stringify([W(),bt(e)]),[o,a]=(0,b.useState)(()=>({identity:i,upserts:{},deleted:new Set})),c=o.identity===i?o:{identity:i,upserts:{},deleted:new Set},u=(0,b.useMemo)(()=>{if(!n)return r.allItems;let p=Object.values(c.upserts),m=new Set(p.map(_=>_.id)),y=[...p,...r.allItems.filter(_=>!m.has(_.id))].filter(_=>!c.deleted.has(_.path)),g=e.sort_by??"updated_at",v=e.sort_dir==="asc"?1:-1;return y.sort((_,w)=>v*String(_[g]??"").localeCompare(String(w[g]??"")))},[n,r.allItems,c,e?.sort_by,e?.sort_dir]),l=(0,b.useRef)(u);l.current=u;let f=(0,b.useRef)(t.shouldReadUpdate);f.current=t.shouldReadUpdate;let h=(0,b.useRef)(r.refetch);return h.current=r.refetch,(0,b.useEffect)(()=>{if(!Cc(e))return;let p=e,m=!1,y=!1,g=!1,v=0,_=new Map,w=()=>{let P=v;h.current().then(k=>{!m&&!k.isError&&v===P&&a({identity:i,upserts:{},deleted:new Set})})},C=P=>{v++,a(T=>{let A=T.identity===i?T:{identity:i,upserts:{},deleted:new Set},O={...A.upserts};return delete O[P],{identity:i,upserts:O,deleted:new Set(A.deleted).add(P)}});let k=_.get("__reconcile__");k&&clearTimeout(k),_.set("__reconcile__",setTimeout(()=>{_.delete("__reconcile__"),w()},250))},R=P=>{let k=_.get(P);k&&clearTimeout(k),_.set(P,setTimeout(()=>{_.delete(P),s.fetchQuery({queryKey:E.item(P),queryFn:()=>yr(P),staleTime:0}).then(T=>{if(!m){if(!T||!Jd(T,p)){let A=l.current.find(O=>O.path===P||O.id===T?.id);A&&C(A.path);return}a(A=>{let O=A.identity===i?A:{identity:i,upserts:{},deleted:new Set},q=new Set(O.deleted);return q.delete(P),{identity:i,upserts:{...O.upserts,[P]:T},deleted:q}})}}).catch(T=>console.warn("[useIncrementalItems] item read failed:",T))},250))},M=ie("vfs_change",P=>{if(!P||typeof P.path!="string"&&typeof P.old_path!="string")return;let k=typeof P.path=="string"?P.path:P.old_path,T=l.current.find(O=>O.path===k||O.path===P.old_path||P.item_id&&O.id===P.item_id),A=!!T;if(!(!he(k,p.scope)&&!he(P.old_path,p.scope)&&!A)&&!(P.item_type&&P.item_type!==p.type&&!A)&&!(p.parent_id&&P.parent_id&&P.parent_id!==p.parent_id&&!A)){if(T&&(k!==T.path||P.old_path&&P.old_path!==k||P.parent_id&&P.parent_id!==T.parent_id||P.item_type&&P.item_type!==p.type)){C(T.path);return}if(!T&&P.old_path&&P.old_path!==k&&he(k,p.scope)){v++,R(k);return}if(P.action==="insert")v++,R(k);else if(P.action==="move")v++,R(k);else if(P.action==="update"){if(!f.current?.(P,l.current))return;v++,R(k)}else P.action==="delete"&&C(T?.path??P.old_path??k)}}),D=ls(P=>{if(P!=="connected"){y&&(g=!0);return}y=!0,g&&(g=!1,w())});return()=>{m=!0,M(),D(),_.forEach(clearTimeout)}},[s,i]),{...r,allItems:u}}function Lc(e){te();let t=20,n=or({queryKey:["vfs",W()??"__unscoped__","infinite-children",e??""],queryFn:async({pageParam:s=0})=>fs(e,t,s),initialPageParam:0,getNextPageParam:(s,i,o)=>{if(!(s.items.length<t))return o+s.items.length},enabled:!!e});return{allItems:(0,b.useMemo)(()=>{if(!n.data?.pages)return[];let s=new Set,i=[];for(let o of n.data.pages)for(let a of o.items)a.id&&!s.has(a.id)&&(s.add(a.id),i.push(a));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 Hc(e){return te(),B({queryKey:E.edges(e),queryFn:()=>ms(e),enabled:!!e})}function Es(e){return te(),B({queryKey:E.types(e),queryFn:()=>ps(e)})}function jc(e,t){let n=Es(t);return{...n,data:n.data?.get(e)??void 0}}function Bc(e,t){te();let n=(0,b.useMemo)(()=>t?.arguments,[JSON.stringify(t?.arguments)]),r=t?.mode,s=t?.strategy,i=t?.width;return B({queryKey:[...E.openEnvelope(e,s),i],queryFn:async()=>{let o=await br(e,{mode:r,strategy:s,arguments:n});if(i&&o.render?.props?.url){let a=o.render.props.url,c=a.includes("?")?"&":"?";o.render.props.url=`${a}${c}w=${i}`}return o},enabled:!!e})}var Ec={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 $c(e){let t=Es(e),n=t.data??new Map;return(0,b.useMemo)(()=>({canHaveChildren:p=>n.get(p.item_type)?.is_container??!1,isScope:p=>n.get(p.item_type)?.is_scope??!1,isScopeType:p=>n.get(p)?.is_scope??!1,isContainerType:p=>n.get(p)?.is_container??!1,getTypeDefinition:p=>n.get(p),getTypeColor:p=>n.get(p)?.color??"gray",getTypeIcon:p=>n.get(p)?.icon??"File",getTypeDisplayName:p=>n.get(p)?.display_name??p,getKnownEdgeTypes:()=>Object.entries(Ec).map(([p,m])=>({key:p,label:m})),getEdgeTypeLabel:p=>Ec[p]??p.replace(/_/g," "),allTypes:n,loading:t.isLoading}),[n,t.isLoading])}function Vc(e,t,n){return te(),B({queryKey:E.memberFocus(e),queryFn:()=>_s(e,t,n),enabled:!!e})}function Wc(e,t={}){let{limit:n=50,offset:r=0,include_snapshots:s=!1}=t;return B({queryKey:E.itemVersions(e,String(n),String(r),String(s)),queryFn:()=>vr(e,{limit:n,offset:r,include_snapshots:s}),enabled:!!e})}function Gc(e,t=50,n=0){return B({queryKey:E.itemHistory(e,String(t),String(n)),queryFn:()=>ys(e,t,n),enabled:!!e})}function zc(e,t=50,n=0){return te(),B({queryKey:E.recentActivity(e,String(t),String(n)),queryFn:()=>hs(e,t,n),enabled:!!e})}function Jc(){let[e,t]=(0,b.useState)(null),[n,r]=(0,b.useState)(!0),[s,i]=(0,b.useState)(null);return(0,b.useEffect)(()=>{let o=!1;return nt().then(a=>{if(!o){let c=typeof window<"u"&&window.__FSAOS_CONFIG__||{};t({path:a.scope_path,scope_id:a.scope_id,fractal_id:a.fractal_id,instance_name:a.instance_name,display_name:a.display_name,componentPath:c.componentPath||"",isEmbed:!!c.embedToken}),r(!1)}}).catch(a=>{o||(i(a instanceof Error?a:new Error(String(a))),r(!1))}),()=>{o=!0}},[]),{data:e,loading:n,error:s}}var Yd=[];function Ic(){if(typeof window>"u")return!1;let e=window.__FSAOS_CONFIG__?.embedToken;return typeof e=="function"||typeof e=="string"&&e.length>0}function Zd(e){return e.filter(t=>t.placement==="switcher_entry").map(t=>({account:t,mountables:e.filter(n=>n.placement!=="switcher_entry"&&n.subordinateTo===t.accountId)}))}function Yc(){let{user:e}=Is(),t=(0,b.useSyncExternalStore)(pa,vi,vi),n=vt()?.principal_id??null,r=(0,b.useRef)(null),[s,i]=(0,b.useState)(null),[o,a]=(0,b.useState)(null);(0,b.useEffect)(()=>{if(n){a(null);return}if(!e?.id&&!Ic()){a(null);return}let _=!1;return nt().then(w=>{_||w.principal_id||a(new Error("Memberships require an authenticated principal"))}).catch(w=>{_||a(w instanceof Error?w:new Error(String(w)))}),()=>{_=!0}},[n,e?.id,t]);let c=B({queryKey:E.memberships(n??"anonymous"),queryFn:bs,enabled:!!n,staleTime:1e3*60*2}),u=c.data??Yd,l=(0,b.useMemo)(()=>u.filter(_=>_.isAccount!==!1&&!_.isSpace),[u]),f=(0,b.useMemo)(()=>{let _=new Set(l.map(C=>C.accountId)),w=C=>!C.subordinateTo||!_.has(C.subordinateTo);return[...l].sort((C,R)=>Number(w(R))-Number(w(C)))},[l]),h=(0,b.useSyncExternalStore)(xe,ee,ee),p=(0,b.useMemo)(()=>{let _=de();return _?u.find(w=>w.accountId===_.id)??null:null},[h,u]),m=(0,b.useMemo)(()=>Zd(l),[l]);(0,b.useEffect)(()=>{if(!n){r.current=null;return}if(r.current!==n)if(i(null),f.length===1){let _=f[0];me()||Kt($e(_)),Wt(_.accountId),_.personalSpacePath&&Gt(_.personalSpacePath,w=>{let C=u.find(R=>R.accountId===w);return C?$e(C):null}).catch(i),r.current=n}else f.length>1&&(r.current=n)},[n,f,u]);let y=(0,b.useCallback)(async _=>{let w=u.find(M=>M.path===_);if(!w)throw new Error("Account membership is unavailable");let C=$e(w);me()||Kt(C);let R=u.find(M=>M.accountId===me()?.id);if(!R?.personalSpacePath)throw new Error("The home membership has no mount declaration location");await Gt(R.personalSpacePath,M=>{let D=u.find(P=>P.accountId===M);return D?$e(D):null}),await Cr(C),i(null),Wt(w.accountId)},[u]),g=(0,b.useCallback)(async _=>{let w=u.find(C=>C.path===_);if(!w)throw new Error("Scope membership is unavailable");await qi($e(w))},[u]),v=(!!e?.id||Ic())&&!n&&!o;return{accounts:f,switcherAccounts:m,allMemberships:u,currentAccount:p,mountedScope:null,switchAccount:y,mountScope:g,loading:v||c.isLoading,error:o??c.error??s}}function Zc(){te();let e=(0,b.useSyncExternalStore)(Gr,lr,lr),t=(0,b.useMemo)(()=>Ae(),[e]),n=de(),r=(0,b.useMemo)(()=>t.filter(i=>i.kind==="space"&&(n?.kind==="account"||i.id===n?.id)),[t,n]),s=(0,b.useMemo)(()=>r.map(i=>i.id).sort(),[r]);return{mounts:t,selectedSpaces:r,readSpaceIds:s,homeAnchor:me(),anchor:n,setAnchor:Cr,replaceMounts:Rs,mount:qi,unmount:Sc}}function Is(){let[e,t]=(0,b.useState)(null),[n,r]=(0,b.useState)(null),[s,i]=(0,b.useState)(!0),o=(0,b.useRef)(null);(0,b.useEffect)(()=>{V.auth.getSession().then(({data:p,error:m})=>{if(m){console.warn("[useAuth] getSession error, clearing stale session:",m.message),V.auth.signOut().catch(()=>{}),r(null),t(null),i(!1);return}r(p?.session??null),t(p?.session?.user??null),i(!1)}).catch(p=>{console.warn("[useAuth] getSession threw, clearing stale session:",p?.message),V.auth.signOut().catch(()=>{}),r(null),t(null),i(!1)});let{data:{subscription:h}}=V.auth.onAuthStateChange((p,m)=>{if(p==="TOKEN_REFRESHED"&&!m){console.warn("[useAuth] TOKEN_REFRESHED with null session \u2014 signing out"),V.auth.signOut().catch(()=>{}),r(null),t(null),i(!1);return}r(m),t(m?.user??null),i(!1)});return o.current=h,()=>{h?.unsubscribe()}},[]);let a=(0,b.useCallback)(async h=>h.provider?V.auth.signInWithOAuth({provider:h.provider,options:h.redirectTo?{redirectTo:h.redirectTo}:{redirectTo:window.location.href}}):V.auth.signInWithPassword({email:h.email,password:h.password}),[]),c=(0,b.useCallback)(async h=>V.auth.signUp({email:h.email,password:h.password,options:{data:h.metadata||{}}}),[]),u=(0,b.useCallback)(async()=>{await V.auth.signOut(),Cn(),N().clear()},[]),l=(0,b.useCallback)(async h=>{let{error:p}=await V.auth.resetPasswordForEmail(h);if(p)throw p},[]),f=(0,b.useCallback)(async(h,p)=>{let{error:m}=await V.auth.signInWithOtp({email:h,options:p?{emailRedirectTo:p}:{emailRedirectTo:window.location.href}});if(m)throw m},[]);return{user:e,session:n,loading:s,signIn:a,signUp:c,signOut:u,resetPassword:l,signInWithMagicLink:f}}function Xc(e){let[t,n]=(0,b.useState)(null),[r,s]=(0,b.useState)(!1),[i,o]=(0,b.useState)(null);return(0,b.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),x("resolve-asset",{asset_id:e}).then(c=>{c.success&&c.public_url?n({url:c.public_url,id:c.asset_id,name:c.name,mimeType:c.mime_type,width:c.width,height:c.height,sizeBytes:c.size_bytes}):o(new Error(c.error||"Asset not found")),s(!1)}).catch(c=>{o(c instanceof Error?c:new Error(String(c))),s(!1)});else{let u=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"";n({url:u+e}),s(!1)}},[e]),{data:t,loading:r,error:i}}var Cs={};se(()=>{for(let e of Object.keys(Cs))delete Cs[e]});var eu=null;function tu(e){eu=e,typeof window<"u"&&!window.__FSAOS_GATEWAY__&&(window.__FSAOS_GATEWAY__=e)}function Xd(e){switch(e){case"react":return typeof window<"u"&&window.React||b.default;case"react-dom":case"react-dom/client":return typeof window<"u"&&window.ReactDOM||Gd;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}:zd;case"@fsaos/gateway":case"@fsaos/react":case"@ai4b-team/fsaos-gateway-sdk":return typeof window<"u"&&window.__FSAOS_GATEWAY__||eu||{};case"@fsaos/ui":case"@ai4b-team/fsaos-gateway-sdk/ui":return typeof window<"u"&&window.__FSAOS_UI__||Ni;case"@fsaos/theme":return{};default:return console.warn(`[useComponent] Unknown module requested: ${e}`),{}}}var Ir={};async function ef(e){try{let t=await fetch(e);if(!t.ok)return null;let n=await t.text();return!n.trim()||n.includes("No CSS bundle for this component")?null:n}catch{return null}}async function nu(e,t=()=>ef(e)){let n=Ir[e];n||(n=Ir[e]={users:0,text:t(),style:null}),n.users+=1;let r=await n.text;if(Ir[e]!==n||n.users===0||n.style||!r||typeof document>"u")return;let s=document.createElement("style");s.setAttribute("data-fsaos-component-css",e),s.textContent=r,document.head.appendChild(s),n.style=s}function Ve(e){let t=Ir[e];t&&(t.users-=1,!(t.users>0)&&(t.style?.remove(),delete Ir[e]))}function ru(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(`
1
+ /* @fsaos/gateway v2.0.0 — Unified FSAOS Edge Runtime — 2026-11-15T22:37:34.135Z */
2
+ "use strict";var __FSAOS_GATEWAY__=(()=>{var ql=Object.create;var Bn=Object.defineProperty;var Nl=Object.getOwnPropertyDescriptor;var Ql=Object.getOwnPropertyNames;var Dl=Object.getPrototypeOf,Ul=Object.prototype.hasOwnProperty;var ao=e=>{throw TypeError(e)};var Kl=(e,t,n)=>t in e?Bn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var $n=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),co=(e,t)=>{for(var n in t)Bn(e,n,{get:t[n],enumerable:!0})},uo=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Ql(t))!Ul.call(e,s)&&s!==n&&Bn(e,s,{get:()=>t[s],enumerable:!(r=Nl(t,s))||r.enumerable});return e};var Y=(e,t,n)=>(n=e!=null?ql(Dl(e)):{},uo(t||!e||!e.__esModule?Bn(n,"default",{value:e,enumerable:!0}):n,e)),Ll=e=>uo(Bn({},"__esModule",{value:!0}),e);var z=(e,t,n)=>Kl(e,typeof t!="symbol"?t+"":t,n),Ds=(e,t,n)=>t.has(e)||ao("Cannot "+n);var d=(e,t,n)=>(Ds(e,t,"read from private field"),n?n.call(e):t.get(e)),I=(e,t,n)=>t.has(e)?ao("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),S=(e,t,n,r)=>(Ds(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n),F=(e,t,n)=>(Ds(e,t,"access private method"),n);var Vn=(e,t,n,r)=>({set _(s){S(e,t,s,n)},get _(){return d(e,t,r)}});var ue=$n((Qf,lo)=>{lo.exports=React});var Hr=$n((Fm,$o)=>{$o.exports={jsx:React.createElement,jsxs:React.createElement,Fragment:React.Fragment}});var sa=$n((dg,ra)=>{ra.exports={createClient:window.supabase.createClient}});var Fa=$n((Tg,Oa)=>{Oa.exports=ReactDOM});var Ju=$n((Iy,zu)=>{zu.exports=ReactDOM});var io={};co(io,{CHANNEL_AI_MODES:()=>_u,ComponentRenderer:()=>mu,EnforcementDeniedError:()=>Fe,FormSubmissionError:()=>jn,GatewayRequestError:()=>ge,HostSessionUnavailableError:()=>Ht,InteractionTrackingError:()=>Ln,KernelProvider:()=>gu,QueryClientProvider:()=>sr,acceptInvitation:()=>wf,acceptInvite:()=>Ji,answerInput:()=>Xi,assignPersonalSection:()=>El,auth:()=>ol,awaitAnchorReady:()=>ur,awaitScopeReady:()=>ha,callTool:()=>rl,cancelInvitation:()=>xf,cancelQueuedTurn:()=>Wu,cancelTurn:()=>$u,clearCachedToken:()=>fi,clearSession:()=>bi,configureGatewayReads:()=>Ia,connectHostSession:()=>_a,createAgent:()=>Zi,createInvitation:()=>vf,createItem:()=>el,disconnectSSE:()=>Mi,disposeVfsRealtimeWs:()=>Fi,electHomeAnchor:()=>Kt,emitEvent:()=>tc,fetchChannelMessages:()=>dc,fetchChannelMessagesPage:()=>wr,fetchChannelMessagesWithCards:()=>vs,fetchEdgesForItem:()=>ms,fetchItemHistory:()=>ys,fetchItemVersions:()=>vr,fetchItems:()=>Vt,fetchMemberFocus:()=>_s,fetchOpenEnvelope:()=>br,fetchRecentActivity:()=>hs,fetchResolvedItems:()=>to,fetchTimelineHistory:()=>no,fetchTurnQueueEntries:()=>cc,fetchTypeDefinitions:()=>ps,fetchVfsChildren:()=>_r,fetchVfsChildrenPage:()=>fs,fetchVfsItem:()=>yr,fetchVfsItemById:()=>hr,fetchVfsTree:()=>gs,gatewayCall:()=>x,getAccessToken:()=>tt,getAnchor:()=>_t,getAnchorRef:()=>de,getAnchorVersion:()=>gi,getAssetUrl:()=>il,getDefaultSort:()=>gl,getHomeAnchor:()=>me,getInvitation:()=>bf,getMountVersion:()=>lr,getMounts:()=>Ae,getPathSubscriptionState:()=>rc,getQueryClient:()=>N,getRequiredFormFields:()=>hl,getScope:()=>W,getScopeVersion:()=>ee,getServerClockOffsetMs:()=>xa,getServerClockSyncedAt:()=>Ra,getSessionEntry:()=>vt,hasServerClock:()=>Sa,initSession:()=>nt,initVfsRealtimeWs:()=>Wt,initializeFsaos:()=>ju,initializeWorkspace:()=>Ms,interpretSchema:()=>eo,invalidateAllVfs:()=>mc,invalidateChannelMessages:()=>hc,invalidateChildren:()=>ds,invalidateItem:()=>Oi,invalidateOpenEnvelope:()=>yc,invalidatePathAndParent:()=>fc,invalidateSubtree:()=>pc,invalidateTypes:()=>gc,inviteMember:()=>zi,isAnchorReady:()=>yi,isChannelPath:()=>he,isListableItemsFilter:()=>qn,isScopeReady:()=>zr,itemsFilterFromQueryFilter:()=>uc,listChildren:()=>Xu,listInvitations:()=>Pf,loadMounts:()=>Gt,loadPublishedBundle:()=>ou,mount:()=>al,mountRealtimeScope:()=>Qn,normalizeItem:()=>Oe,onConnectionStateChange:()=>ls,pathSubscriptionMatches:()=>Ti,personalSectionsKey:()=>Mr,ping:()=>nc,pushChanges:()=>nl,queryClient:()=>La,readItem:()=>Zu,refreshQuery:()=>be,registerCleanup:()=>se,rejectInvitation:()=>Sf,replaceMounts:()=>Rs,resendInvitation:()=>Rf,resetAllSdkState:()=>Cn,resolvePrincipalId:()=>fu,resubscribePath:()=>ic,seatMember:()=>Yi,selectMount:()=>Cr,serveHostSession:()=>Bu,serverDeadlinePassed:()=>Pa,serverMsUntil:()=>Ca,serverNow:()=>Zr,setAnchor:()=>Pn,setCachedToken:()=>aa,setQueryClient:()=>Ka,setScope:()=>ga,setupRequireShim:()=>cl,signal:()=>sl,startTracking:()=>ks,steerTurn:()=>Vu,submitForm:()=>Gu,subscribeAnchor:()=>hi,subscribeArtifactStream:()=>Os,subscribeMounts:()=>Gr,subscribeScope:()=>xe,subscribeToEvents:()=>ie,subscribeToPath:()=>us,subscribeToScope:()=>Fn,trackAction:()=>Ku,trackEvent:()=>Jt,trackPageView:()=>Uu,unmountRealtimeScope:()=>Ss,updateItem:()=>tl,uploadFile:()=>_l,useAcceptInvite:()=>ll,useAccounts:()=>Yc,useAgentTimeline:()=>Rl,useAllChannels:()=>Ts,useAnswerInput:()=>pl,useArrangement:()=>Kn,useArtifactStream:()=>xl,useAsset:()=>Xc,useAuth:()=>Is,useChannelMessages:()=>hu,useChannels:()=>vu,useChildren:()=>qc,useComponent:()=>Hi,useCreate:()=>Su,useCreateAgent:()=>fl,useDelete:()=>Pu,useDmChannels:()=>bu,useEdges:()=>Hc,useEventStream:()=>Tu,useFileUpload:()=>bl,useIncrementalItems:()=>Kc,useInfiniteChannelMessages:()=>yu,useInfiniteChildren:()=>Lc,useInfiniteItems:()=>Li,useInviteMember:()=>ul,useItem:()=>Oc,useItemById:()=>Fc,useItemHistory:()=>Gc,useItemVersions:()=>Wc,useItems:()=>Uc,useLink:()=>Eu,useList:()=>Ki,useMemberFocus:()=>Vc,useMintedAsset:()=>ku,useMounts:()=>Zc,useMove:()=>Cu,useMutation:()=>Iu,useNotifications:()=>ji,useOpen:()=>Bc,usePermission:()=>uu,usePermissions:()=>lu,usePersonalItemOrder:()=>Ou,usePersonalSections:()=>Tl,usePinnedItems:()=>Cl,usePrincipal:()=>pu,usePublishedComponent:()=>au,useRealtimeQuery:()=>Au,useRecentActivity:()=>zc,useResolve:()=>Dc,useResolvedItems:()=>Sl,useScope:()=>Jc,useScopeReady:()=>Mc,useSearch:()=>Qc,useSeatMember:()=>dl,useTheme:()=>cu,useTimelineHistory:()=>Pl,useTree:()=>Nc,useType:()=>jc,useTypeHelpers:()=>$c,useTypes:()=>Es,useUnreadCounts:()=>wu,useUpdate:()=>xu,useUpdatePrincipal:()=>Ru,vfsKeys:()=>E,waitForPathReady:()=>sc});var Fe=class e extends Error{constructor(n){let r=n.message||e.fallbackMessage(n);super(r);z(this,"name","EnforcementDeniedError");z(this,"deniedBy");z(this,"ruleKey");z(this,"displayName");z(this,"payload");this.payload=n,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 Pt=Y(ue(),1);var Ee=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 It,at,Zt,fo,Hl=(fo=class extends Ee{constructor(){super();I(this,It);I(this,at);I(this,Zt);S(this,Zt,t=>{if(typeof window<"u"&&window.addEventListener){let n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){d(this,at)||this.setEventListener(d(this,Zt))}onUnsubscribe(){var t;this.hasListeners()||((t=d(this,at))==null||t.call(this),S(this,at,void 0))}setEventListener(t){var n;S(this,Zt,t),(n=d(this,at))==null||n.call(this),S(this,at,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){d(this,It)!==t&&(S(this,It,t),this.onFocus())}onFocus(){let t=this.isFocused();this.listeners.forEach(n=>{n(t)})}isFocused(){return typeof d(this,It)=="boolean"?d(this,It):globalThis.document?.visibilityState!=="hidden"}},It=new WeakMap,at=new WeakMap,Zt=new WeakMap,fo),Xt=new Hl;var jl={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},ct,Us,po,Bl=(po=class{constructor(){I(this,ct,jl);I(this,Us,!1)}setTimeoutProvider(e){S(this,ct,e)}setTimeout(e,t){return d(this,ct).setTimeout(e,t)}clearTimeout(e){d(this,ct).clearTimeout(e)}setInterval(e,t){return d(this,ct).setInterval(e,t)}clearInterval(e){d(this,ct).clearInterval(e)}},ct=new WeakMap,Us=new WeakMap,po),De=new Bl;function mo(e){setTimeout(e,0)}var Ls=typeof window>"u"||"Deno"in globalThis;function Z(){}function yo(e,t){return typeof e=="function"?e(t):e}function Wn(e){return typeof e=="number"&&e>=0&&e!==1/0}function Or(e,t){return Math.max(e+(t||0)-Date.now(),0)}function qe(e,t){return typeof e=="function"?e(t):e}function ye(e,t){return typeof e=="function"?e(t):e}function Fr(e,t){let{type:n="all",exact:r,fetchStatus:s,predicate:i,queryKey:o,stale:a}=e;if(o){if(r){if(t.queryHash!==Gn(o,t.options))return!1}else if(!Tt(t.queryKey,o))return!1}if(n!=="all"){let c=t.isActive();if(n==="active"&&!c||n==="inactive"&&c)return!1}return!(typeof a=="boolean"&&t.isStale()!==a||s&&s!==t.state.fetchStatus||i&&!i(t))}function qr(e,t){let{exact:n,status:r,predicate:s,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(Ue(t.options.mutationKey)!==Ue(i))return!1}else if(!Tt(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||s&&!s(t))}function Gn(e,t){return(t?.queryKeyHashFn||Ue)(e)}function Ue(e){return JSON.stringify(e,(t,n)=>Ks(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 $l=Object.prototype.hasOwnProperty;function Hs(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=go(e)&&go(t);if(!r&&!(Ks(e)&&Ks(t)))return t;let i=(r?e:Object.keys(e)).length,o=r?t:Object.keys(t),a=o.length,c=r?new Array(a):{},u=0;for(let l=0;l<a;l++){let f=r?l:o[l],h=e[f],p=t[f];if(h===p){c[f]=h,(r?l<i:$l.call(e,f))&&u++;continue}if(h===null||p===null||typeof h!="object"||typeof p!="object"){c[f]=p;continue}let m=Hs(h,p,n+1);c[f]=m,m===h&&u++}return i===a&&u===i?e:c}function en(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 go(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Ks(e){if(!ho(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!ho(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function ho(e){return Object.prototype.toString.call(e)==="[object Object]"}function _o(e){return new Promise(t=>{De.setTimeout(t,e)})}function zn(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?Hs(e,t):t}function vo(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function bo(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var tn=Symbol();function Nr(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===tn?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function nn(e,t){return typeof e=="function"?e(...t):!!e}function wo(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 Ke=(()=>{let e=()=>Ls;return{isServer(){return e()},setIsServer(t){e=t}}})();function Jn(){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 So=mo;function Vl(){let e=[],t=0,n=a=>{a()},r=a=>{a()},s=So,i=a=>{t?e.push(a):s(()=>{n(a)})},o=()=>{let a=e;e=[],a.length&&s(()=>{r(()=>{a.forEach(c=>{n(c)})})})};return{batch:a=>{let c;t++;try{c=a()}finally{t--,t||o()}return c},batchCalls:a=>(...c)=>{i(()=>{a(...c)})},schedule:i,setNotifyFunction:a=>{n=a},setBatchNotifyFunction:a=>{r=a},setScheduler:a=>{s=a}}}var j=Vl();var rn,ut,sn,xo,Wl=(xo=class extends Ee{constructor(){super();I(this,rn,!0);I(this,ut);I(this,sn);S(this,sn,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(){d(this,ut)||this.setEventListener(d(this,sn))}onUnsubscribe(){var t;this.hasListeners()||((t=d(this,ut))==null||t.call(this),S(this,ut,void 0))}setEventListener(t){var n;S(this,sn,t),(n=d(this,ut))==null||n.call(this),S(this,ut,t(this.setOnline.bind(this)))}setOnline(t){d(this,rn)!==t&&(S(this,rn,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return d(this,rn)}},rn=new WeakMap,ut=new WeakMap,sn=new WeakMap,xo),on=new Wl;function Gl(e){return Math.min(1e3*2**e,3e4)}function js(e){return(e??"online")==="online"?on.isOnline():!0}var Qr=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function Dr(e){let t=!1,n=0,r,s=Jn(),i=()=>s.status!=="pending",o=y=>{if(!i()){let g=new Qr(y);h(g),e.onCancel?.(g)}},a=()=>{t=!0},c=()=>{t=!1},u=()=>Xt.isFocused()&&(e.networkMode==="always"||on.isOnline())&&e.canRun(),l=()=>js(e.networkMode)&&e.canRun(),f=y=>{i()||(r?.(),s.resolve(y))},h=y=>{i()||(r?.(),s.reject(y))},p=()=>new Promise(y=>{r=g=>{(i()||u())&&y(g)},e.onPause?.()}).then(()=>{r=void 0,i()||e.onContinue?.()}),m=()=>{if(i())return;let y,g=n===0?e.initialPromise:void 0;try{y=g??e.fn()}catch(v){y=Promise.reject(v)}Promise.resolve(y).then(f).catch(v=>{if(i())return;let _=e.retry??(Ke.isServer()?0:3),w=e.retryDelay??Gl,C=typeof w=="function"?w(n,v):w,R=_===!0||typeof _=="number"&&n<_||typeof _=="function"&&_(n,v);if(t||!R){h(v);return}n++,e.onFail?.(n,v),_o(C).then(()=>u()?void 0:p()).then(()=>{t?h(v):m()})})};return{promise:s,status:()=>s.status,cancel:o,continue:()=>(r?.(),s),cancelRetry:a,continueRetry:c,canStart:l,start:()=>(l()?m():p().then(m),s)}}var At,Ro,Ur=(Ro=class{constructor(){I(this,At)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Wn(this.gcTime)&&S(this,At,De.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Ke.isServer()?1/0:5*60*1e3))}clearGcTimeout(){d(this,At)!==void 0&&(De.clearTimeout(d(this,At)),S(this,At,void 0))}},At=new WeakMap,Ro);var kt,an,Ie,Mt,oe,Yn,Ot,Se,To,We,Eo,Io=(Eo=class extends Ur{constructor(t){super();I(this,Se);I(this,kt);I(this,an);I(this,Ie);I(this,Mt);I(this,oe);I(this,Yn);I(this,Ot);S(this,Ot,!1),S(this,Yn,t.defaultOptions),this.setOptions(t.options),this.observers=[],S(this,Mt,t.client),S(this,Ie,d(this,Mt).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,S(this,kt,Co(this.options)),this.state=t.state??d(this,kt),this.scheduleGc()}get meta(){return this.options.meta}get promise(){return d(this,oe)?.promise}setOptions(t){if(this.options={...d(this,Yn),...t},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let n=Co(this.options);n.data!==void 0&&(this.setState(Po(n.data,n.dataUpdatedAt)),S(this,kt,n))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&d(this,Ie).remove(this)}setData(t,n){let r=zn(this.state.data,t,this.options);return F(this,Se,We).call(this,{data:r,type:"success",dataUpdatedAt:n?.updatedAt,manual:n?.manual}),r}setState(t,n){F(this,Se,We).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){let n=d(this,oe)?.promise;return d(this,oe)?.cancel(t),n?n.then(Z).catch(Z):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return d(this,kt)}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(t=>ye(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===tn||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>qe(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:!Or(this.state.dataUpdatedAt,t)}onFocus(){this.observers.find(n=>n.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),d(this,oe)?.continue()}onOnline(){this.observers.find(n=>n.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),d(this,oe)?.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),d(this,Ie).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(n=>n!==t),this.observers.length||(d(this,oe)&&(d(this,Ot)||F(this,Se,To).call(this)?d(this,oe).cancel({revert:!0}):d(this,oe).cancelRetry()),this.scheduleGc()),d(this,Ie).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||F(this,Se,We).call(this,{type:"invalidate"})}async fetch(t,n){if(this.state.fetchStatus!=="idle"&&d(this,oe)?.status()!=="rejected"){if(this.state.data!==void 0&&n?.cancelRefetch)this.cancel({silent:!0});else if(d(this,oe))return d(this,oe).continueRetry(),d(this,oe).promise}if(t&&this.setOptions(t),!this.options.queryFn){let c=this.observers.find(u=>u.options.queryFn);c&&this.setOptions(c.options)}let r=new AbortController,s=c=>{Object.defineProperty(c,"signal",{enumerable:!0,get:()=>(S(this,Ot,!0),r.signal)})},i=()=>{let c=Nr(this.options,n),l=(()=>{let f={client:d(this,Mt),queryKey:this.queryKey,meta:this.meta};return s(f),f})();return S(this,Ot,!1),this.options.persister?this.options.persister(c,l,this):c(l)},a=(()=>{let c={fetchOptions:n,options:this.options,queryKey:this.queryKey,client:d(this,Mt),state:this.state,fetchFn:i};return s(c),c})();this.options.behavior?.onFetch(a,this),S(this,an,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==a.fetchOptions?.meta)&&F(this,Se,We).call(this,{type:"fetch",meta:a.fetchOptions?.meta}),S(this,oe,Dr({initialPromise:n?.initialPromise,fn:a.fetchFn,onCancel:c=>{c instanceof Qr&&c.revert&&this.setState({...d(this,an),fetchStatus:"idle"}),r.abort()},onFail:(c,u)=>{F(this,Se,We).call(this,{type:"failed",failureCount:c,error:u})},onPause:()=>{F(this,Se,We).call(this,{type:"pause"})},onContinue:()=>{F(this,Se,We).call(this,{type:"continue"})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0}));try{let c=await d(this,oe).start();if(c===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(c),d(this,Ie).config.onSuccess?.(c,this),d(this,Ie).config.onSettled?.(c,this.state.error,this),c}catch(c){if(c instanceof Qr){if(c.silent)return d(this,oe).promise;if(c.revert){if(this.state.data===void 0)throw c;return this.state.data}}throw F(this,Se,We).call(this,{type:"error",error:c}),d(this,Ie).config.onError?.(c,this),d(this,Ie).config.onSettled?.(this.state.data,c,this),c}finally{this.scheduleGc()}}},kt=new WeakMap,an=new WeakMap,Ie=new WeakMap,Mt=new WeakMap,oe=new WeakMap,Yn=new WeakMap,Ot=new WeakMap,Se=new WeakSet,To=function(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"},We=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,...Bs(r.data,this.options),fetchMeta:t.meta??null};case"success":let s={...r,...Po(t.data,t.dataUpdatedAt),dataUpdateCount:r.dataUpdateCount+1,...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return S(this,an,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),j.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),d(this,Ie).notify({query:this,type:"updated",action:t})})},Eo);function Bs(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:js(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function Po(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function Co(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 _e,U,Xn,pe,Ft,cn,Ge,lt,er,un,ln,qt,Nt,dt,dn,H,Zn,$s,Vs,Ws,Gs,zs,Js,Ys,Oo,Mo,tr=(Mo=class extends Ee{constructor(t,n){super();I(this,H);I(this,_e);I(this,U);I(this,Xn);I(this,pe);I(this,Ft);I(this,cn);I(this,Ge);I(this,lt);I(this,er);I(this,un);I(this,ln);I(this,qt);I(this,Nt);I(this,dt);I(this,dn,new Set);this.options=n,S(this,_e,t),S(this,lt,null),S(this,Ge,Jn()),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(d(this,U).addObserver(this),Ao(d(this,U),this.options)?F(this,H,Zn).call(this):this.updateResult(),F(this,H,Gs).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Zs(d(this,U),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Zs(d(this,U),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,F(this,H,zs).call(this),F(this,H,Js).call(this),d(this,U).removeObserver(this)}setOptions(t){let n=this.options,r=d(this,U);if(this.options=d(this,_e).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof ye(this.options.enabled,d(this,U))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");F(this,H,Ys).call(this),d(this,U).setOptions(this.options),n._defaulted&&!en(this.options,n)&&d(this,_e).getQueryCache().notify({type:"observerOptionsUpdated",query:d(this,U),observer:this});let s=this.hasListeners();s&&ko(d(this,U),r,this.options,n)&&F(this,H,Zn).call(this),this.updateResult(),s&&(d(this,U)!==r||ye(this.options.enabled,d(this,U))!==ye(n.enabled,d(this,U))||qe(this.options.staleTime,d(this,U))!==qe(n.staleTime,d(this,U)))&&F(this,H,$s).call(this);let i=F(this,H,Vs).call(this);s&&(d(this,U)!==r||ye(this.options.enabled,d(this,U))!==ye(n.enabled,d(this,U))||i!==d(this,dt))&&F(this,H,Ws).call(this,i)}getOptimisticResult(t){let n=d(this,_e).getQueryCache().build(d(this,_e),t),r=this.createResult(n,t);return Jl(this,r)&&(S(this,pe,r),S(this,cn,this.options),S(this,Ft,d(this,U).state)),r}getCurrentResult(){return d(this,pe)}trackResult(t,n){return new Proxy(t,{get:(r,s)=>(this.trackProp(s),n?.(s),s==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&d(this,Ge).status==="pending"&&d(this,Ge).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(r,s))})}trackProp(t){d(this,dn).add(t)}getCurrentQuery(){return d(this,U)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){let n=d(this,_e).defaultQueryOptions(t),r=d(this,_e).getQueryCache().build(d(this,_e),n);return r.fetch().then(()=>this.createResult(r,n))}fetch(t){return F(this,H,Zn).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),d(this,pe)))}createResult(t,n){let r=d(this,U),s=this.options,i=d(this,pe),o=d(this,Ft),a=d(this,cn),u=t!==r?t.state:d(this,Xn),{state:l}=t,f={...l},h=!1,p;if(n._optimisticResults){let k=this.hasListeners(),T=!k&&Ao(t,n),A=k&&ko(t,r,n,s);(T||A)&&(f={...f,...Bs(l.data,t.options)}),n._optimisticResults==="isRestoring"&&(f.fetchStatus="idle")}let{error:m,errorUpdatedAt:y,status:g}=f;p=f.data;let v=!1;if(n.placeholderData!==void 0&&p===void 0&&g==="pending"){let k;i?.isPlaceholderData&&n.placeholderData===a?.placeholderData?(k=i.data,v=!0):k=typeof n.placeholderData=="function"?n.placeholderData(d(this,ln)?.state.data,d(this,ln)):n.placeholderData,k!==void 0&&(g="success",p=zn(i?.data,k,n),h=!0)}if(n.select&&p!==void 0&&!v)if(i&&p===o?.data&&n.select===d(this,er))p=d(this,un);else try{S(this,er,n.select),p=n.select(p),p=zn(i?.data,p,n),S(this,un,p),S(this,lt,null)}catch(k){S(this,lt,k)}d(this,lt)&&(m=d(this,lt),p=d(this,un),y=Date.now(),g="error");let _=f.fetchStatus==="fetching",w=g==="pending",C=g==="error",R=w&&_,M=p!==void 0,P={status:g,fetchStatus:f.fetchStatus,isPending:w,isSuccess:g==="success",isError:C,isInitialLoading:R,isLoading:R,data:p,dataUpdatedAt:f.dataUpdatedAt,error:m,errorUpdatedAt:y,failureCount:f.fetchFailureCount,failureReason:f.fetchFailureReason,errorUpdateCount:f.errorUpdateCount,isFetched:t.isFetched(),isFetchedAfterMount:f.dataUpdateCount>u.dataUpdateCount||f.errorUpdateCount>u.errorUpdateCount,isFetching:_,isRefetching:_&&!w,isLoadingError:C&&!M,isPaused:f.fetchStatus==="paused",isPlaceholderData:h,isRefetchError:C&&M,isStale:Xs(t,n),refetch:this.refetch,promise:d(this,Ge),isEnabled:ye(n.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){let k=P.data!==void 0,T=P.status==="error"&&!k,A=K=>{T?K.reject(P.error):k&&K.resolve(P.data)},O=()=>{let K=S(this,Ge,P.promise=Jn());A(K)},q=d(this,Ge);switch(q.status){case"pending":t.queryHash===r.queryHash&&A(q);break;case"fulfilled":(T||P.data!==q.value)&&O();break;case"rejected":(!T||P.error!==q.reason)&&O();break}}return P}updateResult(){let t=d(this,pe),n=this.createResult(d(this,U),this.options);if(S(this,Ft,d(this,U).state),S(this,cn,this.options),d(this,Ft).data!==void 0&&S(this,ln,d(this,U)),en(n,t))return;S(this,pe,n);let r=()=>{if(!t)return!0;let{notifyOnChangeProps:s}=this.options,i=typeof s=="function"?s():s;if(i==="all"||!i&&!d(this,dn).size)return!0;let o=new Set(i??d(this,dn));return this.options.throwOnError&&o.add("error"),Object.keys(d(this,pe)).some(a=>{let c=a;return d(this,pe)[c]!==t[c]&&o.has(c)})};F(this,H,Oo).call(this,{listeners:r()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&F(this,H,Gs).call(this)}},_e=new WeakMap,U=new WeakMap,Xn=new WeakMap,pe=new WeakMap,Ft=new WeakMap,cn=new WeakMap,Ge=new WeakMap,lt=new WeakMap,er=new WeakMap,un=new WeakMap,ln=new WeakMap,qt=new WeakMap,Nt=new WeakMap,dt=new WeakMap,dn=new WeakMap,H=new WeakSet,Zn=function(t){F(this,H,Ys).call(this);let n=d(this,U).fetch(this.options,t);return t?.throwOnError||(n=n.catch(Z)),n},$s=function(){F(this,H,zs).call(this);let t=qe(this.options.staleTime,d(this,U));if(Ke.isServer()||d(this,pe).isStale||!Wn(t))return;let r=Or(d(this,pe).dataUpdatedAt,t)+1;S(this,qt,De.setTimeout(()=>{d(this,pe).isStale||this.updateResult()},r))},Vs=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(d(this,U)):this.options.refetchInterval)??!1},Ws=function(t){F(this,H,Js).call(this),S(this,dt,t),!(Ke.isServer()||ye(this.options.enabled,d(this,U))===!1||!Wn(d(this,dt))||d(this,dt)===0)&&S(this,Nt,De.setInterval(()=>{(this.options.refetchIntervalInBackground||Xt.isFocused())&&F(this,H,Zn).call(this)},d(this,dt)))},Gs=function(){F(this,H,$s).call(this),F(this,H,Ws).call(this,F(this,H,Vs).call(this))},zs=function(){d(this,qt)!==void 0&&(De.clearTimeout(d(this,qt)),S(this,qt,void 0))},Js=function(){d(this,Nt)!==void 0&&(De.clearInterval(d(this,Nt)),S(this,Nt,void 0))},Ys=function(){let t=d(this,_e).getQueryCache().build(d(this,_e),this.options);if(t===d(this,U))return;let n=d(this,U);S(this,U,t),S(this,Xn,t.state),this.hasListeners()&&(n?.removeObserver(this),t.addObserver(this))},Oo=function(t){j.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(d(this,pe))}),d(this,_e).getQueryCache().notify({query:d(this,U),type:"observerResultsUpdated"})})},Mo);function zl(e,t){return ye(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function Ao(e,t){return zl(e,t)||e.state.data!==void 0&&Zs(e,t,t.refetchOnMount)}function Zs(e,t,n){if(ye(t.enabled,e)!==!1&&qe(t.staleTime,e)!=="static"){let r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&Xs(e,t)}return!1}function ko(e,t,n,r){return(e!==t||ye(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&Xs(e,n)}function Xs(e,t){return ye(t.enabled,e)!==!1&&e.isStaleByTime(qe(t.staleTime,e))}function Jl(e,t){return!en(e.getCurrentResult(),t)}function fn(e){return{onFetch:(t,n)=>{let r=t.options,s=t.fetchOptions?.meta?.fetchMore?.direction,i=t.state.data?.pages||[],o=t.state.data?.pageParams||[],a={pages:[],pageParams:[]},c=0,u=async()=>{let l=!1,f=m=>{wo(m,()=>t.signal,()=>l=!0)},h=Nr(t.options,t.fetchOptions),p=async(m,y,g)=>{if(l)return Promise.reject();if(y==null&&m.pages.length)return Promise.resolve(m);let _=(()=>{let M={client:t.client,queryKey:t.queryKey,pageParam:y,direction:g?"backward":"forward",meta:t.options.meta};return f(M),M})(),w=await h(_),{maxPages:C}=t.options,R=g?bo:vo;return{pages:R(m.pages,w,C),pageParams:R(m.pageParams,y,C)}};if(s&&i.length){let m=s==="backward",y=m?Fo:ei,g={pages:i,pageParams:o},v=y(r,g);a=await p(g,v,m)}else{let m=e??i.length;do{let y=c===0?o[0]??r.initialPageParam:ei(r,a);if(c>0&&y==null)break;a=await p(a,y),c++}while(c<m)}return a};t.options.persister?t.fetchFn=()=>t.options.persister?.(u,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=u}}}function ei(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 Fo(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function qo(e,t){return t?ei(e,t)!=null:!1}function No(e,t){return!t||!e.getPreviousPageParam?!1:Fo(e,t)!=null}var ti=class extends tr{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:fn()})}getOptimisticResult(e){return e.behavior=fn(),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:o,isRefetchError:a}=r,c=n.fetchMeta?.fetchMore?.direction,u=o&&c==="forward",l=s&&c==="forward",f=o&&c==="backward",h=s&&c==="backward";return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:qo(t,n.data),hasPreviousPage:No(t,n.data),isFetchNextPageError:u,isFetchingNextPage:l,isFetchPreviousPageError:f,isFetchingPreviousPage:h,isRefetchError:a&&!u&&!f,isRefetching:i&&!l&&!h}}};var nr,Le,le,Qt,He,ft,Qo,Do=(Qo=class extends Ur{constructor(t){super();I(this,He);I(this,nr);I(this,Le);I(this,le);I(this,Qt);S(this,nr,t.client),this.mutationId=t.mutationId,S(this,le,t.mutationCache),S(this,Le,[]),this.state=t.state||ni(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){d(this,Le).includes(t)||(d(this,Le).push(t),this.clearGcTimeout(),d(this,le).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){S(this,Le,d(this,Le).filter(n=>n!==t)),this.scheduleGc(),d(this,le).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){d(this,Le).length||(this.state.status==="pending"?this.scheduleGc():d(this,le).remove(this))}continue(){return d(this,Qt)?.continue()??this.execute(this.state.variables)}async execute(t){let n=()=>{F(this,He,ft).call(this,{type:"continue"})},r={client:d(this,nr),meta:this.options.meta,mutationKey:this.options.mutationKey};S(this,Qt,Dr({fn:()=>this.options.mutationFn?this.options.mutationFn(t,r):Promise.reject(new Error("No mutationFn found")),onFail:(o,a)=>{F(this,He,ft).call(this,{type:"failed",failureCount:o,error:a})},onPause:()=>{F(this,He,ft).call(this,{type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>d(this,le).canRun(this)}));let s=this.state.status==="pending",i=!d(this,Qt).canStart();try{if(s)n();else{F(this,He,ft).call(this,{type:"pending",variables:t,isPaused:i}),d(this,le).config.onMutate&&await d(this,le).config.onMutate(t,this,r);let a=await this.options.onMutate?.(t,r);a!==this.state.context&&F(this,He,ft).call(this,{type:"pending",context:a,variables:t,isPaused:i})}let o=await d(this,Qt).start();return await d(this,le).config.onSuccess?.(o,t,this.state.context,this,r),await this.options.onSuccess?.(o,t,this.state.context,r),await d(this,le).config.onSettled?.(o,null,this.state.variables,this.state.context,this,r),await this.options.onSettled?.(o,null,t,this.state.context,r),F(this,He,ft).call(this,{type:"success",data:o}),o}catch(o){try{await d(this,le).config.onError?.(o,t,this.state.context,this,r)}catch(a){Promise.reject(a)}try{await this.options.onError?.(o,t,this.state.context,r)}catch(a){Promise.reject(a)}try{await d(this,le).config.onSettled?.(void 0,o,this.state.variables,this.state.context,this,r)}catch(a){Promise.reject(a)}try{await this.options.onSettled?.(void 0,o,t,this.state.context,r)}catch(a){Promise.reject(a)}throw F(this,He,ft).call(this,{type:"error",error:o}),o}finally{d(this,le).runNext(this)}}},nr=new WeakMap,Le=new WeakMap,le=new WeakMap,Qt=new WeakMap,He=new WeakSet,ft=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),j.batch(()=>{d(this,Le).forEach(r=>{r.onMutationUpdate(t)}),d(this,le).notify({mutation:this,type:"updated",action:t})})},Qo);function ni(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var ze,Ne,rr,Uo,Ko=(Uo=class extends Ee{constructor(t={}){super();I(this,ze);I(this,Ne);I(this,rr);this.config=t,S(this,ze,new Set),S(this,Ne,new Map),S(this,rr,0)}build(t,n,r){let s=new Do({client:t,mutationCache:this,mutationId:++Vn(this,rr)._,options:t.defaultMutationOptions(n),state:r});return this.add(s),s}add(t){d(this,ze).add(t);let n=Kr(t);if(typeof n=="string"){let r=d(this,Ne).get(n);r?r.push(t):d(this,Ne).set(n,[t])}this.notify({type:"added",mutation:t})}remove(t){if(d(this,ze).delete(t)){let n=Kr(t);if(typeof n=="string"){let r=d(this,Ne).get(n);if(r)if(r.length>1){let s=r.indexOf(t);s!==-1&&r.splice(s,1)}else r[0]===t&&d(this,Ne).delete(n)}}this.notify({type:"removed",mutation:t})}canRun(t){let n=Kr(t);if(typeof n=="string"){let s=d(this,Ne).get(n)?.find(i=>i.state.status==="pending");return!s||s===t}else return!0}runNext(t){let n=Kr(t);return typeof n=="string"?d(this,Ne).get(n)?.find(s=>s!==t&&s.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){j.batch(()=>{d(this,ze).forEach(t=>{this.notify({type:"removed",mutation:t})}),d(this,ze).clear(),d(this,Ne).clear()})}getAll(){return Array.from(d(this,ze))}find(t){let n={exact:!0,...t};return this.getAll().find(r=>qr(n,r))}findAll(t={}){return this.getAll().filter(n=>qr(t,n))}notify(t){j.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){let t=this.getAll().filter(n=>n.state.isPaused);return j.batch(()=>Promise.all(t.map(n=>n.continue().catch(Z))))}},ze=new WeakMap,Ne=new WeakMap,rr=new WeakMap,Uo);function Kr(e){return e.options.scope?.id}var Je,pt,ve,Ye,Ze,Lr,ri,Lo,si=(Lo=class extends Ee{constructor(t,n){super();I(this,Ze);I(this,Je);I(this,pt);I(this,ve);I(this,Ye);S(this,Je,t),this.setOptions(n),this.bindMethods(),F(this,Ze,Lr).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(t){let n=this.options;this.options=d(this,Je).defaultMutationOptions(t),en(this.options,n)||d(this,Je).getMutationCache().notify({type:"observerOptionsUpdated",mutation:d(this,ve),observer:this}),n?.mutationKey&&this.options.mutationKey&&Ue(n.mutationKey)!==Ue(this.options.mutationKey)?this.reset():d(this,ve)?.state.status==="pending"&&d(this,ve).setOptions(this.options)}onUnsubscribe(){this.hasListeners()||d(this,ve)?.removeObserver(this)}onMutationUpdate(t){F(this,Ze,Lr).call(this),F(this,Ze,ri).call(this,t)}getCurrentResult(){return d(this,pt)}reset(){d(this,ve)?.removeObserver(this),S(this,ve,void 0),F(this,Ze,Lr).call(this),F(this,Ze,ri).call(this)}mutate(t,n){return S(this,Ye,n),d(this,ve)?.removeObserver(this),S(this,ve,d(this,Je).getMutationCache().build(d(this,Je),this.options)),d(this,ve).addObserver(this),d(this,ve).execute(t)}},Je=new WeakMap,pt=new WeakMap,ve=new WeakMap,Ye=new WeakMap,Ze=new WeakSet,Lr=function(){let t=d(this,ve)?.state??ni();S(this,pt,{...t,isPending:t.status==="pending",isSuccess:t.status==="success",isError:t.status==="error",isIdle:t.status==="idle",mutate:this.mutate,reset:this.reset})},ri=function(t){j.batch(()=>{if(d(this,Ye)&&this.hasListeners()){let n=d(this,pt).variables,r=d(this,pt).context,s={client:d(this,Je),meta:this.options.meta,mutationKey:this.options.mutationKey};if(t?.type==="success"){try{d(this,Ye).onSuccess?.(t.data,n,r,s)}catch(i){Promise.reject(i)}try{d(this,Ye).onSettled?.(t.data,null,n,r,s)}catch(i){Promise.reject(i)}}else if(t?.type==="error"){try{d(this,Ye).onError?.(t.error,n,r,s)}catch(i){Promise.reject(i)}try{d(this,Ye).onSettled?.(void 0,t.error,n,r,s)}catch(i){Promise.reject(i)}}}this.listeners.forEach(n=>{n(d(this,pt))})})},Lo);var je,Ho,jo=(Ho=class extends Ee{constructor(t={}){super();I(this,je);this.config=t,S(this,je,new Map)}build(t,n,r){let s=n.queryKey,i=n.queryHash??Gn(s,n),o=this.get(i);return o||(o=new Io({client:t,queryKey:s,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(s)}),this.add(o)),o}add(t){d(this,je).has(t.queryHash)||(d(this,je).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){let n=d(this,je).get(t.queryHash);n&&(t.destroy(),n===t&&d(this,je).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){j.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return d(this,je).get(t)}getAll(){return[...d(this,je).values()]}find(t){let n={exact:!0,...t};return this.getAll().find(r=>Fr(n,r))}findAll(t={}){let n=this.getAll();return Object.keys(t).length>0?n.filter(r=>Fr(t,r)):n}notify(t){j.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){j.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){j.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},je=new WeakMap,Ho);var X,mt,gt,pn,mn,ht,gn,hn,Bo,ii=(Bo=class{constructor(e={}){I(this,X);I(this,mt);I(this,gt);I(this,pn);I(this,mn);I(this,ht);I(this,gn);I(this,hn);S(this,X,e.queryCache||new jo),S(this,mt,e.mutationCache||new Ko),S(this,gt,e.defaultOptions||{}),S(this,pn,new Map),S(this,mn,new Map),S(this,ht,0)}mount(){Vn(this,ht)._++,d(this,ht)===1&&(S(this,gn,Xt.subscribe(async e=>{e&&(await this.resumePausedMutations(),d(this,X).onFocus())})),S(this,hn,on.subscribe(async e=>{e&&(await this.resumePausedMutations(),d(this,X).onOnline())})))}unmount(){var e,t;Vn(this,ht)._--,d(this,ht)===0&&((e=d(this,gn))==null||e.call(this),S(this,gn,void 0),(t=d(this,hn))==null||t.call(this),S(this,hn,void 0))}isFetching(e){return d(this,X).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return d(this,mt).findAll({...e,status:"pending"}).length}getQueryData(e){let t=this.defaultQueryOptions({queryKey:e});return d(this,X).get(t.queryHash)?.state.data}ensureQueryData(e){let t=this.defaultQueryOptions(e),n=d(this,X).build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(qe(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return d(this,X).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=d(this,X).get(r.queryHash)?.state.data,o=yo(t,i);if(o!==void 0)return d(this,X).build(this,r).setData(o,{...n,manual:!0})}setQueriesData(e,t,n){return j.batch(()=>d(this,X).findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){let t=this.defaultQueryOptions({queryKey:e});return d(this,X).get(t.queryHash)?.state}removeQueries(e){let t=d(this,X);j.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){let n=d(this,X);return j.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){let n={revert:!0,...t},r=j.batch(()=>d(this,X).findAll(e).map(s=>s.cancel(n)));return Promise.all(r).then(Z).catch(Z)}invalidateQueries(e,t={}){return j.batch(()=>(d(this,X).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=j.batch(()=>d(this,X).findAll(e).filter(s=>!s.isDisabled()&&!s.isStatic()).map(s=>{let i=s.fetch(void 0,n);return n.throwOnError||(i=i.catch(Z)),s.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(Z)}fetchQuery(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=d(this,X).build(this,t);return n.isStaleByTime(qe(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Z).catch(Z)}fetchInfiniteQuery(e){return e.behavior=fn(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Z).catch(Z)}ensureInfiniteQueryData(e){return e.behavior=fn(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return on.isOnline()?d(this,mt).resumePausedMutations():Promise.resolve()}getQueryCache(){return d(this,X)}getMutationCache(){return d(this,mt)}getDefaultOptions(){return d(this,gt)}setDefaultOptions(e){S(this,gt,e)}setQueryDefaults(e,t){d(this,pn).set(Ue(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){let t=[...d(this,pn).values()],n={};return t.forEach(r=>{Tt(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){d(this,mn).set(Ue(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){let t=[...d(this,mn).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={...d(this,gt).queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Gn(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===tn&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...d(this,gt).mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){d(this,X).clear(),d(this,mt).clear()}},X=new WeakMap,mt=new WeakMap,gt=new WeakMap,pn=new WeakMap,mn=new WeakMap,ht=new WeakMap,gn=new WeakMap,hn=new WeakMap,Bo);var yn=Y(ue(),1),Vo=Y(Hr(),1),oi=yn.createContext(void 0),L=e=>{let t=yn.useContext(oi);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},sr=({client:e,children:t})=>(yn.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,Vo.jsx)(oi.Provider,{value:e,children:t}));var jr=Y(ue(),1),Wo=jr.createContext(!1),Go=()=>jr.useContext(Wo),Nm=Wo.Provider;var ir=Y(ue(),1),Yl=Y(Hr(),1);function Zl(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Xl=ir.createContext(Zl()),zo=()=>ir.useContext(Xl);var Jo=Y(ue(),1);var Yo=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError=="function"?nn(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},Zo=e=>{Jo.useEffect(()=>{e.clearReset()},[e])},Xo=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:s})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(s&&e.data===void 0||nn(n,[e.error,r]));var ea=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))}},ta=(e,t)=>e.isLoading&&e.isFetching&&!t,na=(e,t)=>e?.suspense&&t.isPending,ai=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});var yt=Y(ue(),1);function Br(e,t,n){let r=Go(),s=zo(),i=L(n),o=i.defaultQueryOptions(e);i.getDefaultOptions().queries?._experimental_beforeQuery?.(o);let a=i.getQueryCache().get(o.queryHash);o._optimisticResults=r?"isRestoring":"optimistic",ea(o),Yo(o,s,a),Zo(s);let c=!i.getQueryCache().get(o.queryHash),[u]=yt.useState(()=>new t(i,o)),l=u.getOptimisticResult(o),f=!r&&e.subscribed!==!1;if(yt.useSyncExternalStore(yt.useCallback(h=>{let p=f?u.subscribe(j.batchCalls(h)):Z;return u.updateResult(),p},[u,f]),()=>u.getCurrentResult(),()=>u.getCurrentResult()),yt.useEffect(()=>{u.setOptions(o)},[o,u]),na(o,l))throw ai(o,u,s);if(Xo({result:l,errorResetBoundary:s,throwOnError:o.throwOnError,query:a,suspense:o.suspense}))throw l.error;return i.getDefaultOptions().queries?._experimental_afterQuery?.(o,l),o.experimental_prefetchInRender&&!Ke.isServer()&&ta(l,r)&&(c?ai(o,u,s):a?.promise)?.catch(Z).finally(()=>{u.updateResult()}),o.notifyOnChangeProps?l:u.trackResult(l)}function B(e,t){return Br(e,tr,t)}var Xe=Y(ue(),1);function ne(e,t){let n=L(t),[r]=Xe.useState(()=>new si(n,e));Xe.useEffect(()=>{r.setOptions(e)},[r,e]);let s=Xe.useSyncExternalStore(Xe.useCallback(o=>r.subscribe(j.batchCalls(o)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),i=Xe.useCallback((o,a)=>{r.mutate(o,a).catch(Z)},[r]);if(s.error&&nn(r.options.throwOnError,[s.error]))throw s.error;return{...s,mutate:i,mutateAsync:s.mutate}}function or(e,t){return Br(e,ti,t)}var ia=Y(sa(),1),_n=typeof window<"u"&&window.__FSAOS_CONFIG__||{},Dt=Array.isArray(_n.sources)?_n.sources:[],et=_n.hostSession===!0,ed=_n.supabaseUrl||"https://vahbmsslxuustnlvsrkg.supabase.co",td=_n.supabaseAnonKey||"sb_publishable_ZjosozAjfpZ4InMNElTr6Q_hHB-f5nc",Te=_n.gatewayUrl||"https://fsaos-mcp-gw-rust.fly.dev",V=(0,ia.createClient)(ed,td,{auth:{persistSession:!0,autoRefreshToken:!0,detectSessionInUrl:!1}});var ar=null,$r=0,oa,di,Vr=!1;oa=new Promise(e=>{di=e});V.auth.onAuthStateChange((e,t)=>{t?.access_token?(ar=t.access_token,$r=t.expires_at??Math.floor(Date.now()/1e3)+3600):(ar=null,$r=0),Vr||(Vr=!0,di())});setTimeout(()=>{Vr||(Vr=!0,di())},5e3);function aa(e,t){ar=e,$r=t??Math.floor(Date.now()/1e3)+3600}function fi(){ar=null,$r=0}async function tt(){let e=typeof window<"u"&&window.__FSAOS_CONFIG__||{};if(et)return null;if(e.embedToken){if(typeof e.embedToken=="function")try{return await e.embedToken()??null}catch{return null}return e.embedToken}return await oa,ar}var Sn=null,xn=null,ca=0,ci=new Set,pi,cr,Rn=!1;pi=new Promise(e=>{cr=e});function mi(){ca++,ci.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Anchor listener error:",t)}})}function Pn(e){let t=typeof e=="string"?e:e.path,n=Sn!==t||xn?.id!==(typeof e=="string"?void 0:e.id);Sn=t,xn=typeof e=="string"?null:e,typeof e!="string"&&!Ut.some(r=>r.id===e.id)&&(Ut=[...Ut,e],_i()),Rn||(Rn=!0,cr()),n&&mi()}function _t(){return Sn}function de(){return xn}function gi(){return ca}function hi(e){return ci.add(e),()=>{ci.delete(e)}}function ur(){return pi}function yi(){return Rn}var Wr=null;function Kt(e,t={}){if(Wr){console.warn("[SDK] electHomeAnchor called twice; ignoring (logout to re-elect).");return}Wr=e,t.activate!==!1&&Pn(e)}function me(){return Wr}var Ut=[],ui=new Set,ua=0;function _i(){ua++,ui.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Mount listener error:",t)}})}function Ae(){return Ut}function lr(){return ua}function Gr(e){return ui.add(e),()=>{ui.delete(e)}}function la(e,t){let n=JSON.stringify(Ut)!==JSON.stringify(e),r=Sn!==t.path||xn?.id!==t.id;Ut=e,Sn=t.path,xn=t,Rn||(Rn=!0,cr()),n&&_i(),r&&mi()}var bn=null,vn=null,wn=0,li=new Set,da=0;function fa(){da++,li.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Session listener error:",t)}})}function ae(){return wn}function vi(){return da}function pa(e){return li.add(e),()=>{li.delete(e)}}async function nt(){if(bn)return bn;if(vn)return vn;let e=wn;return vn=(async()=>{let t=Lt(),n=await tt();if(e!==wn)throw new Error("Session changed during initialization");let r={};n&&(r.Authorization=`Bearer ${n}`);let s=await fetch(`${Te}/d/${t}/init`,{method:"GET",headers:r});if(!s.ok)throw new Error(`Session init failed: ${s.status} ${s.statusText}`);let i=await s.json();if(e!==wn)throw new Error("Session changed during initialization");let o=i.entry||i;return bn={scope_id:o.scope_id,scope_path:o.scope_path,instance_path:o.instance_path||"/root",fractal_id:o.fractal_id||null,instance_name:o.instance_name||null,display_name:o.scope_display_name||o.display_name||null,principal_id:o.principal_id||null},fa(),bn})().catch(t=>{throw e===wn&&(vn=null),t}),vn}function vt(){return bn}function bi(){wn++,bn=null,vn=null,Sn=null,xn=null,Wr=null,Ut=[],fa()}var ma=[];function se(e){ma.push(e)}function Cn(){bi(),fi(),cr(),Rn=!1,pi=new Promise(e=>{cr=e}),mi(),_i();for(let e of ma)try{e()}catch(t){console.warn("[SDK] Cleanup function failed:",t)}}function Lt(){if(typeof window<"u"){let e=window.__FSAOS_CONFIG__;return e?.hostname?e.hostname:window.location.hostname}return"localhost"}var ga=Pn,W=_t,ee=gi,xe=hi,ha=ur,zr=yi;var jt="host-session",nd=5e3;function wi(e){return typeof e=="object"&&e!==null&&e.fsaos===jt&&typeof e.kind=="string"}var Ht=class extends Error{constructor(){super(...arguments);z(this,"name","HostSessionUnavailableError")}},Jr=null,rd=0,Yr=new Map;function ya(){return Jr||(Jr=new Promise((e,t)=>{if(!et){t(new Ht("This page was not started with hostSession."));return}if(typeof window>"u"||!window.parent||window.parent===window){t(new Ht("This page is signed in only inside the app that frames it. Open it from there."));return}let n=window.parent,r=null,s=setTimeout(()=>{r===null&&(window.removeEventListener("message",i),t(new Ht("The window around this page did not sign it in. Open it from the app that owns it.")))},nd);function i(o){if(o.source!==n||!wi(o.data))return;let a=o.data;if(r===null){if(a.kind!=="welcome")return;r=o.origin,clearTimeout(s),a.anchor&&Pn(a.anchor),e({host:n,origin:r,item:a.item??null});return}if(o.origin!==r||a.kind!=="result")return;let c=Yr.get(a.id);c&&(Yr.delete(a.id),c.resolve(a.ok?{ok:!0,response:a.response}:{ok:!1,error:a.error}))}window.addEventListener("message",i),n.postMessage({fsaos:jt,kind:"hello"},"*")}),Jr)}async function _a(){let{item:e}=await ya();return{item:e}}async function va(e,t,n){if(n?.aborted)throw new DOMException("Read cancelled","AbortError");let{host:r,origin:s}=await ya();if(n?.aborted)throw new DOMException("Read cancelled","AbortError");let i=JSON.parse(JSON.stringify(t??{}));return new Promise((o,a)=>{let c=`${Date.now().toString(36)}-${(++rd).toString(36)}`,u=()=>{Yr.delete(c),a(new DOMException("Read cancelled","AbortError"))};Yr.set(c,{resolve:l=>{n?.removeEventListener("abort",u),o(l)}}),n?.addEventListener("abort",u,{once:!0}),r.postMessage({fsaos:jt,kind:"call",id:c,method:e,params:i},s)})}var Si=0,ba=!1,wa=0;function xi(e){if(typeof e!="string")return;let t=Date.parse(e);Number.isNaN(t)||(Si=t-Date.now(),ba=!0,wa=Date.now())}function Zr(){return Date.now()+Si}function Sa(){return ba}function xa(){return Si}function Ra(){return wa}function Pa(e){if(typeof e!="string")return null;let t=Date.parse(e);return Number.isNaN(t)?null:Zr()>=t}function Ca(e){if(typeof e!="string")return null;let t=Date.parse(e);return Number.isNaN(t)?null:Math.max(0,t-Zr())}var En,ke=new Map,Bt=[],Ri=0,Pi={foreground:0,normal:1,background:2},Xr=()=>performance.now(),Ci=()=>new DOMException("Read cancelled","AbortError");function Ia(e={}){En={concurrency:Math.max(1,Math.min(16,Math.floor(e.concurrency??6))),timeoutMs:Math.max(1e3,e.timeoutMs??15e3),onTiming:e.onTiming},ts()}function Ta(){for(let e of ke.values()){e.controller.abort();for(let t of e.consumers)t.detach(),t.reject(Ci());e.consumers.clear(),e.timer&&clearTimeout(e.timer)}ke.clear(),Bt.length=0}function Aa(e,t){return e==="query"?!("materialize"in t):["read","list","search","resolve","resolve-items","get-channel-messages","list-memberships"].includes(e)}function es(e){return Array.isArray(e)?`[${e.map(es).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>`${JSON.stringify(t)}:${es(n)}`).join(",")}}`:JSON.stringify(e)}function ka(e,t,n,r){if(n.signal?.aborted)return Promise.reject(Ci());if(!En)return r(n.signal);let s=ke.get(e);if(s)Pi[n.priority??"normal"]<Pi[s.priority]&&(s.priority=n.priority??"normal");else{s={key:e,method:t,priority:n.priority??"normal",queuedAt:Xr(),controller:new AbortController,consumers:new Set,run:r},ke.set(e,s),Bt.push(s);let a=s;s.timer=setTimeout(()=>{a.controller.abort();let c=new Error("The read timed out. Please retry.");c.name="TimeoutError";for(let u of a.consumers)u.detach(),u.reject(c);a.consumers.clear(),ke.get(a.key)===a&&ke.delete(a.key),Ea(a)},En.timeoutMs)}let i=s,o=new Promise((a,c)=>{let u=()=>{l.detach(),i.consumers.delete(l),c(Ci()),i.consumers.size||(i.controller.abort(),ke.get(i.key)===i&&ke.delete(i.key),Ea(i))},l={resolve:f=>a(structuredClone(f)),reject:c,detach:()=>n.signal?.removeEventListener("abort",u)};i.consumers.add(l),n.signal?.addEventListener("abort",u,{once:!0})});return ts(),o}function Ea(e){let t=Bt.indexOf(e);t>=0&&(Bt.splice(t,1),ke.get(e.key)===e&&ke.delete(e.key),e.timer&&clearTimeout(e.timer)),ts()}function ts(){if(En)for(;Ri<En.concurrency&&Bt.length;){let e=r=>Pi[r.priority]-Math.floor((Xr()-r.queuedAt)/2e3);Bt.sort((r,s)=>e(r)-e(s)||r.queuedAt-s.queuedAt);let t=Bt.shift();if(!t.consumers.size)continue;Ri++,t.startedAt=Xr();let n="success";Promise.resolve().then(()=>t.run(t.controller.signal)).then(r=>{for(let s of t.consumers)s.detach(),s.resolve(r)},r=>{n=t.controller.signal.aborted?"aborted":"error";for(let s of t.consumers)s.detach(),s.reject(r)}).finally(()=>{t.timer&&clearTimeout(t.timer),t.consumers.clear(),ke.get(t.key)===t&&ke.delete(t.key),Ri--;try{En?.onTiming?.({method:t.method,priority:t.priority,queueMs:Math.round(t.startedAt-t.queuedAt),requestMs:Math.round(Xr()-t.startedAt),outcome:n})}catch{}ts()})}}se(Ta);var sd=new Set(["list-memberships","init"]),ge=class extends Error{constructor(n){let r=typeof n.payload?.error=="string"?n.payload.error.trim():"",s=typeof n.payload?.message=="string"?n.payload.message.trim():"",i=n.responseBody.trim()||`Gateway HTTP error: ${n.status} ${n.statusText}`.trim(),o=r&&s?`${r}: ${s}`:s||r||i;super(o);z(this,"name","GatewayRequestError");z(this,"method");z(this,"status");z(this,"statusText");z(this,"payload");z(this,"responseBody");this.method=n.method,this.status=n.status,this.statusText=n.statusText,this.payload=n.payload,this.responseBody=n.responseBody}};async function x(e,t={},n={}){if(et)return id(e,t,n);let r=ae(),s=_t(),i=Lt(),o=`${Te}/d/${i}`,a={"Content-Type":"application/json"},c=await Ma(tt(),n.signal);if(r!==ae())throw new Error("Session changed before gateway request");if(c&&(a.Authorization=`Bearer ${c}`),!sd.has(e)&&!t._scope_path&&await Ma(ur(),n.signal),r!==ae())throw new Error("Session changed before gateway request");let u={...t},l=vt();!u.domain_scope_id&&l?.scope_id&&(u.domain_scope_id=l.scope_id);let f=s??_t();!u._scope_path&&f&&(u._scope_path=f);let h=async p=>{if(r!==ae())throw new Error("Session changed before queued gateway request");let m=await fetch(o,{method:"POST",signal:p,headers:a,body:JSON.stringify({method:e,params:u})}),y=await m.text();if(r!==ae())throw new Error("Session changed during gateway request");let g=null;if(y)try{g=JSON.parse(y)}catch{}if(!m.ok||!g)throw new ge({method:e,status:m.status,statusText:m.statusText,payload:g,responseBody:y});if(g.success===!1){let v=g.error||"",_=g.denied_by||g.error_type||"";throw _==="rule"||_==="access"||_==="entitlement"||v==="RULE_DENIED"||v==="ACCESS_DENIED"||v==="PERMISSION_DENIED"||v==="ENTITLEMENT_REQUIRED"?new Fe(g):new ge({method:e,status:m.status,statusText:m.statusText,payload:g,responseBody:y})}return g&&g.server_now!==void 0&&xi(g.server_now),g};return Aa(e,u)?ka(es([r,i,c,e,u]),e,n,h):h(n.signal)}async function id(e,t,n){let r=await va(e,t,n.signal);if(r.ok){let o=r.response?.server_now;return o!==void 0&&xi(o),r.response}let s=r.error;if(s.kind==="denied")throw new Fe(s.payload);if(s.kind==="gateway")throw new ge({method:s.method,status:s.status,statusText:s.statusText,payload:s.payload,responseBody:s.responseBody});let i=new Error(s.message);throw i.name=s.name,i}function Ma(e,t){return t?t.aborted?Promise.reject(new DOMException("Read cancelled","AbortError")):new Promise((n,r)=>{let s=()=>r(new DOMException("Read cancelled","AbortError"));t.addEventListener("abort",s,{once:!0}),e.then(n,r).finally(()=>t.removeEventListener("abort",s))}):e}var b=Y(ue(),1),Gd=Y(Fa(),1),zd=Y(Hr(),1);var qa=new WeakMap;function be(e,t,n={}){let r=n.exact===!0,s=()=>e.invalidateQueries({queryKey:t,exact:r},{cancelRefetch:!1}),i=e.getQueryCache().findAll({queryKey:t,exact:r,fetchStatus:"fetching"}).flatMap(f=>f.promise?[f.promise]:[]);if(i.length===0)return s();let o=`${r?"=":"^"}${JSON.stringify(t)}`,a=qa.get(e);a||(a=new Map,qa.set(e,a));let c=a.get(o);if(c)return c;let u=a,l=Promise.allSettled(i).then(()=>(u.delete(o),s()));return u.set(o,l),l}function he(e,t){return typeof e=="string"&&(e===t||e.startsWith(`${t}/`))}var ns=new WeakMap,Na=e=>e.meta?.arrangementRealtime===!0;function rt(e,t){let n=e.getQueryCache().find({queryKey:t,exact:!0});if(!n)return;let r=ns.get(e);r||(r=new Map,ns.set(e,r));let s=r.get(n.queryHash);s&&clearTimeout(s),r.set(n.queryHash,setTimeout(()=>{r.delete(n.queryHash),e.getQueryCache().get(n.queryHash)===n&&be(e,t,{exact:!0})},250))}function Qa(e,t){if(!(!t||typeof t!="object"))for(let n of e.getQueryCache().getAll()){if(!Na(n))continue;let r=n.state.data;if(n.meta?.personalSections===!0){(r?.item_path&&[t.path,t.old_path].some(i=>typeof i=="string"&&(i===r.item_path||i.startsWith(r.item_path+"/")))||r?.sections?.some(i=>i.entries?.some(o=>o.target?.id===t.item_id))||!r?.item_id&&t.item_type==="item_arrangement"&&t.name==="sidebar-sections")&&rt(e,n.queryKey);continue}if(!r?.item_id)continue;let s=(i,o)=>!!(i&&t.item_id===i||o&&(t.path===o||t.old_path===o));(s(r.item_id,r.item_path)||t.parent_id===r.item_id||t.old_parent_id===r.item_id||[t.path,t.old_path].some(i=>typeof i=="string"&&i.slice(0,i.lastIndexOf("/"))===r.item_path)||r.resolved_children?.some(i=>s(i.id,i.symlink_path||i.path)||i.target&&s(i.target.id,i.target.path)))&&rt(e,n.queryKey)}}function Da(e){for(let t of e.getQueryCache().getAll())Na(t)&&t.state.data!==void 0&&rt(e,t.queryKey)}function Ua(e){ns.get(e)?.forEach(clearTimeout),ns.delete(e)}var st=null;se(()=>{st&&(st.cancelQueries({queryKey:["vfs"]}),st.removeQueries({queryKey:["vfs"]}))});function Ka(e){if(st&&st!==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.");st=e}function N(){return st||(st=new ii({defaultOptions:{queries:{staleTime:1e3*60*2,gcTime:1e3*60*10,refetchOnWindowFocus:!1,retry:1}}})),st}var La=new Proxy({},{get(e,t,n){let r=N(),s=r[t];return typeof s=="function"?s.bind(r):s}});var rs=new WeakMap;function Ei(e){return e.meta?.infiniteItemsRealtime?.filter}function od(e,t){return e.state.data?.pages?.some(r=>r.items?.some(s=>t.item_id&&s.id===t.item_id||t.path&&s.path===t.path||t.old_path&&s.path===t.old_path))??!1}function ad(e){if(e.type)return new Set([e.type]);if(!e.any_of?.length)return null;let t=new Set;for(let n of e.any_of){if(!n.item_type)return null;t.add(n.item_type)}return t}function cd(e,t,n){if(od(e,n))return!0;if(t.spaceIds!==void 0&&(!t.spaceIds.length||n.space_item_id!==void 0&&!t.spaceIds.includes(n.space_item_id)&&!t.spaceIds.includes(n.old_space_item_id)))return!1;let r=t.scope,s=typeof r=="string"&&r!=="__unscoped__",i=typeof n.path=="string"||typeof n.old_path=="string";if(s&&i&&!he(n.path,r)&&!he(n.old_path,r))return!1;if(n.item_type==="symlink"&&s&&i)return!0;let o=ad(t);return n.item_type&&o&&!o.has(n.item_type)||t.parent_id&&n.parent_id!==void 0&&n.parent_id!==t.parent_id&&n.old_parent_id!==t.parent_id?!1:i||!!(t.parent_id&&n.parent_id===t.parent_id)}function Ha(e,t){let n=rs.get(e);n||(n=new Map,rs.set(e,n));let r=n.get(t.queryHash);r&&clearTimeout(r),n.set(t.queryHash,setTimeout(()=>{n.delete(t.queryHash),!(e.getQueryCache().get(t.queryHash)!==t||!Ei(t))&&be(e,t.queryKey,{exact:!0})},500))}function ja(e,t){if(!(!t||typeof t!="object"))for(let n of e.getQueryCache().getAll()){let r=Ei(n);r&&cd(n,r,t)&&Ha(e,n)}}function Ba(e){for(let t of e.getQueryCache().getAll())Ei(t)&&t.state.data!==void 0&&Ha(e,t)}function $a(e){rs.get(e)?.forEach(clearTimeout),rs.delete(e)}var ss=class extends Error{constructor(){super("The server did not confirm the selected-Space listing contract")}};function Va(e,t){if(!Array.isArray(t)||t.some(n=>typeof n!="string")||JSON.stringify([...new Set(t)].sort())!==JSON.stringify(e))throw new ss}function bt(e){return!e||e.spaceIds===void 0?e:{...e,spaceIds:[...new Set(e.spaceIds.map(t=>t.toLowerCase()))].sort(),...e.limit!==void 0?{limit:Math.max(1,Math.min(e.limit,500))}:{}}}function In(e){return e instanceof ss||e instanceof Fe||e instanceof ge&&(e.payload?.error==="SPACE_SELECTION_UNAVAILABLE"||e.payload?.error==="QUERY_PARAMS_INVALID"||e.status===401||e.status===403)}function ce(){return W()??"__unscoped__"}var E={all:()=>["vfs",ce()],item:e=>["vfs",ce(),"item",e],itemById:e=>["vfs","item-by-id",e],children:e=>["vfs",ce(),"children",e],allChildren:()=>["vfs",ce(),"children"],types:e=>["vfs","types",e??"default"],edges:e=>["vfs","edges",e],search:(e,t)=>["vfs",ce(),"search",e,...t??[]],items:(e,t)=>["vfs",ce(),"items",e,JSON.stringify(bt(t??{}))],allItems:()=>["vfs",ce(),"items"],tree:(e,t)=>["vfs",ce(),"tree",e,t??1],openEnvelope:(e,t)=>["vfs",ce(),"open",e,t??"__default__"],allOpenEnvelopes:()=>["vfs",ce(),"open"],memberFocus:e=>["vfs","member-focus",e],fractalInstances:()=>["vfs","fractal-instances"],recentActivity:(e,t,n)=>["vfs",ce(),"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",ce(),"channel-messages",e,t??"__top__"],allChannelMessages:()=>["vfs",ce(),"channel-messages"],channels:e=>["vfs",ce(),"channels",e??"all"],allChannels:()=>["vfs",ce(),"channels"],notifications:(e,t)=>["vfs",ce(),"notifications",e??"all",t??200],allNotifications:()=>["vfs",ce(),"notifications"],unreadCounts:()=>["vfs",ce(),"unread-counts"],memberships:e=>["memberships",e]};var ud=typeof window<"u"&&(window.location?.hostname==="localhost"||window.location?.hostname==="127.0.0.1"||window.__FSAOS_WS_DEBUG__);function J(...e){ud&&console.log("[WS]",...e)}var Q=null,Tn=null,kn=null,dr=0,ld=3e4,Wa=1e4,On=!1,Ga=!1,Xa=3e4,dd=Xa*2+5e3,is=0,os=null,za=!1;function fd(){pr(),is=Date.now(),os=setInterval(()=>{if(Q&&Q.readyState===WebSocket.OPEN&&Date.now()-is>dd){J("ping: no inbound traffic for",Date.now()-is,"ms \u2014 closing half-open socket");try{Q.close(4e3,"liveness timeout")}catch{}return}ot({type:"ping"})},Xa)}function pr(){os&&(clearInterval(os),os=null)}function pd(){typeof document>"u"||(document.hidden?pr():fr()&&(J("Tab visible, reconnecting..."),$t()))}function md(){za||typeof document>"u"||(document.addEventListener("visibilitychange",pd),za=!0)}var Re={};function Ti(e,t){let n=e.replace(/\/+$/,""),r=t.replace(/\/+$/,"");return!n||!r?n===r:r===n||r.startsWith(`${n}/`)}var Mn=[],it=new Map,An=new Map,Me=new Map;function gd(e){let t=An.get(e);return t?Array.from(new Set(Array.from(t.values()).flatMap(n=>n.event_types))).sort():[]}function Ja(e,t){return e?e.length===t.length&&e.every((n,r)=>n===t[r]):!1}function Ya(e){let t=gd(e);if(t.length===0)return it.delete(e),null;let n={scope_id:e,event_types:t};return it.set(e,n),n}var Be=new Map,wt=new Map,Ii="disconnected",as=[];function cs(e){if(Ii!==e){Ii=e;for(let t of[...as])try{t(e)}catch{}}}function hd(e){Be.set(e,"ready");let t=wt.get(e);if(t){wt.delete(e);for(let n of t)n()}}function yd(){for(let e of Be.keys())Be.set(e,"disconnected")}function Ai(e,t){Be.set(e,"pending"),ot({type:"subscribe_path",path:e,event_types:t})}function _d(){return Object.keys(Re).some(t=>Re[t]&&Re[t].length>0)||Mn.length>0}function fr(){return it.size>0||Me.size>0}async function $t(){if(et){J("ensureConnection: the host holds the session, no realtime connection");return}if(!fr()){J("ensureConnection: no active subscriptions, skipping");return}if(Q&&Q.readyState===WebSocket.OPEN){J("ensureConnection: already open");return}if(Tn)return J("ensureConnection: connection already in flight, waiting..."),Tn;if(Q){J("ensureConnection: killing stale WS in state",Q.readyState);try{Q.close()}catch{}Q=null}return On=!1,Tn=(async()=>{try{let e=typeof window<"u"&&window.__FSAOS_CONFIG__||{},t=Te,n=await tt();if(!n){J("ensureConnection: no token available, will retry"),Za();return}let r=t.startsWith("https")?"wss":"ws",s=t.replace(/^https?:\/\//,""),i=`${r}://${s}/ws`;i+=`?token=${encodeURIComponent(n)}`,J("ensureConnection: opening WS to",i.substring(0,50)+"..."),cs("connecting"),Q=new WebSocket(i);let o=Q;await new Promise((a,c)=>{if(!Q)return c(new Error("WebSocket not created"));let u=setTimeout(()=>{if(Q===o){if(J("ensureConnection: TIMEOUT after",Wa,"ms"),Q&&Q.readyState!==WebSocket.OPEN){try{Q.close()}catch{}Q=null}c(new Error("WebSocket connection timeout"))}},Wa);o.onopen=()=>{if(Q!==o)return;clearTimeout(u),J("ensureConnection: CONNECTED");let l=Ga;Ga=!0,dr=0,cs("connected"),vd(l),(typeof document>"u"||!document.hidden)&&fd(),md(),a()},o.onmessage=l=>{Q===o&&bd(l.data)},o.onerror=()=>{J("ensureConnection: WS error event")},o.onclose=l=>{clearTimeout(u),Q===o&&(J("ensureConnection: WS closed, code:",l.code,"reason:",l.reason),Q=null,pr(),yd(),cs("disconnected"),!On&&fr()&&Za(),c(new Error(`WebSocket closed: ${l.code}`)))}})}catch(e){J("ensureConnection: failed -",e?.message||e)}finally{Tn=null}})(),Tn}function Za(){if(kn||typeof document<"u"&&document.hidden)return;let e=Math.min(1e3*Math.pow(2,dr)+Math.random()*1e3,ld);dr++,J("scheduleReconnect: attempt",dr,"in",Math.round(e),"ms"),kn=setTimeout(()=>{kn=null,fr()&&$t()},e)}function vd(e=!1){for(let t of it.values())J("resubscribeAll: scope",t.scope_id),ot({type:"subscribe",scope_id:t.scope_id,event_types:t.event_types});for(let t of Me.values())J("resubscribeAll: path",t.path),Ai(t.path,t.event_types);e&&ec("reconnect")}function ec(e){try{let t=N();Ba(t),Da(t);for(let n of Me.values())t.invalidateQueries({queryKey:E.item(n.path)}),t.invalidateQueries({queryKey:E.children(n.path)});t.invalidateQueries({queryKey:E.allChannelMessages()}),J("catchUpAfterGap:",e,"- invalidated",Me.size,"paths and the transcripts on screen")}catch(t){J("catchUpAfterGap: cache invalidation skipped",t)}}function ot(e){Q&&Q.readyState===WebSocket.OPEN&&Q.send(JSON.stringify(e))}function bd(e){is=Date.now();try{let t=JSON.parse(e);if(t.type==="subscribed_path"){typeof t.path=="string"&&hd(t.path);return}if(t.type==="subscribed"||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==="resync"){ec(typeof t.reason=="string"?t.reason:"resync");return}if(t.type==="event"||t.event_type){let n=t.event_type||"message",r=t.data||t;if(n==="vfs_change"&&(ja(N(),r),Qa(N(),r)),typeof r.path=="string")for(let[s,i]of Object.entries(Re))s!=="*"&&Ti(s,r.path)&&i.forEach(o=>o(r));Re["*"]&&Re["*"].forEach(s=>s(r));for(let s of Mn)s.eventType!=="*"&&s.eventType!==n||s.filter&&!s.filter(r)||s.callback(r)}}catch{}}function ki(){!_d()&&it.size===0&&Me.size===0&&Q&&(On=!0,pr(),Q.close(),Q=null,On=!1)}function us(e,t){return Re[e]||(Re[e]=[]),Re[e].push(t),Me.has(e)||(Me.set(e,{path:e,event_types:["token_stream"]}),Q&&Q.readyState===WebSocket.OPEN?Ai(e,["token_stream"]):Be.set(e,"pending")),$t(),()=>{let n=Re[e];if(n){let r=n.indexOf(t);r!==-1&&n.splice(r,1),n.length===0&&(delete Re[e],Me.delete(e),Be.delete(e),wt.delete(e),ot({type:"unsubscribe_path",path:e}))}ki()}}function ie(e,t,n){let s=(Array.isArray(e)?e:[e]).map(i=>({eventType:i,callback:t,filter:n}));return Mn.push(...s),fr()&&$t(),()=>{for(let i of s){let o=Mn.indexOf(i);o!==-1&&Mn.splice(o,1)}ki()}}function Fn(e,t=["vfs_change","ccm_change"]){let n=Symbol(e),r=Array.from(new Set(t)).sort();if(r.length===0)return()=>{};let s=An.get(e)??new Map,i=it.get(e)?.event_types;s.set(n,{event_types:r}),An.set(e,s);let o=Ya(e);if(!o)return()=>{};J("subscribeToScope:",e,o.event_types),Q&&Q.readyState===WebSocket.OPEN&&!Ja(i,o.event_types)&&ot({type:"subscribe",scope_id:e,event_types:o.event_types}),$t();let a=!0;return()=>{if(!a)return;a=!1;let c=An.get(e);if(!c?.delete(n))return;let u=it.get(e)?.event_types;if(c.size===0)An.delete(e),it.delete(e),ot({type:"unsubscribe",scope_id:e});else{let l=Ya(e);l&&Q&&Q.readyState===WebSocket.OPEN&&!Ja(u,l.event_types)&&ot({type:"subscribe",scope_id:e,event_types:l.event_types})}ki()}}function tc(e,t,n={}){ot({type:"emit",scope_id:e,event_type:t,payload:n})}function Mi(){J("disconnectSSE: tearing down"),$a(N()),Ua(N()),On=!0,pr(),Q&&(Q.close(),Q=null),kn&&(clearTimeout(kn),kn=null),Tn=null,On=!1,dr=0;for(let e of Object.keys(Re))delete Re[e];Mn.length=0,it.clear(),An.clear(),Me.clear(),Be.clear(),wt.clear(),cs("disconnected")}function nc(){ot({type:"ping"})}function rc(e){return Me.has(e)?Be.get(e)??"pending":"unsubscribed"}function sc(e,t=5e3){return!Me.has(e)||et?Promise.resolve(!1):Be.get(e)==="ready"&&Q&&Q.readyState===WebSocket.OPEN?Promise.resolve(!0):($t(),new Promise(n=>{let r=!1,s=wt.get(e)??[],i=()=>{r||(r=!0,clearTimeout(o),n(!0))};s.push(i),wt.set(e,s);let o=setTimeout(()=>{if(r)return;r=!0;let a=wt.get(e);if(a){let c=a.indexOf(i);c!==-1&&a.splice(c,1),a.length===0&&wt.delete(e)}n(!1)},t)}))}function ic(e){let t=Me.get(e);if(!t){J("resubscribePath: no active subscription for",e);return}Q&&Q.readyState===WebSocket.OPEN?(J("resubscribePath: re-sending frame for",e),Ai(t.path,t.event_types)):(Be.set(e,"pending"),$t())}function ls(e){as.push(e);try{e(Ii)}catch{}return()=>{let t=as.indexOf(e);t!==-1&&as.splice(t,1)}}se(Mi);function oc(){return new Date().toISOString()}function ac(){return crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function Oe(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||oc(),updated_at:e.updated_at||oc(),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 gr(e){return(e.content?.items||e.items||[]).map(Oe)}async function hr(e){try{let t=await x("read",{id:e});if(t.item_name||t.item_path){let r=Oe(t);return r.path&&N().setQueryData(E.item(r.path),r),r}let n=t.item;if(n){let r=Oe(n);return r.path&&N().setQueryData(E.item(r.path),r),r}return null}catch{return null}}async function yr(e){try{let t=await x("read",{path:e});if(t.item_name||t.item_path)return Oe(t);let n=t.item;return n?Oe(n):null}catch{return null}}async function _r(e){try{let t=await x("list",{path:e,limit:200}),n=gr(t);for(let r of n)N().setQueryData(E.item(r.path),r);return n}catch(t){return console.error(`[gateway] Failed to fetch children of ${e}:`,t),[]}}async function cc(e,t){let{items:n}=await Vt({type:"turn_queue_entry",scope:e,parent_id:t,fields:{state:"queued"},sort_by:"created_at",sort_dir:"asc",limit:100});return n.map(r=>{let s=String(r.type_data?.conversation_anchor_item_id??r.type_data?.conversation_root_id??t);return{id:r.id,path:r.path,content:String(r.type_data?.content??""),state:String(r.type_data?.state??"queued"),queue_seq:Number(r.type_data?.queue_seq??0),created_at:r.created_at,conversation_anchor_item_id:s,conversation_root_id:s,client_request_id:typeof r.type_data?.client_request_id=="string"?r.type_data.client_request_id:void 0,promoted_message_id:typeof r.type_data?.promoted_message_id=="string"?r.type_data.promoted_message_id:void 0,promoted_event_id:typeof r.type_data?.promoted_event_id=="string"?r.type_data.promoted_event_id:void 0}}).sort((r,s)=>r.queue_seq-s.queue_seq||r.created_at.localeCompare(s.created_at))}async function fs(e,t,n){try{let r=await x("list",{path:e,limit:t,offset:n}),s=gr(r);for(let i of s)N().setQueryData(E.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 ps(e){let n=await x("types-list",e?{scope_id:e}:{}),r=n.content?.items||n.items||[],s=new Map;for(let i of r){let o=i.name,a=i.type_data;!o||!a||s.set(o,{type_key:o,display_name:a.display_name||o,display_name_plural:a.display_name_plural||o+"s",icon:a.icon||"File",color:a.color||"gray",description:a.description||"",input_schema:a.input_schema||{},system_schema:a.system_schema||{},json_schema:a.input_schema||a.json_schema||{},default_data:a.default_data||{},field_defaults:a.field_defaults||{},renderer_config:a.renderer_config||{},is_system:a.is_system??!1,is_active:a.is_active??!0,is_container:a.is_container??!1,is_scope:a.is_scope??!1,render_mode:a.render_mode||"none",placement_mode:a.placement_mode,direct_parent_types:a.direct_parent_types,allowed_parent_types:a.allowed_parent_types,governed_create:a.governed_create,create_method:a.create_method,dedup:a.dedup,edges:a.edges,events:a.events})}return s}async function ms(e){try{let t=await x("edges",{item_id:e}),n=t.outgoing||[],r=t.incoming||[],s=[];for(let i of n)s.push({id:i.edge_id||ac(),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||ac(),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 gs(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 x("tree",s),o=gr(i);for(let a of o)N().setQueryData(E.item(a.path),a);return o}catch(s){return console.error(`[gateway] Failed to fetch tree at ${e}:`,s),[]}}async function hs(e,t=50,n=0){try{let r=await x("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 vr(e,t={}){let{limit:n=50,offset:r=0,include_snapshots:s=!1}=t;try{let i=await x("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 ys(e,t=50,n=0){return vr(e,{limit:t,offset:n})}async function _s(e,t,n){try{let r={scope_id:e};t?.length&&(r.item_types=t),n&&(r.limit=n);let s=await x("member-focus",r),i=gr(s);for(let o of i)N().setQueryData(E.item(o.path),o);return i}catch(r){return console.error(`[gateway] Failed to fetch member focus for scope ${e}:`,r),[]}}async function br(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 x("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}}function qn(e){return!!e&&(!!e.type||Array.isArray(e.any_of)&&e.any_of.length>0)}function wd(e){let t={};e.item_type&&(t.item_type=e.item_type);for(let[n,r]of Object.entries(e.fields??{}))t[`field.${n}`]=String(r);for(let[n,r]of Object.entries(e.field_in??{}))t[`field_in.${n}`]=r.map(String);return t}var Sd=["catalog","parent_only","internal"];function uc(e,t={}){if(!e||typeof e!="object")return null;let n=o=>typeof o=="string"||typeof o=="number"||typeof o=="boolean",r=o=>{let a={},c={};for(let[u,l]of Object.entries(o))u.startsWith("field.")&&u.length>6&&n(l)?a[u.slice(6)]=l:u.startsWith("field_in.")&&u.length>9&&Array.isArray(l)&&(c[u.slice(9)]=l.filter(n));return{fields:a,field_in:c}},s={};typeof e.type=="string"&&e.type&&(s.type=e.type),typeof e.sort_by=="string"&&(s.sort_by=e.sort_by),(e.sort_dir==="asc"||e.sort_dir==="desc")&&(s.sort_dir=e.sort_dir),typeof e.name=="string"&&e.name&&(s.name=e.name),typeof e.tag=="string"&&e.tag&&(s.tag=e.tag),typeof e.discovery=="string"&&Sd.includes(e.discovery)&&(s.discovery=e.discovery);let i=r(e);if(Object.keys(i.fields).length&&(s.fields=i.fields),Object.keys(i.field_in).length&&(s.field_in=i.field_in),Array.isArray(e.any_of)){let o=[];for(let a of e.any_of){if(!a||typeof a!="object"||Array.isArray(a))continue;let c=a,u={};typeof c.item_type=="string"&&c.item_type&&(u.item_type=c.item_type);let l=r(c);Object.keys(l.fields).length&&(u.fields=l.fields),Object.keys(l.field_in).length&&(u.field_in=l.field_in),Object.keys(u).length&&o.push(u)}o.length&&(s.any_of=o)}return qn(s)?{...s,...t}:null}async function Vt(e,t={}){if(e=bt(e),e.spaceIds?.length===0)return{items:[],total_hint:0};let n={};e.type&&(n.item_type=e.type),e.scope&&(n.scope_path=e.scope);let r={};if(e.spaceIds!==void 0&&(r.space_ids=e.spaceIds),e.name&&(r.name=e.name),e.tag&&(r.tag=e.tag),e.parent_id&&(r.parent_id=e.parent_id),e.sort_by&&(r.sort_by=e.sort_by),e.sort_dir&&(r.sort_dir=e.sort_dir),e.offset!=null&&(r.offset=e.offset),e.fields)for(let[s,i]of Object.entries(e.fields))r[`field.${s}`]=String(i);if(e.field_in)for(let[s,i]of Object.entries(e.field_in))r[`field_in.${s}`]=i.map(String);e.discovery&&(r.discovery=e.discovery),e.any_of?.length&&(r.any_of=e.any_of.map(wd)),Object.keys(r).length>0&&(n.filters=r),e.limit!=null&&(n.limit=e.limit);try{let s=await x("query",n,t);e.spaceIds!==void 0&&Va(e.spaceIds,s.selected_space_ids??s.content?.selected_space_ids);let i=gr(s);for(let o of i)N().setQueryData(E.item(o.path),o);return{items:i,total_hint:s.total??s.content?.total??i.length}}catch(s){if(t.signal?.aborted||s instanceof Error&&s.name==="AbortError"||(console.error(`[gateway] Failed to fetch items of type ${e.type??"(any_of)"}:`,s),t.throwOnError||e.spaceIds!==void 0))throw s;return{items:[],total_hint:0}}}function xd(e){if(!e||typeof e!="object")return;let t=e;if(t.version!==1||typeof t.work_id!="string"||!t.work_id)return;let n=r=>{let s=t[r];return typeof s=="string"&&s?s:void 0};return{version:1,workId:t.work_id,threadRootId:n("thread_root_id"),requestMessageId:n("request_message_id"),replyMessageId:n("reply_message_id"),replyMessagePath:n("reply_message_path"),todoListId:n("todo_list_id"),todoListPath:n("todo_list_path"),stepId:n("step_id"),stepPath:n("step_path"),runId:n("run_id"),parentRunId:n("parent_run_id"),toolCallId:n("tool_call_id"),traceId:n("trace_id")}}function lc(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,origin:xd(n.origin),presentationRole:r.presentation_role==="user-request"?"user-request":r.presentation_role==="output"?"output":void 0}}).sort((t,n)=>t.createdAt.localeCompare(n.createdAt))}function mr(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,status:typeof n.status=="string"?n.status:void 0,delivery_state:typeof n.delivery_state=="string"?n.delivery_state:void 0,cognition_event_id:typeof n.cognition_event_id=="string"?n.cognition_event_id:void 0,seq:n.seq||0,principal_id:n.principal_id,member_id:typeof n.member_id=="string"?n.member_id:void 0,sender_display_name:typeof n.sender_display_name=="string"?n.sender_display_name:void 0,sender_is_ai:typeof n.sender_is_ai=="boolean"?n.sender_is_ai:void 0,sender_role_display_name:typeof n.sender_role_display_name=="string"?n.sender_role_display_name:void 0,reply_count:n.reply_count||0,member_count:n.member_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 dc(e,t){try{let n={channel_path:e};t&&(n.parent_message_id=t);let s=await x("get-channel-messages",n),i=s.messages||s.content?.items||s.items||[];return mr(i)}catch(n){throw console.error(`[gateway] Failed to fetch channel messages for ${e}:`,n),n}}async function vs(e,t){try{let n={channel_path:e};t&&(n.parent_message_id=t);let s=await x("get-channel-messages",n),i=s.messages||[],o=mr(i),a=lc(i),c=new Map,u=[];for(let l of a)if(l.parentMessagePath){let f=c.get(l.parentMessagePath)||[];f.push(l),c.set(l.parentMessagePath,f)}else u.push(l);return{messages:o,activityMessages:mr(s.activity_messages||[]),messageCards:c,siblingCards:u,mode:s.mode||"top_level"}}catch(n){throw console.error(`[gateway] Failed to fetch channel messages with cards for ${e}:`,n),n}}async function wr(e,t){try{let n={channel_path:e};t?.parentMessageId&&(n.parent_message_id=t.parentMessageId),t?.conversationsOnly&&(n.conversations_only=!0),t?.transcriptOnly&&(n.transcript_only=!0),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 x("get-channel-messages",n);if(t?.conversationsOnly&&s.conversations_only!==!0)throw new Error("This server does not support conversation history lists yet. Update the message reader.");if(t?.transcriptOnly&&s.transcript_only!==!0)throw new Error("This server does not support channel transcript pages yet. Update the message reader.");let i=s.messages||[],o=lc(i),a=new Map,c=[];for(let u of o)if(u.parentMessagePath){let l=a.get(u.parentMessagePath)||[];l.push(u),a.set(u.parentMessagePath,l)}else c.push(u);return{messages:mr(i),activityMessages:mr(s.activity_messages||[]),messageCards:a,siblingCards:c,mode:s.mode||"top_level"}}catch(n){throw console.error(`[gateway] Failed to fetch channel messages page for ${e}:`,n),n}}function ds(e){N().invalidateQueries({queryKey:E.children(e)})}function Oi(e){N().invalidateQueries({queryKey:E.item(e)})}function fc(e,t){Oi(e),ds(e);let n=e.split("/");n.pop();let r=n.join("/")||t;r&&ds(r)}function pc(e){let t=e+"/";N().invalidateQueries({predicate:n=>{let r=n.queryKey;return r[0]!=="vfs"?!1:r.some(s=>typeof s=="string"&&(s===e||s.startsWith(t)))}})}function mc(){N().invalidateQueries({queryKey:E.all()})}function gc(e){N().invalidateQueries({queryKey:E.types(e)})}function hc(e,t){e?N().invalidateQueries({queryKey:E.channelMessages(e,t)}):N().invalidateQueries({queryKey:E.allChannelMessages()})}function yc(e,t){e&&t?N().invalidateQueries({queryKey:E.openEnvelope(e,t)}):e?N().invalidateQueries({predicate:n=>{let r=n.queryKey;return r[0]==="vfs"&&r[2]==="open"&&r[3]===e}}):N().invalidateQueries({queryKey:E.allOpenEnvelopes()})}function $e(e){return{id:e.accountId,path:e.path,kind:e.isSpace?"space":"account",name:e.name,grantedUnderAccountId:e.grantedUnderAccountId??void 0}}async function bs(){return((await x("list-memberships",{})).memberships||[]).map(n=>({accountId:n.account_id,path:n.account_path,name:n.account_name,role:n.role||"member",typeData:n.account_type_data||{},joinedAt:n.joined_at,via:n.via,placement:n.placement,subordinateTo:n.subordinate_to??null,cascadeAnchorId:n.cascade_anchor_id??null,isAccount:n.is_account??void 0,isSpace:n.is_space??void 0,isOwner:n.is_owner??void 0,billingResponsible:n.billing_responsible??void 0,grantedVia:n.granted_via??null,invitationAccepted:n.invitation_accepted===!0,grantedUnderAccountId:n.granted_under_account_id??null,membershipPath:n.membership_path??null,personalSpaceId:n.personal_space_id??null,personalSpacePath:n.personal_space_path??null}))}var Nn=new Map,xr=null,ws=null,St=new Map,_c=250,Sr=new Map;function Wt(e){if(xr){Qn(e);return}Qn(e),xr=ie("vfs_change",t=>Rd(t)),ws=ie("ccm_change",t=>Pd(t))}function Qn(e){if(Nn.has(e))return;let t=Fn(e,["vfs_change","ccm_change"]);Nn.set(e,t)}function Ss(e){let t=Nn.get(e);t&&(t(),Nn.delete(e))}function Fi(){for(let[,e]of Nn)e();Nn.clear(),xr&&(xr(),xr=null),ws&&(ws(),ws=null),St.forEach(e=>clearTimeout(e)),St.clear(),Sr.clear()}se(Fi);function Rd(e){let t=e.path,n=e.action;if(!t)return;let r=t.split("/");r.pop();let s=r.join("/")||"/root",i=Sr.get(s);i||(i=new Map,Sr.set(s,i)),i.set(t,{action:n,itemId:typeof e.item_id=="string"?e.item_id:void 0});let o=St.get(s);o&&clearTimeout(o);let a=setTimeout(()=>{St.delete(s);let c=Sr.get(s);Sr.delete(s),c&&Cd(s,c)},_c);St.set(s,a)}function Pd(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)||!t&&!n||e.item_type==="message")return;let s=`ccm:${t??""}:${n??""}`,i=St.get(s);i&&clearTimeout(i);let o=setTimeout(()=>{St.delete(s),t&&N().invalidateQueries({queryKey:E.edges(t)}),n&&N().invalidateQueries({queryKey:E.edges(n)})},_c);St.set(s,o)}function Cd(e,t){let n=N();for(let[s,i]of t)(i.action||"").toUpperCase()==="DELETE"?(n.removeQueries({queryKey:E.item(s)}),n.removeQueries({queryKey:E.children(s)}),n.removeQueries({queryKey:E.tree(s)})):be(n,E.item(s),{exact:!0}),i.itemId&&n.invalidateQueries({queryKey:E.itemById(i.itemId)});n.invalidateQueries({queryKey:E.children(e)});let r=[...t.keys()];n.invalidateQueries({predicate:s=>{let i=s.queryKey;if(i[0]!=="vfs"||i[1]!=="tree")return!1;let o=i[2];return r.some(a=>a.startsWith(o+"/")||a===o)}})}var Dn=null;se(()=>{Dn=null});function xt(e){if(e!==Dn||e.generation!==ae())throw new Error("Workspace session changed")}function Ed(e){return e instanceof ge&&e.payload?.error==="item_not_found"}function Rr(e,t){let n=e.resolve(t.id);if(!n||n.path!==t.path||n.kind!==t.kind)throw new Error("Mount is not an available membership");return n}function Pr(e){let t=me();if(!t)throw new Error("Elect a home account before loading mounts");return[t,...e.filter((n,r)=>n.id!==t.id&&e.findIndex(s=>s.id===n.id)===r)]}function vc(e,t){return JSON.stringify({mounts:e.map(n=>n.id),last_anchor:t.id})}async function bc(e,t,n){xt(e);let r=vc(t,n);if(e.saved===r)return;let s=JSON.parse(r);await x(e.exists?"update":"create",e.exists?{_scope_path:e.scope,path:e.path,type_data:s}:{_scope_path:e.scope,parent_path:e.path.slice(0,e.path.lastIndexOf("/")),name:"mounts",item_type:"file",type_data:s}),xt(e),e.exists=!0,e.saved=r}function wc(e,t){let n=Ae();Wt(me().id);for(let r of n)e.some(s=>s.id===r.id)||Ss(r.id);for(let r of e)Qn(r.id);la(e,t)}async function Gt(e,t,n={}){let r=me();if(!r)throw new Error("Elect a home account before loading mounts");let s=`${e}/settings/mounts`;if(Dn&&Dn.path!==s)throw new Error("Reset the session before changing the mount declaration owner");let i=Dn??(Dn={generation:ae(),path:s,scope:r.path,resolve:t,exists:!1,ready:!1,saved:null,queue:Promise.resolve()});return xt(i),i.resolve=t,i.loading?i.loading:i.ready?Ae():(i.loading=(async()=>{let o=null;try{let l=await x("read",{path:s,_scope_path:i.scope});if(xt(i),o=l.type_data??l.item?.type_data,!o||!Array.isArray(o.mounts)||!o.mounts.every(f=>typeof f=="string"))throw new Error("Invalid saved mount declaration");i.exists=!0}catch(l){if(xt(i),!Ed(l))throw l;i.exists=!1}let a=n.initialAnchor?Rr(i,n.initialAnchor):r,c=Pr(o?o.mounts.map(l=>i.resolve(l)).filter(l=>l!==null):[a]),u=o?c.find(l=>l.id===o.last_anchor)??c.find(l=>l.kind==="space")??r:a;return o?i.saved=vc(c,u):n.initialAnchor&&await bc(i,c,u),xt(i),i.ready=!0,wc(c,u),c})().finally(()=>{i.loading=void 0}),i.loading)}function xs(e){let t=Dn;if(!t?.ready)return Promise.reject(new Error("Workspace mounts are not loaded"));let n=t.queue.then(async()=>{xt(t);let{refs:r,anchor:s}=e(t);await bc(t,r,s),xt(t),wc(r,s)});return t.queue=n.catch(()=>{}),n}function qi(e){return xs(t=>({refs:Pr([...Ae(),Rr(t,e)]),anchor:de()}))}function Sc(e){return xs(()=>{if(e===me().id)throw new Error("The home account cannot be unmounted");let t=Pr(Ae().filter(r=>r.id!==e)),n=t.find(r=>r.id===de()?.id)??t.find(r=>r.kind==="space")??me();return{refs:t,anchor:n}})}function Cr(e){return xs(t=>{let n=Rr(t,e);return{refs:Pr([...Ae(),n]),anchor:n}})}function Rs(e,t){return xs(n=>{let r=Pr(e.map(i=>Rr(n,i))),s=Rr(n,t);if(!r.some(i=>i.id===s.id))throw new Error("Selected mount must be in the working set");return{refs:r,anchor:s}})}var Ni={};co(Ni,{Badge:()=>Od,Breadcrumbs:()=>Bd,Button:()=>qd,Card:()=>Md,DataView:()=>Qd,Detail:()=>Kd,Empty:()=>Nd,FilePreview:()=>Wd,Form:()=>Ud,Grid:()=>Ad,Image:()=>$d,Link:()=>Hd,Page:()=>Id,Router:()=>Ld,Sidebar:()=>kd,Spinner:()=>Fd,Stack:()=>Td,Table:()=>Dd,Tabs:()=>jd,Video:()=>Vd});var G=Y(ue(),1);function xc(){return(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||""}function Id(e){return(0,G.createElement)("div",{style:{minHeight:"100vh",display:"flex",flexDirection:"column"},className:e.className||""},e.children)}function Td(e){let t=e.direction||"vertical";return(0,G.createElement)("div",{style:{display:"flex",flexDirection:t==="horizontal"?"row":"column",gap:e.gap||"0.5rem",padding:e.padding||"0",alignItems:e.align||"stretch",justifyContent:e.justify||"flex-start",flex:e.flex||"initial"},className:e.className||""},e.children)}function Ad(e){return(0,G.createElement)("div",{style:{display:"grid",gridTemplateColumns:"repeat("+(e.columns||3)+", 1fr)",gap:e.gap||"1rem",padding:e.padding||"0"},className:e.className||""},e.children)}function kd(e){return(0,G.createElement)("div",{style:{display:"flex",flexDirection:"row",minHeight:"100vh"},className:e.className||""},e.children)}function Md(e){return(0,G.createElement)("div",{style:{border:"1px solid var(--color-border, #e5e7eb)",borderRadius:"var(--border-radius, 0.5rem)",padding:e.padding||"1rem",background:"var(--color-surface, #fff)"},className:e.className||"",onClick:e.onClick},e.children)}function Od(e){return(0,G.createElement)("span",{style:{display:"inline-flex",alignItems:"center",padding:"0.125rem 0.5rem",fontSize:"0.75rem",fontWeight:"500",borderRadius:"9999px",background:e.color||"#e5e7eb",color:e.textColor||"#374151"},className:e.className||""},e.children||e.label)}function Fd(e){let t=e.size||"1.5rem";return(0,G.createElement)("div",{style:{width:t,height:t,border:"2px solid #e5e7eb",borderTopColor:"var(--color-primary, #3b82f6)",borderRadius:"50%",animation:"fsaos-spin 0.6s linear infinite"}})}function qd(e){return(0,G.createElement)("button",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",padding:"0.5rem 1rem",fontSize:"0.875rem",fontWeight:"500",borderRadius:"var(--border-radius, 0.375rem)",border:e.variant==="outline"?"1px solid var(--color-border, #d1d5db)":"none",background:e.variant==="outline"||e.variant==="ghost"?"transparent":"var(--color-primary, #3b82f6)",color:e.variant==="outline"||e.variant==="ghost"?"var(--color-text, #1a1a1a)":"#fff",cursor:e.disabled?"not-allowed":"pointer",opacity:e.disabled?"0.5":"1",gap:"0.5rem"},className:e.className||"",onClick:e.onClick,disabled:e.disabled},e.children||e.label)}function Nd(e){return(0,G.createElement)("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:"3rem",color:"var(--color-text-secondary, #6b7280)",textAlign:"center"}},e.icon?(0,G.createElement)("div",{style:{fontSize:"2rem",marginBottom:"0.5rem"}},e.icon):null,(0,G.createElement)("div",{style:{fontWeight:500,marginBottom:"0.25rem"}},e.title||e.message||e.children||"No items"),e.description?(0,G.createElement)("div",{style:{fontSize:"0.875rem",opacity:.7}},e.description):null)}function Qd(e){return(0,G.createElement)("div",{className:e.className||""},e.children)}function Dd(e){return(0,G.createElement)("table",{className:e.className||""},e.children)}function Ud(e){return(0,G.createElement)("form",{className:e.className||"",onSubmit:e.onSubmit},e.children)}function Kd(e){return(0,G.createElement)("div",{className:e.className||""},e.children)}function Ld(e){return(0,G.createElement)("div",null,e.children)}function Hd(e){return(0,G.createElement)("a",{href:e.href||e.to,className:e.className||"",onClick:e.onClick},e.children)}function jd(e){return(0,G.createElement)("div",{className:e.className||""},e.children)}function Bd(e){return(0,G.createElement)("nav",{className:e.className||""},e.children)}function $d(e){return(0,G.createElement)("img",{src:e.src||(e.path?xc()+e.path:""),alt:e.alt||"",className:e.className||"",style:e.style})}function Vd(e){return(0,G.createElement)("video",{src:e.src||(e.path?xc()+e.path:""),controls:!0,className:e.className||""})}function Wd(e){return(0,G.createElement)("div",{className:e.className||""},e.children||"File preview")}function Ps(e){if(typeof e.path!="string")return!1;let t=[...Ae().map(n=>n.path),de()?.path].filter(n=>!!n);return!t.length&&W()&&t.push(W()),t.some(n=>he(e.path,n))}function Qi(e,t,n,r){if(!["message","card"].includes(e?.item_type)||!he(e.path,t))return!1;if(!n){let s=e.path.slice(t.length).replace(/^\//,""),i=s?s.split("/").length:0;return e.item_type==="message"?i===1:i===1||i===2}return e.item_id===n||e.parent_id===n?!0:r.some(s=>{if(e.item_id===s.id||e.parent_id===s.id)return!0;let i=s.id===n?s.path:s.parent_message_id===n?s.path.slice(0,s.path.lastIndexOf("/")):void 0;return!!i&&he(e.path,i)})}var Rc=new WeakMap;function Pc(e,t,n){let r=Rc.get(e);r||(r=new Map,Rc.set(e,r));let s=JSON.stringify(t),i=r.get(s);if(!i){let a=!1,c,u=!1,l=!1,f=new Set,h=new Set,p=()=>e.getQueryData(t)??[],m=()=>{a||u||c||(c=setTimeout(()=>{c=void 0,y()},250))},y=async()=>{if(a)return;u=!0;let C=l;l=!1;let R=[...f],M=new Set(h);h.clear(),f.clear();try{if(C)await be(e,t,{exact:!0});else{let P=(await Promise.allSettled(R.map(async k=>{let T=e.getQueryCache().find({queryKey:t,exact:!0});if(!T)return;let A=await x("read",{id:k});if(A.success===!1)throw new Error("Channel refresh failed");if(a||!T||e.getQueryCache().find({queryKey:t,exact:!0})!==T)return;let O=Oe(A.item??A);if(O.id!==k||O.item_type!=="channel")return;let q=p().find(Pe=>Pe.id===k);if(!q)return;let K=n({...O}),$={...q,path:K.path,name:K.name,displayName:K.displayName,messageCount:K.messageCount,aiMode:K.aiMode,activeAgentIds:K.activeAgentIds,isPrivate:K.isPrivate,isDm:K.isDm,autoPilot:K.autoPilot,isArchived:K.isArchived,updatedAt:K.updatedAt};M.has(k)&&(q.name!==$.name||q.displayName!==$.displayName||q.path!==$.path)&&(l=!0),e.setQueryData(t,Pe=>Pe?.map(re=>re.id===k?$:re))}))).find(k=>k.status==="rejected");if(P?.status==="rejected")throw P.reason}}catch(D){console.warn("[channels] refresh failed",D)}finally{u=!1,(l||f.size)&&m()}},g=C=>p().some(R=>R.id===C.item_id||R.path===C.path)?!0:Ps(C),v=C=>{if(!g(C))return;let R=String(C.action??"").toLowerCase();if(["insert","delete","rename","move"].includes(R))l=!0;else if(R==="update"){let M=p().find(D=>D.id===C.item_id||D.path===C.path);M&&(f.add(M.id),h.add(M.id))}(l||f.size)&&m()},_=C=>{let R=p().find(M=>M.id===C.parent_id);R&&(f.add(R.id),m())},w=["vfs_change","ccm_change"].flatMap(C=>[ie(C,v,R=>R.item_type==="channel"),ie(C,_,R=>R.item_type==="message")]);i={users:0,stop:()=>{a=!0,c&&clearTimeout(c),w.forEach(C=>C())}},r.set(s,i)}i.users++;let o=!1;return()=>{o||(o=!0,--i.users===0&&(i.stop(),r.delete(s)))}}function te(){return(0,b.useSyncExternalStore)(xe,ee,ee)}function Mc(){return te(),zr()}function Oc(e){return te(),B({queryKey:E.item(e),queryFn:()=>yr(e),enabled:!!e,staleTime:1/0})}function Fc(e){return te(),B({queryKey:E.itemById(e),queryFn:()=>hr(e),enabled:!!e,staleTime:1/0})}function Ki(e){return te(),B({queryKey:E.children(e),queryFn:()=>_r(e),enabled:!!e})}function qc(e){let t=Ki(e);return{...t,children:t.data??[]}}function Nc(e,t=1){return te(),B({queryKey:E.tree(e,t),queryFn:()=>gs(e,t),enabled:!!e})}function Qc(e,t){return te(),B({queryKey:E.search(e,t),queryFn:async()=>{let n={query:e};t?.length&&(n.item_types=t);let r=await x("search",n);return(r.content?.items||r.items||r.results||[]).map(Oe)},enabled:!!e&&e.length>0})}function Dc(e){te();let t=(0,b.useMemo)(()=>e,[JSON.stringify(e)]);return B({queryKey:["vfs",W()??"__unscoped__","resolve",JSON.stringify(t??{})],queryFn:async()=>await x("resolve",t),enabled:!!t?.query&&t.query.length>0})}function Uc(e){te();let t=bt(e),n=(0,b.useMemo)(()=>t,[JSON.stringify(t)]),r=B({queryKey:E.items(n?.type??"",n),queryFn:({signal:s})=>Vt(n,{signal:s,throwOnError:!0}),enabled:qn(n),...n?.spaceIds!==void 0?{retry:(s,i)=>!In(i)&&Mu(s,i)}:{},select:s=>s.items});return n?.spaceIds!==void 0&&In(r.error)?{...r,data:void 0}:r}function Li(e,t={}){let n=te(),{realtime:r=!1}=t,s=bt(e),i=s?.limit??20,o=(0,b.useMemo)(()=>s,[JSON.stringify(s)]),a=(0,b.useMemo)(()=>["vfs",W()??"__unscoped__","infinite-items",o?.type??"",JSON.stringify(o??{})],[n,o]),c=or({queryKey:a,queryFn:async({pageParam:f=0,signal:h})=>Vt({...o,limit:i,offset:f},{throwOnError:!0,signal:h,priority:t.priority}),initialPageParam:0,getNextPageParam:(f,h,p)=>{if(!(o?.spaceIds!==void 0&&f.total_hint!==void 0&&p+f.items.length>=f.total_hint)&&!(f.items.length<i))return p+f.items.length},enabled:qn(o),...o?.spaceIds!==void 0?{retry:(f,h)=>!In(h)&&Mu(f,h)}:{},staleTime:r?1/0:t.staleTime,meta:r&&o?{infiniteItemsRealtime:{filter:o}}:{}}),u=(0,b.useMemo)(()=>{if(o?.spaceIds!==void 0&&In(c.error))return[];if(!c.data?.pages)return[];let f=new Set,h=[];for(let p of c.data.pages)for(let m of p.items)m.id&&!f.has(m.id)&&(f.add(m.id),h.push(m));return h},[c.data?.pages,c.error,o]),l=o?.spaceIds!==void 0&&In(c.error);return{allItems:u,refetch:c.refetch,fetchNextPage:c.fetchNextPage,isFetchingNextPage:c.isFetchingNextPage,isExhausted:l||!c.hasNextPage,isLoading:c.isLoading,isFetching:c.isFetching,error:c.error,totalHint:l?void 0:c.data?.pages?.[0]?.total_hint}}function Cc(e){return!!e?.type&&!!e.scope&&e.sort_by==="created_at"&&!e.offset&&!e.spaceIds&&!e.any_of&&!e.name&&!e.tag&&!e.discovery}function Jd(e,t){if(e.is_active===!1||e.item_type!==t.type||!he(e.path,t.scope)||t.parent_id&&e.parent_id!==t.parent_id)return!1;let n=e.type_data??{};for(let[r,s]of Object.entries(t.fields??{})){let i=n[r];if(typeof s=="string"&&s.endsWith("*")){if(typeof i!="string"||!i.startsWith(s.slice(0,-1)))return!1}else if(i!==s)return!1}for(let[r,s]of Object.entries(t.field_in??{}))if(!s.includes(n[r]))return!1;return!0}function Kc(e,t={}){let n=Cc(e),r=Li(e,n?{realtime:!1,staleTime:3e4}:{realtime:!0}),s=L(),i=JSON.stringify([W(),bt(e)]),[o,a]=(0,b.useState)(()=>({identity:i,upserts:{},deleted:new Set})),c=o.identity===i?o:{identity:i,upserts:{},deleted:new Set},u=(0,b.useMemo)(()=>{if(!n)return r.allItems;let p=Object.values(c.upserts),m=new Set(p.map(_=>_.id)),y=[...p,...r.allItems.filter(_=>!m.has(_.id))].filter(_=>!c.deleted.has(_.path)),g=e.sort_by??"updated_at",v=e.sort_dir==="asc"?1:-1;return y.sort((_,w)=>v*String(_[g]??"").localeCompare(String(w[g]??"")))},[n,r.allItems,c,e?.sort_by,e?.sort_dir]),l=(0,b.useRef)(u);l.current=u;let f=(0,b.useRef)(t.shouldReadUpdate);f.current=t.shouldReadUpdate;let h=(0,b.useRef)(r.refetch);return h.current=r.refetch,(0,b.useEffect)(()=>{if(!Cc(e))return;let p=e,m=!1,y=!1,g=!1,v=0,_=new Map,w=()=>{let P=v;h.current().then(k=>{!m&&!k.isError&&v===P&&a({identity:i,upserts:{},deleted:new Set})})},C=P=>{v++,a(T=>{let A=T.identity===i?T:{identity:i,upserts:{},deleted:new Set},O={...A.upserts};return delete O[P],{identity:i,upserts:O,deleted:new Set(A.deleted).add(P)}});let k=_.get("__reconcile__");k&&clearTimeout(k),_.set("__reconcile__",setTimeout(()=>{_.delete("__reconcile__"),w()},250))},R=P=>{let k=_.get(P);k&&clearTimeout(k),_.set(P,setTimeout(()=>{_.delete(P),s.fetchQuery({queryKey:E.item(P),queryFn:()=>yr(P),staleTime:0}).then(T=>{if(!m){if(!T||!Jd(T,p)){let A=l.current.find(O=>O.path===P||O.id===T?.id);A&&C(A.path);return}a(A=>{let O=A.identity===i?A:{identity:i,upserts:{},deleted:new Set},q=new Set(O.deleted);return q.delete(P),{identity:i,upserts:{...O.upserts,[P]:T},deleted:q}})}}).catch(T=>console.warn("[useIncrementalItems] item read failed:",T))},250))},M=ie("vfs_change",P=>{if(!P||typeof P.path!="string"&&typeof P.old_path!="string")return;let k=typeof P.path=="string"?P.path:P.old_path,T=l.current.find(O=>O.path===k||O.path===P.old_path||P.item_id&&O.id===P.item_id),A=!!T;if(!(!he(k,p.scope)&&!he(P.old_path,p.scope)&&!A)&&!(P.item_type&&P.item_type!==p.type&&!A)&&!(p.parent_id&&P.parent_id&&P.parent_id!==p.parent_id&&!A)){if(T&&(k!==T.path||P.old_path&&P.old_path!==k||P.parent_id&&P.parent_id!==T.parent_id||P.item_type&&P.item_type!==p.type)){C(T.path);return}if(!T&&P.old_path&&P.old_path!==k&&he(k,p.scope)){v++,R(k);return}if(P.action==="insert")v++,R(k);else if(P.action==="move")v++,R(k);else if(P.action==="update"){if(!f.current?.(P,l.current))return;v++,R(k)}else P.action==="delete"&&C(T?.path??P.old_path??k)}}),D=ls(P=>{if(P!=="connected"){y&&(g=!0);return}y=!0,g&&(g=!1,w())});return()=>{m=!0,M(),D(),_.forEach(clearTimeout)}},[s,i]),{...r,allItems:u}}function Lc(e){te();let t=20,n=or({queryKey:["vfs",W()??"__unscoped__","infinite-children",e??""],queryFn:async({pageParam:s=0})=>fs(e,t,s),initialPageParam:0,getNextPageParam:(s,i,o)=>{if(!(s.items.length<t))return o+s.items.length},enabled:!!e});return{allItems:(0,b.useMemo)(()=>{if(!n.data?.pages)return[];let s=new Set,i=[];for(let o of n.data.pages)for(let a of o.items)a.id&&!s.has(a.id)&&(s.add(a.id),i.push(a));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 Hc(e){return te(),B({queryKey:E.edges(e),queryFn:()=>ms(e),enabled:!!e})}function Es(e){return te(),B({queryKey:E.types(e),queryFn:()=>ps(e)})}function jc(e,t){let n=Es(t);return{...n,data:n.data?.get(e)??void 0}}function Bc(e,t){te();let n=(0,b.useMemo)(()=>t?.arguments,[JSON.stringify(t?.arguments)]),r=t?.mode,s=t?.strategy,i=t?.width;return B({queryKey:[...E.openEnvelope(e,s),i],queryFn:async()=>{let o=await br(e,{mode:r,strategy:s,arguments:n});if(i&&o.render?.props?.url){let a=o.render.props.url,c=a.includes("?")?"&":"?";o.render.props.url=`${a}${c}w=${i}`}return o},enabled:!!e})}var Ec={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 $c(e){let t=Es(e),n=t.data??new Map;return(0,b.useMemo)(()=>({canHaveChildren:p=>n.get(p.item_type)?.is_container??!1,isScope:p=>n.get(p.item_type)?.is_scope??!1,isScopeType:p=>n.get(p)?.is_scope??!1,isContainerType:p=>n.get(p)?.is_container??!1,getTypeDefinition:p=>n.get(p),getTypeColor:p=>n.get(p)?.color??"gray",getTypeIcon:p=>n.get(p)?.icon??"File",getTypeDisplayName:p=>n.get(p)?.display_name??p,getKnownEdgeTypes:()=>Object.entries(Ec).map(([p,m])=>({key:p,label:m})),getEdgeTypeLabel:p=>Ec[p]??p.replace(/_/g," "),allTypes:n,loading:t.isLoading}),[n,t.isLoading])}function Vc(e,t,n){return te(),B({queryKey:E.memberFocus(e),queryFn:()=>_s(e,t,n),enabled:!!e})}function Wc(e,t={}){let{limit:n=50,offset:r=0,include_snapshots:s=!1}=t;return B({queryKey:E.itemVersions(e,String(n),String(r),String(s)),queryFn:()=>vr(e,{limit:n,offset:r,include_snapshots:s}),enabled:!!e})}function Gc(e,t=50,n=0){return B({queryKey:E.itemHistory(e,String(t),String(n)),queryFn:()=>ys(e,t,n),enabled:!!e})}function zc(e,t=50,n=0){return te(),B({queryKey:E.recentActivity(e,String(t),String(n)),queryFn:()=>hs(e,t,n),enabled:!!e})}function Jc(){let[e,t]=(0,b.useState)(null),[n,r]=(0,b.useState)(!0),[s,i]=(0,b.useState)(null);return(0,b.useEffect)(()=>{let o=!1;return nt().then(a=>{if(!o){let c=typeof window<"u"&&window.__FSAOS_CONFIG__||{};t({path:a.scope_path,scope_id:a.scope_id,fractal_id:a.fractal_id,instance_name:a.instance_name,display_name:a.display_name,componentPath:c.componentPath||"",isEmbed:!!c.embedToken}),r(!1)}}).catch(a=>{o||(i(a instanceof Error?a:new Error(String(a))),r(!1))}),()=>{o=!0}},[]),{data:e,loading:n,error:s}}var Yd=[];function Ic(){if(typeof window>"u")return!1;let e=window.__FSAOS_CONFIG__?.embedToken;return typeof e=="function"||typeof e=="string"&&e.length>0}function Zd(e){return e.filter(t=>t.placement==="switcher_entry").map(t=>({account:t,mountables:e.filter(n=>n.placement!=="switcher_entry"&&n.subordinateTo===t.accountId)}))}function Yc(){let{user:e}=Is(),t=(0,b.useSyncExternalStore)(pa,vi,vi),n=vt()?.principal_id??null,r=(0,b.useRef)(null),[s,i]=(0,b.useState)(null),[o,a]=(0,b.useState)(null);(0,b.useEffect)(()=>{if(n){a(null);return}if(!e?.id&&!Ic()){a(null);return}let _=!1;return nt().then(w=>{_||w.principal_id||a(new Error("Memberships require an authenticated principal"))}).catch(w=>{_||a(w instanceof Error?w:new Error(String(w)))}),()=>{_=!0}},[n,e?.id,t]);let c=B({queryKey:E.memberships(n??"anonymous"),queryFn:bs,enabled:!!n,staleTime:1e3*60*2}),u=c.data??Yd,l=(0,b.useMemo)(()=>u.filter(_=>_.isAccount!==!1&&!_.isSpace),[u]),f=(0,b.useMemo)(()=>{let _=new Set(l.map(C=>C.accountId)),w=C=>!C.subordinateTo||!_.has(C.subordinateTo);return[...l].sort((C,R)=>Number(w(R))-Number(w(C)))},[l]),h=(0,b.useSyncExternalStore)(xe,ee,ee),p=(0,b.useMemo)(()=>{let _=de();return _?u.find(w=>w.accountId===_.id)??null:null},[h,u]),m=(0,b.useMemo)(()=>Zd(l),[l]);(0,b.useEffect)(()=>{if(!n){r.current=null;return}if(r.current!==n)if(i(null),f.length===1){let _=f[0];me()||Kt($e(_)),Wt(_.accountId),_.personalSpacePath&&Gt(_.personalSpacePath,w=>{let C=u.find(R=>R.accountId===w);return C?$e(C):null}).catch(i),r.current=n}else f.length>1&&(r.current=n)},[n,f,u]);let y=(0,b.useCallback)(async _=>{let w=u.find(M=>M.path===_);if(!w)throw new Error("Account membership is unavailable");let C=$e(w);me()||Kt(C);let R=u.find(M=>M.accountId===me()?.id);if(!R?.personalSpacePath)throw new Error("The home membership has no mount declaration location");await Gt(R.personalSpacePath,M=>{let D=u.find(P=>P.accountId===M);return D?$e(D):null}),await Cr(C),i(null),Wt(w.accountId)},[u]),g=(0,b.useCallback)(async _=>{let w=u.find(C=>C.path===_);if(!w)throw new Error("Scope membership is unavailable");await qi($e(w))},[u]),v=(!!e?.id||Ic())&&!n&&!o;return{accounts:f,switcherAccounts:m,allMemberships:u,currentAccount:p,mountedScope:null,switchAccount:y,mountScope:g,loading:v||c.isLoading,error:o??c.error??s}}function Zc(){te();let e=(0,b.useSyncExternalStore)(Gr,lr,lr),t=(0,b.useMemo)(()=>Ae(),[e]),n=de(),r=(0,b.useMemo)(()=>t.filter(i=>i.kind==="space"&&(n?.kind==="account"||i.id===n?.id)),[t,n]),s=(0,b.useMemo)(()=>r.map(i=>i.id).sort(),[r]);return{mounts:t,selectedSpaces:r,readSpaceIds:s,homeAnchor:me(),anchor:n,setAnchor:Cr,replaceMounts:Rs,mount:qi,unmount:Sc}}function Is(){let[e,t]=(0,b.useState)(null),[n,r]=(0,b.useState)(null),[s,i]=(0,b.useState)(!0),o=(0,b.useRef)(null);(0,b.useEffect)(()=>{V.auth.getSession().then(({data:p,error:m})=>{if(m){console.warn("[useAuth] getSession error, clearing stale session:",m.message),V.auth.signOut().catch(()=>{}),r(null),t(null),i(!1);return}r(p?.session??null),t(p?.session?.user??null),i(!1)}).catch(p=>{console.warn("[useAuth] getSession threw, clearing stale session:",p?.message),V.auth.signOut().catch(()=>{}),r(null),t(null),i(!1)});let{data:{subscription:h}}=V.auth.onAuthStateChange((p,m)=>{if(p==="TOKEN_REFRESHED"&&!m){console.warn("[useAuth] TOKEN_REFRESHED with null session \u2014 signing out"),V.auth.signOut().catch(()=>{}),r(null),t(null),i(!1);return}r(m),t(m?.user??null),i(!1)});return o.current=h,()=>{h?.unsubscribe()}},[]);let a=(0,b.useCallback)(async h=>h.provider?V.auth.signInWithOAuth({provider:h.provider,options:h.redirectTo?{redirectTo:h.redirectTo}:{redirectTo:window.location.href}}):V.auth.signInWithPassword({email:h.email,password:h.password}),[]),c=(0,b.useCallback)(async h=>V.auth.signUp({email:h.email,password:h.password,options:{data:h.metadata||{}}}),[]),u=(0,b.useCallback)(async()=>{await V.auth.signOut(),Cn(),N().clear()},[]),l=(0,b.useCallback)(async h=>{let{error:p}=await V.auth.resetPasswordForEmail(h);if(p)throw p},[]),f=(0,b.useCallback)(async(h,p)=>{let{error:m}=await V.auth.signInWithOtp({email:h,options:p?{emailRedirectTo:p}:{emailRedirectTo:window.location.href}});if(m)throw m},[]);return{user:e,session:n,loading:s,signIn:a,signUp:c,signOut:u,resetPassword:l,signInWithMagicLink:f}}function Xc(e){let[t,n]=(0,b.useState)(null),[r,s]=(0,b.useState)(!1),[i,o]=(0,b.useState)(null);return(0,b.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),x("resolve-asset",{asset_id:e}).then(c=>{c.success&&c.public_url?n({url:c.public_url,id:c.asset_id,name:c.name,mimeType:c.mime_type,width:c.width,height:c.height,sizeBytes:c.size_bytes}):o(new Error(c.error||"Asset not found")),s(!1)}).catch(c=>{o(c instanceof Error?c:new Error(String(c))),s(!1)});else{let u=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"";n({url:u+e}),s(!1)}},[e]),{data:t,loading:r,error:i}}var Cs={};se(()=>{for(let e of Object.keys(Cs))delete Cs[e]});var eu=null;function tu(e){eu=e,typeof window<"u"&&!window.__FSAOS_GATEWAY__&&(window.__FSAOS_GATEWAY__=e)}function Xd(e){switch(e){case"react":return typeof window<"u"&&window.React||b.default;case"react-dom":case"react-dom/client":return typeof window<"u"&&window.ReactDOM||Gd;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}:zd;case"@fsaos/gateway":case"@fsaos/react":case"@ai4b-team/fsaos-gateway-sdk":return typeof window<"u"&&window.__FSAOS_GATEWAY__||eu||{};case"@fsaos/ui":case"@ai4b-team/fsaos-gateway-sdk/ui":return typeof window<"u"&&window.__FSAOS_UI__||Ni;case"@fsaos/theme":return{};default:return console.warn(`[useComponent] Unknown module requested: ${e}`),{}}}var Ir={};async function ef(e){try{let t=await fetch(e);if(!t.ok)return null;let n=await t.text();return!n.trim()||n.includes("No CSS bundle for this component")?null:n}catch{return null}}async function nu(e,t=()=>ef(e)){let n=Ir[e];n||(n=Ir[e]={users:0,text:t(),style:null}),n.users+=1;let r=await n.text;if(Ir[e]!==n||n.users===0||n.style||!r||typeof document>"u")return;let s=document.createElement("style");s.setAttribute("data-fsaos-component-css",e),s.textContent=r,document.head.appendChild(s),n.style=s}function Ve(e){let t=Ir[e];t&&(t.users-=1,!(t.users>0)&&(t.style?.remove(),delete Ir[e]))}function ru(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
3
  `),i=new Function(r)(Xd),o=t??i;return o?o.default||o:null}finally{n!==void 0?window.__FSAOS_REGISTER__=n:delete window.__FSAOS_REGISTER__}}function Hi(e,t){let[n,r]=(0,b.useState)(null),[s,i]=(0,b.useState)(!0),[o,a]=(0,b.useState)(null),c=(0,b.useRef)(null),u=Number.isSafeInteger(t?.version)&&t.version>0?t.version:null;return(0,b.useEffect)(()=>{if(!e)return;let l=!1;a(null),c.current?.path!==e&&(c.current?.cssUrl&&Ve(c.current.cssUrl),c.current=null,r(null),i(!0));let h=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"";return(async()=>{let p=null;try{let m=1,y=e+"@v1",g=h+e+"/__bundle.js";if(u!==null)m=u,y=e+"@v"+m,g=h+e+"/__bundle.v"+m+".js";else try{let R=await fetch(h+e+"/__meta",{cache:"no-store"});R.ok&&(m=(await R.json()).version||1,y=e+"@v"+m,g=h+e+"/__bundle.v"+m+".js")}catch{g=h+e+"/__bundle.js?v="+Date.now()}if(l)return;let v=g.replace(/__bundle(\.v\d+)?\.js(\?.*)?$/,"__bundle$1.css");p=v;let _=nu(v),w=Cs[y];if(!w){let R=await fetch(g);if(!R.ok)throw new Error(`Failed to fetch bundle: ${R.status} ${R.statusText} (${g})`);let M=await R.text();if(w=ru(M),!w)throw new Error("Bundle did not export a component. Expected window.__FSAOS_COMPONENT__ (FSAOS build) or a __FSAOS_REGISTER__(Component) call.");if(typeof w!="function")throw new Error(`Bundle export is not a React component (got ${typeof w})`);Cs[y]=w}if(await _,l){Ve(v);return}let C=c.current?.cssUrl??null;c.current={path:e,cssUrl:v},p=null,r(()=>w),i(!1),C&&Ve(C)}catch(m){p&&Ve(p),l||(a(m instanceof Error?m:new Error(String(m))),i(!1))}})(),()=>{l=!0}},[e,u]),(0,b.useEffect)(()=>()=>{c.current?.cssUrl&&Ve(c.current.cssUrl),c.current=null},[]),{Component:n,loading:s,error:o}}var tf=/^embed\/bundle-[A-Za-z0-9_-]+\.js$/,nf=/^embed\/bundle-[A-Za-z0-9_-]+\.css$/;function Tc(e,t,n){let r=Object.keys(e).filter(o=>t.test(o));if(r.length>1)throw new Error(`The published release has more than one in-app ${n}.`);let s=r[0];if(!s)return null;let i=Rt(e[s]).sha256;return typeof i=="string"&&i?{path:s,sha256:i}:null}var Er=new Map,Di=new Map;se(()=>{Er.clear(),Di.clear()});function Rt(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function su(e){let t=Rt(Rt(e.type_data).published),n=t.published_release_item_id,r=t.published_version;return typeof n!="string"||!n||typeof r!="number"||!Number.isSafeInteger(r)||r<1?null:{releaseItemId:n,version:r}}async function Ac(e,t,n){let r=await br(e.path,{mode:"render"}),s=Rt(Rt(r.render).props).url;if(typeof s!="string"||!s)throw new Error(`The published ${n} could not be opened.`);let i=await fetch(s);if(!i.ok)throw new Error(`Failed to read the published ${n}: ${i.status} ${i.statusText}`.trim());let o=await i.arrayBuffer();if(Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256",o))).map(c=>c.toString(16).padStart(2,"0")).join("")!==t)throw new Error(`The published ${n} does not match the bytes its release sealed.`);return new TextDecoder().decode(o)}async function rf(e,t,n){let r=await hr(t);if(!r)throw new Error("The published release could not be read.");let s=Rt(r.type_data);if(r.item_type!=="revdev_release"||s.component_item_id!==e||s.status!=="committed"||Number(s.version)!==n)throw new Error("This component's live version does not match its release record.");let i=Rt(s.artifacts),o=Tc(i,tf,"script");if(!o)return{status:"no_in_app_version",releaseItemId:t,version:n};let a=Tc(i,nf,"stylesheet"),c=a?[o.path,a.path]:[o.path],u=s.build_item_id;if(typeof u!="string"||!u)throw new Error("The published release names no build.");let{items:l}=await Vt({type:"file",parent_id:u,field_in:{package_path:c},limit:c.length},{throwOnError:!0}),f=g=>l.find(v=>Rt(v.type_data).package_path===g),h=f(o.path),p=a?f(a.path):void 0;if(!h||a&&!p)throw new Error("The published release's in-app files could not be found in its build.");let[m,y]=await Promise.all([Ac(h,o.sha256,"script"),p&&a?Ac(p,a.sha256,"stylesheet"):Promise.resolve(null)]);return{status:"ready",releaseItemId:t,version:n,script:m,stylesheet:y?.trim()?y:null}}function iu(e,t,n){let r=Er.get(t);return r||(r=rf(e,t,n),Er.set(t,r),r.catch(()=>{Er.get(t)===r&&Er.delete(t)})),r}function ou(e){let t=su(e);return!e.id||!t?Promise.resolve({status:"unpublished"}):iu(e.id,t.releaseItemId,t.version)}function au(e){let[t,n]=(0,b.useState)(null),[r,s]=(0,b.useState)("loading"),[i,o]=(0,b.useState)(null),a=(0,b.useRef)(null),c=e!=null,u=e?.id||null,l=e?su(e):null,f=l?.releaseItemId??null,h=l?.version??null;return(0,b.useEffect)(()=>{if(!c)return;let p=()=>{a.current?.cssKey&&Ve(a.current.cssKey),a.current=null,n(null)};if(!u||!f||h===null){p(),o(null),s("unpublished");return}let m=!1;return o(null),a.current&&a.current.componentId!==u&&p(),a.current||s("loading"),(async()=>{let y=null;try{let g=await iu(u,f,h);if(m)return;if(g.status!=="ready"){p(),s(g.status);return}let v=Di.get(f);if(!v){if(v=ru(g.script),!v)throw new Error("The published script did not hand over a component. Expected a __FSAOS_REGISTER__(Component) call or window.__FSAOS_COMPONENT__.");if(typeof v!="function")throw new Error(`The published script handed over something that is not a React component (${typeof v}).`);Di.set(f,v)}let _=g.stylesheet?`release:${f}`:null;if(_&&(y=_,await nu(_,async()=>g.stylesheet)),m){y&&Ve(y);return}let w=a.current?.cssKey??null;a.current={componentId:u,releaseItemId:f,cssKey:_},y=null,n({Component:v,version:h}),s("ready"),w&&Ve(w)}catch(g){if(y&&Ve(y),m)return;o(g instanceof Error?g:new Error(String(g))),a.current||s("error")}})(),()=>{m=!0}},[c,u,f,h]),(0,b.useEffect)(()=>()=>{a.current?.cssKey&&Ve(a.current.cssKey),a.current=null},[]),{Component:t?.Component??null,status:r,error:i,version:t?.version??null}}var sf=["--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 cu(){return{data:(0,b.useMemo)(()=>{if(typeof document>"u")return{tokens:{}};let t={},n=getComputedStyle(document.documentElement);return sf.forEach(r=>{t[r]=n.getPropertyValue(r).trim()}),{tokens:t}},[]),loading:!1,error:null}}function uu(e,t){return{data:{allowed:!0},loading:!1,error:null}}function lu(e,t){let n={};return(t||[]).forEach(r=>{n[r]=!0}),{data:n,loading:!1,error:null}}var fe=null,Un=null,Ui=new Set;function of(){Ui.forEach(e=>e())}se(()=>{fe=null,Un=null});async function du(e){let t={principalId:null,displayName:null,createdAt:null,metadata:null,vfsPath:null},n=vt()?.principal_id??null;if(n){if(fe&&fe.principalId===n){let{principalId:s,displayName:i,createdAt:o,metadata:a,vfsPath:c}=fe;return{principalId:s,displayName:i,createdAt:o,metadata:a,vfsPath:c}}return{...t,principalId:n}}let r=e;if(!r){let{data:s}=await V.auth.getSession();r=s?.session?.user?.id}if(!r)return t;if(fe&&fe.authUserId===r){let{principalId:s,displayName:i,createdAt:o,metadata:a,vfsPath:c}=fe;return{principalId:s,displayName:i,createdAt:o,metadata:a,vfsPath:c}}return Un||(Un=(async()=>{try{let{data:s,error:i}=await V.from("os_principals").select("id, display_name, created_at, metadata").eq("auth_user_id",r).eq("principal_type","user").maybeSingle();if(i)return console.warn("[SDK] Could not resolve principal:",i.message),t;let o=s?.id??null,a=null;if(o){let{data:u}=await V.from("os_items").select("path").eq("owner_principal_id",o).eq("item_type","principal").eq("is_active",!0).like("path","/root/principals/%"),l=(u??[]).map(f=>f.path);a=l.find(f=>f.split("/").length===4)??l[0]??null}let c={principalId:o,displayName:s?.display_name??null,createdAt:s?.created_at??null,metadata:s?.metadata??null,vfsPath:a};return fe={authUserId:r,...c},c}finally{Un=null}})(),Un)}async function fu(e){return(await du(e)).principalId}function pu(){let e=Is(),t=e.user,n=fe?.authUserId===t?.id?fe:null,[r,s]=(0,b.useState)(n),i=(0,b.useRef)(null);return(0,b.useEffect)(()=>{let o=()=>{let a=fe;a&&a.authUserId===t?.id&&s({principalId:a.principalId,displayName:a.displayName,createdAt:a.createdAt,metadata:a.metadata,vfsPath:a.vfsPath})};return Ui.add(o),()=>{Ui.delete(o)}},[t?.id]),(0,b.useEffect)(()=>{if(!t?.id){s(null),i.current=null;return}i.current===t.id&&r?.principalId!=null||(i.current=t.id,du(t.id).then(o=>{s(o)}))},[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 mu(e){let{path:t,...n}=e,r=Hi(t),s=r.Component,{loading:i,error:o}=r;return i?(0,b.createElement)("div",{className:"fsaos-loading"},""):o?(0,b.createElement)("div",{className:"fsaos-error"},"Failed to load component"):s?(0,b.createElement)(s,n):null}function gu(e){return e.children}function hu(e){let t=te(),{channelPath:n,parentMessageId:r,realtime:s=!0,enabled:i}=e,o=i!==void 0?i&&!!n:!!n,a=(0,b.useMemo)(()=>E.channelMessages(n??"",r),[n,r,t]),c=L(),u=(0,b.useRef)(null),l=B({queryKey:a,queryFn:()=>vs(n,r),enabled:o});(0,b.useEffect)(()=>{if(!s||!o)return;let y=ie("vfs_change",()=>{u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{be(c,a,{exact:!0})},500)},g=>{let v=c.getQueryData(a);return Qi(g,n,r,[...v?.messages??[],...v?.activityMessages??[]])});return()=>{y(),u.current&&clearTimeout(u.current)}},[s,o,n,r,a,c]);let f=l.data,h=f?.messages??[],p=f?.messageCards??new Map,m=f?.siblingCards??[];return{messages:h,activityMessages:f?.activityMessages??[],messageCards:p,siblingCards:m,threads:(0,b.useMemo)(()=>h.filter(y=>y.reply_count>0),[h]),breakouts:(0,b.useMemo)(()=>h.filter(y=>y.member_count>0),[h]),isLoading:l.isLoading,isFetching:l.isFetching,error:l.error,refetch:l.refetch}}function yu(e){te();let{channelPath:t,parentMessageId:n,limit:r=50,realtime:s=!0,enabled:i=!0,conversationsOnly:o=!1,transcriptOnly:a=!1}=e,c=!!n,u=i&&!!t,l=or({queryKey:[...E.channelMessages(t||"",n),"infinite",r,"latest-first",...o?["conversations"]:[],...a?["transcript"]:[]],queryFn:async({pageParam:v})=>wr(t,{parentMessageId:n,limit:r,conversationsOnly:o,transcriptOnly:a,before_seq:v?.before_seq,after_seq:v?.after_seq}),initialPageParam:void 0,getPreviousPageParam:v=>{if(!c||v.messages.length<r)return;let _=v.messages[v.messages.length-1]?.seq;return _==null?void 0:{after_seq:_}},getNextPageParam:v=>{if(v.messages.length<r)return;let _=v.messages[0]?.seq;return _==null?void 0:{before_seq:_}},enabled:u}),f=(0,b.useMemo)(()=>{if(!l.data?.pages)return[];let v=new Set,_=[];for(let w of l.data.pages)for(let C of w.messages)v.has(C.id)||(v.add(C.id),_.push(C));return _.sort((w,C)=>w.seq-C.seq)},[l.data?.pages]),{messageCards:h,siblingCards:p}=(0,b.useMemo)(()=>{let v=new Map,_=[];if(!l.data?.pages)return{messageCards:v,siblingCards:_};let w=new Set;for(let C of l.data.pages){for(let[R,M]of C.messageCards)for(let D of M){if(w.has(D.id))continue;w.add(D.id);let P=v.get(R)||[];P.push(D),v.set(R,P)}for(let R of C.siblingCards)w.has(R.id)||(w.add(R.id),_.push(R))}return{messageCards:v,siblingCards:_}},[l.data?.pages]),m=L(),y=(0,b.useRef)(null),g=(0,b.useMemo)(()=>[...E.channelMessages(t||"",n),"infinite",r,"latest-first",...o?["conversations"]:[],...a?["transcript"]:[]],[t,n,r,o,a]);return(0,b.useEffect)(()=>{if(!s||!t||!u)return;let v=()=>void be(m,g,{exact:!0}),_=!1,w=!1,C=!1,R=async()=>{if(o||a){v();return}let P=m.getQueryData(g);if(!P?.pages?.length){v();return}let k=0;for(let T of P.pages)for(let A of T.messages)A.seq>k&&(k=A.seq);if(k===0){v();return}try{let T=await wr(t,{parentMessageId:n,limit:r,after_seq:k});if(T.messages.length===0&&T.siblingCards.length===0){v();return}if(T.messages.length>0){let A=Math.min(...T.messages.map(O=>O.seq));if(A>k+1){console.warn(`[useInfiniteChannelMessages] sequence gap detected: maxSeq=${k}, minNewSeq=${A}. Triggering full refetch.`),v();return}}m.setQueryData(g,A=>{if(!A)return A;let O=[...A.pages],q=0,K=O[q],$=new Set(K.messages.map(Ce=>Ce.id)),Pe=T.messages.filter(Ce=>!$.has(Ce.id)),re=[...K.messages,...Pe].sort((Ce,Ns)=>Ce.seq-Ns.seq),Et=new Map(K.messageCards);for(let[Ce,Ns]of T.messageCards){let oo=Et.get(Ce)||[],Ol=new Set(oo.map(Qs=>Qs.id)),Fl=Ns.filter(Qs=>!Ol.has(Qs.id));Et.set(Ce,[...oo,...Fl])}let Al=new Set(K.siblingCards.map(Ce=>Ce.id)),kl=T.siblingCards.filter(Ce=>!Al.has(Ce.id)),Ml=[...K.siblingCards,...kl];return O[q]={...K,activityMessages:T.activityMessages??[],messages:re,messageCards:Et,siblingCards:Ml},{...A,pages:O}})}catch(T){console.warn("[useInfiniteChannelMessages] live tail fetch failed, falling back to full invalidation:",T),v()}},M=async()=>{if(_){w=!0;return}_=!0;try{do w=!1,await R();while(w&&!C)}finally{_=!1}},D=ie("vfs_change",()=>{y.current&&clearTimeout(y.current),y.current=setTimeout(()=>{M()},500)},P=>(o||a)&&P?.item_type==="message"&&(m.getQueryData(g)?.pages??[]).some(k=>k.messages.some(T=>T.id===P.parent_id))||Qi(P,t,n,m.getQueryData(g)?.pages.flatMap(k=>k.messages)??[]));return()=>{C=!0,D(),y.current&&clearTimeout(y.current)}},[s,t,u,g,m,n,r,o,a]),{messages:f,activityMessages:l.data?.pages[0]?.activityMessages??[],messageCards:h,siblingCards:p,threads:f.filter(v=>v.reply_count>0),breakouts:f.filter(v=>v.member_count>0),isLoading:l.isLoading,isFetching:l.isFetching,error:l.error,refetch:l.refetch,hasPreviousPage:l.hasNextPage??!1,fetchPreviousPage:l.fetchNextPage,isFetchingPreviousPage:l.isFetchingNextPage??!1,hasNextPage:l.hasPreviousPage??!1,fetchNextPage:l.fetchPreviousPage,isFetchingNextPage:l.isFetchingPreviousPage??!1}}var _u=["open","active","strict","hand_raise"];function af(e){return e==="open"||e==="active"||e==="strict"||e==="hand_raise"?e:e==="on"||e==="auto"?"active":"strict"}function cf(e){if(Array.isArray(e))return e.filter(t=>typeof t=="string")}function kc(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:af(t.ai_mode),activeAgentIds:cf(t.active_agent_ids),isPrivate:t.is_private||!1,isDm:t.is_dm||!1,messageCount:t.message_count||0,createdAt:e.created_at||"",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,isArchived:t.is_archived===!0}}function Ts(e={}){let t=te(),{realtime:n=!0,enabled:r=!0,includeArchived:s=!1}=e,i=L(),o=(0,b.useMemo)(()=>E.channels("all"),[t]),a=B({queryKey:o,queryFn:async()=>((await x("query",{item_type:"channel",include_reader:!0,limit:500})).items||[]).map(kc),enabled:r});return(0,b.useEffect)(()=>{if(!(!n||!r))return Pc(i,o,kc)},[n,r,o,i]),{channels:(0,b.useMemo)(()=>(a.data??[]).filter(u=>s||!u.isArchived),[a.data,s]),isLoading:a.isLoading,isFetching:a.isFetching,error:a.error,refetch:a.refetch}}function vu(e={}){let t=Ts(e),n=(0,b.useMemo)(()=>t.channels.filter(r=>!r.isDm),[t.channels]);return{...t,channels:n}}function bu(e={}){let t=Ts(e),n=(0,b.useMemo)(()=>t.channels.filter(r=>r.isDm),[t.channels]);return{...t,channels:n}}function ji(e={}){let t=te(),{filter:n="all",limit:r=200,realtime:s=!0,enabled:i=!0}=e,o=L(),a=(0,b.useRef)(null),c=(0,b.useMemo)(()=>E.notifications(n,r),[n,r,t]),u=B({queryKey:c,queryFn:async()=>{let f={limit:r};return n==="unread"&&(f.filter="unread"),(await x("get-notifications",f)).notifications||[]},enabled:i});return(0,b.useEffect)(()=>{if(!s||!i)return;let f=["vfs_change","ccm_change"].map(h=>ie(h,()=>{a.current&&clearTimeout(a.current),a.current=setTimeout(()=>{o.invalidateQueries({queryKey:c})},2e3)},p=>p.item_type==="notification"&&Ps(p)));return()=>{f.forEach(h=>h()),a.current&&clearTimeout(a.current)}},[s,i,c,o]),{notifications:u.data??[],isLoading:u.isLoading,isFetching:u.isFetching,error:u.error,refetch:u.refetch}}function wu(e={}){let{channels:t,realtime:n=!0,enabled:r=!0}=e,{notifications:s,isLoading:i,isFetching:o,error:a,refetch:c}=ji({filter:"unread",limit:200,realtime:n,enabled:r}),u=(0,b.useMemo)(()=>{let p=new Map;for(let m of s)m.is_unread&&m.channel_id&&p.set(m.channel_id,(p.get(m.channel_id)||0)+1);return p},[s]),l=(0,b.useMemo)(()=>{let p=0;return u.forEach(m=>{p+=m}),p},[u]),{dmUnread:f,channelUnread:h}=(0,b.useMemo)(()=>{if(!t)return{dmUnread:0,channelUnread:0};let p=new Set(t.filter(g=>g.isDm).map(g=>g.id)),m=0,y=0;return u.forEach((g,v)=>{p.has(v)?m+=g:y+=g}),{dmUnread:m,channelUnread:y}},[t,u]);return{unreadByChannel:u,totalUnread:l,dmUnread:f,channelUnread:h,isLoading:i,isFetching:o,error:a,refetch:c}}function Su(){let e=L();return ne({mutationFn:t=>x("create",t),onSuccess:(t,n)=>{let r=n.parent_path;r&&e.invalidateQueries({queryKey:E.children(r)})}})}function xu(){let e=L();return ne({mutationFn:t=>x("update",t),onSuccess:(t,n)=>{let r=n.path;if(r){e.invalidateQueries({queryKey:E.item(r)});let s=r.split("/");s.pop();let i=s.join("/");i&&e.invalidateQueries({queryKey:E.children(i)})}}})}function Ru(){return ne({mutationFn:e=>x("update-principal",e),onSuccess:(e,t)=>{if(!fe)return;let n=e&&typeof e=="object"&&e.metadata?e.metadata:{...fe.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}:{}};fe={...fe,displayName:typeof t.display_name=="string"?t.display_name:fe.displayName,metadata:n},of()}})}function Pu(){let e=L();return ne({mutationFn:t=>x("delete",t),onSuccess:(t,n)=>{let r=n.path;if(r){e.removeQueries({queryKey:E.item(r)});let s=r.split("/");s.pop();let i=s.join("/");i&&e.invalidateQueries({queryKey:E.children(i)})}}})}function Cu(){let e=L();return ne({mutationFn:t=>x("move",t),onSuccess:(t,n)=>{let r=n.path,s=n.new_parent_path;if(r){e.invalidateQueries({queryKey:E.item(r)});let i=r.split("/");i.pop();let o=i.join("/");o&&e.invalidateQueries({queryKey:E.children(o)})}s&&e.invalidateQueries({queryKey:E.children(s)})}})}function Eu(){let e=L();return ne({mutationFn:t=>x("link",t),onSuccess:(t,n)=>{let r=n.source_id,s=n.target_id;r&&e.invalidateQueries({queryKey:E.edges(r)}),s&&e.invalidateQueries({queryKey:E.edges(s)})}})}function Iu(e,t){let n=L(),{optimistic:r,...s}=t??{};return ne({mutationFn:i=>x(e,i),onMutate:r?async i=>{await n.cancelQueries({queryKey:r.queryKey});let o=n.getQueryData(r.queryKey);return n.setQueryData(r.queryKey,a=>r.update(a,i)),{previous:o}}:void 0,onError:(i,o,a)=>{r&&a?.previous!==void 0&&n.setQueryData(r.queryKey,a.previous),s.onError?.(i)},onSuccess:s.onSuccess,onSettled:r?()=>{n.invalidateQueries({queryKey:r.queryKey})}:void 0})}function Tu(e,t,n){let r,s,i,o=!0;if(typeof e=="string")r=e,s=t,i=n;else{s=e;let u=t;r=u.eventType,i=u.filter,o=u.enabled??!0}let a=(0,b.useRef)(s),c=(0,b.useRef)(i);(0,b.useEffect)(()=>{a.current=s,c.current=i},[s,i]),(0,b.useEffect)(()=>o?ie(r,l=>a.current(l),c.current?l=>c.current(l):void 0):void 0,[r,o])}function Au(e){let{queryKey:t,queryFn:n,eventType:r,filter:s,enabled:i=!0,debounceMs:o=500}=e,a=L(),c=(0,b.useRef)(s);c.current=s;let u=(0,b.useRef)(null),l=B({queryKey:t,queryFn:n,enabled:i});return(0,b.useEffect)(()=>{if(!i)return;let f=ie(r,()=>{u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{be(a,t,{exact:!0})},o)},h=>c.current?.(h)??!0);return()=>{f(),u.current&&clearTimeout(u.current)}},[r,i,o,a,JSON.stringify(t)]),l}function Kn(e){te();let t=W(),n=(0,b.useMemo)(()=>e?typeof e=="string"?{path:e}:e:null,[typeof e=="string"?e:JSON.stringify(e)]),r=n?._scope_path??t,s=!!t&&!!r&&!!n&&!!(n.key||n.path||n.item_id),i=n?.key??n?.path??n?.item_id??"",o=["vfs",r??"__unscoped__","arrangement",i,n?.scope_id??""],a=B({queryKey:o,staleTime:1/0,retry:!1,meta:{arrangementRealtime:!0},queryFn:async()=>{if(!n)return null;let p=await x("resolve-arrangement",{...n,_scope_path:r});if(p?.success===!1)throw new Error(p?.error||"Arrangement could not be loaded");return p??null},enabled:s}),c=a.data??null,u=(0,b.useMemo)(()=>c?.resolved_children??[],[c]),l=c?.resolution_level??null,f=(0,b.useMemo)(()=>{let m=(c?.type_data??null)?.order;return Array.isArray(m)?m:null},[c]),h=(0,b.useCallback)(p=>{if(!f||!p?.length)return p??[];let m=_=>_.id??_.name??"",y=new Map(f.map((_,w)=>[_,w])),g=[],v=[];for(let _ of p)(y.has(m(_))?g:v).push(_);return g.sort((_,w)=>y.get(m(_))-y.get(m(w))),[...g,...v]},[f]);return{...a,arrangement:c,resolvedChildren:u,resolutionLevel:l,order:f,sourceScopeId:c?.scope_item_id??null,arrangementQueryKey:o,applyTo:h}}function ku(e){let{origin:t,originField:n,fallbackUrl:r,mintError:s,scopeId:i,scopePath:o}=e,a=te(),c=vt(),u=i??c?.scope_id??null,l=(0,b.useMemo)(()=>{if(!t)return null;let R="/accounts/",M=t.indexOf(R);if(M===-1)return null;let D=t.indexOf("/",M+R.length);return D===-1?t:t.slice(0,D)},[t]),f=o??l??c?.scope_path??null,h=n?.trim()||null,p=`${a}
4
4
  ${u??""}
5
5
  ${f??""}