@ai4b-team/fsaos-gateway-sdk 4.0.0 → 4.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -0
- package/dist/iife/gateway.js +3 -3
- package/dist/iife/gateway.js.map +2 -2
- package/dist/iife/ui.js +1 -1
- package/dist/index.cjs +5 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +11 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.js +5 -0
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/iife/gateway.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
/* @fsaos/gateway v2.0.0 — Unified FSAOS Edge Runtime — 2026-10-
|
|
2
|
-
"use strict";var __FSAOS_GATEWAY__=(()=>{var zu=Object.create;var Fn=Object.defineProperty;var Ju=Object.getOwnPropertyDescriptor;var Yu=Object.getOwnPropertyNames;var Xu=Object.getPrototypeOf,Zu=Object.prototype.hasOwnProperty;var Ki=e=>{throw TypeError(e)};var el=(e,t,n)=>t in e?Fn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var qn=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),tl=(e,t)=>{for(var n in t)Fn(e,n,{get:t[n],enumerable:!0})},Li=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Yu(t))!Zu.call(e,s)&&s!==n&&Fn(e,s,{get:()=>t[s],enumerable:!(r=Ju(t,s))||r.enumerable});return e};var X=(e,t,n)=>(n=e!=null?zu(Xu(e)):{},Li(t||!e||!e.__esModule?Fn(n,"default",{value:e,enumerable:!0}):n,e)),nl=e=>Li(Fn({},"__esModule",{value:!0}),e);var ee=(e,t,n)=>el(e,typeof t!="symbol"?t+"":t,n),Ps=(e,t,n)=>t.has(e)||Ki("Cannot "+n);var l=(e,t,n)=>(Ps(e,t,"read from private field"),n?n.call(e):t.get(e)),x=(e,t,n)=>t.has(e)?Ki("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),w=(e,t,n,r)=>(Ps(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n),q=(e,t,n)=>(Ps(e,t,"access private method"),n);var Qn=(e,t,n,r)=>({set _(s){w(e,t,s,n)},get _(){return l(e,t,r)}});var oe=qn((wd,ji)=>{ji.exports=React});var Ir=qn((vp,Ro)=>{Ro.exports={jsx:React.createElement,jsxs:React.createElement,Fragment:React.Fragment}});var Qo=qn((Jp,qo)=>{qo.exports={createClient:window.supabase.createClient}});var la=qn((um,ua)=>{ua.exports=ReactDOM});var yu=qn((rg,gu)=>{gu.exports=ReactDOM});var Ui={};tl(Ui,{CHANNEL_AI_MODES:()=>Kc,ComponentRenderer:()=>Qc,EnforcementDeniedError:()=>rt,FormSubmissionError:()=>On,GatewayRequestError:()=>Ie,InteractionTrackingError:()=>kn,KernelProvider:()=>Dc,QueryClientProvider:()=>Gn,assignPersonalSection:()=>ju,auth:()=>Tu,awaitAnchorReady:()=>er,awaitScopeReady:()=>Go,callTool:()=>xu,cancelQueuedTurn:()=>mu,cancelTurn:()=>fu,clearCachedToken:()=>ei,clearSession:()=>ci,configureGatewayReads:()=>sa,createItem:()=>wu,disconnectSSE:()=>_i,disposeVfsRealtimeWs:()=>bi,electHomeAnchor:()=>Mt,emitEvent:()=>Aa,fetchChannelMessages:()=>Ka,fetchChannelMessagesPage:()=>lr,fetchChannelMessagesWithCards:()=>as,fetchEdgesForItem:()=>ts,fetchItemHistory:()=>ss,fetchItemVersions:()=>ur,fetchItems:()=>xn,fetchMemberFocus:()=>is,fetchOpenEnvelope:()=>os,fetchRecentActivity:()=>rs,fetchResolvedItems:()=>Fi,fetchTimelineHistory:()=>qi,fetchTurnQueueEntries:()=>Da,fetchTypeDefinitions:()=>es,fetchVfsChildren:()=>cr,fetchVfsChildrenPage:()=>Zr,fetchVfsItem:()=>ar,fetchVfsItemById:()=>Xr,fetchVfsTree:()=>ns,gatewayCall:()=>C,getAccessToken:()=>Ye,getAnchor:()=>pn,getAnchorRef:()=>ye,getAnchorVersion:()=>ri,getAssetUrl:()=>Pu,getDefaultSort:()=>ku,getHomeAnchor:()=>fe,getMountVersion:()=>tr,getMounts:()=>Te,getPathSubscriptionState:()=>Ma,getQueryClient:()=>O,getRequiredFormFields:()=>Mu,getScope:()=>H,getScopeVersion:()=>Z,getServerClockOffsetMs:()=>Zo,getServerClockSyncedAt:()=>ea,getSessionEntry:()=>ht,hasServerClock:()=>Xo,initSession:()=>Xe,initVfsRealtimeWs:()=>Qt,initializeFsaos:()=>du,initializeWorkspace:()=>vs,interpretSchema:()=>Oi,invalidateAllVfs:()=>Va,invalidateChannelMessages:()=>Wa,invalidateChildren:()=>Yr,invalidateItem:()=>vi,invalidateOpenEnvelope:()=>Ba,invalidatePathAndParent:()=>La,invalidateSubtree:()=>ja,invalidateTypes:()=>$a,isAnchorReady:()=>ii,isChannelPath:()=>pe,isListableItemsFilter:()=>Rn,isScopeReady:()=>Dr,itemsFilterFromQueryFilter:()=>Ua,listChildren:()=>bu,loadMounts:()=>Dt,mount:()=>Eu,mountRealtimeScope:()=>Pn,normalizeItem:()=>_e,onConnectionStateChange:()=>Jr,pathSubscriptionMatches:()=>hi,personalSectionsKey:()=>vr,ping:()=>ka,pushChanges:()=>Ru,queryClient:()=>ya,readItem:()=>vu,refreshQuery:()=>Ae,registerCleanup:()=>te,replaceMounts:()=>fs,resetAllSdkState:()=>mn,resolvePrincipalId:()=>Oc,resubscribePath:()=>Fa,selectMount:()=>mr,serverDeadlinePassed:()=>ta,serverMsUntil:()=>na,serverNow:()=>Ur,setAnchor:()=>qr,setCachedToken:()=>No,setQueryClient:()=>ga,setScope:()=>Ho,setupRequireShim:()=>Iu,signal:()=>Cu,startTracking:()=>_s,steerTurn:()=>pu,submitForm:()=>hu,subscribeAnchor:()=>si,subscribeArtifactStream:()=>bs,subscribeMounts:()=>Qr,subscribeScope:()=>we,subscribeToEvents:()=>ne,subscribeToPath:()=>zr,subscribeToScope:()=>Sn,trackAction:()=>cu,trackEvent:()=>Nt,trackPageView:()=>au,unmountRealtimeScope:()=>ls,updateItem:()=>Su,uploadFile:()=>Ou,useAccounts:()=>xc,useAgentTimeline:()=>Nu,useAllChannels:()=>gs,useArrangement:()=>In,useArtifactStream:()=>Uu,useAsset:()=>Pc,useAuth:()=>hs,useChannelMessages:()=>Uc,useChannels:()=>Lc,useChildren:()=>cc,useComponent:()=>Pi,useCreate:()=>$c,useDelete:()=>Hc,useDmChannels:()=>jc,useEdges:()=>hc,useEventStream:()=>Yc,useFileUpload:()=>qu,useIncrementalItems:()=>pc,useInfiniteChannelMessages:()=>Nc,useInfiniteChildren:()=>mc,useInfiniteItems:()=>Ci,useItem:()=>oc,useItemById:()=>ac,useItemHistory:()=>wc,useItemVersions:()=>bc,useItems:()=>fc,useLink:()=>zc,useList:()=>xi,useMemberFocus:()=>vc,useMintedAsset:()=>Zc,useMounts:()=>Cc,useMove:()=>Gc,useMutation:()=>Jc,useNotifications:()=>Ti,useOpen:()=>yc,usePermission:()=>Ac,usePermissions:()=>kc,usePersonalItemOrder:()=>tu,usePersonalSections:()=>$u,usePinnedItems:()=>Lu,usePrincipal:()=>Fc,useRealtimeQuery:()=>Xc,useRecentActivity:()=>Sc,useResolve:()=>dc,useResolvedItems:()=>Du,useScope:()=>Rc,useScopeReady:()=>ic,useSearch:()=>lc,useTheme:()=>Ic,useTimelineHistory:()=>Ku,useTool:()=>qc,useTree:()=>uc,useType:()=>gc,useTypeHelpers:()=>_c,useTypes:()=>ms,useUnreadCounts:()=>Vc,useUpdate:()=>Wc,useUpdatePrincipal:()=>Bc,vfsKeys:()=>P,waitForPathReady:()=>Oa});var rt=class e extends Error{constructor(n){let r=n.message||e.fallbackMessage(n);super(r);ee(this,"name","EnforcementDeniedError");ee(this,"deniedBy");ee(this,"ruleKey");ee(this,"displayName");this.deniedBy=n.denied_by||n.error_type||n.error||"unknown";let s=n.enforcement;this.ruleKey=s?.rule_key??void 0,this.displayName=s?.display_name??void 0}static fallbackMessage(n){let r=n.error||"",s=n.denied_by||"";return s==="rule"||r==="RULE_DENIED"?"This feature is not enabled for this workspace.":s==="entitlement"||r==="ENTITLEMENT_REQUIRED"?"This feature requires a plan upgrade.":s==="access"||r==="ACCESS_DENIED"||r==="PERMISSION_DENIED"?"You don't have permission to do this.":"This action is not allowed."}get isRuleDenial(){return this.deniedBy==="rule"||this.deniedBy==="RULE_DENIED"}get isAccessDenial(){return this.deniedBy==="access"||this.deniedBy==="ACCESS_DENIED"}get isEntitlementDenial(){return this.deniedBy==="entitlement"||this.deniedBy==="ENTITLEMENT_REQUIRED"}};var An=X(oe(),1);var xe=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 bt,st,Lt,Vi,rl=(Vi=class extends xe{constructor(){super();x(this,bt);x(this,st);x(this,Lt);w(this,Lt,t=>{if(typeof window<"u"&&window.addEventListener){let n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){l(this,st)||this.setEventListener(l(this,Lt))}onUnsubscribe(){var t;this.hasListeners()||((t=l(this,st))==null||t.call(this),w(this,st,void 0))}setEventListener(t){var n;w(this,Lt,t),(n=l(this,st))==null||n.call(this),w(this,st,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){l(this,bt)!==t&&(w(this,bt,t),this.onFocus())}onFocus(){let t=this.isFocused();this.listeners.forEach(n=>{n(t)})}isFocused(){return typeof l(this,bt)=="boolean"?l(this,bt):globalThis.document?.visibilityState!=="hidden"}},bt=new WeakMap,st=new WeakMap,Lt=new WeakMap,Vi),jt=new rl;var sl={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},it,Ts,$i,il=($i=class{constructor(){x(this,it,sl);x(this,Ts,!1)}setTimeoutProvider(e){w(this,it,e)}setTimeout(e,t){return l(this,it).setTimeout(e,t)}clearTimeout(e){l(this,it).clearTimeout(e)}setInterval(e,t){return l(this,it).setInterval(e,t)}clearInterval(e){l(this,it).clearInterval(e)}},it=new WeakMap,Ts=new WeakMap,$i),Qe=new il;function Wi(e){setTimeout(e,0)}var Is=typeof window>"u"||"Deno"in globalThis;function G(){}function Gi(e,t){return typeof e=="function"?e(t):e}function Dn(e){return typeof e=="number"&&e>=0&&e!==1/0}function br(e,t){return Math.max(e+(t||0)-Date.now(),0)}function Me(e,t){return typeof e=="function"?e(t):e}function me(e,t){return typeof e=="function"?e(t):e}function wr(e,t){let{type:n="all",exact:r,fetchStatus:s,predicate:i,queryKey:o,stale:c}=e;if(o){if(r){if(t.queryHash!==Un(o,t.options))return!1}else if(!wt(t.queryKey,o))return!1}if(n!=="all"){let a=t.isActive();if(n==="active"&&!a||n==="inactive"&&a)return!1}return!(typeof c=="boolean"&&t.isStale()!==c||s&&s!==t.state.fetchStatus||i&&!i(t))}function Sr(e,t){let{exact:n,status:r,predicate:s,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(De(t.options.mutationKey)!==De(i))return!1}else if(!wt(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||s&&!s(t))}function Un(e,t){return(t?.queryKeyHashFn||De)(e)}function De(e){return JSON.stringify(e,(t,n)=>Es(n)?Object.keys(n).sort().reduce((r,s)=>(r[s]=n[s],r),{}):n)}function wt(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>wt(e[n],t[n])):!1}var ol=Object.prototype.hasOwnProperty;function As(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=Bi(e)&&Bi(t);if(!r&&!(Es(e)&&Es(t)))return t;let i=(r?e:Object.keys(e)).length,o=r?t:Object.keys(t),c=o.length,a=r?new Array(c):{},u=0;for(let d=0;d<c;d++){let p=r?d:o[d],m=e[p],f=t[p];if(m===f){a[p]=m,(r?d<i:ol.call(e,p))&&u++;continue}if(m===null||f===null||typeof m!="object"||typeof f!="object"){a[p]=f;continue}let y=As(m,f,n+1);a[p]=y,y===m&&u++}return i===c&&u===i?e:a}function Vt(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(let n in e)if(e[n]!==t[n])return!1;return!0}function Bi(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Es(e){if(!Hi(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!Hi(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function Hi(e){return Object.prototype.toString.call(e)==="[object Object]"}function zi(e){return new Promise(t=>{Qe.setTimeout(t,e)})}function Nn(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?As(e,t):t}function Ji(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function Yi(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var $t=Symbol();function Rr(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===$t?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function Wt(e,t){return typeof e=="function"?e(...t):!!e}function Xi(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 Ue=(()=>{let e=()=>Is;return{isServer(){return e()},setIsServer(t){e=t}}})();function Kn(){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 Zi=Wi;function al(){let e=[],t=0,n=c=>{c()},r=c=>{c()},s=Zi,i=c=>{t?e.push(c):s(()=>{n(c)})},o=()=>{let c=e;e=[],c.length&&s(()=>{r(()=>{c.forEach(a=>{n(a)})})})};return{batch:c=>{let a;t++;try{a=c()}finally{t--,t||o()}return a},batchCalls:c=>(...a)=>{i(()=>{c(...a)})},schedule:i,setNotifyFunction:c=>{n=c},setBatchNotifyFunction:c=>{r=c},setScheduler:c=>{s=c}}}var j=al();var Bt,ot,Ht,eo,cl=(eo=class extends xe{constructor(){super();x(this,Bt,!0);x(this,ot);x(this,Ht);w(this,Ht,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(){l(this,ot)||this.setEventListener(l(this,Ht))}onUnsubscribe(){var t;this.hasListeners()||((t=l(this,ot))==null||t.call(this),w(this,ot,void 0))}setEventListener(t){var n;w(this,Ht,t),(n=l(this,ot))==null||n.call(this),w(this,ot,t(this.setOnline.bind(this)))}setOnline(t){l(this,Bt)!==t&&(w(this,Bt,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return l(this,Bt)}},Bt=new WeakMap,ot=new WeakMap,Ht=new WeakMap,eo),Gt=new cl;function ul(e){return Math.min(1e3*2**e,3e4)}function ks(e){return(e??"online")==="online"?Gt.isOnline():!0}var xr=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function Cr(e){let t=!1,n=0,r,s=Kn(),i=()=>s.status!=="pending",o=g=>{if(!i()){let h=new xr(g);m(h),e.onCancel?.(h)}},c=()=>{t=!0},a=()=>{t=!1},u=()=>jt.isFocused()&&(e.networkMode==="always"||Gt.isOnline())&&e.canRun(),d=()=>ks(e.networkMode)&&e.canRun(),p=g=>{i()||(r?.(),s.resolve(g))},m=g=>{i()||(r?.(),s.reject(g))},f=()=>new Promise(g=>{r=h=>{(i()||u())&&g(h)},e.onPause?.()}).then(()=>{r=void 0,i()||e.onContinue?.()}),y=()=>{if(i())return;let g,h=n===0?e.initialPromise:void 0;try{g=h??e.fn()}catch(v){g=Promise.reject(v)}Promise.resolve(g).then(p).catch(v=>{if(i())return;let b=e.retry??(Ue.isServer()?0:3),E=e.retryDelay??ul,I=typeof E=="function"?E(n,v):E,R=b===!0||typeof b=="number"&&n<b||typeof b=="function"&&b(n,v);if(t||!R){m(v);return}n++,e.onFail?.(n,v),zi(I).then(()=>u()?void 0:f()).then(()=>{t?m(v):y()})})};return{promise:s,status:()=>s.status,cancel:o,continue:()=>(r?.(),s),cancelRetry:c,continueRetry:a,canStart:d,start:()=>(d()?y():f().then(y),s)}}var St,to,Pr=(to=class{constructor(){x(this,St)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Dn(this.gcTime)&&w(this,St,Qe.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Ue.isServer()?1/0:5*60*1e3))}clearGcTimeout(){l(this,St)!==void 0&&(Qe.clearTimeout(l(this,St)),w(this,St,void 0))}},St=new WeakMap,to);var Rt,zt,Ce,xt,re,Ln,Ct,be,oo,$e,so,io=(so=class extends Pr{constructor(t){super();x(this,be);x(this,Rt);x(this,zt);x(this,Ce);x(this,xt);x(this,re);x(this,Ln);x(this,Ct);w(this,Ct,!1),w(this,Ln,t.defaultOptions),this.setOptions(t.options),this.observers=[],w(this,xt,t.client),w(this,Ce,l(this,xt).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,w(this,Rt,ro(this.options)),this.state=t.state??l(this,Rt),this.scheduleGc()}get meta(){return this.options.meta}get promise(){return l(this,re)?.promise}setOptions(t){if(this.options={...l(this,Ln),...t},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let n=ro(this.options);n.data!==void 0&&(this.setState(no(n.data,n.dataUpdatedAt)),w(this,Rt,n))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&l(this,Ce).remove(this)}setData(t,n){let r=Nn(this.state.data,t,this.options);return q(this,be,$e).call(this,{data:r,type:"success",dataUpdatedAt:n?.updatedAt,manual:n?.manual}),r}setState(t,n){q(this,be,$e).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){let n=l(this,re)?.promise;return l(this,re)?.cancel(t),n?n.then(G).catch(G):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return l(this,Rt)}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(t=>me(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===$t||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>Me(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:!br(this.state.dataUpdatedAt,t)}onFocus(){this.observers.find(n=>n.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),l(this,re)?.continue()}onOnline(){this.observers.find(n=>n.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),l(this,re)?.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),l(this,Ce).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(n=>n!==t),this.observers.length||(l(this,re)&&(l(this,Ct)||q(this,be,oo).call(this)?l(this,re).cancel({revert:!0}):l(this,re).cancelRetry()),this.scheduleGc()),l(this,Ce).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||q(this,be,$e).call(this,{type:"invalidate"})}async fetch(t,n){if(this.state.fetchStatus!=="idle"&&l(this,re)?.status()!=="rejected"){if(this.state.data!==void 0&&n?.cancelRefetch)this.cancel({silent:!0});else if(l(this,re))return l(this,re).continueRetry(),l(this,re).promise}if(t&&this.setOptions(t),!this.options.queryFn){let a=this.observers.find(u=>u.options.queryFn);a&&this.setOptions(a.options)}let r=new AbortController,s=a=>{Object.defineProperty(a,"signal",{enumerable:!0,get:()=>(w(this,Ct,!0),r.signal)})},i=()=>{let a=Rr(this.options,n),d=(()=>{let p={client:l(this,xt),queryKey:this.queryKey,meta:this.meta};return s(p),p})();return w(this,Ct,!1),this.options.persister?this.options.persister(a,d,this):a(d)},c=(()=>{let a={fetchOptions:n,options:this.options,queryKey:this.queryKey,client:l(this,xt),state:this.state,fetchFn:i};return s(a),a})();this.options.behavior?.onFetch(c,this),w(this,zt,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==c.fetchOptions?.meta)&&q(this,be,$e).call(this,{type:"fetch",meta:c.fetchOptions?.meta}),w(this,re,Cr({initialPromise:n?.initialPromise,fn:c.fetchFn,onCancel:a=>{a instanceof xr&&a.revert&&this.setState({...l(this,zt),fetchStatus:"idle"}),r.abort()},onFail:(a,u)=>{q(this,be,$e).call(this,{type:"failed",failureCount:a,error:u})},onPause:()=>{q(this,be,$e).call(this,{type:"pause"})},onContinue:()=>{q(this,be,$e).call(this,{type:"continue"})},retry:c.options.retry,retryDelay:c.options.retryDelay,networkMode:c.options.networkMode,canRun:()=>!0}));try{let a=await l(this,re).start();if(a===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(a),l(this,Ce).config.onSuccess?.(a,this),l(this,Ce).config.onSettled?.(a,this.state.error,this),a}catch(a){if(a instanceof xr){if(a.silent)return l(this,re).promise;if(a.revert){if(this.state.data===void 0)throw a;return this.state.data}}throw q(this,be,$e).call(this,{type:"error",error:a}),l(this,Ce).config.onError?.(a,this),l(this,Ce).config.onSettled?.(this.state.data,a,this),a}finally{this.scheduleGc()}}},Rt=new WeakMap,zt=new WeakMap,Ce=new WeakMap,xt=new WeakMap,re=new WeakMap,Ln=new WeakMap,Ct=new WeakMap,be=new WeakSet,oo=function(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"},$e=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,...Ms(r.data,this.options),fetchMeta:t.meta??null};case"success":let s={...r,...no(t.data,t.dataUpdatedAt),dataUpdateCount:r.dataUpdateCount+1,...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return w(this,zt,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()}),l(this,Ce).notify({query:this,type:"updated",action:t})})},so);function Ms(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:ks(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function no(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function ro(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 he,K,Vn,le,Pt,Jt,We,at,$n,Yt,Xt,Tt,Et,ct,Zt,L,jn,Os,Fs,qs,Qs,Ds,Us,Ns,lo,uo,Wn=(uo=class extends xe{constructor(t,n){super();x(this,L);x(this,he);x(this,K);x(this,Vn);x(this,le);x(this,Pt);x(this,Jt);x(this,We);x(this,at);x(this,$n);x(this,Yt);x(this,Xt);x(this,Tt);x(this,Et);x(this,ct);x(this,Zt,new Set);this.options=n,w(this,he,t),w(this,at,null),w(this,We,Kn()),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(l(this,K).addObserver(this),ao(l(this,K),this.options)?q(this,L,jn).call(this):this.updateResult(),q(this,L,Qs).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Ks(l(this,K),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Ks(l(this,K),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,q(this,L,Ds).call(this),q(this,L,Us).call(this),l(this,K).removeObserver(this)}setOptions(t){let n=this.options,r=l(this,K);if(this.options=l(this,he).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof me(this.options.enabled,l(this,K))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");q(this,L,Ns).call(this),l(this,K).setOptions(this.options),n._defaulted&&!Vt(this.options,n)&&l(this,he).getQueryCache().notify({type:"observerOptionsUpdated",query:l(this,K),observer:this});let s=this.hasListeners();s&&co(l(this,K),r,this.options,n)&&q(this,L,jn).call(this),this.updateResult(),s&&(l(this,K)!==r||me(this.options.enabled,l(this,K))!==me(n.enabled,l(this,K))||Me(this.options.staleTime,l(this,K))!==Me(n.staleTime,l(this,K)))&&q(this,L,Os).call(this);let i=q(this,L,Fs).call(this);s&&(l(this,K)!==r||me(this.options.enabled,l(this,K))!==me(n.enabled,l(this,K))||i!==l(this,ct))&&q(this,L,qs).call(this,i)}getOptimisticResult(t){let n=l(this,he).getQueryCache().build(l(this,he),t),r=this.createResult(n,t);return dl(this,r)&&(w(this,le,r),w(this,Jt,this.options),w(this,Pt,l(this,K).state)),r}getCurrentResult(){return l(this,le)}trackResult(t,n){return new Proxy(t,{get:(r,s)=>(this.trackProp(s),n?.(s),s==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&l(this,We).status==="pending"&&l(this,We).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(r,s))})}trackProp(t){l(this,Zt).add(t)}getCurrentQuery(){return l(this,K)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){let n=l(this,he).defaultQueryOptions(t),r=l(this,he).getQueryCache().build(l(this,he),n);return r.fetch().then(()=>this.createResult(r,n))}fetch(t){return q(this,L,jn).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),l(this,le)))}createResult(t,n){let r=l(this,K),s=this.options,i=l(this,le),o=l(this,Pt),c=l(this,Jt),u=t!==r?t.state:l(this,Vn),{state:d}=t,p={...d},m=!1,f;if(n._optimisticResults){let T=this.hasListeners(),F=!T&&ao(t,n),k=T&&co(t,r,n,s);(F||k)&&(p={...p,...Ms(d.data,t.options)}),n._optimisticResults==="isRestoring"&&(p.fetchStatus="idle")}let{error:y,errorUpdatedAt:g,status:h}=p;f=p.data;let v=!1;if(n.placeholderData!==void 0&&f===void 0&&h==="pending"){let T;i?.isPlaceholderData&&n.placeholderData===c?.placeholderData?(T=i.data,v=!0):T=typeof n.placeholderData=="function"?n.placeholderData(l(this,Xt)?.state.data,l(this,Xt)):n.placeholderData,T!==void 0&&(h="success",f=Nn(i?.data,T,n),m=!0)}if(n.select&&f!==void 0&&!v)if(i&&f===o?.data&&n.select===l(this,$n))f=l(this,Yt);else try{w(this,$n,n.select),f=n.select(f),f=Nn(i?.data,f,n),w(this,Yt,f),w(this,at,null)}catch(T){w(this,at,T)}l(this,at)&&(y=l(this,at),f=l(this,Yt),g=Date.now(),h="error");let b=p.fetchStatus==="fetching",E=h==="pending",I=h==="error",R=E&&b,M=f!==void 0,S={status:h,fetchStatus:p.fetchStatus,isPending:E,isSuccess:h==="success",isError:I,isInitialLoading:R,isLoading:R,data:f,dataUpdatedAt:p.dataUpdatedAt,error:y,errorUpdatedAt:g,failureCount:p.fetchFailureCount,failureReason:p.fetchFailureReason,errorUpdateCount:p.errorUpdateCount,isFetched:t.isFetched(),isFetchedAfterMount:p.dataUpdateCount>u.dataUpdateCount||p.errorUpdateCount>u.errorUpdateCount,isFetching:b,isRefetching:b&&!E,isLoadingError:I&&!M,isPaused:p.fetchStatus==="paused",isPlaceholderData:m,isRefetchError:I&&M,isStale:Ls(t,n),refetch:this.refetch,promise:l(this,We),isEnabled:me(n.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){let T=S.data!==void 0,F=S.status==="error"&&!T,k=Q=>{F?Q.reject(S.error):T&&Q.resolve(S.data)},A=()=>{let Q=w(this,We,S.promise=Kn());k(Q)},U=l(this,We);switch(U.status){case"pending":t.queryHash===r.queryHash&&k(U);break;case"fulfilled":(F||S.data!==U.value)&&A();break;case"rejected":(!F||S.error!==U.reason)&&A();break}}return S}updateResult(){let t=l(this,le),n=this.createResult(l(this,K),this.options);if(w(this,Pt,l(this,K).state),w(this,Jt,this.options),l(this,Pt).data!==void 0&&w(this,Xt,l(this,K)),Vt(n,t))return;w(this,le,n);let r=()=>{if(!t)return!0;let{notifyOnChangeProps:s}=this.options,i=typeof s=="function"?s():s;if(i==="all"||!i&&!l(this,Zt).size)return!0;let o=new Set(i??l(this,Zt));return this.options.throwOnError&&o.add("error"),Object.keys(l(this,le)).some(c=>{let a=c;return l(this,le)[a]!==t[a]&&o.has(a)})};q(this,L,lo).call(this,{listeners:r()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&q(this,L,Qs).call(this)}},he=new WeakMap,K=new WeakMap,Vn=new WeakMap,le=new WeakMap,Pt=new WeakMap,Jt=new WeakMap,We=new WeakMap,at=new WeakMap,$n=new WeakMap,Yt=new WeakMap,Xt=new WeakMap,Tt=new WeakMap,Et=new WeakMap,ct=new WeakMap,Zt=new WeakMap,L=new WeakSet,jn=function(t){q(this,L,Ns).call(this);let n=l(this,K).fetch(this.options,t);return t?.throwOnError||(n=n.catch(G)),n},Os=function(){q(this,L,Ds).call(this);let t=Me(this.options.staleTime,l(this,K));if(Ue.isServer()||l(this,le).isStale||!Dn(t))return;let r=br(l(this,le).dataUpdatedAt,t)+1;w(this,Tt,Qe.setTimeout(()=>{l(this,le).isStale||this.updateResult()},r))},Fs=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(l(this,K)):this.options.refetchInterval)??!1},qs=function(t){q(this,L,Us).call(this),w(this,ct,t),!(Ue.isServer()||me(this.options.enabled,l(this,K))===!1||!Dn(l(this,ct))||l(this,ct)===0)&&w(this,Et,Qe.setInterval(()=>{(this.options.refetchIntervalInBackground||jt.isFocused())&&q(this,L,jn).call(this)},l(this,ct)))},Qs=function(){q(this,L,Os).call(this),q(this,L,qs).call(this,q(this,L,Fs).call(this))},Ds=function(){l(this,Tt)!==void 0&&(Qe.clearTimeout(l(this,Tt)),w(this,Tt,void 0))},Us=function(){l(this,Et)!==void 0&&(Qe.clearInterval(l(this,Et)),w(this,Et,void 0))},Ns=function(){let t=l(this,he).getQueryCache().build(l(this,he),this.options);if(t===l(this,K))return;let n=l(this,K);w(this,K,t),w(this,Vn,t.state),this.hasListeners()&&(n?.removeObserver(this),t.addObserver(this))},lo=function(t){j.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(l(this,le))}),l(this,he).getQueryCache().notify({query:l(this,K),type:"observerResultsUpdated"})})},uo);function ll(e,t){return me(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function ao(e,t){return ll(e,t)||e.state.data!==void 0&&Ks(e,t,t.refetchOnMount)}function Ks(e,t,n){if(me(t.enabled,e)!==!1&&Me(t.staleTime,e)!=="static"){let r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&Ls(e,t)}return!1}function co(e,t,n,r){return(e!==t||me(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&Ls(e,n)}function Ls(e,t){return me(t.enabled,e)!==!1&&e.isStaleByTime(Me(t.staleTime,e))}function dl(e,t){return!Vt(e.getCurrentResult(),t)}function en(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||[],c={pages:[],pageParams:[]},a=0,u=async()=>{let d=!1,p=y=>{Xi(y,()=>t.signal,()=>d=!0)},m=Rr(t.options,t.fetchOptions),f=async(y,g,h)=>{if(d)return Promise.reject();if(g==null&&y.pages.length)return Promise.resolve(y);let b=(()=>{let M={client:t.client,queryKey:t.queryKey,pageParam:g,direction:h?"backward":"forward",meta:t.options.meta};return p(M),M})(),E=await m(b),{maxPages:I}=t.options,R=h?Yi:Ji;return{pages:R(y.pages,E,I),pageParams:R(y.pageParams,g,I)}};if(s&&i.length){let y=s==="backward",g=y?fo:js,h={pages:i,pageParams:o},v=g(r,h);c=await f(h,v,y)}else{let y=e??i.length;do{let g=a===0?o[0]??r.initialPageParam:js(r,c);if(a>0&&g==null)break;c=await f(c,g),a++}while(a<y)}return c};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 js(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 po(e,t){return t?js(e,t)!=null:!1}function mo(e,t){return!t||!e.getPreviousPageParam?!1:fo(e,t)!=null}var Vs=class extends Wn{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:en()})}getOptimisticResult(e){return e.behavior=en(),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:c}=r,a=n.fetchMeta?.fetchMore?.direction,u=o&&a==="forward",d=s&&a==="forward",p=o&&a==="backward",m=s&&a==="backward";return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:po(t,n.data),hasPreviousPage:mo(t,n.data),isFetchNextPageError:u,isFetchingNextPage:d,isFetchPreviousPageError:p,isFetchingPreviousPage:m,isRefetchError:c&&!u&&!p,isRefetching:i&&!d&&!m}}};var Bn,Ne,ae,It,Ke,ut,ho,go=(ho=class extends Pr{constructor(t){super();x(this,Ke);x(this,Bn);x(this,Ne);x(this,ae);x(this,It);w(this,Bn,t.client),this.mutationId=t.mutationId,w(this,ae,t.mutationCache),w(this,Ne,[]),this.state=t.state||$s(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){l(this,Ne).includes(t)||(l(this,Ne).push(t),this.clearGcTimeout(),l(this,ae).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){w(this,Ne,l(this,Ne).filter(n=>n!==t)),this.scheduleGc(),l(this,ae).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){l(this,Ne).length||(this.state.status==="pending"?this.scheduleGc():l(this,ae).remove(this))}continue(){return l(this,It)?.continue()??this.execute(this.state.variables)}async execute(t){let n=()=>{q(this,Ke,ut).call(this,{type:"continue"})},r={client:l(this,Bn),meta:this.options.meta,mutationKey:this.options.mutationKey};w(this,It,Cr({fn:()=>this.options.mutationFn?this.options.mutationFn(t,r):Promise.reject(new Error("No mutationFn found")),onFail:(o,c)=>{q(this,Ke,ut).call(this,{type:"failed",failureCount:o,error:c})},onPause:()=>{q(this,Ke,ut).call(this,{type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>l(this,ae).canRun(this)}));let s=this.state.status==="pending",i=!l(this,It).canStart();try{if(s)n();else{q(this,Ke,ut).call(this,{type:"pending",variables:t,isPaused:i}),l(this,ae).config.onMutate&&await l(this,ae).config.onMutate(t,this,r);let c=await this.options.onMutate?.(t,r);c!==this.state.context&&q(this,Ke,ut).call(this,{type:"pending",context:c,variables:t,isPaused:i})}let o=await l(this,It).start();return await l(this,ae).config.onSuccess?.(o,t,this.state.context,this,r),await this.options.onSuccess?.(o,t,this.state.context,r),await l(this,ae).config.onSettled?.(o,null,this.state.variables,this.state.context,this,r),await this.options.onSettled?.(o,null,t,this.state.context,r),q(this,Ke,ut).call(this,{type:"success",data:o}),o}catch(o){try{await l(this,ae).config.onError?.(o,t,this.state.context,this,r)}catch(c){Promise.reject(c)}try{await this.options.onError?.(o,t,this.state.context,r)}catch(c){Promise.reject(c)}try{await l(this,ae).config.onSettled?.(void 0,o,this.state.variables,this.state.context,this,r)}catch(c){Promise.reject(c)}try{await this.options.onSettled?.(void 0,o,t,this.state.context,r)}catch(c){Promise.reject(c)}throw q(this,Ke,ut).call(this,{type:"error",error:o}),o}finally{l(this,ae).runNext(this)}}},Bn=new WeakMap,Ne=new WeakMap,ae=new WeakMap,It=new WeakMap,Ke=new WeakSet,ut=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(()=>{l(this,Ne).forEach(r=>{r.onMutationUpdate(t)}),l(this,ae).notify({mutation:this,type:"updated",action:t})})},ho);function $s(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Be,Oe,Hn,yo,_o=(yo=class extends xe{constructor(t={}){super();x(this,Be);x(this,Oe);x(this,Hn);this.config=t,w(this,Be,new Set),w(this,Oe,new Map),w(this,Hn,0)}build(t,n,r){let s=new go({client:t,mutationCache:this,mutationId:++Qn(this,Hn)._,options:t.defaultMutationOptions(n),state:r});return this.add(s),s}add(t){l(this,Be).add(t);let n=Tr(t);if(typeof n=="string"){let r=l(this,Oe).get(n);r?r.push(t):l(this,Oe).set(n,[t])}this.notify({type:"added",mutation:t})}remove(t){if(l(this,Be).delete(t)){let n=Tr(t);if(typeof n=="string"){let r=l(this,Oe).get(n);if(r)if(r.length>1){let s=r.indexOf(t);s!==-1&&r.splice(s,1)}else r[0]===t&&l(this,Oe).delete(n)}}this.notify({type:"removed",mutation:t})}canRun(t){let n=Tr(t);if(typeof n=="string"){let s=l(this,Oe).get(n)?.find(i=>i.state.status==="pending");return!s||s===t}else return!0}runNext(t){let n=Tr(t);return typeof n=="string"?l(this,Oe).get(n)?.find(s=>s!==t&&s.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){j.batch(()=>{l(this,Be).forEach(t=>{this.notify({type:"removed",mutation:t})}),l(this,Be).clear(),l(this,Oe).clear()})}getAll(){return Array.from(l(this,Be))}find(t){let n={exact:!0,...t};return this.getAll().find(r=>Sr(n,r))}findAll(t={}){return this.getAll().filter(n=>Sr(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(G))))}},Be=new WeakMap,Oe=new WeakMap,Hn=new WeakMap,yo);function Tr(e){return e.options.scope?.id}var He,lt,ge,Ge,ze,Er,Ws,vo,Bs=(vo=class extends xe{constructor(t,n){super();x(this,ze);x(this,He);x(this,lt);x(this,ge);x(this,Ge);w(this,He,t),this.setOptions(n),this.bindMethods(),q(this,ze,Er).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(t){let n=this.options;this.options=l(this,He).defaultMutationOptions(t),Vt(this.options,n)||l(this,He).getMutationCache().notify({type:"observerOptionsUpdated",mutation:l(this,ge),observer:this}),n?.mutationKey&&this.options.mutationKey&&De(n.mutationKey)!==De(this.options.mutationKey)?this.reset():l(this,ge)?.state.status==="pending"&&l(this,ge).setOptions(this.options)}onUnsubscribe(){this.hasListeners()||l(this,ge)?.removeObserver(this)}onMutationUpdate(t){q(this,ze,Er).call(this),q(this,ze,Ws).call(this,t)}getCurrentResult(){return l(this,lt)}reset(){l(this,ge)?.removeObserver(this),w(this,ge,void 0),q(this,ze,Er).call(this),q(this,ze,Ws).call(this)}mutate(t,n){return w(this,Ge,n),l(this,ge)?.removeObserver(this),w(this,ge,l(this,He).getMutationCache().build(l(this,He),this.options)),l(this,ge).addObserver(this),l(this,ge).execute(t)}},He=new WeakMap,lt=new WeakMap,ge=new WeakMap,Ge=new WeakMap,ze=new WeakSet,Er=function(){let t=l(this,ge)?.state??$s();w(this,lt,{...t,isPending:t.status==="pending",isSuccess:t.status==="success",isError:t.status==="error",isIdle:t.status==="idle",mutate:this.mutate,reset:this.reset})},Ws=function(t){j.batch(()=>{if(l(this,Ge)&&this.hasListeners()){let n=l(this,lt).variables,r=l(this,lt).context,s={client:l(this,He),meta:this.options.meta,mutationKey:this.options.mutationKey};if(t?.type==="success"){try{l(this,Ge).onSuccess?.(t.data,n,r,s)}catch(i){Promise.reject(i)}try{l(this,Ge).onSettled?.(t.data,null,n,r,s)}catch(i){Promise.reject(i)}}else if(t?.type==="error"){try{l(this,Ge).onError?.(t.error,n,r,s)}catch(i){Promise.reject(i)}try{l(this,Ge).onSettled?.(void 0,t.error,n,r,s)}catch(i){Promise.reject(i)}}}this.listeners.forEach(n=>{n(l(this,lt))})})},vo);var Le,bo,wo=(bo=class extends xe{constructor(t={}){super();x(this,Le);this.config=t,w(this,Le,new Map)}build(t,n,r){let s=n.queryKey,i=n.queryHash??Un(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){l(this,Le).has(t.queryHash)||(l(this,Le).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){let n=l(this,Le).get(t.queryHash);n&&(t.destroy(),n===t&&l(this,Le).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){j.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return l(this,Le).get(t)}getAll(){return[...l(this,Le).values()]}find(t){let n={exact:!0,...t};return this.getAll().find(r=>wr(n,r))}findAll(t={}){let n=this.getAll();return Object.keys(t).length>0?n.filter(r=>wr(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()})})}},Le=new WeakMap,bo);var z,dt,ft,tn,nn,pt,rn,sn,So,Hs=(So=class{constructor(e={}){x(this,z);x(this,dt);x(this,ft);x(this,tn);x(this,nn);x(this,pt);x(this,rn);x(this,sn);w(this,z,e.queryCache||new wo),w(this,dt,e.mutationCache||new _o),w(this,ft,e.defaultOptions||{}),w(this,tn,new Map),w(this,nn,new Map),w(this,pt,0)}mount(){Qn(this,pt)._++,l(this,pt)===1&&(w(this,rn,jt.subscribe(async e=>{e&&(await this.resumePausedMutations(),l(this,z).onFocus())})),w(this,sn,Gt.subscribe(async e=>{e&&(await this.resumePausedMutations(),l(this,z).onOnline())})))}unmount(){var e,t;Qn(this,pt)._--,l(this,pt)===0&&((e=l(this,rn))==null||e.call(this),w(this,rn,void 0),(t=l(this,sn))==null||t.call(this),w(this,sn,void 0))}isFetching(e){return l(this,z).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return l(this,dt).findAll({...e,status:"pending"}).length}getQueryData(e){let t=this.defaultQueryOptions({queryKey:e});return l(this,z).get(t.queryHash)?.state.data}ensureQueryData(e){let t=this.defaultQueryOptions(e),n=l(this,z).build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(Me(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return l(this,z).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=l(this,z).get(r.queryHash)?.state.data,o=Gi(t,i);if(o!==void 0)return l(this,z).build(this,r).setData(o,{...n,manual:!0})}setQueriesData(e,t,n){return j.batch(()=>l(this,z).findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){let t=this.defaultQueryOptions({queryKey:e});return l(this,z).get(t.queryHash)?.state}removeQueries(e){let t=l(this,z);j.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){let n=l(this,z);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(()=>l(this,z).findAll(e).map(s=>s.cancel(n)));return Promise.all(r).then(G).catch(G)}invalidateQueries(e,t={}){return j.batch(()=>(l(this,z).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(()=>l(this,z).findAll(e).filter(s=>!s.isDisabled()&&!s.isStatic()).map(s=>{let i=s.fetch(void 0,n);return n.throwOnError||(i=i.catch(G)),s.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(G)}fetchQuery(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=l(this,z).build(this,t);return n.isStaleByTime(Me(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(G).catch(G)}fetchInfiniteQuery(e){return e.behavior=en(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(G).catch(G)}ensureInfiniteQueryData(e){return e.behavior=en(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return Gt.isOnline()?l(this,dt).resumePausedMutations():Promise.resolve()}getQueryCache(){return l(this,z)}getMutationCache(){return l(this,dt)}getDefaultOptions(){return l(this,ft)}setDefaultOptions(e){w(this,ft,e)}setQueryDefaults(e,t){l(this,tn).set(De(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){let t=[...l(this,tn).values()],n={};return t.forEach(r=>{wt(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){l(this,nn).set(De(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){let t=[...l(this,nn).values()],n={};return t.forEach(r=>{wt(e,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;let t={...l(this,ft).queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Un(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===$t&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...l(this,ft).mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){l(this,z).clear(),l(this,dt).clear()}},z=new WeakMap,dt=new WeakMap,ft=new WeakMap,tn=new WeakMap,nn=new WeakMap,pt=new WeakMap,rn=new WeakMap,sn=new WeakMap,So);var on=X(oe(),1),xo=X(Ir(),1),Gs=on.createContext(void 0),$=e=>{let t=on.useContext(Gs);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},Gn=({client:e,children:t})=>(on.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,xo.jsx)(Gs.Provider,{value:e,children:t}));var Ar=X(oe(),1),Co=Ar.createContext(!1),Po=()=>Ar.useContext(Co),wp=Co.Provider;var zn=X(oe(),1),fl=X(Ir(),1);function pl(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var ml=zn.createContext(pl()),To=()=>zn.useContext(ml);var Eo=X(oe(),1);var Io=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError=="function"?Wt(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},Ao=e=>{Eo.useEffect(()=>{e.clearReset()},[e])},ko=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:s})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(s&&e.data===void 0||Wt(n,[e.error,r]));var Mo=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))}},Oo=(e,t)=>e.isLoading&&e.isFetching&&!t,Fo=(e,t)=>e?.suspense&&t.isPending,zs=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});var mt=X(oe(),1);function kr(e,t,n){let r=Po(),s=To(),i=$(n),o=i.defaultQueryOptions(e);i.getDefaultOptions().queries?._experimental_beforeQuery?.(o);let c=i.getQueryCache().get(o.queryHash);o._optimisticResults=r?"isRestoring":"optimistic",Mo(o),Io(o,s,c),Ao(s);let a=!i.getQueryCache().get(o.queryHash),[u]=mt.useState(()=>new t(i,o)),d=u.getOptimisticResult(o),p=!r&&e.subscribed!==!1;if(mt.useSyncExternalStore(mt.useCallback(m=>{let f=p?u.subscribe(j.batchCalls(m)):G;return u.updateResult(),f},[u,p]),()=>u.getCurrentResult(),()=>u.getCurrentResult()),mt.useEffect(()=>{u.setOptions(o)},[o,u]),Fo(o,d))throw zs(o,u,s);if(ko({result:d,errorResetBoundary:s,throwOnError:o.throwOnError,query:c,suspense:o.suspense}))throw d.error;return i.getDefaultOptions().queries?._experimental_afterQuery?.(o,d),o.experimental_prefetchInRender&&!Ue.isServer()&&Oo(d,r)&&(a?zs(o,u,s):c?.promise)?.catch(G).finally(()=>{u.updateResult()}),o.notifyOnChangeProps?d:u.trackResult(d)}function V(e,t){return kr(e,Wn,t)}var Je=X(oe(),1);function de(e,t){let n=$(t),[r]=Je.useState(()=>new Bs(n,e));Je.useEffect(()=>{r.setOptions(e)},[r,e]);let s=Je.useSyncExternalStore(Je.useCallback(o=>r.subscribe(j.batchCalls(o)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),i=Je.useCallback((o,c)=>{r.mutate(o,c).catch(G)},[r]);if(s.error&&Wt(r.options.throwOnError,[s.error]))throw s.error;return{...s,mutate:i,mutateAsync:s.mutate}}function Jn(e,t){return kr(e,Vs,t)}var Do=X(Qo(),1),Yn=typeof window<"u"&&window.__FSAOS_CONFIG__||{},At=Array.isArray(Yn.sources)?Yn.sources:[],hl=Yn.supabaseUrl||"https://vahbmsslxuustnlvsrkg.supabase.co",gl=Yn.supabaseAnonKey||"sb_publishable_ZjosozAjfpZ4InMNElTr6Q_hHB-f5nc",Pe=Yn.gatewayUrl||"https://fsaos-mcp-gw-rust.fly.dev",W=(0,Do.createClient)(hl,gl,{auth:{persistSession:!0,autoRefreshToken:!0,detectSessionInUrl:!1}});var Xn=null,Mr=0,Uo,Zs,Or=!1;Uo=new Promise(e=>{Zs=e});W.auth.onAuthStateChange((e,t)=>{t?.access_token?(Xn=t.access_token,Mr=t.expires_at??Math.floor(Date.now()/1e3)+3600):(Xn=null,Mr=0),Or||(Or=!0,Zs())});setTimeout(()=>{Or||(Or=!0,Zs())},5e3);function No(e,t){Xn=e,Mr=t??Math.floor(Date.now()/1e3)+3600}function ei(){Xn=null,Mr=0}async function Ye(){let e=typeof window<"u"&&window.__FSAOS_CONFIG__||{};if(e.embedToken){if(typeof e.embedToken=="function")try{return await e.embedToken()??null}catch{return null}return e.embedToken}return await Uo,Xn}var ln=null,dn=null,Ko=0,Js=new Set,ti,Zn,fn=!1;ti=new Promise(e=>{Zn=e});function ni(){Ko++,Js.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Anchor listener error:",t)}})}function qr(e){let t=typeof e=="string"?e:e.path,n=ln!==t||dn?.id!==(typeof e=="string"?void 0:e.id);ln=t,dn=typeof e=="string"?null:e,typeof e!="string"&&!kt.some(r=>r.id===e.id)&&(kt=[...kt,e],oi()),fn||(fn=!0,Zn()),n&&ni()}function pn(){return ln}function ye(){return dn}function ri(){return Ko}function si(e){return Js.add(e),()=>{Js.delete(e)}}function er(){return ti}function ii(){return fn}var Fr=null;function Mt(e,t={}){if(Fr){console.warn("[SDK] electHomeAnchor called twice; ignoring (logout to re-elect).");return}Fr=e,t.activate!==!1&&qr(e)}function fe(){return Fr}var kt=[],Ys=new Set,Lo=0;function oi(){Lo++,Ys.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Mount listener error:",t)}})}function Te(){return kt}function tr(){return Lo}function Qr(e){return Ys.add(e),()=>{Ys.delete(e)}}function jo(e,t){let n=JSON.stringify(kt)!==JSON.stringify(e),r=ln!==t.path||dn?.id!==t.id;kt=e,ln=t.path,dn=t,fn||(fn=!0,Zn()),n&&oi(),r&&ni()}var cn=null,an=null,un=0,Xs=new Set,Vo=0;function $o(){Vo++,Xs.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Session listener error:",t)}})}function se(){return un}function ai(){return Vo}function Wo(e){return Xs.add(e),()=>{Xs.delete(e)}}async function Xe(){if(cn)return cn;if(an)return an;let e=un;return an=(async()=>{let t=Ot(),n=await Ye();if(e!==un)throw new Error("Session changed during initialization");let r={};n&&(r.Authorization=`Bearer ${n}`);let s=await fetch(`${Pe}/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!==un)throw new Error("Session changed during initialization");let o=i.entry||i;return cn={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},$o(),cn})().catch(t=>{throw e===un&&(an=null),t}),an}function ht(){return cn}function ci(){un++,cn=null,an=null,ln=null,dn=null,Fr=null,kt=[],$o()}var Bo=[];function te(e){Bo.push(e)}function mn(){ci(),ei(),Zn(),fn=!1,ti=new Promise(e=>{Zn=e}),ni(),oi();for(let e of Bo)try{e()}catch(t){console.warn("[SDK] Cleanup function failed:",t)}}function Ot(){if(typeof window<"u"){let e=window.__FSAOS_CONFIG__;return e?.hostname?e.hostname:window.location.hostname}return"localhost"}var Ho=qr,H=pn,Z=ri,we=si,Go=er,Dr=ii;var ui=0,zo=!1,Jo=0;function Yo(e){if(typeof e!="string")return;let t=Date.parse(e);Number.isNaN(t)||(ui=t-Date.now(),zo=!0,Jo=Date.now())}function Ur(){return Date.now()+ui}function Xo(){return zo}function Zo(){return ui}function ea(){return Jo}function ta(e){if(typeof e!="string")return null;let t=Date.parse(e);return Number.isNaN(t)?null:Ur()>=t}function na(e){if(typeof e!="string")return null;let t=Date.parse(e);return Number.isNaN(t)?null:Math.max(0,t-Ur())}var hn,Ee=new Map,Ft=[],li=0,di={foreground:0,normal:1,background:2},Nr=()=>performance.now(),fi=()=>new DOMException("Read cancelled","AbortError");function sa(e={}){hn={concurrency:Math.max(1,Math.min(16,Math.floor(e.concurrency??6))),timeoutMs:Math.max(1e3,e.timeoutMs??15e3),onTiming:e.onTiming},Lr()}function ia(){for(let e of Ee.values()){e.controller.abort();for(let t of e.consumers)t.detach(),t.reject(fi());e.consumers.clear(),e.timer&&clearTimeout(e.timer)}Ee.clear(),Ft.length=0}function oa(e,t){return e==="query"?!("materialize"in t):["read","list","search","resolve","resolve-items","get-channel-messages","list-memberships"].includes(e)}function Kr(e){return Array.isArray(e)?`[${e.map(Kr).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)}:${Kr(n)}`).join(",")}}`:JSON.stringify(e)}function aa(e,t,n,r){if(n.signal?.aborted)return Promise.reject(fi());if(!hn)return r(n.signal);let s=Ee.get(e);if(s)di[n.priority??"normal"]<di[s.priority]&&(s.priority=n.priority??"normal");else{s={key:e,method:t,priority:n.priority??"normal",queuedAt:Nr(),controller:new AbortController,consumers:new Set,run:r},Ee.set(e,s),Ft.push(s);let c=s;s.timer=setTimeout(()=>{c.controller.abort();let a=new Error("The read timed out. Please retry.");a.name="TimeoutError";for(let u of c.consumers)u.detach(),u.reject(a);c.consumers.clear(),Ee.get(c.key)===c&&Ee.delete(c.key),ra(c)},hn.timeoutMs)}let i=s,o=new Promise((c,a)=>{let u=()=>{d.detach(),i.consumers.delete(d),a(fi()),i.consumers.size||(i.controller.abort(),Ee.get(i.key)===i&&Ee.delete(i.key),ra(i))},d={resolve:p=>c(structuredClone(p)),reject:a,detach:()=>n.signal?.removeEventListener("abort",u)};i.consumers.add(d),n.signal?.addEventListener("abort",u,{once:!0})});return Lr(),o}function ra(e){let t=Ft.indexOf(e);t>=0&&(Ft.splice(t,1),Ee.get(e.key)===e&&Ee.delete(e.key),e.timer&&clearTimeout(e.timer)),Lr()}function Lr(){if(hn)for(;li<hn.concurrency&&Ft.length;){let e=r=>di[r.priority]-Math.floor((Nr()-r.queuedAt)/2e3);Ft.sort((r,s)=>e(r)-e(s)||r.queuedAt-s.queuedAt);let t=Ft.shift();if(!t.consumers.size)continue;li++,t.startedAt=Nr();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(),Ee.get(t.key)===t&&Ee.delete(t.key),li--;try{hn?.onTiming?.({method:t.method,priority:t.priority,queueMs:Math.round(t.startedAt-t.queuedAt),requestMs:Math.round(Nr()-t.startedAt),outcome:n})}catch{}Lr()})}}te(ia);var yl=new Set(["list-memberships","init"]),Ie=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);ee(this,"name","GatewayRequestError");ee(this,"method");ee(this,"status");ee(this,"statusText");ee(this,"payload");ee(this,"responseBody");this.method=n.method,this.status=n.status,this.statusText=n.statusText,this.payload=n.payload,this.responseBody=n.responseBody}};async function C(e,t={},n={}){let r=se(),s=pn(),i=Ot(),o=`${Pe}/d/${i}`,c={"Content-Type":"application/json"},a=await ca(Ye(),n.signal);if(r!==se())throw new Error("Session changed before gateway request");if(a&&(c.Authorization=`Bearer ${a}`),!yl.has(e)&&!t._scope_path&&await ca(er(),n.signal),r!==se())throw new Error("Session changed before gateway request");let u={...t},d=ht();!u.domain_scope_id&&d?.scope_id&&(u.domain_scope_id=d.scope_id);let p=s??pn();!u._scope_path&&p&&(u._scope_path=p);let m=async f=>{if(r!==se())throw new Error("Session changed before queued gateway request");let y=await fetch(o,{method:"POST",signal:f,headers:c,body:JSON.stringify({method:e,params:u})}),g=await y.text();if(r!==se())throw new Error("Session changed during gateway request");let h=null;if(g)try{h=JSON.parse(g)}catch{}if(!y.ok||!h)throw new Ie({method:e,status:y.status,statusText:y.statusText,payload:h,responseBody:g});if(h.success===!1){let v=h.error||"",b=h.denied_by||h.error_type||"";throw b==="rule"||b==="access"||b==="entitlement"||v==="RULE_DENIED"||v==="ACCESS_DENIED"||v==="PERMISSION_DENIED"||v==="ENTITLEMENT_REQUIRED"?new rt(h):new Ie({method:e,status:y.status,statusText:y.statusText,payload:h,responseBody:g})}return h&&h.server_now!==void 0&&Yo(h.server_now),h};return oa(e,u)?aa(Kr([r,i,a,e,u]),e,n,m):m(n.signal)}function ca(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 _=X(oe(),1),Kl=X(la(),1),Ll=X(Ir(),1);var da=new WeakMap;function Ae(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(p=>p.promise?[p.promise]:[]);if(i.length===0)return s();let o=`${r?"=":"^"}${JSON.stringify(t)}`,c=da.get(e);c||(c=new Map,da.set(e,c));let a=c.get(o);if(a)return a;let u=c,d=Promise.allSettled(i).then(()=>(u.delete(o),s()));return u.set(o,d),d}function pe(e,t){return typeof e=="string"&&(e===t||e.startsWith(`${t}/`))}var jr=new WeakMap,fa=e=>e.meta?.arrangementRealtime===!0;function Ze(e,t){let n=e.getQueryCache().find({queryKey:t,exact:!0});if(!n)return;let r=jr.get(e);r||(r=new Map,jr.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&&Ae(e,t,{exact:!0})},250))}function pa(e,t){if(!(!t||typeof t!="object"))for(let n of e.getQueryCache().getAll()){if(!fa(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")&&Ze(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)))&&Ze(e,n.queryKey)}}function ma(e){for(let t of e.getQueryCache().getAll())fa(t)&&t.state.data!==void 0&&Ze(e,t.queryKey)}function ha(e){jr.get(e)?.forEach(clearTimeout),jr.delete(e)}var et=null;te(()=>{et&&(et.cancelQueries({queryKey:["vfs"]}),et.removeQueries({queryKey:["vfs"]}))});function ga(e){if(et&&et!==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.");et=e}function O(){return et||(et=new Hs({defaultOptions:{queries:{staleTime:1e3*60*2,gcTime:1e3*60*10,refetchOnWindowFocus:!1,retry:1}}})),et}var ya=new Proxy({},{get(e,t,n){let r=O(),s=r[t];return typeof s=="function"?s.bind(r):s}});var Vr=new WeakMap;function pi(e){return e.meta?.infiniteItemsRealtime?.filter}function _l(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 vl(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 bl(e,t,n){if(_l(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&&!pe(n.path,r)&&!pe(n.old_path,r))return!1;if(n.item_type==="symlink"&&s&&i)return!0;let o=vl(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 _a(e,t){let n=Vr.get(e);n||(n=new Map,Vr.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||!pi(t))&&Ae(e,t.queryKey,{exact:!0})},500))}function va(e,t){if(!(!t||typeof t!="object"))for(let n of e.getQueryCache().getAll()){let r=pi(n);r&&bl(n,r,t)&&_a(e,n)}}function ba(e){for(let t of e.getQueryCache().getAll())pi(t)&&t.state.data!==void 0&&_a(e,t)}function wa(e){Vr.get(e)?.forEach(clearTimeout),Vr.delete(e)}var $r=class extends Error{constructor(){super("The server did not confirm the selected-Space listing contract")}};function Sa(e,t){if(!Array.isArray(t)||t.some(n=>typeof n!="string")||JSON.stringify([...new Set(t)].sort())!==JSON.stringify(e))throw new $r}function gt(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 gn(e){return e instanceof $r||e instanceof rt||e instanceof Ie&&(e.payload?.error==="SPACE_SELECTION_UNAVAILABLE"||e.payload?.error==="QUERY_PARAMS_INVALID"||e.status===401||e.status===403)}function ie(){return H()??"__unscoped__"}var P={all:()=>["vfs",ie()],item:e=>["vfs",ie(),"item",e],itemById:e=>["vfs","item-by-id",e],children:e=>["vfs",ie(),"children",e],allChildren:()=>["vfs",ie(),"children"],types:e=>["vfs","types",e??"default"],edges:e=>["vfs","edges",e],search:(e,t)=>["vfs",ie(),"search",e,...t??[]],items:(e,t)=>["vfs",ie(),"items",e,JSON.stringify(gt(t??{}))],allItems:()=>["vfs",ie(),"items"],tree:(e,t)=>["vfs",ie(),"tree",e,t??1],openEnvelope:(e,t)=>["vfs",ie(),"open",e,t??"__default__"],allOpenEnvelopes:()=>["vfs",ie(),"open"],memberFocus:e=>["vfs","member-focus",e],fractalInstances:()=>["vfs","fractal-instances"],recentActivity:(e,t,n)=>["vfs",ie(),"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",ie(),"channel-messages",e,t??"__top__"],allChannelMessages:()=>["vfs",ie(),"channel-messages"],channels:e=>["vfs",ie(),"channels",e??"all"],allChannels:()=>["vfs",ie(),"channels"],notifications:(e,t)=>["vfs",ie(),"notifications",e??"all",t??200],allNotifications:()=>["vfs",ie(),"notifications"],unreadCounts:()=>["vfs",ie(),"unread-counts"],memberships:e=>["memberships",e]};var wl=typeof window<"u"&&(window.location?.hostname==="localhost"||window.location?.hostname==="127.0.0.1"||window.__FSAOS_WS_DEBUG__);function J(...e){wl&&console.log("[WS]",...e)}var D=null,yn=null,vn=null,nr=0,Sl=3e4,Ra=1e4,wn=!1,xa=!1,Ia=3e4,Rl=Ia*2+5e3,Wr=0,Br=null,Ca=!1;function xl(){sr(),Wr=Date.now(),Br=setInterval(()=>{if(D&&D.readyState===WebSocket.OPEN&&Date.now()-Wr>Rl){J("ping: no inbound traffic for",Date.now()-Wr,"ms \u2014 closing half-open socket");try{D.close(4e3,"liveness timeout")}catch{}return}nt({type:"ping"})},Ia)}function sr(){Br&&(clearInterval(Br),Br=null)}function Cl(){typeof document>"u"||(document.hidden?sr():rr()&&(J("Tab visible, reconnecting..."),qt()))}function Pl(){Ca||typeof document>"u"||(document.addEventListener("visibilitychange",Cl),Ca=!0)}var Se={};function hi(e,t){let n=e.replace(/\/+$/,""),r=t.replace(/\/+$/,"");return!n||!r?n===r:r===n||r.startsWith(`${n}/`)}var bn=[],tt=new Map,_n=new Map,ke=new Map;function Tl(e){let t=_n.get(e);return t?Array.from(new Set(Array.from(t.values()).flatMap(n=>n.event_types))).sort():[]}function Pa(e,t){return e?e.length===t.length&&e.every((n,r)=>n===t[r]):!1}function Ta(e){let t=Tl(e);if(t.length===0)return tt.delete(e),null;let n={scope_id:e,event_types:t};return tt.set(e,n),n}var je=new Map,yt=new Map,mi="disconnected",Hr=[];function Gr(e){if(mi!==e){mi=e;for(let t of[...Hr])try{t(e)}catch{}}}function El(e){je.set(e,"ready");let t=yt.get(e);if(t){yt.delete(e);for(let n of t)n()}}function Il(){for(let e of je.keys())je.set(e,"disconnected")}function gi(e,t){je.set(e,"pending"),nt({type:"subscribe_path",path:e,event_types:t})}function Al(){return Object.keys(Se).some(t=>Se[t]&&Se[t].length>0)||bn.length>0}function rr(){return tt.size>0||ke.size>0}async function qt(){if(!rr()){J("ensureConnection: no active subscriptions, skipping");return}if(D&&D.readyState===WebSocket.OPEN){J("ensureConnection: already open");return}if(yn)return J("ensureConnection: connection already in flight, waiting..."),yn;if(D){J("ensureConnection: killing stale WS in state",D.readyState);try{D.close()}catch{}D=null}return wn=!1,yn=(async()=>{try{let e=typeof window<"u"&&window.__FSAOS_CONFIG__||{},t=Pe,n=await Ye();if(!n){J("ensureConnection: no token available, will retry"),Ea();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)+"..."),Gr("connecting"),D=new WebSocket(i);let o=D;await new Promise((c,a)=>{if(!D)return a(new Error("WebSocket not created"));let u=setTimeout(()=>{if(D===o){if(J("ensureConnection: TIMEOUT after",Ra,"ms"),D&&D.readyState!==WebSocket.OPEN){try{D.close()}catch{}D=null}a(new Error("WebSocket connection timeout"))}},Ra);o.onopen=()=>{if(D!==o)return;clearTimeout(u),J("ensureConnection: CONNECTED");let d=xa;xa=!0,nr=0,Gr("connected"),kl(d),(typeof document>"u"||!document.hidden)&&xl(),Pl(),c()},o.onmessage=d=>{D===o&&Ml(d.data)},o.onerror=()=>{J("ensureConnection: WS error event")},o.onclose=d=>{clearTimeout(u),D===o&&(J("ensureConnection: WS closed, code:",d.code,"reason:",d.reason),D=null,sr(),Il(),Gr("disconnected"),!wn&&rr()&&Ea(),a(new Error(`WebSocket closed: ${d.code}`)))}})}catch(e){J("ensureConnection: failed -",e?.message||e)}finally{yn=null}})(),yn}function Ea(){if(vn||typeof document<"u"&&document.hidden)return;let e=Math.min(1e3*Math.pow(2,nr)+Math.random()*1e3,Sl);nr++,J("scheduleReconnect: attempt",nr,"in",Math.round(e),"ms"),vn=setTimeout(()=>{vn=null,rr()&&qt()},e)}function kl(e=!1){for(let t of tt.values())J("resubscribeAll: scope",t.scope_id),nt({type:"subscribe",scope_id:t.scope_id,event_types:t.event_types});for(let t of ke.values())J("resubscribeAll: path",t.path),gi(t.path,t.event_types);if(e)try{let t=O();ba(t),ma(t);for(let n of ke.values())t.invalidateQueries({queryKey:P.item(n.path)}),t.invalidateQueries({queryKey:P.children(n.path)});J("resubscribeAll: invalidated",ke.size,"paths after reconnect")}catch(t){J("resubscribeAll: cache invalidation skipped",t)}}function nt(e){D&&D.readyState===WebSocket.OPEN&&D.send(JSON.stringify(e))}function Ml(e){Wr=Date.now();try{let t=JSON.parse(e);if(t.type==="subscribed_path"){typeof t.path=="string"&&El(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==="event"||t.event_type){let n=t.event_type||"message",r=t.data||t;if(n==="vfs_change"&&(va(O(),r),pa(O(),r)),typeof r.path=="string")for(let[s,i]of Object.entries(Se))s!=="*"&&hi(s,r.path)&&i.forEach(o=>o(r));Se["*"]&&Se["*"].forEach(s=>s(r));for(let s of bn)s.eventType!=="*"&&s.eventType!==n||s.filter&&!s.filter(r)||s.callback(r)}}catch{}}function yi(){!Al()&&tt.size===0&&ke.size===0&&D&&(wn=!0,sr(),D.close(),D=null,wn=!1)}function zr(e,t){return Se[e]||(Se[e]=[]),Se[e].push(t),ke.has(e)||(ke.set(e,{path:e,event_types:["token_stream"]}),D&&D.readyState===WebSocket.OPEN?gi(e,["token_stream"]):je.set(e,"pending")),qt(),()=>{let n=Se[e];if(n){let r=n.indexOf(t);r!==-1&&n.splice(r,1),n.length===0&&(delete Se[e],ke.delete(e),je.delete(e),yt.delete(e),nt({type:"unsubscribe_path",path:e}))}yi()}}function ne(e,t,n){let s=(Array.isArray(e)?e:[e]).map(i=>({eventType:i,callback:t,filter:n}));return bn.push(...s),rr()&&qt(),()=>{for(let i of s){let o=bn.indexOf(i);o!==-1&&bn.splice(o,1)}yi()}}function Sn(e,t=["vfs_change","ccm_change"]){let n=Symbol(e),r=Array.from(new Set(t)).sort();if(r.length===0)return()=>{};let s=_n.get(e)??new Map,i=tt.get(e)?.event_types;s.set(n,{event_types:r}),_n.set(e,s);let o=Ta(e);if(!o)return()=>{};J("subscribeToScope:",e,o.event_types),D&&D.readyState===WebSocket.OPEN&&!Pa(i,o.event_types)&&nt({type:"subscribe",scope_id:e,event_types:o.event_types}),qt();let c=!0;return()=>{if(!c)return;c=!1;let a=_n.get(e);if(!a?.delete(n))return;let u=tt.get(e)?.event_types;if(a.size===0)_n.delete(e),tt.delete(e),nt({type:"unsubscribe",scope_id:e});else{let d=Ta(e);d&&D&&D.readyState===WebSocket.OPEN&&!Pa(u,d.event_types)&&nt({type:"subscribe",scope_id:e,event_types:d.event_types})}yi()}}function Aa(e,t,n={}){nt({type:"emit",scope_id:e,event_type:t,payload:n})}function _i(){J("disconnectSSE: tearing down"),wa(O()),ha(O()),wn=!0,sr(),D&&(D.close(),D=null),vn&&(clearTimeout(vn),vn=null),yn=null,wn=!1,nr=0;for(let e of Object.keys(Se))delete Se[e];bn.length=0,tt.clear(),_n.clear(),ke.clear(),je.clear(),yt.clear(),Gr("disconnected")}function ka(){nt({type:"ping"})}function Ma(e){return ke.has(e)?je.get(e)??"pending":"unsubscribed"}function Oa(e,t=5e3){return ke.has(e)?je.get(e)==="ready"&&D&&D.readyState===WebSocket.OPEN?Promise.resolve(!0):(qt(),new Promise(n=>{let r=!1,s=yt.get(e)??[],i=()=>{r||(r=!0,clearTimeout(o),n(!0))};s.push(i),yt.set(e,s);let o=setTimeout(()=>{if(r)return;r=!0;let c=yt.get(e);if(c){let a=c.indexOf(i);a!==-1&&c.splice(a,1),c.length===0&&yt.delete(e)}n(!1)},t)})):Promise.resolve(!1)}function Fa(e){let t=ke.get(e);if(!t){J("resubscribePath: no active subscription for",e);return}D&&D.readyState===WebSocket.OPEN?(J("resubscribePath: re-sending frame for",e),gi(t.path,t.event_types)):(je.set(e,"pending"),qt())}function Jr(e){Hr.push(e);try{e(mi)}catch{}return()=>{let t=Hr.indexOf(e);t!==-1&&Hr.splice(t,1)}}te(_i);function qa(){return new Date().toISOString()}function Qa(){return crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function _e(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||qa(),updated_at:e.updated_at||qa(),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 or(e){return(e.content?.items||e.items||[]).map(_e)}async function Xr(e){try{let t=await C("read",{id:e});if(t.item_name||t.item_path){let r=_e(t);return r.path&&O().setQueryData(P.item(r.path),r),r}let n=t.item;if(n){let r=_e(n);return r.path&&O().setQueryData(P.item(r.path),r),r}return null}catch{return null}}async function ar(e){try{let t=await C("read",{path:e});if(t.item_name||t.item_path)return _e(t);let n=t.item;return n?_e(n):null}catch{return null}}async function cr(e){try{let t=await C("list",{path:e,limit:200}),n=or(t);for(let r of n)O().setQueryData(P.item(r.path),r);return n}catch(t){return console.error(`[gateway] Failed to fetch children of ${e}:`,t),[]}}async function Da(e,t){let{items:n}=await xn({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 Zr(e,t,n){try{let r=await C("list",{path:e,limit:t,offset:n}),s=or(r);for(let i of s)O().setQueryData(P.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 es(e){let n=await C("types-list",e?{scope_id:e}:{}),r=n.content?.items||n.items||[],s=new Map;for(let i of r){let o=i.name,c=i.type_data;!o||!c||s.set(o,{type_key:o,display_name:c.display_name||o,display_name_plural:c.display_name_plural||o+"s",icon:c.icon||"File",color:c.color||"gray",description:c.description||"",input_schema:c.input_schema||{},system_schema:c.system_schema||{},json_schema:c.input_schema||c.json_schema||{},default_data:c.default_data||{},field_defaults:c.field_defaults||{},renderer_config:c.renderer_config||{},is_system:c.is_system??!1,is_active:c.is_active??!0,is_container:c.is_container??!1,is_scope:c.is_scope??!1,render_mode:c.render_mode||"none",placement_mode:c.placement_mode,direct_parent_types:c.direct_parent_types,allowed_parent_types:c.allowed_parent_types,governed_create:c.governed_create,create_method:c.create_method,dedup:c.dedup,edges:c.edges,events:c.events})}return s}async function ts(e){try{let t=await C("edges",{item_id:e}),n=t.outgoing||[],r=t.incoming||[],s=[];for(let i of n)s.push({id:i.edge_id||Qa(),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||Qa(),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 ns(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 C("tree",s),o=or(i);for(let c of o)O().setQueryData(P.item(c.path),c);return o}catch(s){return console.error(`[gateway] Failed to fetch tree at ${e}:`,s),[]}}async function rs(e,t=50,n=0){try{let r=await C("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 ur(e,t={}){let{limit:n=50,offset:r=0,include_snapshots:s=!1}=t;try{let i=await C("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 ss(e,t=50,n=0){return ur(e,{limit:t,offset:n})}async function is(e,t,n){try{let r={scope_id:e};t?.length&&(r.item_types=t),n&&(r.limit=n);let s=await C("member-focus",r),i=or(s);for(let o of i)O().setQueryData(P.item(o.path),o);return i}catch(r){return console.error(`[gateway] Failed to fetch member focus for scope ${e}:`,r),[]}}async function os(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 C("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 Rn(e){return!!e&&(!!e.type||Array.isArray(e.any_of)&&e.any_of.length>0)}function Ol(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 Fl=["catalog","parent_only","internal"];function Ua(e,t={}){if(!e||typeof e!="object")return null;let n=o=>typeof o=="string"||typeof o=="number"||typeof o=="boolean",r=o=>{let c={},a={};for(let[u,d]of Object.entries(o))u.startsWith("field.")&&u.length>6&&n(d)?c[u.slice(6)]=d:u.startsWith("field_in.")&&u.length>9&&Array.isArray(d)&&(a[u.slice(9)]=d.filter(n));return{fields:c,field_in:a}},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"&&Fl.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 c of e.any_of){if(!c||typeof c!="object"||Array.isArray(c))continue;let a=c,u={};typeof a.item_type=="string"&&a.item_type&&(u.item_type=a.item_type);let d=r(a);Object.keys(d.fields).length&&(u.fields=d.fields),Object.keys(d.field_in).length&&(u.field_in=d.field_in),Object.keys(u).length&&o.push(u)}o.length&&(s.any_of=o)}return Rn(s)?{...s,...t}:null}async function xn(e,t={}){if(e=gt(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(Ol)),Object.keys(r).length>0&&(n.filters=r),e.limit!=null&&(n.limit=e.limit);try{let s=await C("query",n,t);e.spaceIds!==void 0&&Sa(e.spaceIds,s.selected_space_ids??s.content?.selected_space_ids);let i=or(s);for(let o of i)O().setQueryData(P.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 ql(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 Na(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:ql(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 ir(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,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 Ka(e,t){try{let n={channel_path:e};t&&(n.parent_message_id=t);let s=await C("get-channel-messages",n),i=s.messages||s.content?.items||s.items||[];return ir(i)}catch(n){return console.error(`[gateway] Failed to fetch channel messages for ${e}:`,n),[]}}async function as(e,t){try{let n={channel_path:e};t&&(n.parent_message_id=t);let s=await C("get-channel-messages",n),i=s.messages||[],o=ir(i),c=Na(i),a=new Map,u=[];for(let d of c)if(d.parentMessagePath){let p=a.get(d.parentMessagePath)||[];p.push(d),a.set(d.parentMessagePath,p)}else u.push(d);return{messages:o,activityMessages:ir(s.activity_messages||[]),messageCards:a,siblingCards:u,mode:s.mode||"top_level"}}catch(n){return console.error(`[gateway] Failed to fetch channel messages with cards for ${e}:`,n),{messages:[],messageCards:new Map,siblingCards:[],mode:"top_level"}}}async function lr(e,t){try{let n={channel_path:e};t?.parentMessageId&&(n.parent_message_id=t.parentMessageId),t?.limit&&(n.limit=t.limit),t?.before_seq!=null&&(n.before_seq=t.before_seq),t?.after_seq!=null&&(n.after_seq=t.after_seq);let s=await C("get-channel-messages",n),i=s.messages||[],o=Na(i),c=new Map,a=[];for(let u of o)if(u.parentMessagePath){let d=c.get(u.parentMessagePath)||[];d.push(u),c.set(u.parentMessagePath,d)}else a.push(u);return{messages:ir(i),activityMessages:ir(s.activity_messages||[]),messageCards:c,siblingCards:a,mode:s.mode||"top_level"}}catch(n){return console.error(`[gateway] Failed to fetch channel messages page for ${e}:`,n),{messages:[],messageCards:new Map,siblingCards:[],mode:"top_level"}}}function Yr(e){O().invalidateQueries({queryKey:P.children(e)})}function vi(e){O().invalidateQueries({queryKey:P.item(e)})}function La(e,t){vi(e),Yr(e);let n=e.split("/");n.pop();let r=n.join("/")||t;r&&Yr(r)}function ja(e){let t=e+"/";O().invalidateQueries({predicate:n=>{let r=n.queryKey;return r[0]!=="vfs"?!1:r.some(s=>typeof s=="string"&&(s===e||s.startsWith(t)))}})}function Va(){O().invalidateQueries({queryKey:P.all()})}function $a(e){O().invalidateQueries({queryKey:P.types(e)})}function Wa(e,t){e?O().invalidateQueries({queryKey:P.channelMessages(e,t)}):O().invalidateQueries({queryKey:P.allChannelMessages()})}function Ba(e,t){e&&t?O().invalidateQueries({queryKey:P.openEnvelope(e,t)}):e?O().invalidateQueries({predicate:n=>{let r=n.queryKey;return r[0]==="vfs"&&r[2]==="open"&&r[3]===e}}):O().invalidateQueries({queryKey:P.allOpenEnvelopes()})}function Ve(e){return{id:e.accountId,path:e.path,kind:e.isSpace?"space":"account",name:e.name,grantedUnderAccountId:e.grantedUnderAccountId??void 0}}async function cs(){return((await C("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,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 Cn=new Map,dr=null,us=null,_t=new Map,Ha=250;function Qt(e){if(dr){Pn(e);return}Pn(e),dr=ne("vfs_change",t=>Ql(t)),us=ne("ccm_change",t=>Dl(t))}function Pn(e){if(Cn.has(e))return;let t=Sn(e,["vfs_change","ccm_change"]);Cn.set(e,t)}function ls(e){let t=Cn.get(e);t&&(t(),Cn.delete(e))}function bi(){for(let[,e]of Cn)e();Cn.clear(),dr&&(dr(),dr=null),us&&(us(),us=null),_t.forEach(e=>clearTimeout(e)),_t.clear()}te(bi);function Ql(e){let t=e.path,n=e.action;if(!t)return;let r=t.split("/");r.pop();let s=r.join("/")||"/root",i=_t.get(s);i&&clearTimeout(i);let o=setTimeout(()=>{_t.delete(s),Ul(n,t,e,s)},Ha);_t.set(s,o)}function Dl(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=_t.get(s);i&&clearTimeout(i);let o=setTimeout(()=>{_t.delete(s),t&&O().invalidateQueries({queryKey:P.edges(t)}),n&&O().invalidateQueries({queryKey:P.edges(n)})},Ha);_t.set(s,o)}function Ul(e,t,n,r){if((e||"").toUpperCase()==="DELETE")O().removeQueries({queryKey:P.item(t)}),O().removeQueries({queryKey:P.children(t)}),O().removeQueries({queryKey:P.tree(t)});else if(n.item_id)try{let i={id:n.item_id,path:n.path,name:n.name,item_type:n.item_type,parent_id:n.parent_id,scope_item_id:n.scope_item_id},o=_e(i);o&&o.id&&O().setQueryData(P.item(t),o)}catch{}O().invalidateQueries({queryKey:P.children(r)}),O().invalidateQueries({predicate:i=>{let o=i.queryKey;if(o[0]!=="vfs"||o[1]!=="tree")return!1;let c=o[2];return t.startsWith(c+"/")||t===c}}),n.item_id&&O().invalidateQueries({queryKey:P.itemById(n.item_id)})}var Tn=null;te(()=>{Tn=null});function vt(e){if(e!==Tn||e.generation!==se())throw new Error("Workspace session changed")}function Nl(e){return e instanceof Ie&&e.payload?.error==="item_not_found"}function fr(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=fe();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 Ga(e,t){return JSON.stringify({mounts:e.map(n=>n.id),last_anchor:t.id})}async function za(e,t,n){vt(e);let r=Ga(t,n);if(e.saved===r)return;let s=JSON.parse(r);await C(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}),vt(e),e.exists=!0,e.saved=r}function Ja(e,t){let n=Te();Qt(fe().id);for(let r of n)e.some(s=>s.id===r.id)||ls(r.id);for(let r of e)Pn(r.id);jo(e,t)}async function Dt(e,t,n={}){let r=fe();if(!r)throw new Error("Elect a home account before loading mounts");let s=`${e}/settings/mounts`;if(Tn&&Tn.path!==s)throw new Error("Reset the session before changing the mount declaration owner");let i=Tn??(Tn={generation:se(),path:s,scope:r.path,resolve:t,exists:!1,ready:!1,saved:null,queue:Promise.resolve()});return vt(i),i.loading?i.loading:i.ready?Te():(i.resolve=t,i.loading=(async()=>{let o=null;try{let d=await C("read",{path:s,_scope_path:i.scope});if(vt(i),o=d.type_data??d.item?.type_data,!o||!Array.isArray(o.mounts)||!o.mounts.every(p=>typeof p=="string"))throw new Error("Invalid saved mount declaration");i.exists=!0}catch(d){if(vt(i),!Nl(d))throw d;i.exists=!1}let c=n.initialAnchor?fr(i,n.initialAnchor):r,a=pr(o?o.mounts.map(t).filter(d=>d!==null):[c]),u=o?a.find(d=>d.id===o.last_anchor)??a.find(d=>d.kind==="space")??r:c;return o?i.saved=Ga(a,u):n.initialAnchor&&await za(i,a,u),vt(i),i.ready=!0,Ja(a,u),a})().finally(()=>{i.loading=void 0}),i.loading)}function ds(e){let t=Tn;if(!t?.ready)return Promise.reject(new Error("Workspace mounts are not loaded"));let n=t.queue.then(async()=>{vt(t);let{refs:r,anchor:s}=e(t);await za(t,r,s),vt(t),Ja(r,s)});return t.queue=n.catch(()=>{}),n}function wi(e){return ds(t=>({refs:pr([...Te(),fr(t,e)]),anchor:ye()}))}function Ya(e){return ds(()=>{if(e===fe().id)throw new Error("The home account cannot be unmounted");let t=pr(Te().filter(r=>r.id!==e)),n=t.find(r=>r.id===ye()?.id)??t.find(r=>r.kind==="space")??fe();return{refs:t,anchor:n}})}function mr(e){return ds(t=>{let n=fr(t,e);return{refs:pr([...Te(),n]),anchor:n}})}function fs(e,t){return ds(n=>{let r=pr(e.map(i=>fr(n,i))),s=fr(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}})}function ps(e){if(typeof e.path!="string")return!1;let t=[...Te().map(n=>n.path),ye()?.path].filter(n=>!!n);return!t.length&&H()&&t.push(H()),t.some(n=>pe(e.path,n))}function Si(e,t,n,r){if(!["message","card"].includes(e?.item_type)||!pe(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&&pe(e.path,i)})}var Xa=new WeakMap;function Za(e,t,n){let r=Xa.get(e);r||(r=new Map,Xa.set(e,r));let s=JSON.stringify(t),i=r.get(s);if(!i){let c=!1,a,u=!1,d=!1,p=new Set,m=new Set,f=()=>e.getQueryData(t)??[],y=()=>{c||u||a||(a=setTimeout(()=>{a=void 0,g()},250))},g=async()=>{if(c)return;u=!0;let I=d;d=!1;let R=[...p],M=new Set(m);m.clear(),p.clear();try{if(I)await Ae(e,t,{exact:!0});else{let S=(await Promise.allSettled(R.map(async T=>{let F=e.getQueryCache().find({queryKey:t,exact:!0});if(!F)return;let k=await C("read",{id:T});if(k.success===!1)throw new Error("Channel refresh failed");if(c||!F||e.getQueryCache().find({queryKey:t,exact:!0})!==F)return;let A=_e(k.item??k);if(A.id!==T||A.item_type!=="channel")return;let U=f().find(B=>B.id===T);if(!U)return;let Q=n({...A}),ue={...U,path:Q.path,name:Q.name,displayName:Q.displayName,messageCount:Q.messageCount,aiMode:Q.aiMode,activeAgentIds:Q.activeAgentIds,isPrivate:Q.isPrivate,isDm:Q.isDm,autoPilot:Q.autoPilot,isArchived:Q.isArchived,updatedAt:Q.updatedAt};M.has(T)&&(U.name!==ue.name||U.displayName!==ue.displayName||U.path!==ue.path)&&(d=!0),e.setQueryData(t,B=>B?.map(qe=>qe.id===T?ue:qe))}))).find(T=>T.status==="rejected");if(S?.status==="rejected")throw S.reason}}catch(N){console.warn("[channels] refresh failed",N)}finally{u=!1,(d||p.size)&&y()}},h=I=>f().some(R=>R.id===I.item_id||R.path===I.path)?!0:ps(I),v=I=>{if(!h(I))return;let R=String(I.action??"").toLowerCase();if(["insert","delete","rename","move"].includes(R))d=!0;else if(R==="update"){let M=f().find(N=>N.id===I.item_id||N.path===I.path);M&&(p.add(M.id),m.add(M.id))}(d||p.size)&&y()},b=I=>{let R=f().find(M=>M.id===I.parent_id);R&&(p.add(R.id),y())},E=["vfs_change","ccm_change"].flatMap(I=>[ne(I,v,R=>R.item_type==="channel"),ne(I,b,R=>R.item_type==="message")]);i={users:0,stop:()=>{c=!0,a&&clearTimeout(a),E.forEach(I=>I())}},r.set(s,i)}i.users++;let o=!1;return()=>{o||(o=!0,--i.users===0&&(i.stop(),r.delete(s)))}}function Y(){return(0,_.useSyncExternalStore)(we,Z,Z)}function ic(){return Y(),Dr()}function oc(e){return Y(),V({queryKey:P.item(e),queryFn:()=>ar(e),enabled:!!e,staleTime:1/0})}function ac(e){return Y(),V({queryKey:P.itemById(e),queryFn:()=>Xr(e),enabled:!!e,staleTime:1/0})}function xi(e){return Y(),V({queryKey:P.children(e),queryFn:()=>cr(e),enabled:!!e})}function cc(e){let t=xi(e);return{...t,children:t.data??[]}}function uc(e,t=1){return Y(),V({queryKey:P.tree(e,t),queryFn:()=>ns(e,t),enabled:!!e})}function lc(e,t){return Y(),V({queryKey:P.search(e,t),queryFn:async()=>{let n={query:e};t?.length&&(n.item_types=t);let r=await C("search",n);return(r.content?.items||r.items||r.results||[]).map(_e)},enabled:!!e&&e.length>0})}function dc(e){Y();let t=(0,_.useMemo)(()=>e,[JSON.stringify(e)]);return V({queryKey:["vfs",H()??"__unscoped__","resolve",JSON.stringify(t??{})],queryFn:async()=>await C("resolve",t),enabled:!!t?.query&&t.query.length>0})}function fc(e){Y();let t=gt(e),n=(0,_.useMemo)(()=>t,[JSON.stringify(t)]),r=V({queryKey:P.items(n?.type??"",n),queryFn:({signal:s})=>xn(n,{signal:s,throwOnError:!0}),enabled:Rn(n),...n?.spaceIds!==void 0?{retry:(s,i)=>!gn(i)&&eu(s,i)}:{},select:s=>s.items});return n?.spaceIds!==void 0&&gn(r.error)?{...r,data:void 0}:r}function Ci(e,t={}){let n=Y(),{realtime:r=!1}=t,s=gt(e),i=s?.limit??20,o=(0,_.useMemo)(()=>s,[JSON.stringify(s)]),c=(0,_.useMemo)(()=>["vfs",H()??"__unscoped__","infinite-items",o?.type??"",JSON.stringify(o??{})],[n,o]),a=Jn({queryKey:c,queryFn:async({pageParam:p=0,signal:m})=>xn({...o,limit:i,offset:p},{throwOnError:!0,signal:m,priority:t.priority}),initialPageParam:0,getNextPageParam:(p,m,f)=>{if(!(o?.spaceIds!==void 0&&p.total_hint!==void 0&&f+p.items.length>=p.total_hint)&&!(p.items.length<i))return f+p.items.length},enabled:Rn(o),...o?.spaceIds!==void 0?{retry:(p,m)=>!gn(m)&&eu(p,m)}:{},staleTime:r?1/0:t.staleTime,meta:r&&o?{infiniteItemsRealtime:{filter:o}}:{}}),u=(0,_.useMemo)(()=>{if(o?.spaceIds!==void 0&&gn(a.error))return[];if(!a.data?.pages)return[];let p=new Set,m=[];for(let f of a.data.pages)for(let y of f.items)y.id&&!p.has(y.id)&&(p.add(y.id),m.push(y));return m},[a.data?.pages,a.error,o]),d=o?.spaceIds!==void 0&&gn(a.error);return{allItems:u,refetch:a.refetch,fetchNextPage:a.fetchNextPage,isFetchingNextPage:a.isFetchingNextPage,isExhausted:d||!a.hasNextPage,isLoading:a.isLoading,isFetching:a.isFetching,error:a.error,totalHint:d?void 0:a.data?.pages?.[0]?.total_hint}}function ec(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 jl(e,t){if(e.is_active===!1||e.item_type!==t.type||!pe(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 pc(e,t={}){let n=ec(e),r=Ci(e,n?{realtime:!1,staleTime:3e4}:{realtime:!0}),s=$(),i=JSON.stringify([H(),gt(e)]),[o,c]=(0,_.useState)(()=>({identity:i,upserts:{},deleted:new Set})),a=o.identity===i?o:{identity:i,upserts:{},deleted:new Set},u=(0,_.useMemo)(()=>{if(!n)return r.allItems;let f=Object.values(a.upserts),y=new Set(f.map(b=>b.id)),g=[...f,...r.allItems.filter(b=>!y.has(b.id))].filter(b=>!a.deleted.has(b.path)),h=e.sort_by??"updated_at",v=e.sort_dir==="asc"?1:-1;return g.sort((b,E)=>v*String(b[h]??"").localeCompare(String(E[h]??"")))},[n,r.allItems,a,e?.sort_by,e?.sort_dir]),d=(0,_.useRef)(u);d.current=u;let p=(0,_.useRef)(t.shouldReadUpdate);p.current=t.shouldReadUpdate;let m=(0,_.useRef)(r.refetch);return m.current=r.refetch,(0,_.useEffect)(()=>{if(!ec(e))return;let f=e,y=!1,g=!1,h=!1,v=0,b=new Map,E=()=>{let S=v;m.current().then(T=>{!y&&!T.isError&&v===S&&c({identity:i,upserts:{},deleted:new Set})})},I=S=>{v++,c(F=>{let k=F.identity===i?F:{identity:i,upserts:{},deleted:new Set},A={...k.upserts};return delete A[S],{identity:i,upserts:A,deleted:new Set(k.deleted).add(S)}});let T=b.get("__reconcile__");T&&clearTimeout(T),b.set("__reconcile__",setTimeout(()=>{b.delete("__reconcile__"),E()},250))},R=S=>{let T=b.get(S);T&&clearTimeout(T),b.set(S,setTimeout(()=>{b.delete(S),s.fetchQuery({queryKey:P.item(S),queryFn:()=>ar(S),staleTime:0}).then(F=>{if(!y){if(!F||!jl(F,f)){let k=d.current.find(A=>A.path===S||A.id===F?.id);k&&I(k.path);return}c(k=>{let A=k.identity===i?k:{identity:i,upserts:{},deleted:new Set},U=new Set(A.deleted);return U.delete(S),{identity:i,upserts:{...A.upserts,[S]:F},deleted:U}})}}).catch(F=>console.warn("[useIncrementalItems] item read failed:",F))},250))},M=ne("vfs_change",S=>{if(!S||typeof S.path!="string"&&typeof S.old_path!="string")return;let T=typeof S.path=="string"?S.path:S.old_path,F=d.current.find(A=>A.path===T||A.path===S.old_path||S.item_id&&A.id===S.item_id),k=!!F;if(!(!pe(T,f.scope)&&!pe(S.old_path,f.scope)&&!k)&&!(S.item_type&&S.item_type!==f.type&&!k)&&!(f.parent_id&&S.parent_id&&S.parent_id!==f.parent_id&&!k)){if(F&&(T!==F.path||S.old_path&&S.old_path!==T||S.parent_id&&S.parent_id!==F.parent_id||S.item_type&&S.item_type!==f.type)){I(F.path);return}if(!F&&S.old_path&&S.old_path!==T&&pe(T,f.scope)){v++,R(T);return}if(S.action==="insert")v++,R(T);else if(S.action==="move")v++,R(T);else if(S.action==="update"){if(!p.current?.(S,d.current))return;v++,R(T)}else S.action==="delete"&&I(F?.path??S.old_path??T)}}),N=Jr(S=>{if(S!=="connected"){g&&(h=!0);return}g=!0,h&&(h=!1,E())});return()=>{y=!0,M(),N(),b.forEach(clearTimeout)}},[s,i]),{...r,allItems:u}}function mc(e){Y();let t=20,n=Jn({queryKey:["vfs",H()??"__unscoped__","infinite-children",e??""],queryFn:async({pageParam:s=0})=>Zr(e,t,s),initialPageParam:0,getNextPageParam:(s,i,o)=>{if(!(s.items.length<t))return o+s.items.length},enabled:!!e});return{allItems:(0,_.useMemo)(()=>{if(!n.data?.pages)return[];let s=new Set,i=[];for(let o of n.data.pages)for(let c of o.items)c.id&&!s.has(c.id)&&(s.add(c.id),i.push(c));return i},[n.data?.pages]),fetchNextPage:n.fetchNextPage,isFetchingNextPage:n.isFetchingNextPage,isExhausted:!n.hasNextPage,isLoading:n.isLoading,isFetching:n.isFetching,error:n.error,totalHint:n.data?.pages?.[0]?.total_hint}}function hc(e){return Y(),V({queryKey:P.edges(e),queryFn:()=>ts(e),enabled:!!e})}function ms(e){return Y(),V({queryKey:P.types(e),queryFn:()=>es(e)})}function gc(e,t){let n=ms(t);return{...n,data:n.data?.get(e)??void 0}}function yc(e,t){Y();let n=(0,_.useMemo)(()=>t?.arguments,[JSON.stringify(t?.arguments)]),r=t?.mode,s=t?.strategy,i=t?.width;return V({queryKey:[...P.openEnvelope(e,s),i],queryFn:async()=>{let o=await os(e,{mode:r,strategy:s,arguments:n});if(i&&o.render?.props?.url){let c=o.render.props.url,a=c.includes("?")?"&":"?";o.render.props.url=`${c}${a}w=${i}`}return o},enabled:!!e})}var tc={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=ms(e),n=t.data??new Map;return(0,_.useMemo)(()=>({canHaveChildren:f=>n.get(f.item_type)?.is_container??!1,isScope:f=>n.get(f.item_type)?.is_scope??!1,isScopeType:f=>n.get(f)?.is_scope??!1,isContainerType:f=>n.get(f)?.is_container??!1,getTypeDefinition:f=>n.get(f),getTypeColor:f=>n.get(f)?.color??"gray",getTypeIcon:f=>n.get(f)?.icon??"File",getTypeDisplayName:f=>n.get(f)?.display_name??f,getKnownEdgeTypes:()=>Object.entries(tc).map(([f,y])=>({key:f,label:y})),getEdgeTypeLabel:f=>tc[f]??f.replace(/_/g," "),allTypes:n,loading:t.isLoading}),[n,t.isLoading])}function vc(e,t,n){return Y(),V({queryKey:P.memberFocus(e),queryFn:()=>is(e,t,n),enabled:!!e})}function bc(e,t={}){let{limit:n=50,offset:r=0,include_snapshots:s=!1}=t;return V({queryKey:P.itemVersions(e,String(n),String(r),String(s)),queryFn:()=>ur(e,{limit:n,offset:r,include_snapshots:s}),enabled:!!e})}function wc(e,t=50,n=0){return V({queryKey:P.itemHistory(e,String(t),String(n)),queryFn:()=>ss(e,t,n),enabled:!!e})}function Sc(e,t=50,n=0){return Y(),V({queryKey:P.recentActivity(e,String(t),String(n)),queryFn:()=>rs(e,t,n),enabled:!!e})}function Rc(){let[e,t]=(0,_.useState)(null),[n,r]=(0,_.useState)(!0),[s,i]=(0,_.useState)(null);return(0,_.useEffect)(()=>{let o=!1;return Xe().then(c=>{if(!o){let a=typeof window<"u"&&window.__FSAOS_CONFIG__||{};t({path:c.scope_path,scope_id:c.scope_id,fractal_id:c.fractal_id,instance_name:c.instance_name,display_name:c.display_name,componentPath:a.componentPath||"",isEmbed:!!a.embedToken}),r(!1)}}).catch(c=>{o||(i(c instanceof Error?c:new Error(String(c))),r(!1))}),()=>{o=!0}},[]),{data:e,loading:n,error:s}}var Vl=[];function nc(){if(typeof window>"u")return!1;let e=window.__FSAOS_CONFIG__?.embedToken;return typeof e=="function"||typeof e=="string"&&e.length>0}function $l(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 xc(){let{user:e}=hs(),t=(0,_.useSyncExternalStore)(Wo,ai,ai),n=ht()?.principal_id??null,r=(0,_.useRef)(null),[s,i]=(0,_.useState)(null),[o,c]=(0,_.useState)(null);(0,_.useEffect)(()=>{if(n){c(null);return}if(!e?.id&&!nc()){c(null);return}let b=!1;return Xe().then(E=>{b||E.principal_id||c(new Error("Memberships require an authenticated principal"))}).catch(E=>{b||c(E instanceof Error?E:new Error(String(E)))}),()=>{b=!0}},[n,e?.id,t]);let a=V({queryKey:P.memberships(n??"anonymous"),queryFn:cs,enabled:!!n,staleTime:1e3*60*2}),u=a.data??Vl,d=(0,_.useMemo)(()=>u.filter(b=>b.isAccount!==!1&&!b.isSpace),[u]),p=(0,_.useMemo)(()=>{let b=new Set(d.map(I=>I.accountId)),E=I=>!I.subordinateTo||!b.has(I.subordinateTo);return[...d].sort((I,R)=>Number(E(R))-Number(E(I)))},[d]),m=(0,_.useSyncExternalStore)(we,Z,Z),f=(0,_.useMemo)(()=>{let b=ye();return b?u.find(E=>E.accountId===b.id)??null:null},[m,u]),y=(0,_.useMemo)(()=>$l(d),[d]);(0,_.useEffect)(()=>{if(!n){r.current=null;return}if(r.current!==n)if(i(null),p.length===1){let b=p[0];fe()||Mt(Ve(b)),Qt(b.accountId),b.personalSpacePath&&Dt(b.personalSpacePath,E=>{let I=u.find(R=>R.accountId===E);return I?Ve(I):null}).catch(i),r.current=n}else p.length>1&&(r.current=n)},[n,p,u]);let g=(0,_.useCallback)(async b=>{let E=u.find(M=>M.path===b);if(!E)throw new Error("Account membership is unavailable");let I=Ve(E);fe()||Mt(I);let R=u.find(M=>M.accountId===fe()?.id);if(!R?.personalSpacePath)throw new Error("The home membership has no mount declaration location");await Dt(R.personalSpacePath,M=>{let N=u.find(S=>S.accountId===M);return N?Ve(N):null}),await mr(I),i(null),Qt(E.accountId)},[u]),h=(0,_.useCallback)(async b=>{let E=u.find(I=>I.path===b);if(!E)throw new Error("Scope membership is unavailable");await wi(Ve(E))},[u]),v=(!!e?.id||nc())&&!n&&!o;return{accounts:p,switcherAccounts:y,allMemberships:u,currentAccount:f,mountedScope:null,switchAccount:g,mountScope:h,loading:v||a.isLoading,error:o??a.error??s}}function Cc(){Y();let e=(0,_.useSyncExternalStore)(Qr,tr,tr),t=(0,_.useMemo)(()=>Te(),[e]),n=ye(),r=(0,_.useMemo)(()=>t.filter(i=>i.kind==="space"&&(n?.kind==="account"||i.id===n?.id)),[t,n]),s=(0,_.useMemo)(()=>r.map(i=>i.id).sort(),[r]);return{mounts:t,selectedSpaces:r,readSpaceIds:s,homeAnchor:fe(),anchor:n,setAnchor:mr,replaceMounts:fs,mount:wi,unmount:Ya}}function hs(){let[e,t]=(0,_.useState)(null),[n,r]=(0,_.useState)(null),[s,i]=(0,_.useState)(!0),o=(0,_.useRef)(null);(0,_.useEffect)(()=>{W.auth.getSession().then(({data:f,error:y})=>{if(y){console.warn("[useAuth] getSession error, clearing stale session:",y.message),W.auth.signOut().catch(()=>{}),r(null),t(null),i(!1);return}r(f?.session??null),t(f?.session?.user??null),i(!1)}).catch(f=>{console.warn("[useAuth] getSession threw, clearing stale session:",f?.message),W.auth.signOut().catch(()=>{}),r(null),t(null),i(!1)});let{data:{subscription:m}}=W.auth.onAuthStateChange((f,y)=>{if(f==="TOKEN_REFRESHED"&&!y){console.warn("[useAuth] TOKEN_REFRESHED with null session \u2014 signing out"),W.auth.signOut().catch(()=>{}),r(null),t(null),i(!1);return}r(y),t(y?.user??null),i(!1)});return o.current=m,()=>{m?.unsubscribe()}},[]);let c=(0,_.useCallback)(async m=>m.provider?W.auth.signInWithOAuth({provider:m.provider,options:m.redirectTo?{redirectTo:m.redirectTo}:{redirectTo:window.location.href}}):W.auth.signInWithPassword({email:m.email,password:m.password}),[]),a=(0,_.useCallback)(async m=>W.auth.signUp({email:m.email,password:m.password,options:{data:m.metadata||{}}}),[]),u=(0,_.useCallback)(async()=>{await W.auth.signOut(),mn(),O().clear()},[]),d=(0,_.useCallback)(async m=>{let{error:f}=await W.auth.resetPasswordForEmail(m);if(f)throw f},[]),p=(0,_.useCallback)(async(m,f)=>{let{error:y}=await W.auth.signInWithOtp({email:m,options:f?{emailRedirectTo:f}:{emailRedirectTo:window.location.href}});if(y)throw y},[]);return{user:e,session:n,loading:s,signIn:c,signUp:a,signOut:u,resetPassword:d,signInWithMagicLink:p}}function Pc(e){let[t,n]=(0,_.useState)(null),[r,s]=(0,_.useState)(!1),[i,o]=(0,_.useState)(null);return(0,_.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),C("resolve-asset",{asset_id:e}).then(a=>{a.success&&a.public_url?n({url:a.public_url,id:a.asset_id,name:a.name,mimeType:a.mime_type,width:a.width,height:a.height,sizeBytes:a.size_bytes}):o(new Error(a.error||"Asset not found")),s(!1)}).catch(a=>{o(a instanceof Error?a:new Error(String(a))),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 hr={},rc={};te(()=>{for(let e of Object.keys(hr))delete hr[e]});var Tc=null;function Ec(e){Tc=e,typeof window<"u"&&!window.__FSAOS_GATEWAY__&&(window.__FSAOS_GATEWAY__=e)}function Wl(e){switch(e){case"react":return typeof window<"u"&&window.React||_.default;case"react-dom":case"react-dom/client":return typeof window<"u"&&window.ReactDOM||Kl;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}:Ll;case"@fsaos/gateway":case"@fsaos/react":return typeof window<"u"&&window.__FSAOS_GATEWAY__||Tc||{};case"@fsaos/ui":return typeof window<"u"&&window.__FSAOS_UI__||{};case"@fsaos/theme":return{};default:return console.warn(`[useComponent] Unknown module requested: ${e}`),{}}}function Bl(e,t){return e.replace(/^(\s*)(:root|body)(\s*[{,])/gm,(n,r,s,i)=>`${r}.${t}${i}`)}async function Hl(e,t){if(!rc[e])try{let n=await fetch(e);if(!n.ok)return;let r=await n.text();if(!r.trim()||r.includes("No CSS bundle for this component"))return;t&&!r.includes(`.fsaos-c-${t}`)&&(r=Bl(r,`fsaos-c-${t}`));let s=document.createElement("style");s.setAttribute("data-fsaos-component-css",e),t&&s.setAttribute("data-fsaos-component-id",t),s.textContent=r,document.head.appendChild(s),rc[e]=s}catch{}}function Gl(e){let t=null,n=window.__FSAOS_REGISTER__;window.__FSAOS_REGISTER__=r=>{t=r};try{let r=["var require = arguments[0];",e,"return window.__FSAOS_COMPONENT__;"].join(`
|
|
3
|
-
`),i=new Function(r)(Wl),o=t??i;return o?o.default||o:null}finally{n!==void 0?window.__FSAOS_REGISTER__=n:delete window.__FSAOS_REGISTER__}}function Pi(e){let[t,n]=(0,_.useState)(null),[r,s]=(0,_.useState)(!0),[i,o]=(0,_.useState)(null);return(0,_.useEffect)(()=>{if(!e)return;let c=!1;s(!0),o(null);let u=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"";return(async()=>{try{let d=1,p=e+"@v1",m=u+e+"/__bundle.js";try{let v=await fetch(u+e+"/__meta",{cache:"no-store"});v.ok&&(d=(await v.json()).version||1,p=e+"@v"+d,m=u+e+"/__bundle.v"+d+".js")}catch{m=u+e+"/__bundle.js?v="+Date.now()}if(c)return;if(hr[p]){n(()=>hr[p]),s(!1);return}let f=await fetch(m);if(!f.ok)throw new Error(`Failed to fetch bundle: ${f.status} ${f.statusText} (${m})`);let y=await f.text();if(c)return;let g=m.replace(/__bundle(\.v\d+)?\.js(\?.*)?$/,"__bundle$1.css");Hl(g).catch(()=>{});let h=Gl(y);if(!h)throw new Error("Bundle did not export a component. Expected window.__FSAOS_COMPONENT__ (FSAOS build) or a __FSAOS_REGISTER__(Component) call.");if(typeof h!="function")throw new Error(`Bundle export is not a React component (got ${typeof h})`);hr[p]=h,c||(n(()=>h),s(!1))}catch(d){c||(o(d instanceof Error?d:new Error(String(d))),s(!1))}})(),()=>{c=!0}},[e]),{Component:t,loading:r,error:i}}var zl=["--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 Ic(){return{data:(0,_.useMemo)(()=>{if(typeof document>"u")return{tokens:{}};let t={},n=getComputedStyle(document.documentElement);return zl.forEach(r=>{t[r]=n.getPropertyValue(r).trim()}),{tokens:t}},[]),loading:!1,error:null}}function Ac(e,t){return{data:{allowed:!0},loading:!1,error:null}}function kc(e,t){let n={};return(t||[]).forEach(r=>{n[r]=!0}),{data:n,loading:!1,error:null}}var ce=null,En=null,Ri=new Set;function Jl(){Ri.forEach(e=>e())}te(()=>{ce=null,En=null});async function Mc(e){let t={principalId:null,displayName:null,createdAt:null,metadata:null,vfsPath:null},n=ht()?.principal_id??null;if(n){if(ce&&ce.principalId===n){let{principalId:s,displayName:i,createdAt:o,metadata:c,vfsPath:a}=ce;return{principalId:s,displayName:i,createdAt:o,metadata:c,vfsPath:a}}return{...t,principalId:n}}let r=e;if(!r){let{data:s}=await W.auth.getSession();r=s?.session?.user?.id}if(!r)return t;if(ce&&ce.authUserId===r){let{principalId:s,displayName:i,createdAt:o,metadata:c,vfsPath:a}=ce;return{principalId:s,displayName:i,createdAt:o,metadata:c,vfsPath:a}}return En||(En=(async()=>{try{let{data:s,error:i}=await W.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,c=null;if(o){let{data:u}=await W.from("os_items").select("path").eq("owner_principal_id",o).eq("item_type","principal").eq("is_active",!0).like("path","/root/principals/%"),d=(u??[]).map(p=>p.path);c=d.find(p=>p.split("/").length===4)??d[0]??null}let a={principalId:o,displayName:s?.display_name??null,createdAt:s?.created_at??null,metadata:s?.metadata??null,vfsPath:c};return ce={authUserId:r,...a},a}finally{En=null}})(),En)}async function Oc(e){return(await Mc(e)).principalId}function Fc(){let e=hs(),t=e.user,n=ce?.authUserId===t?.id?ce:null,[r,s]=(0,_.useState)(n),i=(0,_.useRef)(null);return(0,_.useEffect)(()=>{let o=()=>{let c=ce;c&&c.authUserId===t?.id&&s({principalId:c.principalId,displayName:c.displayName,createdAt:c.createdAt,metadata:c.metadata,vfsPath:c.vfsPath})};return Ri.add(o),()=>{Ri.delete(o)}},[t?.id]),(0,_.useEffect)(()=>{if(!t?.id){s(null),i.current=null;return}i.current===t.id&&r?.principalId!=null||(i.current=t.id,Mc(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 qc(){return{data:null,loading:!1,error:null}}function Qc(e){let{path:t,...n}=e,r=Pi(t),s=r.Component,{loading:i,error:o}=r;return i?(0,_.createElement)("div",{className:"fsaos-loading"},""):o?(0,_.createElement)("div",{className:"fsaos-error"},"Failed to load component"):s?(0,_.createElement)(s,n):null}function Dc(e){return e.children}function Uc(e){let t=Y(),{channelPath:n,parentMessageId:r,realtime:s=!0,enabled:i}=e,o=i!==void 0?i&&!!n:!!n,c=(0,_.useMemo)(()=>P.channelMessages(n??"",r),[n,r,t]),a=$(),u=(0,_.useRef)(null),d=V({queryKey:c,queryFn:()=>as(n,r),enabled:o});(0,_.useEffect)(()=>{if(!s||!o)return;let g=ne("vfs_change",()=>{u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{Ae(a,c,{exact:!0})},500)},h=>{let v=a.getQueryData(c);return Si(h,n,r,[...v?.messages??[],...v?.activityMessages??[]])});return()=>{g(),u.current&&clearTimeout(u.current)}},[s,o,n,r,c,a]);let p=d.data,m=p?.messages??[],f=p?.messageCards??new Map,y=p?.siblingCards??[];return{messages:m,activityMessages:p?.activityMessages??[],messageCards:f,siblingCards:y,threads:(0,_.useMemo)(()=>m.filter(g=>g.reply_count>0),[m]),isLoading:d.isLoading,isFetching:d.isFetching,error:d.error,refetch:d.refetch}}function Nc(e){Y();let{channelPath:t,parentMessageId:n,limit:r=50,realtime:s=!0,enabled:i=!0}=e,o=!!n,c=i&&!!t,a=Jn({queryKey:[...P.channelMessages(t||"",n),"infinite",r],queryFn:async({pageParam:g})=>lr(t,{parentMessageId:n,limit:r,before_seq:o?void 0:g,after_seq:o?g:void 0}),initialPageParam:void 0,getNextPageParam:g=>!o||g.messages.length<r?void 0:g.messages[g.messages.length-1]?.seq,getPreviousPageParam:g=>o||g.messages.length<r?void 0:g.messages[0]?.seq,enabled:c}),u=(0,_.useMemo)(()=>{if(!a.data?.pages)return[];let g=new Set,h=[];for(let v of a.data.pages)for(let b of v.messages)g.has(b.id)||(g.add(b.id),h.push(b));return h.sort((v,b)=>v.seq-b.seq)},[a.data?.pages]),{messageCards:d,siblingCards:p}=(0,_.useMemo)(()=>{let g=new Map,h=[];if(!a.data?.pages)return{messageCards:g,siblingCards:h};let v=new Set;for(let b of a.data.pages){for(let[E,I]of b.messageCards)for(let R of I){if(v.has(R.id))continue;v.add(R.id);let M=g.get(E)||[];M.push(R),g.set(E,M)}for(let E of b.siblingCards)v.has(E.id)||(v.add(E.id),h.push(E))}return{messageCards:g,siblingCards:h}},[a.data?.pages]),m=$(),f=(0,_.useRef)(null),y=(0,_.useMemo)(()=>[...P.channelMessages(t||"",n),"infinite",r],[t,n,r]);return(0,_.useEffect)(()=>{if(!s||!t||!c)return;let g=()=>void Ae(m,y,{exact:!0}),h=!1,v=!1,b=!1,E=async()=>{let M=m.getQueryData(y);if(!M?.pages?.length){g();return}let N=0;for(let S of M.pages)for(let T of S.messages)T.seq>N&&(N=T.seq);if(N===0){g();return}try{let S=await lr(t,{parentMessageId:n,limit:r,after_seq:N});if(S.messages.length===0&&S.siblingCards.length===0){g();return}if(S.messages.length>0){let T=Math.min(...S.messages.map(F=>F.seq));if(T>N+1){console.warn(`[useInfiniteChannelMessages] sequence gap detected: maxSeq=${N}, minNewSeq=${T}. Triggering full refetch.`),g();return}}m.setQueryData(y,T=>{if(!T)return T;let F=[...T.pages],k=F.length-1,A=F[k],U=new Set(A.messages.map(Re=>Re.id)),Q=S.messages.filter(Re=>!U.has(Re.id)),ue=[...A.messages,...Q].sort((Re,xs)=>Re.seq-xs.seq),B=new Map(A.messageCards);for(let[Re,xs]of S.messageCards){let Ni=B.get(Re)||[],Hu=new Set(Ni.map(Cs=>Cs.id)),Gu=xs.filter(Cs=>!Hu.has(Cs.id));B.set(Re,[...Ni,...Gu])}let qe=new Set(A.siblingCards.map(Re=>Re.id)),Wu=S.siblingCards.filter(Re=>!qe.has(Re.id)),Bu=[...A.siblingCards,...Wu];return F[k]={...A,activityMessages:S.activityMessages??[],messages:ue,messageCards:B,siblingCards:Bu},{...T,pages:F}})}catch(S){console.warn("[useInfiniteChannelMessages] live tail fetch failed, falling back to full invalidation:",S),g()}},I=async()=>{if(h){v=!0;return}h=!0;try{do v=!1,await E();while(v&&!b)}finally{h=!1}},R=ne("vfs_change",()=>{f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{I()},500)},M=>Si(M,t,n,m.getQueryData(y)?.pages.flatMap(N=>N.messages)??[]));return()=>{b=!0,R(),f.current&&clearTimeout(f.current)}},[s,t,c,y,m,n,r]),{messages:u,activityMessages:a.data?.pages.at(-1)?.activityMessages??[],messageCards:d,siblingCards:p,threads:u.filter(g=>g.reply_count>0),isLoading:a.isLoading,isFetching:a.isFetching,error:a.error,refetch:a.refetch,hasPreviousPage:a.hasPreviousPage??!1,fetchPreviousPage:a.fetchPreviousPage,isFetchingPreviousPage:a.isFetchingPreviousPage??!1,hasNextPage:a.hasNextPage??!1,fetchNextPage:a.fetchNextPage,isFetchingNextPage:a.isFetchingNextPage??!1}}var Kc=["open","active","strict","hand_raise"];function Yl(e){return e==="open"||e==="active"||e==="strict"||e==="hand_raise"?e:e==="on"||e==="auto"?"active":"strict"}function Xl(e){if(Array.isArray(e))return e.filter(t=>typeof t=="string")}function sc(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:Yl(t.ai_mode),activeAgentIds:Xl(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 gs(e={}){let t=Y(),{realtime:n=!0,enabled:r=!0,includeArchived:s=!1}=e,i=$(),o=(0,_.useMemo)(()=>P.channels("all"),[t]),c=V({queryKey:o,queryFn:async()=>((await C("query",{item_type:"channel",include_reader:!0,limit:500})).items||[]).map(sc),enabled:r});return(0,_.useEffect)(()=>{if(!(!n||!r))return Za(i,o,sc)},[n,r,o,i]),{channels:(0,_.useMemo)(()=>(c.data??[]).filter(u=>s||!u.isArchived),[c.data,s]),isLoading:c.isLoading,isFetching:c.isFetching,error:c.error,refetch:c.refetch}}function Lc(e={}){let t=gs(e),n=(0,_.useMemo)(()=>t.channels.filter(r=>!r.isDm),[t.channels]);return{...t,channels:n}}function jc(e={}){let t=gs(e),n=(0,_.useMemo)(()=>t.channels.filter(r=>r.isDm),[t.channels]);return{...t,channels:n}}function Ti(e={}){let t=Y(),{filter:n="all",limit:r=200,realtime:s=!0,enabled:i=!0}=e,o=$(),c=(0,_.useRef)(null),a=(0,_.useMemo)(()=>P.notifications(n,r),[n,r,t]),u=V({queryKey:a,queryFn:async()=>{let p={limit:r};return n==="unread"&&(p.filter="unread"),(await C("get-notifications",p)).notifications||[]},enabled:i});return(0,_.useEffect)(()=>{if(!s||!i)return;let p=["vfs_change","ccm_change"].map(m=>ne(m,()=>{c.current&&clearTimeout(c.current),c.current=setTimeout(()=>{o.invalidateQueries({queryKey:a})},2e3)},f=>f.item_type==="notification"&&ps(f)));return()=>{p.forEach(m=>m()),c.current&&clearTimeout(c.current)}},[s,i,a,o]),{notifications:u.data??[],isLoading:u.isLoading,isFetching:u.isFetching,error:u.error,refetch:u.refetch}}function Vc(e={}){let{channels:t,realtime:n=!0,enabled:r=!0}=e,{notifications:s,isLoading:i,isFetching:o,error:c,refetch:a}=Ti({filter:"unread",limit:200,realtime:n,enabled:r}),u=(0,_.useMemo)(()=>{let f=new Map;for(let y of s)y.is_unread&&y.channel_id&&f.set(y.channel_id,(f.get(y.channel_id)||0)+1);return f},[s]),d=(0,_.useMemo)(()=>{let f=0;return u.forEach(y=>{f+=y}),f},[u]),{dmUnread:p,channelUnread:m}=(0,_.useMemo)(()=>{if(!t)return{dmUnread:0,channelUnread:0};let f=new Set(t.filter(h=>h.isDm).map(h=>h.id)),y=0,g=0;return u.forEach((h,v)=>{f.has(v)?y+=h:g+=h}),{dmUnread:y,channelUnread:g}},[t,u]);return{unreadByChannel:u,totalUnread:d,dmUnread:p,channelUnread:m,isLoading:i,isFetching:o,error:c,refetch:a}}function $c(){let e=$();return de({mutationFn:t=>C("create",t),onSuccess:(t,n)=>{let r=n.parent_path;r&&e.invalidateQueries({queryKey:P.children(r)})}})}function Wc(){let e=$();return de({mutationFn:t=>C("update",t),onSuccess:(t,n)=>{let r=n.path;if(r){e.invalidateQueries({queryKey:P.item(r)});let s=r.split("/");s.pop();let i=s.join("/");i&&e.invalidateQueries({queryKey:P.children(i)})}}})}function Bc(){return de({mutationFn:e=>C("update-principal",e),onSuccess:(e,t)=>{if(!ce)return;let n=e&&typeof e=="object"&&e.metadata?e.metadata:{...ce.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}:{}};ce={...ce,displayName:typeof t.display_name=="string"?t.display_name:ce.displayName,metadata:n},Jl()}})}function Hc(){let e=$();return de({mutationFn:t=>C("delete",t),onSuccess:(t,n)=>{let r=n.path;if(r){e.removeQueries({queryKey:P.item(r)});let s=r.split("/");s.pop();let i=s.join("/");i&&e.invalidateQueries({queryKey:P.children(i)})}}})}function Gc(){let e=$();return de({mutationFn:t=>C("move",t),onSuccess:(t,n)=>{let r=n.path,s=n.new_parent_path;if(r){e.invalidateQueries({queryKey:P.item(r)});let i=r.split("/");i.pop();let o=i.join("/");o&&e.invalidateQueries({queryKey:P.children(o)})}s&&e.invalidateQueries({queryKey:P.children(s)})}})}function zc(){let e=$();return de({mutationFn:t=>C("link",t),onSuccess:(t,n)=>{let r=n.source_id,s=n.target_id;r&&e.invalidateQueries({queryKey:P.edges(r)}),s&&e.invalidateQueries({queryKey:P.edges(s)})}})}function Jc(e,t){let n=$(),{optimistic:r,...s}=t??{};return de({mutationFn:i=>C(e,i),onMutate:r?async i=>{await n.cancelQueries({queryKey:r.queryKey});let o=n.getQueryData(r.queryKey);return n.setQueryData(r.queryKey,c=>r.update(c,i)),{previous:o}}:void 0,onError:(i,o,c)=>{r&&c?.previous!==void 0&&n.setQueryData(r.queryKey,c.previous),s.onError?.(i)},onSuccess:s.onSuccess,onSettled:r?()=>{n.invalidateQueries({queryKey:r.queryKey})}:void 0})}function Yc(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 c=(0,_.useRef)(s),a=(0,_.useRef)(i);(0,_.useEffect)(()=>{c.current=s,a.current=i},[s,i]),(0,_.useEffect)(()=>o?ne(r,d=>c.current(d),a.current?d=>a.current(d):void 0):void 0,[r,o])}function Xc(e){let{queryKey:t,queryFn:n,eventType:r,filter:s,enabled:i=!0,debounceMs:o=500}=e,c=$(),a=(0,_.useRef)(s);a.current=s;let u=(0,_.useRef)(null),d=V({queryKey:t,queryFn:n,enabled:i});return(0,_.useEffect)(()=>{if(!i)return;let p=ne(r,()=>{u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{Ae(c,t,{exact:!0})},o)},m=>a.current?.(m)??!0);return()=>{p(),u.current&&clearTimeout(u.current)}},[r,i,o,c,JSON.stringify(t)]),d}function In(e){Y();let t=H(),n=(0,_.useMemo)(()=>e?typeof e=="string"?{path:e}:e:null,[typeof e=="string"?e:JSON.stringify(e)]),r=!!t&&!!n&&!!(n.key||n.path||n.item_id),s=n?.key??n?.path??n?.item_id??"",i=["vfs",t??"__unscoped__","arrangement",s,n?.scope_id??""],o=V({queryKey:i,staleTime:1/0,retry:!1,meta:{arrangementRealtime:!0},queryFn:async()=>{if(!n)return null;let m=await C("resolve-arrangement",{...n,_scope_path:t});if(m?.success===!1)throw new Error(m?.error||"Arrangement could not be loaded");return m??null},enabled:r}),c=o.data??null,a=(0,_.useMemo)(()=>c?.resolved_children??[],[c]),u=c?.resolution_level??null,d=(0,_.useMemo)(()=>{let f=(c?.type_data??null)?.order;return Array.isArray(f)?f:null},[c]),p=(0,_.useCallback)(m=>{if(!d||!m?.length)return m??[];let f=v=>v.id??v.name??"",y=new Map(d.map((v,b)=>[v,b])),g=[],h=[];for(let v of m)(y.has(f(v))?g:h).push(v);return g.sort((v,b)=>y.get(f(v))-y.get(f(b))),[...g,...h]},[d]);return{...o,arrangement:c,resolvedChildren:a,resolutionLevel:u,order:d,sourceScopeId:c?.scope_item_id??null,arrangementQueryKey:i,applyTo:p}}function Zc(e){let{origin:t,originField:n,fallbackUrl:r,mintError:s,scopeId:i,scopePath:o}=e,c=Y(),a=ht(),u=i??a?.scope_id??null,d=(0,_.useMemo)(()=>{if(!t)return null;let R="/accounts/",M=t.indexOf(R);if(M===-1)return null;let N=t.indexOf("/",M+R.length);return N===-1?t:t.slice(0,N)},[t]),p=o??d??a?.scope_path??null,m=n?.trim()||null,f=`${c}
|
|
1
|
+
/* @fsaos/gateway v2.0.0 — Unified FSAOS Edge Runtime — 2026-10-30T16:20:52.029Z */
|
|
2
|
+
"use strict";var __FSAOS_GATEWAY__=(()=>{var zu=Object.create;var Fn=Object.defineProperty;var Ju=Object.getOwnPropertyDescriptor;var Yu=Object.getOwnPropertyNames;var Xu=Object.getPrototypeOf,Zu=Object.prototype.hasOwnProperty;var Ki=e=>{throw TypeError(e)};var el=(e,t,n)=>t in e?Fn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var qn=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),tl=(e,t)=>{for(var n in t)Fn(e,n,{get:t[n],enumerable:!0})},Li=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Yu(t))!Zu.call(e,s)&&s!==n&&Fn(e,s,{get:()=>t[s],enumerable:!(r=Ju(t,s))||r.enumerable});return e};var X=(e,t,n)=>(n=e!=null?zu(Xu(e)):{},Li(t||!e||!e.__esModule?Fn(n,"default",{value:e,enumerable:!0}):n,e)),nl=e=>Li(Fn({},"__esModule",{value:!0}),e);var ee=(e,t,n)=>el(e,typeof t!="symbol"?t+"":t,n),Ps=(e,t,n)=>t.has(e)||Ki("Cannot "+n);var l=(e,t,n)=>(Ps(e,t,"read from private field"),n?n.call(e):t.get(e)),x=(e,t,n)=>t.has(e)?Ki("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),w=(e,t,n,r)=>(Ps(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n),q=(e,t,n)=>(Ps(e,t,"access private method"),n);var Qn=(e,t,n,r)=>({set _(s){w(e,t,s,n)},get _(){return l(e,t,r)}});var oe=qn((wd,ji)=>{ji.exports=React});var Ir=qn((vp,Ro)=>{Ro.exports={jsx:React.createElement,jsxs:React.createElement,Fragment:React.Fragment}});var Qo=qn((Jp,qo)=>{qo.exports={createClient:window.supabase.createClient}});var la=qn((um,ua)=>{ua.exports=ReactDOM});var yu=qn((rg,gu)=>{gu.exports=ReactDOM});var Ui={};tl(Ui,{CHANNEL_AI_MODES:()=>Kc,ComponentRenderer:()=>Qc,EnforcementDeniedError:()=>rt,FormSubmissionError:()=>On,GatewayRequestError:()=>Ie,InteractionTrackingError:()=>kn,KernelProvider:()=>Dc,QueryClientProvider:()=>Gn,assignPersonalSection:()=>ju,auth:()=>Tu,awaitAnchorReady:()=>er,awaitScopeReady:()=>Go,callTool:()=>xu,cancelQueuedTurn:()=>mu,cancelTurn:()=>fu,clearCachedToken:()=>ei,clearSession:()=>ci,configureGatewayReads:()=>sa,createItem:()=>wu,disconnectSSE:()=>_i,disposeVfsRealtimeWs:()=>bi,electHomeAnchor:()=>Mt,emitEvent:()=>Aa,fetchChannelMessages:()=>Ka,fetchChannelMessagesPage:()=>lr,fetchChannelMessagesWithCards:()=>as,fetchEdgesForItem:()=>ts,fetchItemHistory:()=>ss,fetchItemVersions:()=>ur,fetchItems:()=>xn,fetchMemberFocus:()=>is,fetchOpenEnvelope:()=>os,fetchRecentActivity:()=>rs,fetchResolvedItems:()=>Fi,fetchTimelineHistory:()=>qi,fetchTurnQueueEntries:()=>Da,fetchTypeDefinitions:()=>es,fetchVfsChildren:()=>cr,fetchVfsChildrenPage:()=>Zr,fetchVfsItem:()=>ar,fetchVfsItemById:()=>Xr,fetchVfsTree:()=>ns,gatewayCall:()=>C,getAccessToken:()=>Ye,getAnchor:()=>pn,getAnchorRef:()=>ye,getAnchorVersion:()=>ri,getAssetUrl:()=>Pu,getDefaultSort:()=>ku,getHomeAnchor:()=>fe,getMountVersion:()=>tr,getMounts:()=>Te,getPathSubscriptionState:()=>Ma,getQueryClient:()=>O,getRequiredFormFields:()=>Mu,getScope:()=>H,getScopeVersion:()=>Z,getServerClockOffsetMs:()=>Zo,getServerClockSyncedAt:()=>ea,getSessionEntry:()=>ht,hasServerClock:()=>Xo,initSession:()=>Xe,initVfsRealtimeWs:()=>Qt,initializeFsaos:()=>du,initializeWorkspace:()=>vs,interpretSchema:()=>Oi,invalidateAllVfs:()=>Va,invalidateChannelMessages:()=>Wa,invalidateChildren:()=>Yr,invalidateItem:()=>vi,invalidateOpenEnvelope:()=>Ba,invalidatePathAndParent:()=>La,invalidateSubtree:()=>ja,invalidateTypes:()=>$a,isAnchorReady:()=>ii,isChannelPath:()=>pe,isListableItemsFilter:()=>Rn,isScopeReady:()=>Dr,itemsFilterFromQueryFilter:()=>Ua,listChildren:()=>bu,loadMounts:()=>Dt,mount:()=>Eu,mountRealtimeScope:()=>Pn,normalizeItem:()=>_e,onConnectionStateChange:()=>Jr,pathSubscriptionMatches:()=>hi,personalSectionsKey:()=>vr,ping:()=>ka,pushChanges:()=>Ru,queryClient:()=>ya,readItem:()=>vu,refreshQuery:()=>Ae,registerCleanup:()=>te,replaceMounts:()=>fs,resetAllSdkState:()=>mn,resolvePrincipalId:()=>Oc,resubscribePath:()=>Fa,selectMount:()=>mr,serverDeadlinePassed:()=>ta,serverMsUntil:()=>na,serverNow:()=>Ur,setAnchor:()=>qr,setCachedToken:()=>No,setQueryClient:()=>ga,setScope:()=>Ho,setupRequireShim:()=>Iu,signal:()=>Cu,startTracking:()=>_s,steerTurn:()=>pu,submitForm:()=>hu,subscribeAnchor:()=>si,subscribeArtifactStream:()=>bs,subscribeMounts:()=>Qr,subscribeScope:()=>we,subscribeToEvents:()=>ne,subscribeToPath:()=>zr,subscribeToScope:()=>Sn,trackAction:()=>cu,trackEvent:()=>Nt,trackPageView:()=>au,unmountRealtimeScope:()=>ls,updateItem:()=>Su,uploadFile:()=>Ou,useAccounts:()=>xc,useAgentTimeline:()=>Nu,useAllChannels:()=>gs,useArrangement:()=>In,useArtifactStream:()=>Uu,useAsset:()=>Pc,useAuth:()=>hs,useChannelMessages:()=>Uc,useChannels:()=>Lc,useChildren:()=>cc,useComponent:()=>Pi,useCreate:()=>$c,useDelete:()=>Hc,useDmChannels:()=>jc,useEdges:()=>hc,useEventStream:()=>Yc,useFileUpload:()=>qu,useIncrementalItems:()=>pc,useInfiniteChannelMessages:()=>Nc,useInfiniteChildren:()=>mc,useInfiniteItems:()=>Ci,useItem:()=>oc,useItemById:()=>ac,useItemHistory:()=>wc,useItemVersions:()=>bc,useItems:()=>fc,useLink:()=>zc,useList:()=>xi,useMemberFocus:()=>vc,useMintedAsset:()=>Zc,useMounts:()=>Cc,useMove:()=>Gc,useMutation:()=>Jc,useNotifications:()=>Ti,useOpen:()=>yc,usePermission:()=>Ac,usePermissions:()=>kc,usePersonalItemOrder:()=>tu,usePersonalSections:()=>$u,usePinnedItems:()=>Lu,usePrincipal:()=>Fc,useRealtimeQuery:()=>Xc,useRecentActivity:()=>Sc,useResolve:()=>dc,useResolvedItems:()=>Du,useScope:()=>Rc,useScopeReady:()=>ic,useSearch:()=>lc,useTheme:()=>Ic,useTimelineHistory:()=>Ku,useTool:()=>qc,useTree:()=>uc,useType:()=>gc,useTypeHelpers:()=>_c,useTypes:()=>ms,useUnreadCounts:()=>Vc,useUpdate:()=>Wc,useUpdatePrincipal:()=>Bc,vfsKeys:()=>P,waitForPathReady:()=>Oa});var rt=class e extends Error{constructor(n){let r=n.message||e.fallbackMessage(n);super(r);ee(this,"name","EnforcementDeniedError");ee(this,"deniedBy");ee(this,"ruleKey");ee(this,"displayName");this.deniedBy=n.denied_by||n.error_type||n.error||"unknown";let s=n.enforcement;this.ruleKey=s?.rule_key??void 0,this.displayName=s?.display_name??void 0}static fallbackMessage(n){let r=n.error||"",s=n.denied_by||"";return s==="rule"||r==="RULE_DENIED"?"This feature is not enabled for this workspace.":s==="entitlement"||r==="ENTITLEMENT_REQUIRED"?"This feature requires a plan upgrade.":s==="access"||r==="ACCESS_DENIED"||r==="PERMISSION_DENIED"?"You don't have permission to do this.":"This action is not allowed."}get isRuleDenial(){return this.deniedBy==="rule"||this.deniedBy==="RULE_DENIED"}get isAccessDenial(){return this.deniedBy==="access"||this.deniedBy==="ACCESS_DENIED"}get isEntitlementDenial(){return this.deniedBy==="entitlement"||this.deniedBy==="ENTITLEMENT_REQUIRED"}};var An=X(oe(),1);var xe=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 bt,st,Lt,Vi,rl=(Vi=class extends xe{constructor(){super();x(this,bt);x(this,st);x(this,Lt);w(this,Lt,t=>{if(typeof window<"u"&&window.addEventListener){let n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){l(this,st)||this.setEventListener(l(this,Lt))}onUnsubscribe(){var t;this.hasListeners()||((t=l(this,st))==null||t.call(this),w(this,st,void 0))}setEventListener(t){var n;w(this,Lt,t),(n=l(this,st))==null||n.call(this),w(this,st,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){l(this,bt)!==t&&(w(this,bt,t),this.onFocus())}onFocus(){let t=this.isFocused();this.listeners.forEach(n=>{n(t)})}isFocused(){return typeof l(this,bt)=="boolean"?l(this,bt):globalThis.document?.visibilityState!=="hidden"}},bt=new WeakMap,st=new WeakMap,Lt=new WeakMap,Vi),jt=new rl;var sl={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},it,Ts,$i,il=($i=class{constructor(){x(this,it,sl);x(this,Ts,!1)}setTimeoutProvider(e){w(this,it,e)}setTimeout(e,t){return l(this,it).setTimeout(e,t)}clearTimeout(e){l(this,it).clearTimeout(e)}setInterval(e,t){return l(this,it).setInterval(e,t)}clearInterval(e){l(this,it).clearInterval(e)}},it=new WeakMap,Ts=new WeakMap,$i),Qe=new il;function Wi(e){setTimeout(e,0)}var Is=typeof window>"u"||"Deno"in globalThis;function G(){}function Gi(e,t){return typeof e=="function"?e(t):e}function Dn(e){return typeof e=="number"&&e>=0&&e!==1/0}function br(e,t){return Math.max(e+(t||0)-Date.now(),0)}function Me(e,t){return typeof e=="function"?e(t):e}function me(e,t){return typeof e=="function"?e(t):e}function wr(e,t){let{type:n="all",exact:r,fetchStatus:s,predicate:i,queryKey:o,stale:c}=e;if(o){if(r){if(t.queryHash!==Un(o,t.options))return!1}else if(!wt(t.queryKey,o))return!1}if(n!=="all"){let a=t.isActive();if(n==="active"&&!a||n==="inactive"&&a)return!1}return!(typeof c=="boolean"&&t.isStale()!==c||s&&s!==t.state.fetchStatus||i&&!i(t))}function Sr(e,t){let{exact:n,status:r,predicate:s,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(De(t.options.mutationKey)!==De(i))return!1}else if(!wt(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||s&&!s(t))}function Un(e,t){return(t?.queryKeyHashFn||De)(e)}function De(e){return JSON.stringify(e,(t,n)=>Es(n)?Object.keys(n).sort().reduce((r,s)=>(r[s]=n[s],r),{}):n)}function wt(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>wt(e[n],t[n])):!1}var ol=Object.prototype.hasOwnProperty;function As(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=Bi(e)&&Bi(t);if(!r&&!(Es(e)&&Es(t)))return t;let i=(r?e:Object.keys(e)).length,o=r?t:Object.keys(t),c=o.length,a=r?new Array(c):{},u=0;for(let d=0;d<c;d++){let p=r?d:o[d],m=e[p],f=t[p];if(m===f){a[p]=m,(r?d<i:ol.call(e,p))&&u++;continue}if(m===null||f===null||typeof m!="object"||typeof f!="object"){a[p]=f;continue}let y=As(m,f,n+1);a[p]=y,y===m&&u++}return i===c&&u===i?e:a}function Vt(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(let n in e)if(e[n]!==t[n])return!1;return!0}function Bi(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Es(e){if(!Hi(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!Hi(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function Hi(e){return Object.prototype.toString.call(e)==="[object Object]"}function zi(e){return new Promise(t=>{Qe.setTimeout(t,e)})}function Nn(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?As(e,t):t}function Ji(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function Yi(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var $t=Symbol();function Rr(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===$t?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function Wt(e,t){return typeof e=="function"?e(...t):!!e}function Xi(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 Ue=(()=>{let e=()=>Is;return{isServer(){return e()},setIsServer(t){e=t}}})();function Kn(){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 Zi=Wi;function al(){let e=[],t=0,n=c=>{c()},r=c=>{c()},s=Zi,i=c=>{t?e.push(c):s(()=>{n(c)})},o=()=>{let c=e;e=[],c.length&&s(()=>{r(()=>{c.forEach(a=>{n(a)})})})};return{batch:c=>{let a;t++;try{a=c()}finally{t--,t||o()}return a},batchCalls:c=>(...a)=>{i(()=>{c(...a)})},schedule:i,setNotifyFunction:c=>{n=c},setBatchNotifyFunction:c=>{r=c},setScheduler:c=>{s=c}}}var j=al();var Bt,ot,Ht,eo,cl=(eo=class extends xe{constructor(){super();x(this,Bt,!0);x(this,ot);x(this,Ht);w(this,Ht,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(){l(this,ot)||this.setEventListener(l(this,Ht))}onUnsubscribe(){var t;this.hasListeners()||((t=l(this,ot))==null||t.call(this),w(this,ot,void 0))}setEventListener(t){var n;w(this,Ht,t),(n=l(this,ot))==null||n.call(this),w(this,ot,t(this.setOnline.bind(this)))}setOnline(t){l(this,Bt)!==t&&(w(this,Bt,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return l(this,Bt)}},Bt=new WeakMap,ot=new WeakMap,Ht=new WeakMap,eo),Gt=new cl;function ul(e){return Math.min(1e3*2**e,3e4)}function ks(e){return(e??"online")==="online"?Gt.isOnline():!0}var xr=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function Cr(e){let t=!1,n=0,r,s=Kn(),i=()=>s.status!=="pending",o=g=>{if(!i()){let h=new xr(g);m(h),e.onCancel?.(h)}},c=()=>{t=!0},a=()=>{t=!1},u=()=>jt.isFocused()&&(e.networkMode==="always"||Gt.isOnline())&&e.canRun(),d=()=>ks(e.networkMode)&&e.canRun(),p=g=>{i()||(r?.(),s.resolve(g))},m=g=>{i()||(r?.(),s.reject(g))},f=()=>new Promise(g=>{r=h=>{(i()||u())&&g(h)},e.onPause?.()}).then(()=>{r=void 0,i()||e.onContinue?.()}),y=()=>{if(i())return;let g,h=n===0?e.initialPromise:void 0;try{g=h??e.fn()}catch(v){g=Promise.reject(v)}Promise.resolve(g).then(p).catch(v=>{if(i())return;let b=e.retry??(Ue.isServer()?0:3),E=e.retryDelay??ul,I=typeof E=="function"?E(n,v):E,R=b===!0||typeof b=="number"&&n<b||typeof b=="function"&&b(n,v);if(t||!R){m(v);return}n++,e.onFail?.(n,v),zi(I).then(()=>u()?void 0:f()).then(()=>{t?m(v):y()})})};return{promise:s,status:()=>s.status,cancel:o,continue:()=>(r?.(),s),cancelRetry:c,continueRetry:a,canStart:d,start:()=>(d()?y():f().then(y),s)}}var St,to,Pr=(to=class{constructor(){x(this,St)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Dn(this.gcTime)&&w(this,St,Qe.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Ue.isServer()?1/0:5*60*1e3))}clearGcTimeout(){l(this,St)!==void 0&&(Qe.clearTimeout(l(this,St)),w(this,St,void 0))}},St=new WeakMap,to);var Rt,zt,Ce,xt,re,Ln,Ct,be,oo,$e,so,io=(so=class extends Pr{constructor(t){super();x(this,be);x(this,Rt);x(this,zt);x(this,Ce);x(this,xt);x(this,re);x(this,Ln);x(this,Ct);w(this,Ct,!1),w(this,Ln,t.defaultOptions),this.setOptions(t.options),this.observers=[],w(this,xt,t.client),w(this,Ce,l(this,xt).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,w(this,Rt,ro(this.options)),this.state=t.state??l(this,Rt),this.scheduleGc()}get meta(){return this.options.meta}get promise(){return l(this,re)?.promise}setOptions(t){if(this.options={...l(this,Ln),...t},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let n=ro(this.options);n.data!==void 0&&(this.setState(no(n.data,n.dataUpdatedAt)),w(this,Rt,n))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&l(this,Ce).remove(this)}setData(t,n){let r=Nn(this.state.data,t,this.options);return q(this,be,$e).call(this,{data:r,type:"success",dataUpdatedAt:n?.updatedAt,manual:n?.manual}),r}setState(t,n){q(this,be,$e).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){let n=l(this,re)?.promise;return l(this,re)?.cancel(t),n?n.then(G).catch(G):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return l(this,Rt)}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(t=>me(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===$t||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>Me(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:!br(this.state.dataUpdatedAt,t)}onFocus(){this.observers.find(n=>n.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),l(this,re)?.continue()}onOnline(){this.observers.find(n=>n.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),l(this,re)?.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),l(this,Ce).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(n=>n!==t),this.observers.length||(l(this,re)&&(l(this,Ct)||q(this,be,oo).call(this)?l(this,re).cancel({revert:!0}):l(this,re).cancelRetry()),this.scheduleGc()),l(this,Ce).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||q(this,be,$e).call(this,{type:"invalidate"})}async fetch(t,n){if(this.state.fetchStatus!=="idle"&&l(this,re)?.status()!=="rejected"){if(this.state.data!==void 0&&n?.cancelRefetch)this.cancel({silent:!0});else if(l(this,re))return l(this,re).continueRetry(),l(this,re).promise}if(t&&this.setOptions(t),!this.options.queryFn){let a=this.observers.find(u=>u.options.queryFn);a&&this.setOptions(a.options)}let r=new AbortController,s=a=>{Object.defineProperty(a,"signal",{enumerable:!0,get:()=>(w(this,Ct,!0),r.signal)})},i=()=>{let a=Rr(this.options,n),d=(()=>{let p={client:l(this,xt),queryKey:this.queryKey,meta:this.meta};return s(p),p})();return w(this,Ct,!1),this.options.persister?this.options.persister(a,d,this):a(d)},c=(()=>{let a={fetchOptions:n,options:this.options,queryKey:this.queryKey,client:l(this,xt),state:this.state,fetchFn:i};return s(a),a})();this.options.behavior?.onFetch(c,this),w(this,zt,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==c.fetchOptions?.meta)&&q(this,be,$e).call(this,{type:"fetch",meta:c.fetchOptions?.meta}),w(this,re,Cr({initialPromise:n?.initialPromise,fn:c.fetchFn,onCancel:a=>{a instanceof xr&&a.revert&&this.setState({...l(this,zt),fetchStatus:"idle"}),r.abort()},onFail:(a,u)=>{q(this,be,$e).call(this,{type:"failed",failureCount:a,error:u})},onPause:()=>{q(this,be,$e).call(this,{type:"pause"})},onContinue:()=>{q(this,be,$e).call(this,{type:"continue"})},retry:c.options.retry,retryDelay:c.options.retryDelay,networkMode:c.options.networkMode,canRun:()=>!0}));try{let a=await l(this,re).start();if(a===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(a),l(this,Ce).config.onSuccess?.(a,this),l(this,Ce).config.onSettled?.(a,this.state.error,this),a}catch(a){if(a instanceof xr){if(a.silent)return l(this,re).promise;if(a.revert){if(this.state.data===void 0)throw a;return this.state.data}}throw q(this,be,$e).call(this,{type:"error",error:a}),l(this,Ce).config.onError?.(a,this),l(this,Ce).config.onSettled?.(this.state.data,a,this),a}finally{this.scheduleGc()}}},Rt=new WeakMap,zt=new WeakMap,Ce=new WeakMap,xt=new WeakMap,re=new WeakMap,Ln=new WeakMap,Ct=new WeakMap,be=new WeakSet,oo=function(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"},$e=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,...Ms(r.data,this.options),fetchMeta:t.meta??null};case"success":let s={...r,...no(t.data,t.dataUpdatedAt),dataUpdateCount:r.dataUpdateCount+1,...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return w(this,zt,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()}),l(this,Ce).notify({query:this,type:"updated",action:t})})},so);function Ms(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:ks(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function no(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function ro(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 he,K,Vn,le,Pt,Jt,We,at,$n,Yt,Xt,Tt,Et,ct,Zt,L,jn,Os,Fs,qs,Qs,Ds,Us,Ns,lo,uo,Wn=(uo=class extends xe{constructor(t,n){super();x(this,L);x(this,he);x(this,K);x(this,Vn);x(this,le);x(this,Pt);x(this,Jt);x(this,We);x(this,at);x(this,$n);x(this,Yt);x(this,Xt);x(this,Tt);x(this,Et);x(this,ct);x(this,Zt,new Set);this.options=n,w(this,he,t),w(this,at,null),w(this,We,Kn()),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(l(this,K).addObserver(this),ao(l(this,K),this.options)?q(this,L,jn).call(this):this.updateResult(),q(this,L,Qs).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Ks(l(this,K),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Ks(l(this,K),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,q(this,L,Ds).call(this),q(this,L,Us).call(this),l(this,K).removeObserver(this)}setOptions(t){let n=this.options,r=l(this,K);if(this.options=l(this,he).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof me(this.options.enabled,l(this,K))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");q(this,L,Ns).call(this),l(this,K).setOptions(this.options),n._defaulted&&!Vt(this.options,n)&&l(this,he).getQueryCache().notify({type:"observerOptionsUpdated",query:l(this,K),observer:this});let s=this.hasListeners();s&&co(l(this,K),r,this.options,n)&&q(this,L,jn).call(this),this.updateResult(),s&&(l(this,K)!==r||me(this.options.enabled,l(this,K))!==me(n.enabled,l(this,K))||Me(this.options.staleTime,l(this,K))!==Me(n.staleTime,l(this,K)))&&q(this,L,Os).call(this);let i=q(this,L,Fs).call(this);s&&(l(this,K)!==r||me(this.options.enabled,l(this,K))!==me(n.enabled,l(this,K))||i!==l(this,ct))&&q(this,L,qs).call(this,i)}getOptimisticResult(t){let n=l(this,he).getQueryCache().build(l(this,he),t),r=this.createResult(n,t);return dl(this,r)&&(w(this,le,r),w(this,Jt,this.options),w(this,Pt,l(this,K).state)),r}getCurrentResult(){return l(this,le)}trackResult(t,n){return new Proxy(t,{get:(r,s)=>(this.trackProp(s),n?.(s),s==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&l(this,We).status==="pending"&&l(this,We).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(r,s))})}trackProp(t){l(this,Zt).add(t)}getCurrentQuery(){return l(this,K)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){let n=l(this,he).defaultQueryOptions(t),r=l(this,he).getQueryCache().build(l(this,he),n);return r.fetch().then(()=>this.createResult(r,n))}fetch(t){return q(this,L,jn).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),l(this,le)))}createResult(t,n){let r=l(this,K),s=this.options,i=l(this,le),o=l(this,Pt),c=l(this,Jt),u=t!==r?t.state:l(this,Vn),{state:d}=t,p={...d},m=!1,f;if(n._optimisticResults){let T=this.hasListeners(),F=!T&&ao(t,n),k=T&&co(t,r,n,s);(F||k)&&(p={...p,...Ms(d.data,t.options)}),n._optimisticResults==="isRestoring"&&(p.fetchStatus="idle")}let{error:y,errorUpdatedAt:g,status:h}=p;f=p.data;let v=!1;if(n.placeholderData!==void 0&&f===void 0&&h==="pending"){let T;i?.isPlaceholderData&&n.placeholderData===c?.placeholderData?(T=i.data,v=!0):T=typeof n.placeholderData=="function"?n.placeholderData(l(this,Xt)?.state.data,l(this,Xt)):n.placeholderData,T!==void 0&&(h="success",f=Nn(i?.data,T,n),m=!0)}if(n.select&&f!==void 0&&!v)if(i&&f===o?.data&&n.select===l(this,$n))f=l(this,Yt);else try{w(this,$n,n.select),f=n.select(f),f=Nn(i?.data,f,n),w(this,Yt,f),w(this,at,null)}catch(T){w(this,at,T)}l(this,at)&&(y=l(this,at),f=l(this,Yt),g=Date.now(),h="error");let b=p.fetchStatus==="fetching",E=h==="pending",I=h==="error",R=E&&b,M=f!==void 0,S={status:h,fetchStatus:p.fetchStatus,isPending:E,isSuccess:h==="success",isError:I,isInitialLoading:R,isLoading:R,data:f,dataUpdatedAt:p.dataUpdatedAt,error:y,errorUpdatedAt:g,failureCount:p.fetchFailureCount,failureReason:p.fetchFailureReason,errorUpdateCount:p.errorUpdateCount,isFetched:t.isFetched(),isFetchedAfterMount:p.dataUpdateCount>u.dataUpdateCount||p.errorUpdateCount>u.errorUpdateCount,isFetching:b,isRefetching:b&&!E,isLoadingError:I&&!M,isPaused:p.fetchStatus==="paused",isPlaceholderData:m,isRefetchError:I&&M,isStale:Ls(t,n),refetch:this.refetch,promise:l(this,We),isEnabled:me(n.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){let T=S.data!==void 0,F=S.status==="error"&&!T,k=Q=>{F?Q.reject(S.error):T&&Q.resolve(S.data)},A=()=>{let Q=w(this,We,S.promise=Kn());k(Q)},U=l(this,We);switch(U.status){case"pending":t.queryHash===r.queryHash&&k(U);break;case"fulfilled":(F||S.data!==U.value)&&A();break;case"rejected":(!F||S.error!==U.reason)&&A();break}}return S}updateResult(){let t=l(this,le),n=this.createResult(l(this,K),this.options);if(w(this,Pt,l(this,K).state),w(this,Jt,this.options),l(this,Pt).data!==void 0&&w(this,Xt,l(this,K)),Vt(n,t))return;w(this,le,n);let r=()=>{if(!t)return!0;let{notifyOnChangeProps:s}=this.options,i=typeof s=="function"?s():s;if(i==="all"||!i&&!l(this,Zt).size)return!0;let o=new Set(i??l(this,Zt));return this.options.throwOnError&&o.add("error"),Object.keys(l(this,le)).some(c=>{let a=c;return l(this,le)[a]!==t[a]&&o.has(a)})};q(this,L,lo).call(this,{listeners:r()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&q(this,L,Qs).call(this)}},he=new WeakMap,K=new WeakMap,Vn=new WeakMap,le=new WeakMap,Pt=new WeakMap,Jt=new WeakMap,We=new WeakMap,at=new WeakMap,$n=new WeakMap,Yt=new WeakMap,Xt=new WeakMap,Tt=new WeakMap,Et=new WeakMap,ct=new WeakMap,Zt=new WeakMap,L=new WeakSet,jn=function(t){q(this,L,Ns).call(this);let n=l(this,K).fetch(this.options,t);return t?.throwOnError||(n=n.catch(G)),n},Os=function(){q(this,L,Ds).call(this);let t=Me(this.options.staleTime,l(this,K));if(Ue.isServer()||l(this,le).isStale||!Dn(t))return;let r=br(l(this,le).dataUpdatedAt,t)+1;w(this,Tt,Qe.setTimeout(()=>{l(this,le).isStale||this.updateResult()},r))},Fs=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(l(this,K)):this.options.refetchInterval)??!1},qs=function(t){q(this,L,Us).call(this),w(this,ct,t),!(Ue.isServer()||me(this.options.enabled,l(this,K))===!1||!Dn(l(this,ct))||l(this,ct)===0)&&w(this,Et,Qe.setInterval(()=>{(this.options.refetchIntervalInBackground||jt.isFocused())&&q(this,L,jn).call(this)},l(this,ct)))},Qs=function(){q(this,L,Os).call(this),q(this,L,qs).call(this,q(this,L,Fs).call(this))},Ds=function(){l(this,Tt)!==void 0&&(Qe.clearTimeout(l(this,Tt)),w(this,Tt,void 0))},Us=function(){l(this,Et)!==void 0&&(Qe.clearInterval(l(this,Et)),w(this,Et,void 0))},Ns=function(){let t=l(this,he).getQueryCache().build(l(this,he),this.options);if(t===l(this,K))return;let n=l(this,K);w(this,K,t),w(this,Vn,t.state),this.hasListeners()&&(n?.removeObserver(this),t.addObserver(this))},lo=function(t){j.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(l(this,le))}),l(this,he).getQueryCache().notify({query:l(this,K),type:"observerResultsUpdated"})})},uo);function ll(e,t){return me(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function ao(e,t){return ll(e,t)||e.state.data!==void 0&&Ks(e,t,t.refetchOnMount)}function Ks(e,t,n){if(me(t.enabled,e)!==!1&&Me(t.staleTime,e)!=="static"){let r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&Ls(e,t)}return!1}function co(e,t,n,r){return(e!==t||me(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&Ls(e,n)}function Ls(e,t){return me(t.enabled,e)!==!1&&e.isStaleByTime(Me(t.staleTime,e))}function dl(e,t){return!Vt(e.getCurrentResult(),t)}function en(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||[],c={pages:[],pageParams:[]},a=0,u=async()=>{let d=!1,p=y=>{Xi(y,()=>t.signal,()=>d=!0)},m=Rr(t.options,t.fetchOptions),f=async(y,g,h)=>{if(d)return Promise.reject();if(g==null&&y.pages.length)return Promise.resolve(y);let b=(()=>{let M={client:t.client,queryKey:t.queryKey,pageParam:g,direction:h?"backward":"forward",meta:t.options.meta};return p(M),M})(),E=await m(b),{maxPages:I}=t.options,R=h?Yi:Ji;return{pages:R(y.pages,E,I),pageParams:R(y.pageParams,g,I)}};if(s&&i.length){let y=s==="backward",g=y?fo:js,h={pages:i,pageParams:o},v=g(r,h);c=await f(h,v,y)}else{let y=e??i.length;do{let g=a===0?o[0]??r.initialPageParam:js(r,c);if(a>0&&g==null)break;c=await f(c,g),a++}while(a<y)}return c};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 js(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 po(e,t){return t?js(e,t)!=null:!1}function mo(e,t){return!t||!e.getPreviousPageParam?!1:fo(e,t)!=null}var Vs=class extends Wn{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:en()})}getOptimisticResult(e){return e.behavior=en(),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:c}=r,a=n.fetchMeta?.fetchMore?.direction,u=o&&a==="forward",d=s&&a==="forward",p=o&&a==="backward",m=s&&a==="backward";return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:po(t,n.data),hasPreviousPage:mo(t,n.data),isFetchNextPageError:u,isFetchingNextPage:d,isFetchPreviousPageError:p,isFetchingPreviousPage:m,isRefetchError:c&&!u&&!p,isRefetching:i&&!d&&!m}}};var Bn,Ne,ae,It,Ke,ut,ho,go=(ho=class extends Pr{constructor(t){super();x(this,Ke);x(this,Bn);x(this,Ne);x(this,ae);x(this,It);w(this,Bn,t.client),this.mutationId=t.mutationId,w(this,ae,t.mutationCache),w(this,Ne,[]),this.state=t.state||$s(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){l(this,Ne).includes(t)||(l(this,Ne).push(t),this.clearGcTimeout(),l(this,ae).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){w(this,Ne,l(this,Ne).filter(n=>n!==t)),this.scheduleGc(),l(this,ae).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){l(this,Ne).length||(this.state.status==="pending"?this.scheduleGc():l(this,ae).remove(this))}continue(){return l(this,It)?.continue()??this.execute(this.state.variables)}async execute(t){let n=()=>{q(this,Ke,ut).call(this,{type:"continue"})},r={client:l(this,Bn),meta:this.options.meta,mutationKey:this.options.mutationKey};w(this,It,Cr({fn:()=>this.options.mutationFn?this.options.mutationFn(t,r):Promise.reject(new Error("No mutationFn found")),onFail:(o,c)=>{q(this,Ke,ut).call(this,{type:"failed",failureCount:o,error:c})},onPause:()=>{q(this,Ke,ut).call(this,{type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>l(this,ae).canRun(this)}));let s=this.state.status==="pending",i=!l(this,It).canStart();try{if(s)n();else{q(this,Ke,ut).call(this,{type:"pending",variables:t,isPaused:i}),l(this,ae).config.onMutate&&await l(this,ae).config.onMutate(t,this,r);let c=await this.options.onMutate?.(t,r);c!==this.state.context&&q(this,Ke,ut).call(this,{type:"pending",context:c,variables:t,isPaused:i})}let o=await l(this,It).start();return await l(this,ae).config.onSuccess?.(o,t,this.state.context,this,r),await this.options.onSuccess?.(o,t,this.state.context,r),await l(this,ae).config.onSettled?.(o,null,this.state.variables,this.state.context,this,r),await this.options.onSettled?.(o,null,t,this.state.context,r),q(this,Ke,ut).call(this,{type:"success",data:o}),o}catch(o){try{await l(this,ae).config.onError?.(o,t,this.state.context,this,r)}catch(c){Promise.reject(c)}try{await this.options.onError?.(o,t,this.state.context,r)}catch(c){Promise.reject(c)}try{await l(this,ae).config.onSettled?.(void 0,o,this.state.variables,this.state.context,this,r)}catch(c){Promise.reject(c)}try{await this.options.onSettled?.(void 0,o,t,this.state.context,r)}catch(c){Promise.reject(c)}throw q(this,Ke,ut).call(this,{type:"error",error:o}),o}finally{l(this,ae).runNext(this)}}},Bn=new WeakMap,Ne=new WeakMap,ae=new WeakMap,It=new WeakMap,Ke=new WeakSet,ut=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(()=>{l(this,Ne).forEach(r=>{r.onMutationUpdate(t)}),l(this,ae).notify({mutation:this,type:"updated",action:t})})},ho);function $s(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Be,Oe,Hn,yo,_o=(yo=class extends xe{constructor(t={}){super();x(this,Be);x(this,Oe);x(this,Hn);this.config=t,w(this,Be,new Set),w(this,Oe,new Map),w(this,Hn,0)}build(t,n,r){let s=new go({client:t,mutationCache:this,mutationId:++Qn(this,Hn)._,options:t.defaultMutationOptions(n),state:r});return this.add(s),s}add(t){l(this,Be).add(t);let n=Tr(t);if(typeof n=="string"){let r=l(this,Oe).get(n);r?r.push(t):l(this,Oe).set(n,[t])}this.notify({type:"added",mutation:t})}remove(t){if(l(this,Be).delete(t)){let n=Tr(t);if(typeof n=="string"){let r=l(this,Oe).get(n);if(r)if(r.length>1){let s=r.indexOf(t);s!==-1&&r.splice(s,1)}else r[0]===t&&l(this,Oe).delete(n)}}this.notify({type:"removed",mutation:t})}canRun(t){let n=Tr(t);if(typeof n=="string"){let s=l(this,Oe).get(n)?.find(i=>i.state.status==="pending");return!s||s===t}else return!0}runNext(t){let n=Tr(t);return typeof n=="string"?l(this,Oe).get(n)?.find(s=>s!==t&&s.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){j.batch(()=>{l(this,Be).forEach(t=>{this.notify({type:"removed",mutation:t})}),l(this,Be).clear(),l(this,Oe).clear()})}getAll(){return Array.from(l(this,Be))}find(t){let n={exact:!0,...t};return this.getAll().find(r=>Sr(n,r))}findAll(t={}){return this.getAll().filter(n=>Sr(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(G))))}},Be=new WeakMap,Oe=new WeakMap,Hn=new WeakMap,yo);function Tr(e){return e.options.scope?.id}var He,lt,ge,Ge,ze,Er,Ws,vo,Bs=(vo=class extends xe{constructor(t,n){super();x(this,ze);x(this,He);x(this,lt);x(this,ge);x(this,Ge);w(this,He,t),this.setOptions(n),this.bindMethods(),q(this,ze,Er).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(t){let n=this.options;this.options=l(this,He).defaultMutationOptions(t),Vt(this.options,n)||l(this,He).getMutationCache().notify({type:"observerOptionsUpdated",mutation:l(this,ge),observer:this}),n?.mutationKey&&this.options.mutationKey&&De(n.mutationKey)!==De(this.options.mutationKey)?this.reset():l(this,ge)?.state.status==="pending"&&l(this,ge).setOptions(this.options)}onUnsubscribe(){this.hasListeners()||l(this,ge)?.removeObserver(this)}onMutationUpdate(t){q(this,ze,Er).call(this),q(this,ze,Ws).call(this,t)}getCurrentResult(){return l(this,lt)}reset(){l(this,ge)?.removeObserver(this),w(this,ge,void 0),q(this,ze,Er).call(this),q(this,ze,Ws).call(this)}mutate(t,n){return w(this,Ge,n),l(this,ge)?.removeObserver(this),w(this,ge,l(this,He).getMutationCache().build(l(this,He),this.options)),l(this,ge).addObserver(this),l(this,ge).execute(t)}},He=new WeakMap,lt=new WeakMap,ge=new WeakMap,Ge=new WeakMap,ze=new WeakSet,Er=function(){let t=l(this,ge)?.state??$s();w(this,lt,{...t,isPending:t.status==="pending",isSuccess:t.status==="success",isError:t.status==="error",isIdle:t.status==="idle",mutate:this.mutate,reset:this.reset})},Ws=function(t){j.batch(()=>{if(l(this,Ge)&&this.hasListeners()){let n=l(this,lt).variables,r=l(this,lt).context,s={client:l(this,He),meta:this.options.meta,mutationKey:this.options.mutationKey};if(t?.type==="success"){try{l(this,Ge).onSuccess?.(t.data,n,r,s)}catch(i){Promise.reject(i)}try{l(this,Ge).onSettled?.(t.data,null,n,r,s)}catch(i){Promise.reject(i)}}else if(t?.type==="error"){try{l(this,Ge).onError?.(t.error,n,r,s)}catch(i){Promise.reject(i)}try{l(this,Ge).onSettled?.(void 0,t.error,n,r,s)}catch(i){Promise.reject(i)}}}this.listeners.forEach(n=>{n(l(this,lt))})})},vo);var Le,bo,wo=(bo=class extends xe{constructor(t={}){super();x(this,Le);this.config=t,w(this,Le,new Map)}build(t,n,r){let s=n.queryKey,i=n.queryHash??Un(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){l(this,Le).has(t.queryHash)||(l(this,Le).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){let n=l(this,Le).get(t.queryHash);n&&(t.destroy(),n===t&&l(this,Le).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){j.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return l(this,Le).get(t)}getAll(){return[...l(this,Le).values()]}find(t){let n={exact:!0,...t};return this.getAll().find(r=>wr(n,r))}findAll(t={}){let n=this.getAll();return Object.keys(t).length>0?n.filter(r=>wr(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()})})}},Le=new WeakMap,bo);var z,dt,ft,tn,nn,pt,rn,sn,So,Hs=(So=class{constructor(e={}){x(this,z);x(this,dt);x(this,ft);x(this,tn);x(this,nn);x(this,pt);x(this,rn);x(this,sn);w(this,z,e.queryCache||new wo),w(this,dt,e.mutationCache||new _o),w(this,ft,e.defaultOptions||{}),w(this,tn,new Map),w(this,nn,new Map),w(this,pt,0)}mount(){Qn(this,pt)._++,l(this,pt)===1&&(w(this,rn,jt.subscribe(async e=>{e&&(await this.resumePausedMutations(),l(this,z).onFocus())})),w(this,sn,Gt.subscribe(async e=>{e&&(await this.resumePausedMutations(),l(this,z).onOnline())})))}unmount(){var e,t;Qn(this,pt)._--,l(this,pt)===0&&((e=l(this,rn))==null||e.call(this),w(this,rn,void 0),(t=l(this,sn))==null||t.call(this),w(this,sn,void 0))}isFetching(e){return l(this,z).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return l(this,dt).findAll({...e,status:"pending"}).length}getQueryData(e){let t=this.defaultQueryOptions({queryKey:e});return l(this,z).get(t.queryHash)?.state.data}ensureQueryData(e){let t=this.defaultQueryOptions(e),n=l(this,z).build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(Me(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return l(this,z).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=l(this,z).get(r.queryHash)?.state.data,o=Gi(t,i);if(o!==void 0)return l(this,z).build(this,r).setData(o,{...n,manual:!0})}setQueriesData(e,t,n){return j.batch(()=>l(this,z).findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){let t=this.defaultQueryOptions({queryKey:e});return l(this,z).get(t.queryHash)?.state}removeQueries(e){let t=l(this,z);j.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){let n=l(this,z);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(()=>l(this,z).findAll(e).map(s=>s.cancel(n)));return Promise.all(r).then(G).catch(G)}invalidateQueries(e,t={}){return j.batch(()=>(l(this,z).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(()=>l(this,z).findAll(e).filter(s=>!s.isDisabled()&&!s.isStatic()).map(s=>{let i=s.fetch(void 0,n);return n.throwOnError||(i=i.catch(G)),s.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(G)}fetchQuery(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=l(this,z).build(this,t);return n.isStaleByTime(Me(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(G).catch(G)}fetchInfiniteQuery(e){return e.behavior=en(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(G).catch(G)}ensureInfiniteQueryData(e){return e.behavior=en(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return Gt.isOnline()?l(this,dt).resumePausedMutations():Promise.resolve()}getQueryCache(){return l(this,z)}getMutationCache(){return l(this,dt)}getDefaultOptions(){return l(this,ft)}setDefaultOptions(e){w(this,ft,e)}setQueryDefaults(e,t){l(this,tn).set(De(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){let t=[...l(this,tn).values()],n={};return t.forEach(r=>{wt(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){l(this,nn).set(De(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){let t=[...l(this,nn).values()],n={};return t.forEach(r=>{wt(e,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;let t={...l(this,ft).queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Un(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===$t&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...l(this,ft).mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){l(this,z).clear(),l(this,dt).clear()}},z=new WeakMap,dt=new WeakMap,ft=new WeakMap,tn=new WeakMap,nn=new WeakMap,pt=new WeakMap,rn=new WeakMap,sn=new WeakMap,So);var on=X(oe(),1),xo=X(Ir(),1),Gs=on.createContext(void 0),$=e=>{let t=on.useContext(Gs);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},Gn=({client:e,children:t})=>(on.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,xo.jsx)(Gs.Provider,{value:e,children:t}));var Ar=X(oe(),1),Co=Ar.createContext(!1),Po=()=>Ar.useContext(Co),wp=Co.Provider;var zn=X(oe(),1),fl=X(Ir(),1);function pl(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var ml=zn.createContext(pl()),To=()=>zn.useContext(ml);var Eo=X(oe(),1);var Io=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError=="function"?Wt(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},Ao=e=>{Eo.useEffect(()=>{e.clearReset()},[e])},ko=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:s})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(s&&e.data===void 0||Wt(n,[e.error,r]));var Mo=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))}},Oo=(e,t)=>e.isLoading&&e.isFetching&&!t,Fo=(e,t)=>e?.suspense&&t.isPending,zs=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});var mt=X(oe(),1);function kr(e,t,n){let r=Po(),s=To(),i=$(n),o=i.defaultQueryOptions(e);i.getDefaultOptions().queries?._experimental_beforeQuery?.(o);let c=i.getQueryCache().get(o.queryHash);o._optimisticResults=r?"isRestoring":"optimistic",Mo(o),Io(o,s,c),Ao(s);let a=!i.getQueryCache().get(o.queryHash),[u]=mt.useState(()=>new t(i,o)),d=u.getOptimisticResult(o),p=!r&&e.subscribed!==!1;if(mt.useSyncExternalStore(mt.useCallback(m=>{let f=p?u.subscribe(j.batchCalls(m)):G;return u.updateResult(),f},[u,p]),()=>u.getCurrentResult(),()=>u.getCurrentResult()),mt.useEffect(()=>{u.setOptions(o)},[o,u]),Fo(o,d))throw zs(o,u,s);if(ko({result:d,errorResetBoundary:s,throwOnError:o.throwOnError,query:c,suspense:o.suspense}))throw d.error;return i.getDefaultOptions().queries?._experimental_afterQuery?.(o,d),o.experimental_prefetchInRender&&!Ue.isServer()&&Oo(d,r)&&(a?zs(o,u,s):c?.promise)?.catch(G).finally(()=>{u.updateResult()}),o.notifyOnChangeProps?d:u.trackResult(d)}function V(e,t){return kr(e,Wn,t)}var Je=X(oe(),1);function de(e,t){let n=$(t),[r]=Je.useState(()=>new Bs(n,e));Je.useEffect(()=>{r.setOptions(e)},[r,e]);let s=Je.useSyncExternalStore(Je.useCallback(o=>r.subscribe(j.batchCalls(o)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),i=Je.useCallback((o,c)=>{r.mutate(o,c).catch(G)},[r]);if(s.error&&Wt(r.options.throwOnError,[s.error]))throw s.error;return{...s,mutate:i,mutateAsync:s.mutate}}function Jn(e,t){return kr(e,Vs,t)}var Do=X(Qo(),1),Yn=typeof window<"u"&&window.__FSAOS_CONFIG__||{},At=Array.isArray(Yn.sources)?Yn.sources:[],hl=Yn.supabaseUrl||"https://vahbmsslxuustnlvsrkg.supabase.co",gl=Yn.supabaseAnonKey||"sb_publishable_ZjosozAjfpZ4InMNElTr6Q_hHB-f5nc",Pe=Yn.gatewayUrl||"https://fsaos-mcp-gw-rust.fly.dev",W=(0,Do.createClient)(hl,gl,{auth:{persistSession:!0,autoRefreshToken:!0,detectSessionInUrl:!1}});var Xn=null,Mr=0,Uo,Zs,Or=!1;Uo=new Promise(e=>{Zs=e});W.auth.onAuthStateChange((e,t)=>{t?.access_token?(Xn=t.access_token,Mr=t.expires_at??Math.floor(Date.now()/1e3)+3600):(Xn=null,Mr=0),Or||(Or=!0,Zs())});setTimeout(()=>{Or||(Or=!0,Zs())},5e3);function No(e,t){Xn=e,Mr=t??Math.floor(Date.now()/1e3)+3600}function ei(){Xn=null,Mr=0}async function Ye(){let e=typeof window<"u"&&window.__FSAOS_CONFIG__||{};if(e.embedToken){if(typeof e.embedToken=="function")try{return await e.embedToken()??null}catch{return null}return e.embedToken}return await Uo,Xn}var ln=null,dn=null,Ko=0,Js=new Set,ti,Zn,fn=!1;ti=new Promise(e=>{Zn=e});function ni(){Ko++,Js.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Anchor listener error:",t)}})}function qr(e){let t=typeof e=="string"?e:e.path,n=ln!==t||dn?.id!==(typeof e=="string"?void 0:e.id);ln=t,dn=typeof e=="string"?null:e,typeof e!="string"&&!kt.some(r=>r.id===e.id)&&(kt=[...kt,e],oi()),fn||(fn=!0,Zn()),n&&ni()}function pn(){return ln}function ye(){return dn}function ri(){return Ko}function si(e){return Js.add(e),()=>{Js.delete(e)}}function er(){return ti}function ii(){return fn}var Fr=null;function Mt(e,t={}){if(Fr){console.warn("[SDK] electHomeAnchor called twice; ignoring (logout to re-elect).");return}Fr=e,t.activate!==!1&&qr(e)}function fe(){return Fr}var kt=[],Ys=new Set,Lo=0;function oi(){Lo++,Ys.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Mount listener error:",t)}})}function Te(){return kt}function tr(){return Lo}function Qr(e){return Ys.add(e),()=>{Ys.delete(e)}}function jo(e,t){let n=JSON.stringify(kt)!==JSON.stringify(e),r=ln!==t.path||dn?.id!==t.id;kt=e,ln=t.path,dn=t,fn||(fn=!0,Zn()),n&&oi(),r&&ni()}var cn=null,an=null,un=0,Xs=new Set,Vo=0;function $o(){Vo++,Xs.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Session listener error:",t)}})}function se(){return un}function ai(){return Vo}function Wo(e){return Xs.add(e),()=>{Xs.delete(e)}}async function Xe(){if(cn)return cn;if(an)return an;let e=un;return an=(async()=>{let t=Ot(),n=await Ye();if(e!==un)throw new Error("Session changed during initialization");let r={};n&&(r.Authorization=`Bearer ${n}`);let s=await fetch(`${Pe}/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!==un)throw new Error("Session changed during initialization");let o=i.entry||i;return cn={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},$o(),cn})().catch(t=>{throw e===un&&(an=null),t}),an}function ht(){return cn}function ci(){un++,cn=null,an=null,ln=null,dn=null,Fr=null,kt=[],$o()}var Bo=[];function te(e){Bo.push(e)}function mn(){ci(),ei(),Zn(),fn=!1,ti=new Promise(e=>{Zn=e}),ni(),oi();for(let e of Bo)try{e()}catch(t){console.warn("[SDK] Cleanup function failed:",t)}}function Ot(){if(typeof window<"u"){let e=window.__FSAOS_CONFIG__;return e?.hostname?e.hostname:window.location.hostname}return"localhost"}var Ho=qr,H=pn,Z=ri,we=si,Go=er,Dr=ii;var ui=0,zo=!1,Jo=0;function Yo(e){if(typeof e!="string")return;let t=Date.parse(e);Number.isNaN(t)||(ui=t-Date.now(),zo=!0,Jo=Date.now())}function Ur(){return Date.now()+ui}function Xo(){return zo}function Zo(){return ui}function ea(){return Jo}function ta(e){if(typeof e!="string")return null;let t=Date.parse(e);return Number.isNaN(t)?null:Ur()>=t}function na(e){if(typeof e!="string")return null;let t=Date.parse(e);return Number.isNaN(t)?null:Math.max(0,t-Ur())}var hn,Ee=new Map,Ft=[],li=0,di={foreground:0,normal:1,background:2},Nr=()=>performance.now(),fi=()=>new DOMException("Read cancelled","AbortError");function sa(e={}){hn={concurrency:Math.max(1,Math.min(16,Math.floor(e.concurrency??6))),timeoutMs:Math.max(1e3,e.timeoutMs??15e3),onTiming:e.onTiming},Lr()}function ia(){for(let e of Ee.values()){e.controller.abort();for(let t of e.consumers)t.detach(),t.reject(fi());e.consumers.clear(),e.timer&&clearTimeout(e.timer)}Ee.clear(),Ft.length=0}function oa(e,t){return e==="query"?!("materialize"in t):["read","list","search","resolve","resolve-items","get-channel-messages","list-memberships"].includes(e)}function Kr(e){return Array.isArray(e)?`[${e.map(Kr).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)}:${Kr(n)}`).join(",")}}`:JSON.stringify(e)}function aa(e,t,n,r){if(n.signal?.aborted)return Promise.reject(fi());if(!hn)return r(n.signal);let s=Ee.get(e);if(s)di[n.priority??"normal"]<di[s.priority]&&(s.priority=n.priority??"normal");else{s={key:e,method:t,priority:n.priority??"normal",queuedAt:Nr(),controller:new AbortController,consumers:new Set,run:r},Ee.set(e,s),Ft.push(s);let c=s;s.timer=setTimeout(()=>{c.controller.abort();let a=new Error("The read timed out. Please retry.");a.name="TimeoutError";for(let u of c.consumers)u.detach(),u.reject(a);c.consumers.clear(),Ee.get(c.key)===c&&Ee.delete(c.key),ra(c)},hn.timeoutMs)}let i=s,o=new Promise((c,a)=>{let u=()=>{d.detach(),i.consumers.delete(d),a(fi()),i.consumers.size||(i.controller.abort(),Ee.get(i.key)===i&&Ee.delete(i.key),ra(i))},d={resolve:p=>c(structuredClone(p)),reject:a,detach:()=>n.signal?.removeEventListener("abort",u)};i.consumers.add(d),n.signal?.addEventListener("abort",u,{once:!0})});return Lr(),o}function ra(e){let t=Ft.indexOf(e);t>=0&&(Ft.splice(t,1),Ee.get(e.key)===e&&Ee.delete(e.key),e.timer&&clearTimeout(e.timer)),Lr()}function Lr(){if(hn)for(;li<hn.concurrency&&Ft.length;){let e=r=>di[r.priority]-Math.floor((Nr()-r.queuedAt)/2e3);Ft.sort((r,s)=>e(r)-e(s)||r.queuedAt-s.queuedAt);let t=Ft.shift();if(!t.consumers.size)continue;li++,t.startedAt=Nr();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(),Ee.get(t.key)===t&&Ee.delete(t.key),li--;try{hn?.onTiming?.({method:t.method,priority:t.priority,queueMs:Math.round(t.startedAt-t.queuedAt),requestMs:Math.round(Nr()-t.startedAt),outcome:n})}catch{}Lr()})}}te(ia);var yl=new Set(["list-memberships","init"]),Ie=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);ee(this,"name","GatewayRequestError");ee(this,"method");ee(this,"status");ee(this,"statusText");ee(this,"payload");ee(this,"responseBody");this.method=n.method,this.status=n.status,this.statusText=n.statusText,this.payload=n.payload,this.responseBody=n.responseBody}};async function C(e,t={},n={}){let r=se(),s=pn(),i=Ot(),o=`${Pe}/d/${i}`,c={"Content-Type":"application/json"},a=await ca(Ye(),n.signal);if(r!==se())throw new Error("Session changed before gateway request");if(a&&(c.Authorization=`Bearer ${a}`),!yl.has(e)&&!t._scope_path&&await ca(er(),n.signal),r!==se())throw new Error("Session changed before gateway request");let u={...t},d=ht();!u.domain_scope_id&&d?.scope_id&&(u.domain_scope_id=d.scope_id);let p=s??pn();!u._scope_path&&p&&(u._scope_path=p);let m=async f=>{if(r!==se())throw new Error("Session changed before queued gateway request");let y=await fetch(o,{method:"POST",signal:f,headers:c,body:JSON.stringify({method:e,params:u})}),g=await y.text();if(r!==se())throw new Error("Session changed during gateway request");let h=null;if(g)try{h=JSON.parse(g)}catch{}if(!y.ok||!h)throw new Ie({method:e,status:y.status,statusText:y.statusText,payload:h,responseBody:g});if(h.success===!1){let v=h.error||"",b=h.denied_by||h.error_type||"";throw b==="rule"||b==="access"||b==="entitlement"||v==="RULE_DENIED"||v==="ACCESS_DENIED"||v==="PERMISSION_DENIED"||v==="ENTITLEMENT_REQUIRED"?new rt(h):new Ie({method:e,status:y.status,statusText:y.statusText,payload:h,responseBody:g})}return h&&h.server_now!==void 0&&Yo(h.server_now),h};return oa(e,u)?aa(Kr([r,i,a,e,u]),e,n,m):m(n.signal)}function ca(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 _=X(oe(),1),Kl=X(la(),1),Ll=X(Ir(),1);var da=new WeakMap;function Ae(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(p=>p.promise?[p.promise]:[]);if(i.length===0)return s();let o=`${r?"=":"^"}${JSON.stringify(t)}`,c=da.get(e);c||(c=new Map,da.set(e,c));let a=c.get(o);if(a)return a;let u=c,d=Promise.allSettled(i).then(()=>(u.delete(o),s()));return u.set(o,d),d}function pe(e,t){return typeof e=="string"&&(e===t||e.startsWith(`${t}/`))}var jr=new WeakMap,fa=e=>e.meta?.arrangementRealtime===!0;function Ze(e,t){let n=e.getQueryCache().find({queryKey:t,exact:!0});if(!n)return;let r=jr.get(e);r||(r=new Map,jr.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&&Ae(e,t,{exact:!0})},250))}function pa(e,t){if(!(!t||typeof t!="object"))for(let n of e.getQueryCache().getAll()){if(!fa(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")&&Ze(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)))&&Ze(e,n.queryKey)}}function ma(e){for(let t of e.getQueryCache().getAll())fa(t)&&t.state.data!==void 0&&Ze(e,t.queryKey)}function ha(e){jr.get(e)?.forEach(clearTimeout),jr.delete(e)}var et=null;te(()=>{et&&(et.cancelQueries({queryKey:["vfs"]}),et.removeQueries({queryKey:["vfs"]}))});function ga(e){if(et&&et!==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.");et=e}function O(){return et||(et=new Hs({defaultOptions:{queries:{staleTime:1e3*60*2,gcTime:1e3*60*10,refetchOnWindowFocus:!1,retry:1}}})),et}var ya=new Proxy({},{get(e,t,n){let r=O(),s=r[t];return typeof s=="function"?s.bind(r):s}});var Vr=new WeakMap;function pi(e){return e.meta?.infiniteItemsRealtime?.filter}function _l(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 vl(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 bl(e,t,n){if(_l(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&&!pe(n.path,r)&&!pe(n.old_path,r))return!1;if(n.item_type==="symlink"&&s&&i)return!0;let o=vl(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 _a(e,t){let n=Vr.get(e);n||(n=new Map,Vr.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||!pi(t))&&Ae(e,t.queryKey,{exact:!0})},500))}function va(e,t){if(!(!t||typeof t!="object"))for(let n of e.getQueryCache().getAll()){let r=pi(n);r&&bl(n,r,t)&&_a(e,n)}}function ba(e){for(let t of e.getQueryCache().getAll())pi(t)&&t.state.data!==void 0&&_a(e,t)}function wa(e){Vr.get(e)?.forEach(clearTimeout),Vr.delete(e)}var $r=class extends Error{constructor(){super("The server did not confirm the selected-Space listing contract")}};function Sa(e,t){if(!Array.isArray(t)||t.some(n=>typeof n!="string")||JSON.stringify([...new Set(t)].sort())!==JSON.stringify(e))throw new $r}function gt(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 gn(e){return e instanceof $r||e instanceof rt||e instanceof Ie&&(e.payload?.error==="SPACE_SELECTION_UNAVAILABLE"||e.payload?.error==="QUERY_PARAMS_INVALID"||e.status===401||e.status===403)}function ie(){return H()??"__unscoped__"}var P={all:()=>["vfs",ie()],item:e=>["vfs",ie(),"item",e],itemById:e=>["vfs","item-by-id",e],children:e=>["vfs",ie(),"children",e],allChildren:()=>["vfs",ie(),"children"],types:e=>["vfs","types",e??"default"],edges:e=>["vfs","edges",e],search:(e,t)=>["vfs",ie(),"search",e,...t??[]],items:(e,t)=>["vfs",ie(),"items",e,JSON.stringify(gt(t??{}))],allItems:()=>["vfs",ie(),"items"],tree:(e,t)=>["vfs",ie(),"tree",e,t??1],openEnvelope:(e,t)=>["vfs",ie(),"open",e,t??"__default__"],allOpenEnvelopes:()=>["vfs",ie(),"open"],memberFocus:e=>["vfs","member-focus",e],fractalInstances:()=>["vfs","fractal-instances"],recentActivity:(e,t,n)=>["vfs",ie(),"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",ie(),"channel-messages",e,t??"__top__"],allChannelMessages:()=>["vfs",ie(),"channel-messages"],channels:e=>["vfs",ie(),"channels",e??"all"],allChannels:()=>["vfs",ie(),"channels"],notifications:(e,t)=>["vfs",ie(),"notifications",e??"all",t??200],allNotifications:()=>["vfs",ie(),"notifications"],unreadCounts:()=>["vfs",ie(),"unread-counts"],memberships:e=>["memberships",e]};var wl=typeof window<"u"&&(window.location?.hostname==="localhost"||window.location?.hostname==="127.0.0.1"||window.__FSAOS_WS_DEBUG__);function J(...e){wl&&console.log("[WS]",...e)}var D=null,yn=null,vn=null,nr=0,Sl=3e4,Ra=1e4,wn=!1,xa=!1,Ia=3e4,Rl=Ia*2+5e3,Wr=0,Br=null,Ca=!1;function xl(){sr(),Wr=Date.now(),Br=setInterval(()=>{if(D&&D.readyState===WebSocket.OPEN&&Date.now()-Wr>Rl){J("ping: no inbound traffic for",Date.now()-Wr,"ms \u2014 closing half-open socket");try{D.close(4e3,"liveness timeout")}catch{}return}nt({type:"ping"})},Ia)}function sr(){Br&&(clearInterval(Br),Br=null)}function Cl(){typeof document>"u"||(document.hidden?sr():rr()&&(J("Tab visible, reconnecting..."),qt()))}function Pl(){Ca||typeof document>"u"||(document.addEventListener("visibilitychange",Cl),Ca=!0)}var Se={};function hi(e,t){let n=e.replace(/\/+$/,""),r=t.replace(/\/+$/,"");return!n||!r?n===r:r===n||r.startsWith(`${n}/`)}var bn=[],tt=new Map,_n=new Map,ke=new Map;function Tl(e){let t=_n.get(e);return t?Array.from(new Set(Array.from(t.values()).flatMap(n=>n.event_types))).sort():[]}function Pa(e,t){return e?e.length===t.length&&e.every((n,r)=>n===t[r]):!1}function Ta(e){let t=Tl(e);if(t.length===0)return tt.delete(e),null;let n={scope_id:e,event_types:t};return tt.set(e,n),n}var je=new Map,yt=new Map,mi="disconnected",Hr=[];function Gr(e){if(mi!==e){mi=e;for(let t of[...Hr])try{t(e)}catch{}}}function El(e){je.set(e,"ready");let t=yt.get(e);if(t){yt.delete(e);for(let n of t)n()}}function Il(){for(let e of je.keys())je.set(e,"disconnected")}function gi(e,t){je.set(e,"pending"),nt({type:"subscribe_path",path:e,event_types:t})}function Al(){return Object.keys(Se).some(t=>Se[t]&&Se[t].length>0)||bn.length>0}function rr(){return tt.size>0||ke.size>0}async function qt(){if(!rr()){J("ensureConnection: no active subscriptions, skipping");return}if(D&&D.readyState===WebSocket.OPEN){J("ensureConnection: already open");return}if(yn)return J("ensureConnection: connection already in flight, waiting..."),yn;if(D){J("ensureConnection: killing stale WS in state",D.readyState);try{D.close()}catch{}D=null}return wn=!1,yn=(async()=>{try{let e=typeof window<"u"&&window.__FSAOS_CONFIG__||{},t=Pe,n=await Ye();if(!n){J("ensureConnection: no token available, will retry"),Ea();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)+"..."),Gr("connecting"),D=new WebSocket(i);let o=D;await new Promise((c,a)=>{if(!D)return a(new Error("WebSocket not created"));let u=setTimeout(()=>{if(D===o){if(J("ensureConnection: TIMEOUT after",Ra,"ms"),D&&D.readyState!==WebSocket.OPEN){try{D.close()}catch{}D=null}a(new Error("WebSocket connection timeout"))}},Ra);o.onopen=()=>{if(D!==o)return;clearTimeout(u),J("ensureConnection: CONNECTED");let d=xa;xa=!0,nr=0,Gr("connected"),kl(d),(typeof document>"u"||!document.hidden)&&xl(),Pl(),c()},o.onmessage=d=>{D===o&&Ml(d.data)},o.onerror=()=>{J("ensureConnection: WS error event")},o.onclose=d=>{clearTimeout(u),D===o&&(J("ensureConnection: WS closed, code:",d.code,"reason:",d.reason),D=null,sr(),Il(),Gr("disconnected"),!wn&&rr()&&Ea(),a(new Error(`WebSocket closed: ${d.code}`)))}})}catch(e){J("ensureConnection: failed -",e?.message||e)}finally{yn=null}})(),yn}function Ea(){if(vn||typeof document<"u"&&document.hidden)return;let e=Math.min(1e3*Math.pow(2,nr)+Math.random()*1e3,Sl);nr++,J("scheduleReconnect: attempt",nr,"in",Math.round(e),"ms"),vn=setTimeout(()=>{vn=null,rr()&&qt()},e)}function kl(e=!1){for(let t of tt.values())J("resubscribeAll: scope",t.scope_id),nt({type:"subscribe",scope_id:t.scope_id,event_types:t.event_types});for(let t of ke.values())J("resubscribeAll: path",t.path),gi(t.path,t.event_types);if(e)try{let t=O();ba(t),ma(t);for(let n of ke.values())t.invalidateQueries({queryKey:P.item(n.path)}),t.invalidateQueries({queryKey:P.children(n.path)});J("resubscribeAll: invalidated",ke.size,"paths after reconnect")}catch(t){J("resubscribeAll: cache invalidation skipped",t)}}function nt(e){D&&D.readyState===WebSocket.OPEN&&D.send(JSON.stringify(e))}function Ml(e){Wr=Date.now();try{let t=JSON.parse(e);if(t.type==="subscribed_path"){typeof t.path=="string"&&El(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==="event"||t.event_type){let n=t.event_type||"message",r=t.data||t;if(n==="vfs_change"&&(va(O(),r),pa(O(),r)),typeof r.path=="string")for(let[s,i]of Object.entries(Se))s!=="*"&&hi(s,r.path)&&i.forEach(o=>o(r));Se["*"]&&Se["*"].forEach(s=>s(r));for(let s of bn)s.eventType!=="*"&&s.eventType!==n||s.filter&&!s.filter(r)||s.callback(r)}}catch{}}function yi(){!Al()&&tt.size===0&&ke.size===0&&D&&(wn=!0,sr(),D.close(),D=null,wn=!1)}function zr(e,t){return Se[e]||(Se[e]=[]),Se[e].push(t),ke.has(e)||(ke.set(e,{path:e,event_types:["token_stream"]}),D&&D.readyState===WebSocket.OPEN?gi(e,["token_stream"]):je.set(e,"pending")),qt(),()=>{let n=Se[e];if(n){let r=n.indexOf(t);r!==-1&&n.splice(r,1),n.length===0&&(delete Se[e],ke.delete(e),je.delete(e),yt.delete(e),nt({type:"unsubscribe_path",path:e}))}yi()}}function ne(e,t,n){let s=(Array.isArray(e)?e:[e]).map(i=>({eventType:i,callback:t,filter:n}));return bn.push(...s),rr()&&qt(),()=>{for(let i of s){let o=bn.indexOf(i);o!==-1&&bn.splice(o,1)}yi()}}function Sn(e,t=["vfs_change","ccm_change"]){let n=Symbol(e),r=Array.from(new Set(t)).sort();if(r.length===0)return()=>{};let s=_n.get(e)??new Map,i=tt.get(e)?.event_types;s.set(n,{event_types:r}),_n.set(e,s);let o=Ta(e);if(!o)return()=>{};J("subscribeToScope:",e,o.event_types),D&&D.readyState===WebSocket.OPEN&&!Pa(i,o.event_types)&&nt({type:"subscribe",scope_id:e,event_types:o.event_types}),qt();let c=!0;return()=>{if(!c)return;c=!1;let a=_n.get(e);if(!a?.delete(n))return;let u=tt.get(e)?.event_types;if(a.size===0)_n.delete(e),tt.delete(e),nt({type:"unsubscribe",scope_id:e});else{let d=Ta(e);d&&D&&D.readyState===WebSocket.OPEN&&!Pa(u,d.event_types)&&nt({type:"subscribe",scope_id:e,event_types:d.event_types})}yi()}}function Aa(e,t,n={}){nt({type:"emit",scope_id:e,event_type:t,payload:n})}function _i(){J("disconnectSSE: tearing down"),wa(O()),ha(O()),wn=!0,sr(),D&&(D.close(),D=null),vn&&(clearTimeout(vn),vn=null),yn=null,wn=!1,nr=0;for(let e of Object.keys(Se))delete Se[e];bn.length=0,tt.clear(),_n.clear(),ke.clear(),je.clear(),yt.clear(),Gr("disconnected")}function ka(){nt({type:"ping"})}function Ma(e){return ke.has(e)?je.get(e)??"pending":"unsubscribed"}function Oa(e,t=5e3){return ke.has(e)?je.get(e)==="ready"&&D&&D.readyState===WebSocket.OPEN?Promise.resolve(!0):(qt(),new Promise(n=>{let r=!1,s=yt.get(e)??[],i=()=>{r||(r=!0,clearTimeout(o),n(!0))};s.push(i),yt.set(e,s);let o=setTimeout(()=>{if(r)return;r=!0;let c=yt.get(e);if(c){let a=c.indexOf(i);a!==-1&&c.splice(a,1),c.length===0&&yt.delete(e)}n(!1)},t)})):Promise.resolve(!1)}function Fa(e){let t=ke.get(e);if(!t){J("resubscribePath: no active subscription for",e);return}D&&D.readyState===WebSocket.OPEN?(J("resubscribePath: re-sending frame for",e),gi(t.path,t.event_types)):(je.set(e,"pending"),qt())}function Jr(e){Hr.push(e);try{e(mi)}catch{}return()=>{let t=Hr.indexOf(e);t!==-1&&Hr.splice(t,1)}}te(_i);function qa(){return new Date().toISOString()}function Qa(){return crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function _e(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||qa(),updated_at:e.updated_at||qa(),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 or(e){return(e.content?.items||e.items||[]).map(_e)}async function Xr(e){try{let t=await C("read",{id:e});if(t.item_name||t.item_path){let r=_e(t);return r.path&&O().setQueryData(P.item(r.path),r),r}let n=t.item;if(n){let r=_e(n);return r.path&&O().setQueryData(P.item(r.path),r),r}return null}catch{return null}}async function ar(e){try{let t=await C("read",{path:e});if(t.item_name||t.item_path)return _e(t);let n=t.item;return n?_e(n):null}catch{return null}}async function cr(e){try{let t=await C("list",{path:e,limit:200}),n=or(t);for(let r of n)O().setQueryData(P.item(r.path),r);return n}catch(t){return console.error(`[gateway] Failed to fetch children of ${e}:`,t),[]}}async function Da(e,t){let{items:n}=await xn({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 Zr(e,t,n){try{let r=await C("list",{path:e,limit:t,offset:n}),s=or(r);for(let i of s)O().setQueryData(P.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 es(e){let n=await C("types-list",e?{scope_id:e}:{}),r=n.content?.items||n.items||[],s=new Map;for(let i of r){let o=i.name,c=i.type_data;!o||!c||s.set(o,{type_key:o,display_name:c.display_name||o,display_name_plural:c.display_name_plural||o+"s",icon:c.icon||"File",color:c.color||"gray",description:c.description||"",input_schema:c.input_schema||{},system_schema:c.system_schema||{},json_schema:c.input_schema||c.json_schema||{},default_data:c.default_data||{},field_defaults:c.field_defaults||{},renderer_config:c.renderer_config||{},is_system:c.is_system??!1,is_active:c.is_active??!0,is_container:c.is_container??!1,is_scope:c.is_scope??!1,render_mode:c.render_mode||"none",placement_mode:c.placement_mode,direct_parent_types:c.direct_parent_types,allowed_parent_types:c.allowed_parent_types,governed_create:c.governed_create,create_method:c.create_method,dedup:c.dedup,edges:c.edges,events:c.events})}return s}async function ts(e){try{let t=await C("edges",{item_id:e}),n=t.outgoing||[],r=t.incoming||[],s=[];for(let i of n)s.push({id:i.edge_id||Qa(),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||Qa(),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 ns(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 C("tree",s),o=or(i);for(let c of o)O().setQueryData(P.item(c.path),c);return o}catch(s){return console.error(`[gateway] Failed to fetch tree at ${e}:`,s),[]}}async function rs(e,t=50,n=0){try{let r=await C("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 ur(e,t={}){let{limit:n=50,offset:r=0,include_snapshots:s=!1}=t;try{let i=await C("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 ss(e,t=50,n=0){return ur(e,{limit:t,offset:n})}async function is(e,t,n){try{let r={scope_id:e};t?.length&&(r.item_types=t),n&&(r.limit=n);let s=await C("member-focus",r),i=or(s);for(let o of i)O().setQueryData(P.item(o.path),o);return i}catch(r){return console.error(`[gateway] Failed to fetch member focus for scope ${e}:`,r),[]}}async function os(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 C("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 Rn(e){return!!e&&(!!e.type||Array.isArray(e.any_of)&&e.any_of.length>0)}function Ol(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 Fl=["catalog","parent_only","internal"];function Ua(e,t={}){if(!e||typeof e!="object")return null;let n=o=>typeof o=="string"||typeof o=="number"||typeof o=="boolean",r=o=>{let c={},a={};for(let[u,d]of Object.entries(o))u.startsWith("field.")&&u.length>6&&n(d)?c[u.slice(6)]=d:u.startsWith("field_in.")&&u.length>9&&Array.isArray(d)&&(a[u.slice(9)]=d.filter(n));return{fields:c,field_in:a}},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"&&Fl.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 c of e.any_of){if(!c||typeof c!="object"||Array.isArray(c))continue;let a=c,u={};typeof a.item_type=="string"&&a.item_type&&(u.item_type=a.item_type);let d=r(a);Object.keys(d.fields).length&&(u.fields=d.fields),Object.keys(d.field_in).length&&(u.field_in=d.field_in),Object.keys(u).length&&o.push(u)}o.length&&(s.any_of=o)}return Rn(s)?{...s,...t}:null}async function xn(e,t={}){if(e=gt(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(Ol)),Object.keys(r).length>0&&(n.filters=r),e.limit!=null&&(n.limit=e.limit);try{let s=await C("query",n,t);e.spaceIds!==void 0&&Sa(e.spaceIds,s.selected_space_ids??s.content?.selected_space_ids);let i=or(s);for(let o of i)O().setQueryData(P.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 ql(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 Na(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:ql(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 ir(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 Ka(e,t){try{let n={channel_path:e};t&&(n.parent_message_id=t);let s=await C("get-channel-messages",n),i=s.messages||s.content?.items||s.items||[];return ir(i)}catch(n){return console.error(`[gateway] Failed to fetch channel messages for ${e}:`,n),[]}}async function as(e,t){try{let n={channel_path:e};t&&(n.parent_message_id=t);let s=await C("get-channel-messages",n),i=s.messages||[],o=ir(i),c=Na(i),a=new Map,u=[];for(let d of c)if(d.parentMessagePath){let p=a.get(d.parentMessagePath)||[];p.push(d),a.set(d.parentMessagePath,p)}else u.push(d);return{messages:o,activityMessages:ir(s.activity_messages||[]),messageCards:a,siblingCards:u,mode:s.mode||"top_level"}}catch(n){return console.error(`[gateway] Failed to fetch channel messages with cards for ${e}:`,n),{messages:[],messageCards:new Map,siblingCards:[],mode:"top_level"}}}async function lr(e,t){try{let n={channel_path:e};t?.parentMessageId&&(n.parent_message_id=t.parentMessageId),t?.limit&&(n.limit=t.limit),t?.before_seq!=null&&(n.before_seq=t.before_seq),t?.after_seq!=null&&(n.after_seq=t.after_seq);let s=await C("get-channel-messages",n),i=s.messages||[],o=Na(i),c=new Map,a=[];for(let u of o)if(u.parentMessagePath){let d=c.get(u.parentMessagePath)||[];d.push(u),c.set(u.parentMessagePath,d)}else a.push(u);return{messages:ir(i),activityMessages:ir(s.activity_messages||[]),messageCards:c,siblingCards:a,mode:s.mode||"top_level"}}catch(n){return console.error(`[gateway] Failed to fetch channel messages page for ${e}:`,n),{messages:[],messageCards:new Map,siblingCards:[],mode:"top_level"}}}function Yr(e){O().invalidateQueries({queryKey:P.children(e)})}function vi(e){O().invalidateQueries({queryKey:P.item(e)})}function La(e,t){vi(e),Yr(e);let n=e.split("/");n.pop();let r=n.join("/")||t;r&&Yr(r)}function ja(e){let t=e+"/";O().invalidateQueries({predicate:n=>{let r=n.queryKey;return r[0]!=="vfs"?!1:r.some(s=>typeof s=="string"&&(s===e||s.startsWith(t)))}})}function Va(){O().invalidateQueries({queryKey:P.all()})}function $a(e){O().invalidateQueries({queryKey:P.types(e)})}function Wa(e,t){e?O().invalidateQueries({queryKey:P.channelMessages(e,t)}):O().invalidateQueries({queryKey:P.allChannelMessages()})}function Ba(e,t){e&&t?O().invalidateQueries({queryKey:P.openEnvelope(e,t)}):e?O().invalidateQueries({predicate:n=>{let r=n.queryKey;return r[0]==="vfs"&&r[2]==="open"&&r[3]===e}}):O().invalidateQueries({queryKey:P.allOpenEnvelopes()})}function Ve(e){return{id:e.accountId,path:e.path,kind:e.isSpace?"space":"account",name:e.name,grantedUnderAccountId:e.grantedUnderAccountId??void 0}}async function cs(){return((await C("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,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 Cn=new Map,dr=null,us=null,_t=new Map,Ha=250;function Qt(e){if(dr){Pn(e);return}Pn(e),dr=ne("vfs_change",t=>Ql(t)),us=ne("ccm_change",t=>Dl(t))}function Pn(e){if(Cn.has(e))return;let t=Sn(e,["vfs_change","ccm_change"]);Cn.set(e,t)}function ls(e){let t=Cn.get(e);t&&(t(),Cn.delete(e))}function bi(){for(let[,e]of Cn)e();Cn.clear(),dr&&(dr(),dr=null),us&&(us(),us=null),_t.forEach(e=>clearTimeout(e)),_t.clear()}te(bi);function Ql(e){let t=e.path,n=e.action;if(!t)return;let r=t.split("/");r.pop();let s=r.join("/")||"/root",i=_t.get(s);i&&clearTimeout(i);let o=setTimeout(()=>{_t.delete(s),Ul(n,t,e,s)},Ha);_t.set(s,o)}function Dl(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=_t.get(s);i&&clearTimeout(i);let o=setTimeout(()=>{_t.delete(s),t&&O().invalidateQueries({queryKey:P.edges(t)}),n&&O().invalidateQueries({queryKey:P.edges(n)})},Ha);_t.set(s,o)}function Ul(e,t,n,r){if((e||"").toUpperCase()==="DELETE")O().removeQueries({queryKey:P.item(t)}),O().removeQueries({queryKey:P.children(t)}),O().removeQueries({queryKey:P.tree(t)});else if(n.item_id)try{let i={id:n.item_id,path:n.path,name:n.name,item_type:n.item_type,parent_id:n.parent_id,scope_item_id:n.scope_item_id},o=_e(i);o&&o.id&&O().setQueryData(P.item(t),o)}catch{}O().invalidateQueries({queryKey:P.children(r)}),O().invalidateQueries({predicate:i=>{let o=i.queryKey;if(o[0]!=="vfs"||o[1]!=="tree")return!1;let c=o[2];return t.startsWith(c+"/")||t===c}}),n.item_id&&O().invalidateQueries({queryKey:P.itemById(n.item_id)})}var Tn=null;te(()=>{Tn=null});function vt(e){if(e!==Tn||e.generation!==se())throw new Error("Workspace session changed")}function Nl(e){return e instanceof Ie&&e.payload?.error==="item_not_found"}function fr(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=fe();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 Ga(e,t){return JSON.stringify({mounts:e.map(n=>n.id),last_anchor:t.id})}async function za(e,t,n){vt(e);let r=Ga(t,n);if(e.saved===r)return;let s=JSON.parse(r);await C(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}),vt(e),e.exists=!0,e.saved=r}function Ja(e,t){let n=Te();Qt(fe().id);for(let r of n)e.some(s=>s.id===r.id)||ls(r.id);for(let r of e)Pn(r.id);jo(e,t)}async function Dt(e,t,n={}){let r=fe();if(!r)throw new Error("Elect a home account before loading mounts");let s=`${e}/settings/mounts`;if(Tn&&Tn.path!==s)throw new Error("Reset the session before changing the mount declaration owner");let i=Tn??(Tn={generation:se(),path:s,scope:r.path,resolve:t,exists:!1,ready:!1,saved:null,queue:Promise.resolve()});return vt(i),i.loading?i.loading:i.ready?Te():(i.resolve=t,i.loading=(async()=>{let o=null;try{let d=await C("read",{path:s,_scope_path:i.scope});if(vt(i),o=d.type_data??d.item?.type_data,!o||!Array.isArray(o.mounts)||!o.mounts.every(p=>typeof p=="string"))throw new Error("Invalid saved mount declaration");i.exists=!0}catch(d){if(vt(i),!Nl(d))throw d;i.exists=!1}let c=n.initialAnchor?fr(i,n.initialAnchor):r,a=pr(o?o.mounts.map(t).filter(d=>d!==null):[c]),u=o?a.find(d=>d.id===o.last_anchor)??a.find(d=>d.kind==="space")??r:c;return o?i.saved=Ga(a,u):n.initialAnchor&&await za(i,a,u),vt(i),i.ready=!0,Ja(a,u),a})().finally(()=>{i.loading=void 0}),i.loading)}function ds(e){let t=Tn;if(!t?.ready)return Promise.reject(new Error("Workspace mounts are not loaded"));let n=t.queue.then(async()=>{vt(t);let{refs:r,anchor:s}=e(t);await za(t,r,s),vt(t),Ja(r,s)});return t.queue=n.catch(()=>{}),n}function wi(e){return ds(t=>({refs:pr([...Te(),fr(t,e)]),anchor:ye()}))}function Ya(e){return ds(()=>{if(e===fe().id)throw new Error("The home account cannot be unmounted");let t=pr(Te().filter(r=>r.id!==e)),n=t.find(r=>r.id===ye()?.id)??t.find(r=>r.kind==="space")??fe();return{refs:t,anchor:n}})}function mr(e){return ds(t=>{let n=fr(t,e);return{refs:pr([...Te(),n]),anchor:n}})}function fs(e,t){return ds(n=>{let r=pr(e.map(i=>fr(n,i))),s=fr(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}})}function ps(e){if(typeof e.path!="string")return!1;let t=[...Te().map(n=>n.path),ye()?.path].filter(n=>!!n);return!t.length&&H()&&t.push(H()),t.some(n=>pe(e.path,n))}function Si(e,t,n,r){if(!["message","card"].includes(e?.item_type)||!pe(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&&pe(e.path,i)})}var Xa=new WeakMap;function Za(e,t,n){let r=Xa.get(e);r||(r=new Map,Xa.set(e,r));let s=JSON.stringify(t),i=r.get(s);if(!i){let c=!1,a,u=!1,d=!1,p=new Set,m=new Set,f=()=>e.getQueryData(t)??[],y=()=>{c||u||a||(a=setTimeout(()=>{a=void 0,g()},250))},g=async()=>{if(c)return;u=!0;let I=d;d=!1;let R=[...p],M=new Set(m);m.clear(),p.clear();try{if(I)await Ae(e,t,{exact:!0});else{let S=(await Promise.allSettled(R.map(async T=>{let F=e.getQueryCache().find({queryKey:t,exact:!0});if(!F)return;let k=await C("read",{id:T});if(k.success===!1)throw new Error("Channel refresh failed");if(c||!F||e.getQueryCache().find({queryKey:t,exact:!0})!==F)return;let A=_e(k.item??k);if(A.id!==T||A.item_type!=="channel")return;let U=f().find(B=>B.id===T);if(!U)return;let Q=n({...A}),ue={...U,path:Q.path,name:Q.name,displayName:Q.displayName,messageCount:Q.messageCount,aiMode:Q.aiMode,activeAgentIds:Q.activeAgentIds,isPrivate:Q.isPrivate,isDm:Q.isDm,autoPilot:Q.autoPilot,isArchived:Q.isArchived,updatedAt:Q.updatedAt};M.has(T)&&(U.name!==ue.name||U.displayName!==ue.displayName||U.path!==ue.path)&&(d=!0),e.setQueryData(t,B=>B?.map(qe=>qe.id===T?ue:qe))}))).find(T=>T.status==="rejected");if(S?.status==="rejected")throw S.reason}}catch(N){console.warn("[channels] refresh failed",N)}finally{u=!1,(d||p.size)&&y()}},h=I=>f().some(R=>R.id===I.item_id||R.path===I.path)?!0:ps(I),v=I=>{if(!h(I))return;let R=String(I.action??"").toLowerCase();if(["insert","delete","rename","move"].includes(R))d=!0;else if(R==="update"){let M=f().find(N=>N.id===I.item_id||N.path===I.path);M&&(p.add(M.id),m.add(M.id))}(d||p.size)&&y()},b=I=>{let R=f().find(M=>M.id===I.parent_id);R&&(p.add(R.id),y())},E=["vfs_change","ccm_change"].flatMap(I=>[ne(I,v,R=>R.item_type==="channel"),ne(I,b,R=>R.item_type==="message")]);i={users:0,stop:()=>{c=!0,a&&clearTimeout(a),E.forEach(I=>I())}},r.set(s,i)}i.users++;let o=!1;return()=>{o||(o=!0,--i.users===0&&(i.stop(),r.delete(s)))}}function Y(){return(0,_.useSyncExternalStore)(we,Z,Z)}function ic(){return Y(),Dr()}function oc(e){return Y(),V({queryKey:P.item(e),queryFn:()=>ar(e),enabled:!!e,staleTime:1/0})}function ac(e){return Y(),V({queryKey:P.itemById(e),queryFn:()=>Xr(e),enabled:!!e,staleTime:1/0})}function xi(e){return Y(),V({queryKey:P.children(e),queryFn:()=>cr(e),enabled:!!e})}function cc(e){let t=xi(e);return{...t,children:t.data??[]}}function uc(e,t=1){return Y(),V({queryKey:P.tree(e,t),queryFn:()=>ns(e,t),enabled:!!e})}function lc(e,t){return Y(),V({queryKey:P.search(e,t),queryFn:async()=>{let n={query:e};t?.length&&(n.item_types=t);let r=await C("search",n);return(r.content?.items||r.items||r.results||[]).map(_e)},enabled:!!e&&e.length>0})}function dc(e){Y();let t=(0,_.useMemo)(()=>e,[JSON.stringify(e)]);return V({queryKey:["vfs",H()??"__unscoped__","resolve",JSON.stringify(t??{})],queryFn:async()=>await C("resolve",t),enabled:!!t?.query&&t.query.length>0})}function fc(e){Y();let t=gt(e),n=(0,_.useMemo)(()=>t,[JSON.stringify(t)]),r=V({queryKey:P.items(n?.type??"",n),queryFn:({signal:s})=>xn(n,{signal:s,throwOnError:!0}),enabled:Rn(n),...n?.spaceIds!==void 0?{retry:(s,i)=>!gn(i)&&eu(s,i)}:{},select:s=>s.items});return n?.spaceIds!==void 0&&gn(r.error)?{...r,data:void 0}:r}function Ci(e,t={}){let n=Y(),{realtime:r=!1}=t,s=gt(e),i=s?.limit??20,o=(0,_.useMemo)(()=>s,[JSON.stringify(s)]),c=(0,_.useMemo)(()=>["vfs",H()??"__unscoped__","infinite-items",o?.type??"",JSON.stringify(o??{})],[n,o]),a=Jn({queryKey:c,queryFn:async({pageParam:p=0,signal:m})=>xn({...o,limit:i,offset:p},{throwOnError:!0,signal:m,priority:t.priority}),initialPageParam:0,getNextPageParam:(p,m,f)=>{if(!(o?.spaceIds!==void 0&&p.total_hint!==void 0&&f+p.items.length>=p.total_hint)&&!(p.items.length<i))return f+p.items.length},enabled:Rn(o),...o?.spaceIds!==void 0?{retry:(p,m)=>!gn(m)&&eu(p,m)}:{},staleTime:r?1/0:t.staleTime,meta:r&&o?{infiniteItemsRealtime:{filter:o}}:{}}),u=(0,_.useMemo)(()=>{if(o?.spaceIds!==void 0&&gn(a.error))return[];if(!a.data?.pages)return[];let p=new Set,m=[];for(let f of a.data.pages)for(let y of f.items)y.id&&!p.has(y.id)&&(p.add(y.id),m.push(y));return m},[a.data?.pages,a.error,o]),d=o?.spaceIds!==void 0&&gn(a.error);return{allItems:u,refetch:a.refetch,fetchNextPage:a.fetchNextPage,isFetchingNextPage:a.isFetchingNextPage,isExhausted:d||!a.hasNextPage,isLoading:a.isLoading,isFetching:a.isFetching,error:a.error,totalHint:d?void 0:a.data?.pages?.[0]?.total_hint}}function ec(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 jl(e,t){if(e.is_active===!1||e.item_type!==t.type||!pe(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 pc(e,t={}){let n=ec(e),r=Ci(e,n?{realtime:!1,staleTime:3e4}:{realtime:!0}),s=$(),i=JSON.stringify([H(),gt(e)]),[o,c]=(0,_.useState)(()=>({identity:i,upserts:{},deleted:new Set})),a=o.identity===i?o:{identity:i,upserts:{},deleted:new Set},u=(0,_.useMemo)(()=>{if(!n)return r.allItems;let f=Object.values(a.upserts),y=new Set(f.map(b=>b.id)),g=[...f,...r.allItems.filter(b=>!y.has(b.id))].filter(b=>!a.deleted.has(b.path)),h=e.sort_by??"updated_at",v=e.sort_dir==="asc"?1:-1;return g.sort((b,E)=>v*String(b[h]??"").localeCompare(String(E[h]??"")))},[n,r.allItems,a,e?.sort_by,e?.sort_dir]),d=(0,_.useRef)(u);d.current=u;let p=(0,_.useRef)(t.shouldReadUpdate);p.current=t.shouldReadUpdate;let m=(0,_.useRef)(r.refetch);return m.current=r.refetch,(0,_.useEffect)(()=>{if(!ec(e))return;let f=e,y=!1,g=!1,h=!1,v=0,b=new Map,E=()=>{let S=v;m.current().then(T=>{!y&&!T.isError&&v===S&&c({identity:i,upserts:{},deleted:new Set})})},I=S=>{v++,c(F=>{let k=F.identity===i?F:{identity:i,upserts:{},deleted:new Set},A={...k.upserts};return delete A[S],{identity:i,upserts:A,deleted:new Set(k.deleted).add(S)}});let T=b.get("__reconcile__");T&&clearTimeout(T),b.set("__reconcile__",setTimeout(()=>{b.delete("__reconcile__"),E()},250))},R=S=>{let T=b.get(S);T&&clearTimeout(T),b.set(S,setTimeout(()=>{b.delete(S),s.fetchQuery({queryKey:P.item(S),queryFn:()=>ar(S),staleTime:0}).then(F=>{if(!y){if(!F||!jl(F,f)){let k=d.current.find(A=>A.path===S||A.id===F?.id);k&&I(k.path);return}c(k=>{let A=k.identity===i?k:{identity:i,upserts:{},deleted:new Set},U=new Set(A.deleted);return U.delete(S),{identity:i,upserts:{...A.upserts,[S]:F},deleted:U}})}}).catch(F=>console.warn("[useIncrementalItems] item read failed:",F))},250))},M=ne("vfs_change",S=>{if(!S||typeof S.path!="string"&&typeof S.old_path!="string")return;let T=typeof S.path=="string"?S.path:S.old_path,F=d.current.find(A=>A.path===T||A.path===S.old_path||S.item_id&&A.id===S.item_id),k=!!F;if(!(!pe(T,f.scope)&&!pe(S.old_path,f.scope)&&!k)&&!(S.item_type&&S.item_type!==f.type&&!k)&&!(f.parent_id&&S.parent_id&&S.parent_id!==f.parent_id&&!k)){if(F&&(T!==F.path||S.old_path&&S.old_path!==T||S.parent_id&&S.parent_id!==F.parent_id||S.item_type&&S.item_type!==f.type)){I(F.path);return}if(!F&&S.old_path&&S.old_path!==T&&pe(T,f.scope)){v++,R(T);return}if(S.action==="insert")v++,R(T);else if(S.action==="move")v++,R(T);else if(S.action==="update"){if(!p.current?.(S,d.current))return;v++,R(T)}else S.action==="delete"&&I(F?.path??S.old_path??T)}}),N=Jr(S=>{if(S!=="connected"){g&&(h=!0);return}g=!0,h&&(h=!1,E())});return()=>{y=!0,M(),N(),b.forEach(clearTimeout)}},[s,i]),{...r,allItems:u}}function mc(e){Y();let t=20,n=Jn({queryKey:["vfs",H()??"__unscoped__","infinite-children",e??""],queryFn:async({pageParam:s=0})=>Zr(e,t,s),initialPageParam:0,getNextPageParam:(s,i,o)=>{if(!(s.items.length<t))return o+s.items.length},enabled:!!e});return{allItems:(0,_.useMemo)(()=>{if(!n.data?.pages)return[];let s=new Set,i=[];for(let o of n.data.pages)for(let c of o.items)c.id&&!s.has(c.id)&&(s.add(c.id),i.push(c));return i},[n.data?.pages]),fetchNextPage:n.fetchNextPage,isFetchingNextPage:n.isFetchingNextPage,isExhausted:!n.hasNextPage,isLoading:n.isLoading,isFetching:n.isFetching,error:n.error,totalHint:n.data?.pages?.[0]?.total_hint}}function hc(e){return Y(),V({queryKey:P.edges(e),queryFn:()=>ts(e),enabled:!!e})}function ms(e){return Y(),V({queryKey:P.types(e),queryFn:()=>es(e)})}function gc(e,t){let n=ms(t);return{...n,data:n.data?.get(e)??void 0}}function yc(e,t){Y();let n=(0,_.useMemo)(()=>t?.arguments,[JSON.stringify(t?.arguments)]),r=t?.mode,s=t?.strategy,i=t?.width;return V({queryKey:[...P.openEnvelope(e,s),i],queryFn:async()=>{let o=await os(e,{mode:r,strategy:s,arguments:n});if(i&&o.render?.props?.url){let c=o.render.props.url,a=c.includes("?")?"&":"?";o.render.props.url=`${c}${a}w=${i}`}return o},enabled:!!e})}var tc={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=ms(e),n=t.data??new Map;return(0,_.useMemo)(()=>({canHaveChildren:f=>n.get(f.item_type)?.is_container??!1,isScope:f=>n.get(f.item_type)?.is_scope??!1,isScopeType:f=>n.get(f)?.is_scope??!1,isContainerType:f=>n.get(f)?.is_container??!1,getTypeDefinition:f=>n.get(f),getTypeColor:f=>n.get(f)?.color??"gray",getTypeIcon:f=>n.get(f)?.icon??"File",getTypeDisplayName:f=>n.get(f)?.display_name??f,getKnownEdgeTypes:()=>Object.entries(tc).map(([f,y])=>({key:f,label:y})),getEdgeTypeLabel:f=>tc[f]??f.replace(/_/g," "),allTypes:n,loading:t.isLoading}),[n,t.isLoading])}function vc(e,t,n){return Y(),V({queryKey:P.memberFocus(e),queryFn:()=>is(e,t,n),enabled:!!e})}function bc(e,t={}){let{limit:n=50,offset:r=0,include_snapshots:s=!1}=t;return V({queryKey:P.itemVersions(e,String(n),String(r),String(s)),queryFn:()=>ur(e,{limit:n,offset:r,include_snapshots:s}),enabled:!!e})}function wc(e,t=50,n=0){return V({queryKey:P.itemHistory(e,String(t),String(n)),queryFn:()=>ss(e,t,n),enabled:!!e})}function Sc(e,t=50,n=0){return Y(),V({queryKey:P.recentActivity(e,String(t),String(n)),queryFn:()=>rs(e,t,n),enabled:!!e})}function Rc(){let[e,t]=(0,_.useState)(null),[n,r]=(0,_.useState)(!0),[s,i]=(0,_.useState)(null);return(0,_.useEffect)(()=>{let o=!1;return Xe().then(c=>{if(!o){let a=typeof window<"u"&&window.__FSAOS_CONFIG__||{};t({path:c.scope_path,scope_id:c.scope_id,fractal_id:c.fractal_id,instance_name:c.instance_name,display_name:c.display_name,componentPath:a.componentPath||"",isEmbed:!!a.embedToken}),r(!1)}}).catch(c=>{o||(i(c instanceof Error?c:new Error(String(c))),r(!1))}),()=>{o=!0}},[]),{data:e,loading:n,error:s}}var Vl=[];function nc(){if(typeof window>"u")return!1;let e=window.__FSAOS_CONFIG__?.embedToken;return typeof e=="function"||typeof e=="string"&&e.length>0}function $l(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 xc(){let{user:e}=hs(),t=(0,_.useSyncExternalStore)(Wo,ai,ai),n=ht()?.principal_id??null,r=(0,_.useRef)(null),[s,i]=(0,_.useState)(null),[o,c]=(0,_.useState)(null);(0,_.useEffect)(()=>{if(n){c(null);return}if(!e?.id&&!nc()){c(null);return}let b=!1;return Xe().then(E=>{b||E.principal_id||c(new Error("Memberships require an authenticated principal"))}).catch(E=>{b||c(E instanceof Error?E:new Error(String(E)))}),()=>{b=!0}},[n,e?.id,t]);let a=V({queryKey:P.memberships(n??"anonymous"),queryFn:cs,enabled:!!n,staleTime:1e3*60*2}),u=a.data??Vl,d=(0,_.useMemo)(()=>u.filter(b=>b.isAccount!==!1&&!b.isSpace),[u]),p=(0,_.useMemo)(()=>{let b=new Set(d.map(I=>I.accountId)),E=I=>!I.subordinateTo||!b.has(I.subordinateTo);return[...d].sort((I,R)=>Number(E(R))-Number(E(I)))},[d]),m=(0,_.useSyncExternalStore)(we,Z,Z),f=(0,_.useMemo)(()=>{let b=ye();return b?u.find(E=>E.accountId===b.id)??null:null},[m,u]),y=(0,_.useMemo)(()=>$l(d),[d]);(0,_.useEffect)(()=>{if(!n){r.current=null;return}if(r.current!==n)if(i(null),p.length===1){let b=p[0];fe()||Mt(Ve(b)),Qt(b.accountId),b.personalSpacePath&&Dt(b.personalSpacePath,E=>{let I=u.find(R=>R.accountId===E);return I?Ve(I):null}).catch(i),r.current=n}else p.length>1&&(r.current=n)},[n,p,u]);let g=(0,_.useCallback)(async b=>{let E=u.find(M=>M.path===b);if(!E)throw new Error("Account membership is unavailable");let I=Ve(E);fe()||Mt(I);let R=u.find(M=>M.accountId===fe()?.id);if(!R?.personalSpacePath)throw new Error("The home membership has no mount declaration location");await Dt(R.personalSpacePath,M=>{let N=u.find(S=>S.accountId===M);return N?Ve(N):null}),await mr(I),i(null),Qt(E.accountId)},[u]),h=(0,_.useCallback)(async b=>{let E=u.find(I=>I.path===b);if(!E)throw new Error("Scope membership is unavailable");await wi(Ve(E))},[u]),v=(!!e?.id||nc())&&!n&&!o;return{accounts:p,switcherAccounts:y,allMemberships:u,currentAccount:f,mountedScope:null,switchAccount:g,mountScope:h,loading:v||a.isLoading,error:o??a.error??s}}function Cc(){Y();let e=(0,_.useSyncExternalStore)(Qr,tr,tr),t=(0,_.useMemo)(()=>Te(),[e]),n=ye(),r=(0,_.useMemo)(()=>t.filter(i=>i.kind==="space"&&(n?.kind==="account"||i.id===n?.id)),[t,n]),s=(0,_.useMemo)(()=>r.map(i=>i.id).sort(),[r]);return{mounts:t,selectedSpaces:r,readSpaceIds:s,homeAnchor:fe(),anchor:n,setAnchor:mr,replaceMounts:fs,mount:wi,unmount:Ya}}function hs(){let[e,t]=(0,_.useState)(null),[n,r]=(0,_.useState)(null),[s,i]=(0,_.useState)(!0),o=(0,_.useRef)(null);(0,_.useEffect)(()=>{W.auth.getSession().then(({data:f,error:y})=>{if(y){console.warn("[useAuth] getSession error, clearing stale session:",y.message),W.auth.signOut().catch(()=>{}),r(null),t(null),i(!1);return}r(f?.session??null),t(f?.session?.user??null),i(!1)}).catch(f=>{console.warn("[useAuth] getSession threw, clearing stale session:",f?.message),W.auth.signOut().catch(()=>{}),r(null),t(null),i(!1)});let{data:{subscription:m}}=W.auth.onAuthStateChange((f,y)=>{if(f==="TOKEN_REFRESHED"&&!y){console.warn("[useAuth] TOKEN_REFRESHED with null session \u2014 signing out"),W.auth.signOut().catch(()=>{}),r(null),t(null),i(!1);return}r(y),t(y?.user??null),i(!1)});return o.current=m,()=>{m?.unsubscribe()}},[]);let c=(0,_.useCallback)(async m=>m.provider?W.auth.signInWithOAuth({provider:m.provider,options:m.redirectTo?{redirectTo:m.redirectTo}:{redirectTo:window.location.href}}):W.auth.signInWithPassword({email:m.email,password:m.password}),[]),a=(0,_.useCallback)(async m=>W.auth.signUp({email:m.email,password:m.password,options:{data:m.metadata||{}}}),[]),u=(0,_.useCallback)(async()=>{await W.auth.signOut(),mn(),O().clear()},[]),d=(0,_.useCallback)(async m=>{let{error:f}=await W.auth.resetPasswordForEmail(m);if(f)throw f},[]),p=(0,_.useCallback)(async(m,f)=>{let{error:y}=await W.auth.signInWithOtp({email:m,options:f?{emailRedirectTo:f}:{emailRedirectTo:window.location.href}});if(y)throw y},[]);return{user:e,session:n,loading:s,signIn:c,signUp:a,signOut:u,resetPassword:d,signInWithMagicLink:p}}function Pc(e){let[t,n]=(0,_.useState)(null),[r,s]=(0,_.useState)(!1),[i,o]=(0,_.useState)(null);return(0,_.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),C("resolve-asset",{asset_id:e}).then(a=>{a.success&&a.public_url?n({url:a.public_url,id:a.asset_id,name:a.name,mimeType:a.mime_type,width:a.width,height:a.height,sizeBytes:a.size_bytes}):o(new Error(a.error||"Asset not found")),s(!1)}).catch(a=>{o(a instanceof Error?a:new Error(String(a))),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 hr={},rc={};te(()=>{for(let e of Object.keys(hr))delete hr[e]});var Tc=null;function Ec(e){Tc=e,typeof window<"u"&&!window.__FSAOS_GATEWAY__&&(window.__FSAOS_GATEWAY__=e)}function Wl(e){switch(e){case"react":return typeof window<"u"&&window.React||_.default;case"react-dom":case"react-dom/client":return typeof window<"u"&&window.ReactDOM||Kl;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}:Ll;case"@fsaos/gateway":case"@fsaos/react":return typeof window<"u"&&window.__FSAOS_GATEWAY__||Tc||{};case"@fsaos/ui":return typeof window<"u"&&window.__FSAOS_UI__||{};case"@fsaos/theme":return{};default:return console.warn(`[useComponent] Unknown module requested: ${e}`),{}}}function Bl(e,t){return e.replace(/^(\s*)(:root|body)(\s*[{,])/gm,(n,r,s,i)=>`${r}.${t}${i}`)}async function Hl(e,t){if(!rc[e])try{let n=await fetch(e);if(!n.ok)return;let r=await n.text();if(!r.trim()||r.includes("No CSS bundle for this component"))return;t&&!r.includes(`.fsaos-c-${t}`)&&(r=Bl(r,`fsaos-c-${t}`));let s=document.createElement("style");s.setAttribute("data-fsaos-component-css",e),t&&s.setAttribute("data-fsaos-component-id",t),s.textContent=r,document.head.appendChild(s),rc[e]=s}catch{}}function Gl(e){let t=null,n=window.__FSAOS_REGISTER__;window.__FSAOS_REGISTER__=r=>{t=r};try{let r=["var require = arguments[0];",e,"return window.__FSAOS_COMPONENT__;"].join(`
|
|
3
|
+
`),i=new Function(r)(Wl),o=t??i;return o?o.default||o:null}finally{n!==void 0?window.__FSAOS_REGISTER__=n:delete window.__FSAOS_REGISTER__}}function Pi(e){let[t,n]=(0,_.useState)(null),[r,s]=(0,_.useState)(!0),[i,o]=(0,_.useState)(null);return(0,_.useEffect)(()=>{if(!e)return;let c=!1;s(!0),o(null);let u=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"";return(async()=>{try{let d=1,p=e+"@v1",m=u+e+"/__bundle.js";try{let v=await fetch(u+e+"/__meta",{cache:"no-store"});v.ok&&(d=(await v.json()).version||1,p=e+"@v"+d,m=u+e+"/__bundle.v"+d+".js")}catch{m=u+e+"/__bundle.js?v="+Date.now()}if(c)return;if(hr[p]){n(()=>hr[p]),s(!1);return}let f=await fetch(m);if(!f.ok)throw new Error(`Failed to fetch bundle: ${f.status} ${f.statusText} (${m})`);let y=await f.text();if(c)return;let g=m.replace(/__bundle(\.v\d+)?\.js(\?.*)?$/,"__bundle$1.css");Hl(g).catch(()=>{});let h=Gl(y);if(!h)throw new Error("Bundle did not export a component. Expected window.__FSAOS_COMPONENT__ (FSAOS build) or a __FSAOS_REGISTER__(Component) call.");if(typeof h!="function")throw new Error(`Bundle export is not a React component (got ${typeof h})`);hr[p]=h,c||(n(()=>h),s(!1))}catch(d){c||(o(d instanceof Error?d:new Error(String(d))),s(!1))}})(),()=>{c=!0}},[e]),{Component:t,loading:r,error:i}}var zl=["--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 Ic(){return{data:(0,_.useMemo)(()=>{if(typeof document>"u")return{tokens:{}};let t={},n=getComputedStyle(document.documentElement);return zl.forEach(r=>{t[r]=n.getPropertyValue(r).trim()}),{tokens:t}},[]),loading:!1,error:null}}function Ac(e,t){return{data:{allowed:!0},loading:!1,error:null}}function kc(e,t){let n={};return(t||[]).forEach(r=>{n[r]=!0}),{data:n,loading:!1,error:null}}var ce=null,En=null,Ri=new Set;function Jl(){Ri.forEach(e=>e())}te(()=>{ce=null,En=null});async function Mc(e){let t={principalId:null,displayName:null,createdAt:null,metadata:null,vfsPath:null},n=ht()?.principal_id??null;if(n){if(ce&&ce.principalId===n){let{principalId:s,displayName:i,createdAt:o,metadata:c,vfsPath:a}=ce;return{principalId:s,displayName:i,createdAt:o,metadata:c,vfsPath:a}}return{...t,principalId:n}}let r=e;if(!r){let{data:s}=await W.auth.getSession();r=s?.session?.user?.id}if(!r)return t;if(ce&&ce.authUserId===r){let{principalId:s,displayName:i,createdAt:o,metadata:c,vfsPath:a}=ce;return{principalId:s,displayName:i,createdAt:o,metadata:c,vfsPath:a}}return En||(En=(async()=>{try{let{data:s,error:i}=await W.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,c=null;if(o){let{data:u}=await W.from("os_items").select("path").eq("owner_principal_id",o).eq("item_type","principal").eq("is_active",!0).like("path","/root/principals/%"),d=(u??[]).map(p=>p.path);c=d.find(p=>p.split("/").length===4)??d[0]??null}let a={principalId:o,displayName:s?.display_name??null,createdAt:s?.created_at??null,metadata:s?.metadata??null,vfsPath:c};return ce={authUserId:r,...a},a}finally{En=null}})(),En)}async function Oc(e){return(await Mc(e)).principalId}function Fc(){let e=hs(),t=e.user,n=ce?.authUserId===t?.id?ce:null,[r,s]=(0,_.useState)(n),i=(0,_.useRef)(null);return(0,_.useEffect)(()=>{let o=()=>{let c=ce;c&&c.authUserId===t?.id&&s({principalId:c.principalId,displayName:c.displayName,createdAt:c.createdAt,metadata:c.metadata,vfsPath:c.vfsPath})};return Ri.add(o),()=>{Ri.delete(o)}},[t?.id]),(0,_.useEffect)(()=>{if(!t?.id){s(null),i.current=null;return}i.current===t.id&&r?.principalId!=null||(i.current=t.id,Mc(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 qc(){return{data:null,loading:!1,error:null}}function Qc(e){let{path:t,...n}=e,r=Pi(t),s=r.Component,{loading:i,error:o}=r;return i?(0,_.createElement)("div",{className:"fsaos-loading"},""):o?(0,_.createElement)("div",{className:"fsaos-error"},"Failed to load component"):s?(0,_.createElement)(s,n):null}function Dc(e){return e.children}function Uc(e){let t=Y(),{channelPath:n,parentMessageId:r,realtime:s=!0,enabled:i}=e,o=i!==void 0?i&&!!n:!!n,c=(0,_.useMemo)(()=>P.channelMessages(n??"",r),[n,r,t]),a=$(),u=(0,_.useRef)(null),d=V({queryKey:c,queryFn:()=>as(n,r),enabled:o});(0,_.useEffect)(()=>{if(!s||!o)return;let g=ne("vfs_change",()=>{u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{Ae(a,c,{exact:!0})},500)},h=>{let v=a.getQueryData(c);return Si(h,n,r,[...v?.messages??[],...v?.activityMessages??[]])});return()=>{g(),u.current&&clearTimeout(u.current)}},[s,o,n,r,c,a]);let p=d.data,m=p?.messages??[],f=p?.messageCards??new Map,y=p?.siblingCards??[];return{messages:m,activityMessages:p?.activityMessages??[],messageCards:f,siblingCards:y,threads:(0,_.useMemo)(()=>m.filter(g=>g.reply_count>0),[m]),breakouts:(0,_.useMemo)(()=>m.filter(g=>g.member_count>0),[m]),isLoading:d.isLoading,isFetching:d.isFetching,error:d.error,refetch:d.refetch}}function Nc(e){Y();let{channelPath:t,parentMessageId:n,limit:r=50,realtime:s=!0,enabled:i=!0}=e,o=!!n,c=i&&!!t,a=Jn({queryKey:[...P.channelMessages(t||"",n),"infinite",r],queryFn:async({pageParam:g})=>lr(t,{parentMessageId:n,limit:r,before_seq:o?void 0:g,after_seq:o?g:void 0}),initialPageParam:void 0,getNextPageParam:g=>!o||g.messages.length<r?void 0:g.messages[g.messages.length-1]?.seq,getPreviousPageParam:g=>o||g.messages.length<r?void 0:g.messages[0]?.seq,enabled:c}),u=(0,_.useMemo)(()=>{if(!a.data?.pages)return[];let g=new Set,h=[];for(let v of a.data.pages)for(let b of v.messages)g.has(b.id)||(g.add(b.id),h.push(b));return h.sort((v,b)=>v.seq-b.seq)},[a.data?.pages]),{messageCards:d,siblingCards:p}=(0,_.useMemo)(()=>{let g=new Map,h=[];if(!a.data?.pages)return{messageCards:g,siblingCards:h};let v=new Set;for(let b of a.data.pages){for(let[E,I]of b.messageCards)for(let R of I){if(v.has(R.id))continue;v.add(R.id);let M=g.get(E)||[];M.push(R),g.set(E,M)}for(let E of b.siblingCards)v.has(E.id)||(v.add(E.id),h.push(E))}return{messageCards:g,siblingCards:h}},[a.data?.pages]),m=$(),f=(0,_.useRef)(null),y=(0,_.useMemo)(()=>[...P.channelMessages(t||"",n),"infinite",r],[t,n,r]);return(0,_.useEffect)(()=>{if(!s||!t||!c)return;let g=()=>void Ae(m,y,{exact:!0}),h=!1,v=!1,b=!1,E=async()=>{let M=m.getQueryData(y);if(!M?.pages?.length){g();return}let N=0;for(let S of M.pages)for(let T of S.messages)T.seq>N&&(N=T.seq);if(N===0){g();return}try{let S=await lr(t,{parentMessageId:n,limit:r,after_seq:N});if(S.messages.length===0&&S.siblingCards.length===0){g();return}if(S.messages.length>0){let T=Math.min(...S.messages.map(F=>F.seq));if(T>N+1){console.warn(`[useInfiniteChannelMessages] sequence gap detected: maxSeq=${N}, minNewSeq=${T}. Triggering full refetch.`),g();return}}m.setQueryData(y,T=>{if(!T)return T;let F=[...T.pages],k=F.length-1,A=F[k],U=new Set(A.messages.map(Re=>Re.id)),Q=S.messages.filter(Re=>!U.has(Re.id)),ue=[...A.messages,...Q].sort((Re,xs)=>Re.seq-xs.seq),B=new Map(A.messageCards);for(let[Re,xs]of S.messageCards){let Ni=B.get(Re)||[],Hu=new Set(Ni.map(Cs=>Cs.id)),Gu=xs.filter(Cs=>!Hu.has(Cs.id));B.set(Re,[...Ni,...Gu])}let qe=new Set(A.siblingCards.map(Re=>Re.id)),Wu=S.siblingCards.filter(Re=>!qe.has(Re.id)),Bu=[...A.siblingCards,...Wu];return F[k]={...A,activityMessages:S.activityMessages??[],messages:ue,messageCards:B,siblingCards:Bu},{...T,pages:F}})}catch(S){console.warn("[useInfiniteChannelMessages] live tail fetch failed, falling back to full invalidation:",S),g()}},I=async()=>{if(h){v=!0;return}h=!0;try{do v=!1,await E();while(v&&!b)}finally{h=!1}},R=ne("vfs_change",()=>{f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{I()},500)},M=>Si(M,t,n,m.getQueryData(y)?.pages.flatMap(N=>N.messages)??[]));return()=>{b=!0,R(),f.current&&clearTimeout(f.current)}},[s,t,c,y,m,n,r]),{messages:u,activityMessages:a.data?.pages.at(-1)?.activityMessages??[],messageCards:d,siblingCards:p,threads:u.filter(g=>g.reply_count>0),breakouts:u.filter(g=>g.member_count>0),isLoading:a.isLoading,isFetching:a.isFetching,error:a.error,refetch:a.refetch,hasPreviousPage:a.hasPreviousPage??!1,fetchPreviousPage:a.fetchPreviousPage,isFetchingPreviousPage:a.isFetchingPreviousPage??!1,hasNextPage:a.hasNextPage??!1,fetchNextPage:a.fetchNextPage,isFetchingNextPage:a.isFetchingNextPage??!1}}var Kc=["open","active","strict","hand_raise"];function Yl(e){return e==="open"||e==="active"||e==="strict"||e==="hand_raise"?e:e==="on"||e==="auto"?"active":"strict"}function Xl(e){if(Array.isArray(e))return e.filter(t=>typeof t=="string")}function sc(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:Yl(t.ai_mode),activeAgentIds:Xl(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 gs(e={}){let t=Y(),{realtime:n=!0,enabled:r=!0,includeArchived:s=!1}=e,i=$(),o=(0,_.useMemo)(()=>P.channels("all"),[t]),c=V({queryKey:o,queryFn:async()=>((await C("query",{item_type:"channel",include_reader:!0,limit:500})).items||[]).map(sc),enabled:r});return(0,_.useEffect)(()=>{if(!(!n||!r))return Za(i,o,sc)},[n,r,o,i]),{channels:(0,_.useMemo)(()=>(c.data??[]).filter(u=>s||!u.isArchived),[c.data,s]),isLoading:c.isLoading,isFetching:c.isFetching,error:c.error,refetch:c.refetch}}function Lc(e={}){let t=gs(e),n=(0,_.useMemo)(()=>t.channels.filter(r=>!r.isDm),[t.channels]);return{...t,channels:n}}function jc(e={}){let t=gs(e),n=(0,_.useMemo)(()=>t.channels.filter(r=>r.isDm),[t.channels]);return{...t,channels:n}}function Ti(e={}){let t=Y(),{filter:n="all",limit:r=200,realtime:s=!0,enabled:i=!0}=e,o=$(),c=(0,_.useRef)(null),a=(0,_.useMemo)(()=>P.notifications(n,r),[n,r,t]),u=V({queryKey:a,queryFn:async()=>{let p={limit:r};return n==="unread"&&(p.filter="unread"),(await C("get-notifications",p)).notifications||[]},enabled:i});return(0,_.useEffect)(()=>{if(!s||!i)return;let p=["vfs_change","ccm_change"].map(m=>ne(m,()=>{c.current&&clearTimeout(c.current),c.current=setTimeout(()=>{o.invalidateQueries({queryKey:a})},2e3)},f=>f.item_type==="notification"&&ps(f)));return()=>{p.forEach(m=>m()),c.current&&clearTimeout(c.current)}},[s,i,a,o]),{notifications:u.data??[],isLoading:u.isLoading,isFetching:u.isFetching,error:u.error,refetch:u.refetch}}function Vc(e={}){let{channels:t,realtime:n=!0,enabled:r=!0}=e,{notifications:s,isLoading:i,isFetching:o,error:c,refetch:a}=Ti({filter:"unread",limit:200,realtime:n,enabled:r}),u=(0,_.useMemo)(()=>{let f=new Map;for(let y of s)y.is_unread&&y.channel_id&&f.set(y.channel_id,(f.get(y.channel_id)||0)+1);return f},[s]),d=(0,_.useMemo)(()=>{let f=0;return u.forEach(y=>{f+=y}),f},[u]),{dmUnread:p,channelUnread:m}=(0,_.useMemo)(()=>{if(!t)return{dmUnread:0,channelUnread:0};let f=new Set(t.filter(h=>h.isDm).map(h=>h.id)),y=0,g=0;return u.forEach((h,v)=>{f.has(v)?y+=h:g+=h}),{dmUnread:y,channelUnread:g}},[t,u]);return{unreadByChannel:u,totalUnread:d,dmUnread:p,channelUnread:m,isLoading:i,isFetching:o,error:c,refetch:a}}function $c(){let e=$();return de({mutationFn:t=>C("create",t),onSuccess:(t,n)=>{let r=n.parent_path;r&&e.invalidateQueries({queryKey:P.children(r)})}})}function Wc(){let e=$();return de({mutationFn:t=>C("update",t),onSuccess:(t,n)=>{let r=n.path;if(r){e.invalidateQueries({queryKey:P.item(r)});let s=r.split("/");s.pop();let i=s.join("/");i&&e.invalidateQueries({queryKey:P.children(i)})}}})}function Bc(){return de({mutationFn:e=>C("update-principal",e),onSuccess:(e,t)=>{if(!ce)return;let n=e&&typeof e=="object"&&e.metadata?e.metadata:{...ce.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}:{}};ce={...ce,displayName:typeof t.display_name=="string"?t.display_name:ce.displayName,metadata:n},Jl()}})}function Hc(){let e=$();return de({mutationFn:t=>C("delete",t),onSuccess:(t,n)=>{let r=n.path;if(r){e.removeQueries({queryKey:P.item(r)});let s=r.split("/");s.pop();let i=s.join("/");i&&e.invalidateQueries({queryKey:P.children(i)})}}})}function Gc(){let e=$();return de({mutationFn:t=>C("move",t),onSuccess:(t,n)=>{let r=n.path,s=n.new_parent_path;if(r){e.invalidateQueries({queryKey:P.item(r)});let i=r.split("/");i.pop();let o=i.join("/");o&&e.invalidateQueries({queryKey:P.children(o)})}s&&e.invalidateQueries({queryKey:P.children(s)})}})}function zc(){let e=$();return de({mutationFn:t=>C("link",t),onSuccess:(t,n)=>{let r=n.source_id,s=n.target_id;r&&e.invalidateQueries({queryKey:P.edges(r)}),s&&e.invalidateQueries({queryKey:P.edges(s)})}})}function Jc(e,t){let n=$(),{optimistic:r,...s}=t??{};return de({mutationFn:i=>C(e,i),onMutate:r?async i=>{await n.cancelQueries({queryKey:r.queryKey});let o=n.getQueryData(r.queryKey);return n.setQueryData(r.queryKey,c=>r.update(c,i)),{previous:o}}:void 0,onError:(i,o,c)=>{r&&c?.previous!==void 0&&n.setQueryData(r.queryKey,c.previous),s.onError?.(i)},onSuccess:s.onSuccess,onSettled:r?()=>{n.invalidateQueries({queryKey:r.queryKey})}:void 0})}function Yc(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 c=(0,_.useRef)(s),a=(0,_.useRef)(i);(0,_.useEffect)(()=>{c.current=s,a.current=i},[s,i]),(0,_.useEffect)(()=>o?ne(r,d=>c.current(d),a.current?d=>a.current(d):void 0):void 0,[r,o])}function Xc(e){let{queryKey:t,queryFn:n,eventType:r,filter:s,enabled:i=!0,debounceMs:o=500}=e,c=$(),a=(0,_.useRef)(s);a.current=s;let u=(0,_.useRef)(null),d=V({queryKey:t,queryFn:n,enabled:i});return(0,_.useEffect)(()=>{if(!i)return;let p=ne(r,()=>{u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{Ae(c,t,{exact:!0})},o)},m=>a.current?.(m)??!0);return()=>{p(),u.current&&clearTimeout(u.current)}},[r,i,o,c,JSON.stringify(t)]),d}function In(e){Y();let t=H(),n=(0,_.useMemo)(()=>e?typeof e=="string"?{path:e}:e:null,[typeof e=="string"?e:JSON.stringify(e)]),r=!!t&&!!n&&!!(n.key||n.path||n.item_id),s=n?.key??n?.path??n?.item_id??"",i=["vfs",t??"__unscoped__","arrangement",s,n?.scope_id??""],o=V({queryKey:i,staleTime:1/0,retry:!1,meta:{arrangementRealtime:!0},queryFn:async()=>{if(!n)return null;let m=await C("resolve-arrangement",{...n,_scope_path:t});if(m?.success===!1)throw new Error(m?.error||"Arrangement could not be loaded");return m??null},enabled:r}),c=o.data??null,a=(0,_.useMemo)(()=>c?.resolved_children??[],[c]),u=c?.resolution_level??null,d=(0,_.useMemo)(()=>{let f=(c?.type_data??null)?.order;return Array.isArray(f)?f:null},[c]),p=(0,_.useCallback)(m=>{if(!d||!m?.length)return m??[];let f=v=>v.id??v.name??"",y=new Map(d.map((v,b)=>[v,b])),g=[],h=[];for(let v of m)(y.has(f(v))?g:h).push(v);return g.sort((v,b)=>y.get(f(v))-y.get(f(b))),[...g,...h]},[d]);return{...o,arrangement:c,resolvedChildren:a,resolutionLevel:u,order:d,sourceScopeId:c?.scope_item_id??null,arrangementQueryKey:i,applyTo:p}}function Zc(e){let{origin:t,originField:n,fallbackUrl:r,mintError:s,scopeId:i,scopePath:o}=e,c=Y(),a=ht(),u=i??a?.scope_id??null,d=(0,_.useMemo)(()=>{if(!t)return null;let R="/accounts/",M=t.indexOf(R);if(M===-1)return null;let N=t.indexOf("/",M+R.length);return N===-1?t:t.slice(0,N)},[t]),p=o??d??a?.scope_path??null,m=n?.trim()||null,f=`${c}
|
|
4
4
|
${u??""}
|
|
5
5
|
${p??""}
|
|
6
6
|
${m??""}
|