@ai4b-team/fsaos-gateway-sdk 3.37.0 → 3.38.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,10 +1,10 @@
1
- /* @fsaos/gateway v2.0.0 — Unified FSAOS Edge Runtime — 2026-10-14T05:04:56.586Z */
2
- "use strict";var __FSAOS_GATEWAY__=(()=>{var Cu=Object.create;var An=Object.defineProperty;var xu=Object.getOwnPropertyDescriptor;var Pu=Object.getOwnPropertyNames;var Tu=Object.getPrototypeOf,Eu=Object.prototype.hasOwnProperty;var Ti=e=>{throw TypeError(e)};var Iu=(e,t,n)=>t in e?An(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var kn=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Au=(e,t)=>{for(var n in t)An(e,n,{get:t[n],enumerable:!0})},Ei=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Pu(t))!Eu.call(e,s)&&s!==n&&An(e,s,{get:()=>t[s],enumerable:!(r=xu(t,s))||r.enumerable});return e};var X=(e,t,n)=>(n=e!=null?Cu(Tu(e)):{},Ei(t||!e||!e.__esModule?An(n,"default",{value:e,enumerable:!0}):n,e)),ku=e=>Ei(An({},"__esModule",{value:!0}),e);var ee=(e,t,n)=>Iu(e,typeof t!="symbol"?t+"":t,n),vs=(e,t,n)=>t.has(e)||Ti("Cannot "+n);var u=(e,t,n)=>(vs(e,t,"read from private field"),n?n.call(e):t.get(e)),w=(e,t,n)=>t.has(e)?Ti("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),b=(e,t,n,r)=>(vs(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n),T=(e,t,n)=>(vs(e,t,"access private method"),n);var Mn=(e,t,n,r)=>({set _(s){b(e,t,s,n)},get _(){return u(e,t,r)}});var oe=kn(($l,Ii)=>{Ii.exports=React});var xr=kn((Wf,uo)=>{uo.exports={jsx:React.createElement,jsxs:React.createElement,Fragment:React.Fragment}});var Ro=kn((bp,So)=>{So.exports={createClient:window.supabase.createClient}});var jo=kn((kp,Lo)=>{Lo.exports=ReactDOM});var Vc=kn((Ph,$c)=>{$c.exports=ReactDOM});var xi={};Au(xi,{ComponentRenderer:()=>pc,EnforcementDeniedError:()=>tt,FormSubmissionError:()=>In,GatewayRequestError:()=>Te,InteractionTrackingError:()=>Pn,KernelProvider:()=>mc,QueryClientProvider:()=>Bn,assignPersonalSection:()=>yu,auth:()=>nu,awaitAnchorReady:()=>Yn,awaitScopeReady:()=>Mo,callTool:()=>Zc,cancelQueuedTurn:()=>Wc,cancelTurn:()=>Lc,clearCachedToken:()=>Vs,clearSession:()=>Zs,createItem:()=>Jc,disconnectSSE:()=>oi,disposeVfsRealtimeWs:()=>ci,electHomeAnchor:()=>Et,emitEvent:()=>ca,fetchChannelMessages:()=>va,fetchChannelMessagesPage:()=>or,fetchChannelMessagesWithCards:()=>es,fetchEdgesForItem:()=>Gr,fetchItemHistory:()=>Yr,fetchItemVersions:()=>ir,fetchItems:()=>vn,fetchMemberFocus:()=>Xr,fetchOpenEnvelope:()=>Zr,fetchRecentActivity:()=>Jr,fetchResolvedItems:()=>wi,fetchTimelineHistory:()=>Si,fetchTurnQueueEntries:()=>ga,fetchTypeDefinitions:()=>Hr,fetchVfsChildren:()=>sr,fetchVfsChildrenPage:()=>Vr,fetchVfsItem:()=>$r,fetchVfsItemById:()=>Br,fetchVfsTree:()=>zr,gatewayCall:()=>S,getAccessToken:()=>Je,getAnchor:()=>un,getAnchorRef:()=>ge,getAnchorVersion:()=>zs,getAssetUrl:()=>tu,getDefaultSort:()=>ou,getHomeAnchor:()=>fe,getMountVersion:()=>Xn,getMounts:()=>Pe,getPathSubscriptionState:()=>la,getQueryClient:()=>P,getRequiredFormFields:()=>au,getScope:()=>H,getScopeVersion:()=>Z,getServerClockOffsetMs:()=>Do,getServerClockSyncedAt:()=>Uo,getSessionEntry:()=>It,hasServerClock:()=>Qo,initSession:()=>pt,initVfsRealtimeWs:()=>Ot,initializeFsaos:()=>Kc,initializeWorkspace:()=>fs,interpretSchema:()=>bi,invalidateAllVfs:()=>Sa,invalidateChannelMessages:()=>Ca,invalidateChildren:()=>Wr,invalidateItem:()=>ai,invalidateOpenEnvelope:()=>xa,invalidatePathAndParent:()=>ba,invalidateSubtree:()=>wa,invalidateTypes:()=>Ra,isAnchorReady:()=>Ys,isChannelPath:()=>Ke,isListableItemsFilter:()=>_n,isScopeReady:()=>Or,itemsFilterFromQueryFilter:()=>ya,listChildren:()=>zc,loadMounts:()=>Ft,mount:()=>ru,mountRealtimeScope:()=>wn,normalizeItem:()=>ye,onConnectionStateChange:()=>pa,pathSubscriptionMatches:()=>ri,personalSectionsKey:()=>hr,ping:()=>ua,pushChanges:()=>Xc,queryClient:()=>zo,readItem:()=>Gc,refreshQuery:()=>Ee,registerCleanup:()=>ie,replaceMounts:()=>is,resetAllSdkState:()=>ln,resolvePrincipalId:()=>lc,resubscribePath:()=>fa,selectMount:()=>lr,serverDeadlinePassed:()=>No,serverMsUntil:()=>Ko,serverNow:()=>Fr,setAnchor:()=>kr,setCachedToken:()=>Po,setQueryClient:()=>Go,setScope:()=>ko,setupRequireShim:()=>su,signal:()=>eu,startTracking:()=>ds,steerTurn:()=>jc,submitForm:()=>Bc,subscribeAnchor:()=>Js,subscribeArtifactStream:()=>ps,subscribeMounts:()=>Mr,subscribeScope:()=>be,subscribeToEvents:()=>re,subscribeToPath:()=>jr,subscribeToScope:()=>yn,trackAction:()=>Dc,trackEvent:()=>qt,trackPageView:()=>Qc,unmountRealtimeScope:()=>rs,updateItem:()=>Yc,uploadFile:()=>cu,useAccounts:()=>tc,useAgentTimeline:()=>mu,useAllChannels:()=>us,useArrangement:()=>Cn,useArtifactStream:()=>pu,useAsset:()=>rc,useAuth:()=>cs,useChannelMessages:()=>hc,useChannels:()=>yc,useChildren:()=>Na,useComponent:()=>pi,useCreate:()=>bc,useDelete:()=>Rc,useDmChannels:()=>_c,useEdges:()=>Va,useEventStream:()=>Tc,useFileUpload:()=>lu,useInfiniteChannelMessages:()=>gc,useInfiniteChildren:()=>$a,useInfiniteItems:()=>Ba,useItem:()=>Da,useItemById:()=>Ua,useItemHistory:()=>Xa,useItemVersions:()=>Ya,useItems:()=>Wa,useLink:()=>xc,useList:()=>fi,useMemberFocus:()=>Ja,useMintedAsset:()=>Ic,useMounts:()=>nc,useMove:()=>Cc,useMutation:()=>Pc,useNotifications:()=>mi,useOpen:()=>Ga,usePermission:()=>ac,usePermissions:()=>cc,usePersonalItemOrder:()=>Ac,usePersonalSections:()=>vu,usePinnedItems:()=>gu,usePrincipal:()=>dc,useRealtimeQuery:()=>Ec,useRecentActivity:()=>Za,useResolve:()=>ja,useResolvedItems:()=>fu,useScope:()=>ec,useScopeReady:()=>Qa,useSearch:()=>La,useTheme:()=>oc,useTimelineHistory:()=>hu,useTool:()=>fc,useTree:()=>Ka,useType:()=>Ha,useTypeHelpers:()=>za,useTypes:()=>as,useUnreadCounts:()=>vc,useUpdate:()=>wc,useUpdatePrincipal:()=>Sc,vfsKeys:()=>R,waitForPathReady:()=>da});var tt=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 xn=X(oe(),1);var Re=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 yt,nt,Dt,Ai,Mu=(Ai=class extends Re{constructor(){super();w(this,yt);w(this,nt);w(this,Dt);b(this,Dt,t=>{if(typeof window<"u"&&window.addEventListener){let n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){u(this,nt)||this.setEventListener(u(this,Dt))}onUnsubscribe(){var t;this.hasListeners()||((t=u(this,nt))==null||t.call(this),b(this,nt,void 0))}setEventListener(t){var n;b(this,Dt,t),(n=u(this,nt))==null||n.call(this),b(this,nt,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){u(this,yt)!==t&&(b(this,yt,t),this.onFocus())}onFocus(){let t=this.isFocused();this.listeners.forEach(n=>{n(t)})}isFocused(){return typeof u(this,yt)=="boolean"?u(this,yt):globalThis.document?.visibilityState!=="hidden"}},yt=new WeakMap,nt=new WeakMap,Dt=new WeakMap,Ai),Ut=new Mu;var Ou={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},rt,bs,ki,Fu=(ki=class{constructor(){w(this,rt,Ou);w(this,bs,!1)}setTimeoutProvider(e){b(this,rt,e)}setTimeout(e,t){return u(this,rt).setTimeout(e,t)}clearTimeout(e){u(this,rt).clearTimeout(e)}setInterval(e,t){return u(this,rt).setInterval(e,t)}clearInterval(e){u(this,rt).clearInterval(e)}},rt=new WeakMap,bs=new WeakMap,ki),Fe=new Fu;function Mi(e){setTimeout(e,0)}var Ss=typeof window>"u"||"Deno"in globalThis;function G(){}function qi(e,t){return typeof e=="function"?e(t):e}function On(e){return typeof e=="number"&&e>=0&&e!==1/0}function gr(e,t){return Math.max(e+(t||0)-Date.now(),0)}function Ae(e,t){return typeof e=="function"?e(t):e}function pe(e,t){return typeof e=="function"?e(t):e}function yr(e,t){let{type:n="all",exact:r,fetchStatus:s,predicate:i,queryKey:o,stale:c}=e;if(o){if(r){if(t.queryHash!==Fn(o,t.options))return!1}else if(!_t(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 _r(e,t){let{exact:n,status:r,predicate:s,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(qe(t.options.mutationKey)!==qe(i))return!1}else if(!_t(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||s&&!s(t))}function Fn(e,t){return(t?.queryKeyHashFn||qe)(e)}function qe(e){return JSON.stringify(e,(t,n)=>ws(n)?Object.keys(n).sort().reduce((r,s)=>(r[s]=n[s],r),{}):n)}function _t(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>_t(e[n],t[n])):!1}var qu=Object.prototype.hasOwnProperty;function Rs(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=Oi(e)&&Oi(t);if(!r&&!(ws(e)&&ws(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):{},l=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:qu.call(e,p))&&l++;continue}if(m===null||f===null||typeof m!="object"||typeof f!="object"){a[p]=f;continue}let y=Rs(m,f,n+1);a[p]=y,y===m&&l++}return i===c&&l===i?e:a}function Nt(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 Oi(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function ws(e){if(!Fi(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!Fi(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function Fi(e){return Object.prototype.toString.call(e)==="[object Object]"}function Qi(e){return new Promise(t=>{Fe.setTimeout(t,e)})}function qn(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?Rs(e,t):t}function Di(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function Ui(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var Kt=Symbol();function vr(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===Kt?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function Lt(e,t){return typeof e=="function"?e(...t):!!e}function Ni(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 Qe=(()=>{let e=()=>Ss;return{isServer(){return e()},setIsServer(t){e=t}}})();function Qn(){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 Ki=Mi;function Qu(){let e=[],t=0,n=c=>{c()},r=c=>{c()},s=Ki,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 L=Qu();var jt,st,Wt,Li,Du=(Li=class extends Re{constructor(){super();w(this,jt,!0);w(this,st);w(this,Wt);b(this,Wt,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(){u(this,st)||this.setEventListener(u(this,Wt))}onUnsubscribe(){var t;this.hasListeners()||((t=u(this,st))==null||t.call(this),b(this,st,void 0))}setEventListener(t){var n;b(this,Wt,t),(n=u(this,st))==null||n.call(this),b(this,st,t(this.setOnline.bind(this)))}setOnline(t){u(this,jt)!==t&&(b(this,jt,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return u(this,jt)}},jt=new WeakMap,st=new WeakMap,Wt=new WeakMap,Li),Bt=new Du;function Uu(e){return Math.min(1e3*2**e,3e4)}function Cs(e){return(e??"online")==="online"?Bt.isOnline():!0}var br=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function wr(e){let t=!1,n=0,r,s=Qn(),i=()=>s.status!=="pending",o=h=>{if(!i()){let g=new br(h);m(g),e.onCancel?.(g)}},c=()=>{t=!0},a=()=>{t=!1},l=()=>Ut.isFocused()&&(e.networkMode==="always"||Bt.isOnline())&&e.canRun(),d=()=>Cs(e.networkMode)&&e.canRun(),p=h=>{i()||(r?.(),s.resolve(h))},m=h=>{i()||(r?.(),s.reject(h))},f=()=>new Promise(h=>{r=g=>{(i()||l())&&h(g)},e.onPause?.()}).then(()=>{r=void 0,i()||e.onContinue?.()}),y=()=>{if(i())return;let h,g=n===0?e.initialPromise:void 0;try{h=g??e.fn()}catch(v){h=Promise.reject(v)}Promise.resolve(h).then(p).catch(v=>{if(i())return;let x=e.retry??(Qe.isServer()?0:3),q=e.retryDelay??Uu,F=typeof q=="function"?q(n,v):q,C=x===!0||typeof x=="number"&&n<x||typeof x=="function"&&x(n,v);if(t||!C){m(v);return}n++,e.onFail?.(n,v),Qi(F).then(()=>l()?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 vt,ji,Sr=(ji=class{constructor(){w(this,vt)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),On(this.gcTime)&&b(this,vt,Fe.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Qe.isServer()?1/0:5*60*1e3))}clearGcTimeout(){u(this,vt)!==void 0&&(Fe.clearTimeout(u(this,vt)),b(this,vt,void 0))}},vt=new WeakMap,ji);var bt,$t,Ce,wt,te,Dn,St,ve,Hi,We,$i,Vi=($i=class extends Sr{constructor(t){super();w(this,ve);w(this,bt);w(this,$t);w(this,Ce);w(this,wt);w(this,te);w(this,Dn);w(this,St);b(this,St,!1),b(this,Dn,t.defaultOptions),this.setOptions(t.options),this.observers=[],b(this,wt,t.client),b(this,Ce,u(this,wt).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,b(this,bt,Bi(this.options)),this.state=t.state??u(this,bt),this.scheduleGc()}get meta(){return this.options.meta}get promise(){return u(this,te)?.promise}setOptions(t){if(this.options={...u(this,Dn),...t},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let n=Bi(this.options);n.data!==void 0&&(this.setState(Wi(n.data,n.dataUpdatedAt)),b(this,bt,n))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&u(this,Ce).remove(this)}setData(t,n){let r=qn(this.state.data,t,this.options);return T(this,ve,We).call(this,{data:r,type:"success",dataUpdatedAt:n?.updatedAt,manual:n?.manual}),r}setState(t,n){T(this,ve,We).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){let n=u(this,te)?.promise;return u(this,te)?.cancel(t),n?n.then(G).catch(G):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return u(this,bt)}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(t=>pe(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Kt||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>Ae(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:!gr(this.state.dataUpdatedAt,t)}onFocus(){this.observers.find(n=>n.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),u(this,te)?.continue()}onOnline(){this.observers.find(n=>n.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),u(this,te)?.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),u(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||(u(this,te)&&(u(this,St)||T(this,ve,Hi).call(this)?u(this,te).cancel({revert:!0}):u(this,te).cancelRetry()),this.scheduleGc()),u(this,Ce).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||T(this,ve,We).call(this,{type:"invalidate"})}async fetch(t,n){if(this.state.fetchStatus!=="idle"&&u(this,te)?.status()!=="rejected"){if(this.state.data!==void 0&&n?.cancelRefetch)this.cancel({silent:!0});else if(u(this,te))return u(this,te).continueRetry(),u(this,te).promise}if(t&&this.setOptions(t),!this.options.queryFn){let a=this.observers.find(l=>l.options.queryFn);a&&this.setOptions(a.options)}let r=new AbortController,s=a=>{Object.defineProperty(a,"signal",{enumerable:!0,get:()=>(b(this,St,!0),r.signal)})},i=()=>{let a=vr(this.options,n),d=(()=>{let p={client:u(this,wt),queryKey:this.queryKey,meta:this.meta};return s(p),p})();return b(this,St,!1),this.options.persister?this.options.persister(a,d,this):a(d)},c=(()=>{let a={fetchOptions:n,options:this.options,queryKey:this.queryKey,client:u(this,wt),state:this.state,fetchFn:i};return s(a),a})();this.options.behavior?.onFetch(c,this),b(this,$t,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==c.fetchOptions?.meta)&&T(this,ve,We).call(this,{type:"fetch",meta:c.fetchOptions?.meta}),b(this,te,wr({initialPromise:n?.initialPromise,fn:c.fetchFn,onCancel:a=>{a instanceof br&&a.revert&&this.setState({...u(this,$t),fetchStatus:"idle"}),r.abort()},onFail:(a,l)=>{T(this,ve,We).call(this,{type:"failed",failureCount:a,error:l})},onPause:()=>{T(this,ve,We).call(this,{type:"pause"})},onContinue:()=>{T(this,ve,We).call(this,{type:"continue"})},retry:c.options.retry,retryDelay:c.options.retryDelay,networkMode:c.options.networkMode,canRun:()=>!0}));try{let a=await u(this,te).start();if(a===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(a),u(this,Ce).config.onSuccess?.(a,this),u(this,Ce).config.onSettled?.(a,this.state.error,this),a}catch(a){if(a instanceof br){if(a.silent)return u(this,te).promise;if(a.revert){if(this.state.data===void 0)throw a;return this.state.data}}throw T(this,ve,We).call(this,{type:"error",error:a}),u(this,Ce).config.onError?.(a,this),u(this,Ce).config.onSettled?.(this.state.data,a,this),a}finally{this.scheduleGc()}}},bt=new WeakMap,$t=new WeakMap,Ce=new WeakMap,wt=new WeakMap,te=new WeakMap,Dn=new WeakMap,St=new WeakMap,ve=new WeakSet,Hi=function(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"},We=function(t){let n=r=>{switch(t.type){case"failed":return{...r,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,...xs(r.data,this.options),fetchMeta:t.meta??null};case"success":let s={...r,...Wi(t.data,t.dataUpdatedAt),dataUpdateCount:r.dataUpdateCount+1,...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return b(this,$t,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),L.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),u(this,Ce).notify({query:this,type:"updated",action:t})})},$i);function xs(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Cs(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function Wi(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function Bi(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 me,D,Nn,le,Rt,Vt,Be,it,Kn,Ht,Gt,Ct,xt,ot,zt,K,Un,Ps,Ts,Es,Is,As,ks,Ms,Yi,Ji,Ln=(Ji=class extends Re{constructor(t,n){super();w(this,K);w(this,me);w(this,D);w(this,Nn);w(this,le);w(this,Rt);w(this,Vt);w(this,Be);w(this,it);w(this,Kn);w(this,Ht);w(this,Gt);w(this,Ct);w(this,xt);w(this,ot);w(this,zt,new Set);this.options=n,b(this,me,t),b(this,it,null),b(this,Be,Qn()),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(u(this,D).addObserver(this),Gi(u(this,D),this.options)?T(this,K,Un).call(this):this.updateResult(),T(this,K,Is).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Os(u(this,D),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Os(u(this,D),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,T(this,K,As).call(this),T(this,K,ks).call(this),u(this,D).removeObserver(this)}setOptions(t){let n=this.options,r=u(this,D);if(this.options=u(this,me).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof pe(this.options.enabled,u(this,D))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");T(this,K,Ms).call(this),u(this,D).setOptions(this.options),n._defaulted&&!Nt(this.options,n)&&u(this,me).getQueryCache().notify({type:"observerOptionsUpdated",query:u(this,D),observer:this});let s=this.hasListeners();s&&zi(u(this,D),r,this.options,n)&&T(this,K,Un).call(this),this.updateResult(),s&&(u(this,D)!==r||pe(this.options.enabled,u(this,D))!==pe(n.enabled,u(this,D))||Ae(this.options.staleTime,u(this,D))!==Ae(n.staleTime,u(this,D)))&&T(this,K,Ps).call(this);let i=T(this,K,Ts).call(this);s&&(u(this,D)!==r||pe(this.options.enabled,u(this,D))!==pe(n.enabled,u(this,D))||i!==u(this,ot))&&T(this,K,Es).call(this,i)}getOptimisticResult(t){let n=u(this,me).getQueryCache().build(u(this,me),t),r=this.createResult(n,t);return Ku(this,r)&&(b(this,le,r),b(this,Vt,this.options),b(this,Rt,u(this,D).state)),r}getCurrentResult(){return u(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&&u(this,Be).status==="pending"&&u(this,Be).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(r,s))})}trackProp(t){u(this,zt).add(t)}getCurrentQuery(){return u(this,D)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){let n=u(this,me).defaultQueryOptions(t),r=u(this,me).getQueryCache().build(u(this,me),n);return r.fetch().then(()=>this.createResult(r,n))}fetch(t){return T(this,K,Un).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),u(this,le)))}createResult(t,n){let r=u(this,D),s=this.options,i=u(this,le),o=u(this,Rt),c=u(this,Vt),l=t!==r?t.state:u(this,Nn),{state:d}=t,p={...d},m=!1,f;if(n._optimisticResults){let I=this.hasListeners(),$=!I&&Gi(t,n),M=I&&zi(t,r,n,s);($||M)&&(p={...p,...xs(d.data,t.options)}),n._optimisticResults==="isRestoring"&&(p.fetchStatus="idle")}let{error:y,errorUpdatedAt:h,status:g}=p;f=p.data;let v=!1;if(n.placeholderData!==void 0&&f===void 0&&g==="pending"){let I;i?.isPlaceholderData&&n.placeholderData===c?.placeholderData?(I=i.data,v=!0):I=typeof n.placeholderData=="function"?n.placeholderData(u(this,Gt)?.state.data,u(this,Gt)):n.placeholderData,I!==void 0&&(g="success",f=qn(i?.data,I,n),m=!0)}if(n.select&&f!==void 0&&!v)if(i&&f===o?.data&&n.select===u(this,Kn))f=u(this,Ht);else try{b(this,Kn,n.select),f=n.select(f),f=qn(i?.data,f,n),b(this,Ht,f),b(this,it,null)}catch(I){b(this,it,I)}u(this,it)&&(y=u(this,it),f=u(this,Ht),h=Date.now(),g="error");let x=p.fetchStatus==="fetching",q=g==="pending",F=g==="error",C=q&&x,k=f!==void 0,N={status:g,fetchStatus:p.fetchStatus,isPending:q,isSuccess:g==="success",isError:F,isInitialLoading:C,isLoading:C,data:f,dataUpdatedAt:p.dataUpdatedAt,error:y,errorUpdatedAt:h,failureCount:p.fetchFailureCount,failureReason:p.fetchFailureReason,errorUpdateCount:p.errorUpdateCount,isFetched:t.isFetched(),isFetchedAfterMount:p.dataUpdateCount>l.dataUpdateCount||p.errorUpdateCount>l.errorUpdateCount,isFetching:x,isRefetching:x&&!q,isLoadingError:F&&!k,isPaused:p.fetchStatus==="paused",isPlaceholderData:m,isRefetchError:F&&k,isStale:Fs(t,n),refetch:this.refetch,promise:u(this,Be),isEnabled:pe(n.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){let I=N.data!==void 0,$=N.status==="error"&&!I,M=O=>{$?O.reject(N.error):I&&O.resolve(N.data)},E=()=>{let O=b(this,Be,N.promise=Qn());M(O)},Q=u(this,Be);switch(Q.status){case"pending":t.queryHash===r.queryHash&&M(Q);break;case"fulfilled":($||N.data!==Q.value)&&E();break;case"rejected":(!$||N.error!==Q.reason)&&E();break}}return N}updateResult(){let t=u(this,le),n=this.createResult(u(this,D),this.options);if(b(this,Rt,u(this,D).state),b(this,Vt,this.options),u(this,Rt).data!==void 0&&b(this,Gt,u(this,D)),Nt(n,t))return;b(this,le,n);let r=()=>{if(!t)return!0;let{notifyOnChangeProps:s}=this.options,i=typeof s=="function"?s():s;if(i==="all"||!i&&!u(this,zt).size)return!0;let o=new Set(i??u(this,zt));return this.options.throwOnError&&o.add("error"),Object.keys(u(this,le)).some(c=>{let a=c;return u(this,le)[a]!==t[a]&&o.has(a)})};T(this,K,Yi).call(this,{listeners:r()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&T(this,K,Is).call(this)}},me=new WeakMap,D=new WeakMap,Nn=new WeakMap,le=new WeakMap,Rt=new WeakMap,Vt=new WeakMap,Be=new WeakMap,it=new WeakMap,Kn=new WeakMap,Ht=new WeakMap,Gt=new WeakMap,Ct=new WeakMap,xt=new WeakMap,ot=new WeakMap,zt=new WeakMap,K=new WeakSet,Un=function(t){T(this,K,Ms).call(this);let n=u(this,D).fetch(this.options,t);return t?.throwOnError||(n=n.catch(G)),n},Ps=function(){T(this,K,As).call(this);let t=Ae(this.options.staleTime,u(this,D));if(Qe.isServer()||u(this,le).isStale||!On(t))return;let r=gr(u(this,le).dataUpdatedAt,t)+1;b(this,Ct,Fe.setTimeout(()=>{u(this,le).isStale||this.updateResult()},r))},Ts=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(u(this,D)):this.options.refetchInterval)??!1},Es=function(t){T(this,K,ks).call(this),b(this,ot,t),!(Qe.isServer()||pe(this.options.enabled,u(this,D))===!1||!On(u(this,ot))||u(this,ot)===0)&&b(this,xt,Fe.setInterval(()=>{(this.options.refetchIntervalInBackground||Ut.isFocused())&&T(this,K,Un).call(this)},u(this,ot)))},Is=function(){T(this,K,Ps).call(this),T(this,K,Es).call(this,T(this,K,Ts).call(this))},As=function(){u(this,Ct)!==void 0&&(Fe.clearTimeout(u(this,Ct)),b(this,Ct,void 0))},ks=function(){u(this,xt)!==void 0&&(Fe.clearInterval(u(this,xt)),b(this,xt,void 0))},Ms=function(){let t=u(this,me).getQueryCache().build(u(this,me),this.options);if(t===u(this,D))return;let n=u(this,D);b(this,D,t),b(this,Nn,t.state),this.hasListeners()&&(n?.removeObserver(this),t.addObserver(this))},Yi=function(t){L.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(u(this,le))}),u(this,me).getQueryCache().notify({query:u(this,D),type:"observerResultsUpdated"})})},Ji);function Nu(e,t){return pe(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function Gi(e,t){return Nu(e,t)||e.state.data!==void 0&&Os(e,t,t.refetchOnMount)}function Os(e,t,n){if(pe(t.enabled,e)!==!1&&Ae(t.staleTime,e)!=="static"){let r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&Fs(e,t)}return!1}function zi(e,t,n,r){return(e!==t||pe(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&Fs(e,n)}function Fs(e,t){return pe(t.enabled,e)!==!1&&e.isStaleByTime(Ae(t.staleTime,e))}function Ku(e,t){return!Nt(e.getCurrentResult(),t)}function Jt(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,l=async()=>{let d=!1,p=y=>{Ni(y,()=>t.signal,()=>d=!0)},m=vr(t.options,t.fetchOptions),f=async(y,h,g)=>{if(d)return Promise.reject();if(h==null&&y.pages.length)return Promise.resolve(y);let x=(()=>{let k={client:t.client,queryKey:t.queryKey,pageParam:h,direction:g?"backward":"forward",meta:t.options.meta};return p(k),k})(),q=await m(x),{maxPages:F}=t.options,C=g?Ui:Di;return{pages:C(y.pages,q,F),pageParams:C(y.pageParams,h,F)}};if(s&&i.length){let y=s==="backward",h=y?Xi:qs,g={pages:i,pageParams:o},v=h(r,g);c=await f(g,v,y)}else{let y=e??i.length;do{let h=a===0?o[0]??r.initialPageParam:qs(r,c);if(a>0&&h==null)break;c=await f(c,h),a++}while(a<y)}return c};t.options.persister?t.fetchFn=()=>t.options.persister?.(l,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=l}}}function qs(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 Xi(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function Zi(e,t){return t?qs(e,t)!=null:!1}function eo(e,t){return!t||!e.getPreviousPageParam?!1:Xi(e,t)!=null}var Qs=class extends Ln{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:Jt()})}getOptimisticResult(e){return e.behavior=Jt(),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,l=o&&a==="forward",d=s&&a==="forward",p=o&&a==="backward",m=s&&a==="backward";return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:Zi(t,n.data),hasPreviousPage:eo(t,n.data),isFetchNextPageError:l,isFetchingNextPage:d,isFetchPreviousPageError:p,isFetchingPreviousPage:m,isRefetchError:c&&!l&&!p,isRefetching:i&&!d&&!m}}};var jn,De,ae,Pt,Ue,at,to,no=(to=class extends Sr{constructor(t){super();w(this,Ue);w(this,jn);w(this,De);w(this,ae);w(this,Pt);b(this,jn,t.client),this.mutationId=t.mutationId,b(this,ae,t.mutationCache),b(this,De,[]),this.state=t.state||Ds(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){u(this,De).includes(t)||(u(this,De).push(t),this.clearGcTimeout(),u(this,ae).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){b(this,De,u(this,De).filter(n=>n!==t)),this.scheduleGc(),u(this,ae).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){u(this,De).length||(this.state.status==="pending"?this.scheduleGc():u(this,ae).remove(this))}continue(){return u(this,Pt)?.continue()??this.execute(this.state.variables)}async execute(t){let n=()=>{T(this,Ue,at).call(this,{type:"continue"})},r={client:u(this,jn),meta:this.options.meta,mutationKey:this.options.mutationKey};b(this,Pt,wr({fn:()=>this.options.mutationFn?this.options.mutationFn(t,r):Promise.reject(new Error("No mutationFn found")),onFail:(o,c)=>{T(this,Ue,at).call(this,{type:"failed",failureCount:o,error:c})},onPause:()=>{T(this,Ue,at).call(this,{type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>u(this,ae).canRun(this)}));let s=this.state.status==="pending",i=!u(this,Pt).canStart();try{if(s)n();else{T(this,Ue,at).call(this,{type:"pending",variables:t,isPaused:i}),u(this,ae).config.onMutate&&await u(this,ae).config.onMutate(t,this,r);let c=await this.options.onMutate?.(t,r);c!==this.state.context&&T(this,Ue,at).call(this,{type:"pending",context:c,variables:t,isPaused:i})}let o=await u(this,Pt).start();return await u(this,ae).config.onSuccess?.(o,t,this.state.context,this,r),await this.options.onSuccess?.(o,t,this.state.context,r),await u(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),T(this,Ue,at).call(this,{type:"success",data:o}),o}catch(o){try{await u(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 u(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 T(this,Ue,at).call(this,{type:"error",error:o}),o}finally{u(this,ae).runNext(this)}}},jn=new WeakMap,De=new WeakMap,ae=new WeakMap,Pt=new WeakMap,Ue=new WeakSet,at=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),L.batch(()=>{u(this,De).forEach(r=>{r.onMutationUpdate(t)}),u(this,ae).notify({mutation:this,type:"updated",action:t})})},to);function Ds(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var $e,ke,Wn,ro,so=(ro=class extends Re{constructor(t={}){super();w(this,$e);w(this,ke);w(this,Wn);this.config=t,b(this,$e,new Set),b(this,ke,new Map),b(this,Wn,0)}build(t,n,r){let s=new no({client:t,mutationCache:this,mutationId:++Mn(this,Wn)._,options:t.defaultMutationOptions(n),state:r});return this.add(s),s}add(t){u(this,$e).add(t);let n=Rr(t);if(typeof n=="string"){let r=u(this,ke).get(n);r?r.push(t):u(this,ke).set(n,[t])}this.notify({type:"added",mutation:t})}remove(t){if(u(this,$e).delete(t)){let n=Rr(t);if(typeof n=="string"){let r=u(this,ke).get(n);if(r)if(r.length>1){let s=r.indexOf(t);s!==-1&&r.splice(s,1)}else r[0]===t&&u(this,ke).delete(n)}}this.notify({type:"removed",mutation:t})}canRun(t){let n=Rr(t);if(typeof n=="string"){let s=u(this,ke).get(n)?.find(i=>i.state.status==="pending");return!s||s===t}else return!0}runNext(t){let n=Rr(t);return typeof n=="string"?u(this,ke).get(n)?.find(s=>s!==t&&s.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){L.batch(()=>{u(this,$e).forEach(t=>{this.notify({type:"removed",mutation:t})}),u(this,$e).clear(),u(this,ke).clear()})}getAll(){return Array.from(u(this,$e))}find(t){let n={exact:!0,...t};return this.getAll().find(r=>_r(n,r))}findAll(t={}){return this.getAll().filter(n=>_r(t,n))}notify(t){L.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){let t=this.getAll().filter(n=>n.state.isPaused);return L.batch(()=>Promise.all(t.map(n=>n.continue().catch(G))))}},$e=new WeakMap,ke=new WeakMap,Wn=new WeakMap,ro);function Rr(e){return e.options.scope?.id}var Ve,ct,he,He,Ge,Cr,Us,io,Ns=(io=class extends Re{constructor(t,n){super();w(this,Ge);w(this,Ve);w(this,ct);w(this,he);w(this,He);b(this,Ve,t),this.setOptions(n),this.bindMethods(),T(this,Ge,Cr).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(t){let n=this.options;this.options=u(this,Ve).defaultMutationOptions(t),Nt(this.options,n)||u(this,Ve).getMutationCache().notify({type:"observerOptionsUpdated",mutation:u(this,he),observer:this}),n?.mutationKey&&this.options.mutationKey&&qe(n.mutationKey)!==qe(this.options.mutationKey)?this.reset():u(this,he)?.state.status==="pending"&&u(this,he).setOptions(this.options)}onUnsubscribe(){this.hasListeners()||u(this,he)?.removeObserver(this)}onMutationUpdate(t){T(this,Ge,Cr).call(this),T(this,Ge,Us).call(this,t)}getCurrentResult(){return u(this,ct)}reset(){u(this,he)?.removeObserver(this),b(this,he,void 0),T(this,Ge,Cr).call(this),T(this,Ge,Us).call(this)}mutate(t,n){return b(this,He,n),u(this,he)?.removeObserver(this),b(this,he,u(this,Ve).getMutationCache().build(u(this,Ve),this.options)),u(this,he).addObserver(this),u(this,he).execute(t)}},Ve=new WeakMap,ct=new WeakMap,he=new WeakMap,He=new WeakMap,Ge=new WeakSet,Cr=function(){let t=u(this,he)?.state??Ds();b(this,ct,{...t,isPending:t.status==="pending",isSuccess:t.status==="success",isError:t.status==="error",isIdle:t.status==="idle",mutate:this.mutate,reset:this.reset})},Us=function(t){L.batch(()=>{if(u(this,He)&&this.hasListeners()){let n=u(this,ct).variables,r=u(this,ct).context,s={client:u(this,Ve),meta:this.options.meta,mutationKey:this.options.mutationKey};if(t?.type==="success"){try{u(this,He).onSuccess?.(t.data,n,r,s)}catch(i){Promise.reject(i)}try{u(this,He).onSettled?.(t.data,null,n,r,s)}catch(i){Promise.reject(i)}}else if(t?.type==="error"){try{u(this,He).onError?.(t.error,n,r,s)}catch(i){Promise.reject(i)}try{u(this,He).onSettled?.(void 0,t.error,n,r,s)}catch(i){Promise.reject(i)}}}this.listeners.forEach(n=>{n(u(this,ct))})})},io);var Ne,oo,ao=(oo=class extends Re{constructor(t={}){super();w(this,Ne);this.config=t,b(this,Ne,new Map)}build(t,n,r){let s=n.queryKey,i=n.queryHash??Fn(s,n),o=this.get(i);return o||(o=new Vi({client:t,queryKey:s,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(s)}),this.add(o)),o}add(t){u(this,Ne).has(t.queryHash)||(u(this,Ne).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){let n=u(this,Ne).get(t.queryHash);n&&(t.destroy(),n===t&&u(this,Ne).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){L.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return u(this,Ne).get(t)}getAll(){return[...u(this,Ne).values()]}find(t){let n={exact:!0,...t};return this.getAll().find(r=>yr(n,r))}findAll(t={}){let n=this.getAll();return Object.keys(t).length>0?n.filter(r=>yr(t,r)):n}notify(t){L.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){L.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){L.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},Ne=new WeakMap,oo);var z,ut,lt,Yt,Xt,dt,Zt,en,co,Ks=(co=class{constructor(e={}){w(this,z);w(this,ut);w(this,lt);w(this,Yt);w(this,Xt);w(this,dt);w(this,Zt);w(this,en);b(this,z,e.queryCache||new ao),b(this,ut,e.mutationCache||new so),b(this,lt,e.defaultOptions||{}),b(this,Yt,new Map),b(this,Xt,new Map),b(this,dt,0)}mount(){Mn(this,dt)._++,u(this,dt)===1&&(b(this,Zt,Ut.subscribe(async e=>{e&&(await this.resumePausedMutations(),u(this,z).onFocus())})),b(this,en,Bt.subscribe(async e=>{e&&(await this.resumePausedMutations(),u(this,z).onOnline())})))}unmount(){var e,t;Mn(this,dt)._--,u(this,dt)===0&&((e=u(this,Zt))==null||e.call(this),b(this,Zt,void 0),(t=u(this,en))==null||t.call(this),b(this,en,void 0))}isFetching(e){return u(this,z).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return u(this,ut).findAll({...e,status:"pending"}).length}getQueryData(e){let t=this.defaultQueryOptions({queryKey:e});return u(this,z).get(t.queryHash)?.state.data}ensureQueryData(e){let t=this.defaultQueryOptions(e),n=u(this,z).build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(Ae(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return u(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=u(this,z).get(r.queryHash)?.state.data,o=qi(t,i);if(o!==void 0)return u(this,z).build(this,r).setData(o,{...n,manual:!0})}setQueriesData(e,t,n){return L.batch(()=>u(this,z).findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){let t=this.defaultQueryOptions({queryKey:e});return u(this,z).get(t.queryHash)?.state}removeQueries(e){let t=u(this,z);L.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){let n=u(this,z);return L.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){let n={revert:!0,...t},r=L.batch(()=>u(this,z).findAll(e).map(s=>s.cancel(n)));return Promise.all(r).then(G).catch(G)}invalidateQueries(e,t={}){return L.batch(()=>(u(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=L.batch(()=>u(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=u(this,z).build(this,t);return n.isStaleByTime(Ae(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=Jt(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(G).catch(G)}ensureInfiniteQueryData(e){return e.behavior=Jt(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return Bt.isOnline()?u(this,ut).resumePausedMutations():Promise.resolve()}getQueryCache(){return u(this,z)}getMutationCache(){return u(this,ut)}getDefaultOptions(){return u(this,lt)}setDefaultOptions(e){b(this,lt,e)}setQueryDefaults(e,t){u(this,Yt).set(qe(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){let t=[...u(this,Yt).values()],n={};return t.forEach(r=>{_t(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){u(this,Xt).set(qe(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){let t=[...u(this,Xt).values()],n={};return t.forEach(r=>{_t(e,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;let t={...u(this,lt).queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Fn(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===Kt&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...u(this,lt).mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){u(this,z).clear(),u(this,ut).clear()}},z=new WeakMap,ut=new WeakMap,lt=new WeakMap,Yt=new WeakMap,Xt=new WeakMap,dt=new WeakMap,Zt=new WeakMap,en=new WeakMap,co);var tn=X(oe(),1),lo=X(xr(),1),Ls=tn.createContext(void 0),W=e=>{let t=tn.useContext(Ls);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},Bn=({client:e,children:t})=>(tn.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,lo.jsx)(Ls.Provider,{value:e,children:t}));var Pr=X(oe(),1),fo=Pr.createContext(!1),po=()=>Pr.useContext(fo),$f=fo.Provider;var $n=X(oe(),1),Lu=X(xr(),1);function ju(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Wu=$n.createContext(ju()),mo=()=>$n.useContext(Wu);var ho=X(oe(),1);var go=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError=="function"?Lt(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},yo=e=>{ho.useEffect(()=>{e.clearReset()},[e])},_o=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:s})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(s&&e.data===void 0||Lt(n,[e.error,r]));var vo=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))}},bo=(e,t)=>e.isLoading&&e.isFetching&&!t,wo=(e,t)=>e?.suspense&&t.isPending,js=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});var ft=X(oe(),1);function Tr(e,t,n){let r=po(),s=mo(),i=W(n),o=i.defaultQueryOptions(e);i.getDefaultOptions().queries?._experimental_beforeQuery?.(o);let c=i.getQueryCache().get(o.queryHash);o._optimisticResults=r?"isRestoring":"optimistic",vo(o),go(o,s,c),yo(s);let a=!i.getQueryCache().get(o.queryHash),[l]=ft.useState(()=>new t(i,o)),d=l.getOptimisticResult(o),p=!r&&e.subscribed!==!1;if(ft.useSyncExternalStore(ft.useCallback(m=>{let f=p?l.subscribe(L.batchCalls(m)):G;return l.updateResult(),f},[l,p]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),ft.useEffect(()=>{l.setOptions(o)},[o,l]),wo(o,d))throw js(o,l,s);if(_o({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&&!Qe.isServer()&&bo(d,r)&&(a?js(o,l,s):c?.promise)?.catch(G).finally(()=>{l.updateResult()}),o.notifyOnChangeProps?d:l.trackResult(d)}function j(e,t){return Tr(e,Ln,t)}var ze=X(oe(),1);function de(e,t){let n=W(t),[r]=ze.useState(()=>new Ns(n,e));ze.useEffect(()=>{r.setOptions(e)},[r,e]);let s=ze.useSyncExternalStore(ze.useCallback(o=>r.subscribe(L.batchCalls(o)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),i=ze.useCallback((o,c)=>{r.mutate(o,c).catch(G)},[r]);if(s.error&&Lt(r.options.throwOnError,[s.error]))throw s.error;return{...s,mutate:i,mutateAsync:s.mutate}}function Vn(e,t){return Tr(e,Qs,t)}var Co=X(Ro(),1),Hn=typeof window<"u"&&window.__FSAOS_CONFIG__||{},Gn=Array.isArray(Hn.sources)?Hn.sources:[],Bu=Hn.supabaseUrl||"https://vahbmsslxuustnlvsrkg.supabase.co",$u=Hn.supabaseAnonKey||"sb_publishable_ZjosozAjfpZ4InMNElTr6Q_hHB-f5nc",xe=Hn.gatewayUrl||"https://fsaos-mcp-gw-rust.fly.dev",B=(0,Co.createClient)(Bu,$u,{auth:{persistSession:!0,autoRefreshToken:!0,detectSessionInUrl:!1}});var zn=null,Er=0,xo,$s,Ir=!1;xo=new Promise(e=>{$s=e});B.auth.onAuthStateChange((e,t)=>{t?.access_token?(zn=t.access_token,Er=t.expires_at??Math.floor(Date.now()/1e3)+3600):(zn=null,Er=0),Ir||(Ir=!0,$s())});setTimeout(()=>{Ir||(Ir=!0,$s())},5e3);function Po(e,t){zn=e,Er=t??Math.floor(Date.now()/1e3)+3600}function Vs(){zn=null,Er=0}async function Je(){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 xo,zn}var on=null,an=null,To=0,Ws=new Set,Hs,Jn,cn=!1;Hs=new Promise(e=>{Jn=e});function Gs(){To++,Ws.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Anchor listener error:",t)}})}function kr(e){let t=typeof e=="string"?e:e.path,n=on!==t||an?.id!==(typeof e=="string"?void 0:e.id);on=t,an=typeof e=="string"?null:e,typeof e!="string"&&!Tt.some(r=>r.id===e.id)&&(Tt=[...Tt,e],Xs()),cn||(cn=!0,Jn()),n&&Gs()}function un(){return on}function ge(){return an}function zs(){return To}function Js(e){return Ws.add(e),()=>{Ws.delete(e)}}function Yn(){return Hs}function Ys(){return cn}var Ar=null;function Et(e,t={}){if(Ar){console.warn("[SDK] electHomeAnchor called twice; ignoring (logout to re-elect).");return}Ar=e,t.activate!==!1&&kr(e)}function fe(){return Ar}var Tt=[],Bs=new Set,Eo=0;function Xs(){Eo++,Bs.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Mount listener error:",t)}})}function Pe(){return Tt}function Xn(){return Eo}function Mr(e){return Bs.add(e),()=>{Bs.delete(e)}}function Io(e,t){let n=JSON.stringify(Tt)!==JSON.stringify(e),r=on!==t.path||an?.id!==t.id;Tt=e,on=t.path,an=t,cn||(cn=!0,Jn()),n&&Xs(),r&&Gs()}var rn=null,nn=null,sn=0;function se(){return sn}async function pt(){if(rn)return rn;if(nn)return nn;let e=sn;return nn=(async()=>{let t=At(),n=await Je();if(e!==sn)throw new Error("Session changed during initialization");let r={};n&&(r.Authorization=`Bearer ${n}`);let s=await fetch(`${xe}/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!==sn)throw new Error("Session changed during initialization");let o=i.entry||i;return rn={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},rn})().catch(t=>{throw e===sn&&(nn=null),t}),nn}function It(){return rn}function Zs(){sn++,rn=null,nn=null,on=null,an=null,Ar=null,Tt=[]}var Ao=[];function ie(e){Ao.push(e)}function ln(){Zs(),Vs(),Jn(),cn=!1,Hs=new Promise(e=>{Jn=e}),Gs(),Xs();for(let e of Ao)try{e()}catch(t){console.warn("[SDK] Cleanup function failed:",t)}}function At(){if(typeof window<"u"){let e=window.__FSAOS_CONFIG__;return e?.hostname?e.hostname:window.location.hostname}return"localhost"}var ko=kr,H=un,Z=zs,be=Js,Mo=Yn,Or=Ys;var ei=0,Oo=!1,Fo=0;function qo(e){if(typeof e!="string")return;let t=Date.parse(e);Number.isNaN(t)||(ei=t-Date.now(),Oo=!0,Fo=Date.now())}function Fr(){return Date.now()+ei}function Qo(){return Oo}function Do(){return ei}function Uo(){return Fo}function No(e){if(typeof e!="string")return null;let t=Date.parse(e);return Number.isNaN(t)?null:Fr()>=t}function Ko(e){if(typeof e!="string")return null;let t=Date.parse(e);return Number.isNaN(t)?null:Math.max(0,t-Fr())}var Vu=new Set(["list-memberships","init"]),Te=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 S(e,t={}){let n=se(),r=un(),s=At(),i=`${xe}/d/${s}`,o={"Content-Type":"application/json"},c=await Je();if(n!==se())throw new Error("Session changed before gateway request");if(c&&(o.Authorization=`Bearer ${c}`),!Vu.has(e)&&!t._scope_path&&await Yn(),n!==se())throw new Error("Session changed before gateway request");let a={...t},l=It();!a.domain_scope_id&&l?.scope_id&&(a.domain_scope_id=l.scope_id);let d=r??un();!a._scope_path&&d&&(a._scope_path=d);let p=await fetch(i,{method:"POST",headers:o,body:JSON.stringify({method:e,params:a})}),m=await p.text();if(n!==se())throw new Error("Session changed during gateway request");let f=null;if(m)try{f=JSON.parse(m)}catch{}if(!p.ok||!f)throw new Te({method:e,status:p.status,statusText:p.statusText,payload:f,responseBody:m});if(f.success===!1){let y=f.error||"",h=f.denied_by||f.error_type||"";throw h==="rule"||h==="access"||h==="entitlement"||y==="RULE_DENIED"||y==="ACCESS_DENIED"||y==="PERMISSION_DENIED"||y==="ENTITLEMENT_REQUIRED"?new tt(f):new Te({method:e,status:p.status,statusText:p.statusText,payload:f,responseBody:m})}return f&&f.server_now!==void 0&&qo(f.server_now),f}var _=X(oe(),1),hl=X(jo(),1),gl=X(xr(),1);var Wo=new WeakMap;function Ee(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=Wo.get(e);c||(c=new Map,Wo.set(e,c));let a=c.get(o);if(a)return a;let l=c,d=Promise.allSettled(i).then(()=>(l.delete(o),s()));return l.set(o,d),d}function Ke(e,t){return typeof e=="string"&&(e===t||e.startsWith(`${t}/`))}var qr=new WeakMap,Bo=e=>e.meta?.arrangementRealtime===!0;function Ye(e,t){let n=e.getQueryCache().find({queryKey:t,exact:!0});if(!n)return;let r=qr.get(e);r||(r=new Map,qr.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&&Ee(e,t,{exact:!0})},250))}function $o(e,t){if(!(!t||typeof t!="object"))for(let n of e.getQueryCache().getAll()){if(!Bo(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")&&Ye(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)))&&Ye(e,n.queryKey)}}function Vo(e){for(let t of e.getQueryCache().getAll())Bo(t)&&t.state.data!==void 0&&Ye(e,t.queryKey)}function Ho(e){qr.get(e)?.forEach(clearTimeout),qr.delete(e)}var Xe=null;ie(()=>{Xe&&(Xe.cancelQueries({queryKey:["vfs"]}),Xe.removeQueries({queryKey:["vfs"]}))});function Go(e){if(Xe&&Xe!==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.");Xe=e}function P(){return Xe||(Xe=new Ks({defaultOptions:{queries:{staleTime:1e3*60*2,gcTime:1e3*60*10,refetchOnWindowFocus:!1,retry:1}}})),Xe}var zo=new Proxy({},{get(e,t,n){let r=P(),s=r[t];return typeof s=="function"?s.bind(r):s}});var Qr=new WeakMap;function ti(e){return e.meta?.infiniteItemsRealtime?.filter}function Hu(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 Gu(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 zu(e,t,n){if(Hu(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&&!Ke(n.path,r)&&!Ke(n.old_path,r))return!1;if(n.item_type==="symlink"&&s&&i)return!0;let o=Gu(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 Jo(e,t){let n=Qr.get(e);n||(n=new Map,Qr.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||!ti(t))&&Ee(e,t.queryKey,{exact:!0})},500))}function Yo(e,t){if(!(!t||typeof t!="object"))for(let n of e.getQueryCache().getAll()){let r=ti(n);r&&zu(n,r,t)&&Jo(e,n)}}function Xo(e){for(let t of e.getQueryCache().getAll())ti(t)&&t.state.data!==void 0&&Jo(e,t)}function Zo(e){Qr.get(e)?.forEach(clearTimeout),Qr.delete(e)}var Dr=class extends Error{constructor(){super("The server did not confirm the selected-Space listing contract")}};function ea(e,t){if(!Array.isArray(t)||t.some(n=>typeof n!="string")||JSON.stringify([...new Set(t)].sort())!==JSON.stringify(e))throw new Dr}function kt(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 dn(e){return e instanceof Dr||e instanceof tt||e instanceof Te&&(e.payload?.error==="SPACE_SELECTION_UNAVAILABLE"||e.payload?.error==="QUERY_PARAMS_INVALID"||e.status===401||e.status===403)}function ne(){return H()??"__unscoped__"}var R={all:()=>["vfs",ne()],item:e=>["vfs",ne(),"item",e],itemById:e=>["vfs","item-by-id",e],children:e=>["vfs",ne(),"children",e],allChildren:()=>["vfs",ne(),"children"],types:e=>["vfs","types",e??"default"],edges:e=>["vfs","edges",e],search:(e,t)=>["vfs",ne(),"search",e,...t??[]],items:(e,t)=>["vfs",ne(),"items",e,JSON.stringify(kt(t??{}))],allItems:()=>["vfs",ne(),"items"],tree:(e,t)=>["vfs",ne(),"tree",e,t??1],openEnvelope:(e,t)=>["vfs",ne(),"open",e,t??"__default__"],allOpenEnvelopes:()=>["vfs",ne(),"open"],memberFocus:e=>["vfs","member-focus",e],fractalInstances:()=>["vfs","fractal-instances"],recentActivity:(e,t,n)=>["vfs",ne(),"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",ne(),"channel-messages",e,t??"__top__"],allChannelMessages:()=>["vfs",ne(),"channel-messages"],channels:e=>["vfs",ne(),"channels",e??"all"],allChannels:()=>["vfs",ne(),"channels"],notifications:(e,t)=>["vfs",ne(),"notifications",e??"all",t??200],allNotifications:()=>["vfs",ne(),"notifications"],unreadCounts:()=>["vfs",ne(),"unread-counts"],memberships:e=>["memberships",e]};var Ju=typeof window<"u"&&(window.location?.hostname==="localhost"||window.location?.hostname==="127.0.0.1"||window.__FSAOS_WS_DEBUG__);function J(...e){Ju&&console.log("[WS]",...e)}var A=null,fn=null,mn=null,Zn=0,Yu=3e4,ta=1e4,gn=!1,na=!1,aa=3e4,Xu=aa*2+5e3,Ur=0,Nr=null,ra=!1;function Zu(){tr(),Ur=Date.now(),Nr=setInterval(()=>{if(A&&A.readyState===WebSocket.OPEN&&Date.now()-Ur>Xu){J("ping: no inbound traffic for",Date.now()-Ur,"ms \u2014 closing half-open socket");try{A.close(4e3,"liveness timeout")}catch{}return}et({type:"ping"})},aa)}function tr(){Nr&&(clearInterval(Nr),Nr=null)}function el(){typeof document>"u"||(document.hidden?tr():er()&&(J("Tab visible, reconnecting..."),Mt()))}function tl(){ra||typeof document>"u"||(document.addEventListener("visibilitychange",el),ra=!0)}var we={};function ri(e,t){let n=e.replace(/\/+$/,""),r=t.replace(/\/+$/,"");return!n||!r?n===r:r===n||r.startsWith(`${n}/`)}var hn=[],Ze=new Map,pn=new Map,Ie=new Map;function nl(e){let t=pn.get(e);return t?Array.from(new Set(Array.from(t.values()).flatMap(n=>n.event_types))).sort():[]}function sa(e,t){return e?e.length===t.length&&e.every((n,r)=>n===t[r]):!1}function ia(e){let t=nl(e);if(t.length===0)return Ze.delete(e),null;let n={scope_id:e,event_types:t};return Ze.set(e,n),n}var Le=new Map,mt=new Map,ni="disconnected",Kr=[];function Lr(e){if(ni!==e){ni=e;for(let t of[...Kr])try{t(e)}catch{}}}function rl(e){Le.set(e,"ready");let t=mt.get(e);if(t){mt.delete(e);for(let n of t)n()}}function sl(){for(let e of Le.keys())Le.set(e,"disconnected")}function si(e,t){Le.set(e,"pending"),et({type:"subscribe_path",path:e,event_types:t})}function il(){return Object.keys(we).some(t=>we[t]&&we[t].length>0)||hn.length>0}function er(){return Ze.size>0||Ie.size>0}async function Mt(){if(!er()){J("ensureConnection: no active subscriptions, skipping");return}if(A&&A.readyState===WebSocket.OPEN){J("ensureConnection: already open");return}if(fn)return J("ensureConnection: connection already in flight, waiting..."),fn;if(A){J("ensureConnection: killing stale WS in state",A.readyState);try{A.close()}catch{}A=null}return gn=!1,fn=(async()=>{try{let e=typeof window<"u"&&window.__FSAOS_CONFIG__||{},t=xe,n=await Je();if(!n){J("ensureConnection: no token available, will retry"),oa();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)+"..."),Lr("connecting"),A=new WebSocket(i);let o=A;await new Promise((c,a)=>{if(!A)return a(new Error("WebSocket not created"));let l=setTimeout(()=>{if(A===o){if(J("ensureConnection: TIMEOUT after",ta,"ms"),A&&A.readyState!==WebSocket.OPEN){try{A.close()}catch{}A=null}a(new Error("WebSocket connection timeout"))}},ta);o.onopen=()=>{if(A!==o)return;clearTimeout(l),J("ensureConnection: CONNECTED");let d=na;na=!0,Zn=0,Lr("connected"),ol(d),(typeof document>"u"||!document.hidden)&&Zu(),tl(),c()},o.onmessage=d=>{A===o&&al(d.data)},o.onerror=()=>{J("ensureConnection: WS error event")},o.onclose=d=>{clearTimeout(l),A===o&&(J("ensureConnection: WS closed, code:",d.code,"reason:",d.reason),A=null,tr(),sl(),Lr("disconnected"),!gn&&er()&&oa(),a(new Error(`WebSocket closed: ${d.code}`)))}})}catch(e){J("ensureConnection: failed -",e?.message||e)}finally{fn=null}})(),fn}function oa(){if(mn||typeof document<"u"&&document.hidden)return;let e=Math.min(1e3*Math.pow(2,Zn)+Math.random()*1e3,Yu);Zn++,J("scheduleReconnect: attempt",Zn,"in",Math.round(e),"ms"),mn=setTimeout(()=>{mn=null,er()&&Mt()},e)}function ol(e=!1){for(let t of Ze.values())J("resubscribeAll: scope",t.scope_id),et({type:"subscribe",scope_id:t.scope_id,event_types:t.event_types});for(let t of Ie.values())J("resubscribeAll: path",t.path),si(t.path,t.event_types);if(e)try{let t=P();Xo(t),Vo(t);for(let n of Ie.values())t.invalidateQueries({queryKey:R.item(n.path)}),t.invalidateQueries({queryKey:R.children(n.path)});J("resubscribeAll: invalidated",Ie.size,"paths after reconnect")}catch(t){J("resubscribeAll: cache invalidation skipped",t)}}function et(e){A&&A.readyState===WebSocket.OPEN&&A.send(JSON.stringify(e))}function al(e){Ur=Date.now();try{let t=JSON.parse(e);if(t.type==="subscribed_path"){typeof t.path=="string"&&rl(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"&&(Yo(P(),r),$o(P(),r)),typeof r.path=="string")for(let[s,i]of Object.entries(we))s!=="*"&&ri(s,r.path)&&i.forEach(o=>o(r));we["*"]&&we["*"].forEach(s=>s(r));for(let s of hn)s.eventType!=="*"&&s.eventType!==n||s.filter&&!s.filter(r)||s.callback(r)}}catch{}}function ii(){!il()&&Ze.size===0&&Ie.size===0&&A&&(gn=!0,tr(),A.close(),A=null,gn=!1)}function jr(e,t){return we[e]||(we[e]=[]),we[e].push(t),Ie.has(e)||(Ie.set(e,{path:e,event_types:["token_stream"]}),A&&A.readyState===WebSocket.OPEN?si(e,["token_stream"]):Le.set(e,"pending")),Mt(),()=>{let n=we[e];if(n){let r=n.indexOf(t);r!==-1&&n.splice(r,1),n.length===0&&(delete we[e],Ie.delete(e),Le.delete(e),mt.delete(e),et({type:"unsubscribe_path",path:e}))}ii()}}function re(e,t,n){let s=(Array.isArray(e)?e:[e]).map(i=>({eventType:i,callback:t,filter:n}));return hn.push(...s),er()&&Mt(),()=>{for(let i of s){let o=hn.indexOf(i);o!==-1&&hn.splice(o,1)}ii()}}function yn(e,t=["vfs_change","ccm_change"]){let n=Symbol(e),r=Array.from(new Set(t)).sort();if(r.length===0)return()=>{};let s=pn.get(e)??new Map,i=Ze.get(e)?.event_types;s.set(n,{event_types:r}),pn.set(e,s);let o=ia(e);if(!o)return()=>{};J("subscribeToScope:",e,o.event_types),A&&A.readyState===WebSocket.OPEN&&!sa(i,o.event_types)&&et({type:"subscribe",scope_id:e,event_types:o.event_types}),Mt();let c=!0;return()=>{if(!c)return;c=!1;let a=pn.get(e);if(!a?.delete(n))return;let l=Ze.get(e)?.event_types;if(a.size===0)pn.delete(e),Ze.delete(e),et({type:"unsubscribe",scope_id:e});else{let d=ia(e);d&&A&&A.readyState===WebSocket.OPEN&&!sa(l,d.event_types)&&et({type:"subscribe",scope_id:e,event_types:d.event_types})}ii()}}function ca(e,t,n={}){et({type:"emit",scope_id:e,event_type:t,payload:n})}function oi(){J("disconnectSSE: tearing down"),Zo(P()),Ho(P()),gn=!0,tr(),A&&(A.close(),A=null),mn&&(clearTimeout(mn),mn=null),fn=null,gn=!1,Zn=0;for(let e of Object.keys(we))delete we[e];hn.length=0,Ze.clear(),pn.clear(),Ie.clear(),Le.clear(),mt.clear(),Lr("disconnected")}function ua(){et({type:"ping"})}function la(e){return Ie.has(e)?Le.get(e)??"pending":"unsubscribed"}function da(e,t=5e3){return Ie.has(e)?Le.get(e)==="ready"&&A&&A.readyState===WebSocket.OPEN?Promise.resolve(!0):(Mt(),new Promise(n=>{let r=!1,s=mt.get(e)??[],i=()=>{r||(r=!0,clearTimeout(o),n(!0))};s.push(i),mt.set(e,s);let o=setTimeout(()=>{if(r)return;r=!0;let c=mt.get(e);if(c){let a=c.indexOf(i);a!==-1&&c.splice(a,1),c.length===0&&mt.delete(e)}n(!1)},t)})):Promise.resolve(!1)}function fa(e){let t=Ie.get(e);if(!t){J("resubscribePath: no active subscription for",e);return}A&&A.readyState===WebSocket.OPEN?(J("resubscribePath: re-sending frame for",e),si(t.path,t.event_types)):(Le.set(e,"pending"),Mt())}function pa(e){Kr.push(e);try{e(ni)}catch{}return()=>{let t=Kr.indexOf(e);t!==-1&&Kr.splice(t,1)}}ie(oi);function ma(){return new Date().toISOString()}function ha(){return crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function ye(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||ma(),updated_at:e.updated_at||ma(),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 rr(e){return(e.content?.items||e.items||[]).map(ye)}async function Br(e){try{let t=await S("read",{id:e});if(t.item_name||t.item_path){let r=ye(t);return r.path&&P().setQueryData(R.item(r.path),r),r}let n=t.item;if(n){let r=ye(n);return r.path&&P().setQueryData(R.item(r.path),r),r}return null}catch{return null}}async function $r(e){try{let t=await S("read",{path:e});if(t.item_name||t.item_path)return ye(t);let n=t.item;return n?ye(n):null}catch{return null}}async function sr(e){try{let t=await S("list",{path:e,limit:200}),n=rr(t);for(let r of n)P().setQueryData(R.item(r.path),r);return n}catch(t){return console.error(`[gateway] Failed to fetch children of ${e}:`,t),[]}}async function ga(e,t){let{items:n}=await vn({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 Vr(e,t,n){try{let r=await S("list",{path:e,limit:t,offset:n}),s=rr(r);for(let i of s)P().setQueryData(R.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 Hr(e){let n=await S("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 Gr(e){try{let t=await S("edges",{item_id:e}),n=t.outgoing||[],r=t.incoming||[],s=[];for(let i of n)s.push({id:i.edge_id||ha(),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||ha(),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 zr(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 S("tree",s),o=rr(i);for(let c of o)P().setQueryData(R.item(c.path),c);return o}catch(s){return console.error(`[gateway] Failed to fetch tree at ${e}:`,s),[]}}async function Jr(e,t=50,n=0){try{let r=await S("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 ir(e,t={}){let{limit:n=50,offset:r=0,include_snapshots:s=!1}=t;try{let i=await S("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 Yr(e,t=50,n=0){return ir(e,{limit:t,offset:n})}async function Xr(e,t,n){try{let r={scope_id:e};t?.length&&(r.item_types=t),n&&(r.limit=n);let s=await S("member-focus",r),i=rr(s);for(let o of i)P().setQueryData(R.item(o.path),o);return i}catch(r){return console.error(`[gateway] Failed to fetch member focus for scope ${e}:`,r),[]}}async function Zr(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 S("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 _n(e){return!!e&&(!!e.type||Array.isArray(e.any_of)&&e.any_of.length>0)}function cl(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 ul=["catalog","parent_only","internal"];function ya(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[l,d]of Object.entries(o))l.startsWith("field.")&&l.length>6&&n(d)?c[l.slice(6)]=d:l.startsWith("field_in.")&&l.length>9&&Array.isArray(d)&&(a[l.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"&&ul.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,l={};typeof a.item_type=="string"&&a.item_type&&(l.item_type=a.item_type);let d=r(a);Object.keys(d.fields).length&&(l.fields=d.fields),Object.keys(d.field_in).length&&(l.field_in=d.field_in),Object.keys(l).length&&o.push(l)}o.length&&(s.any_of=o)}return _n(s)?{...s,...t}:null}async function vn(e,t={}){if(e=kt(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(cl)),Object.keys(r).length>0&&(n.filters=r),e.limit!=null&&(n.limit=e.limit);try{let s=await S("query",n);e.spaceIds!==void 0&&ea(e.spaceIds,s.selected_space_ids??s.content?.selected_space_ids);let i=rr(s);for(let o of i)P().setQueryData(R.item(o.path),o);return{items:i,total_hint:s.total??s.content?.total??i.length}}catch(s){if(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 ll(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 _a(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:ll(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 nr(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,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 va(e,t){try{let n={channel_path:e};t&&(n.parent_message_id=t);let s=await S("get-channel-messages",n),i=s.messages||s.content?.items||s.items||[];return nr(i)}catch(n){return console.error(`[gateway] Failed to fetch channel messages for ${e}:`,n),[]}}async function es(e,t){try{let n={channel_path:e};t&&(n.parent_message_id=t);let s=await S("get-channel-messages",n),i=s.messages||[],o=nr(i),c=_a(i),a=new Map,l=[];for(let d of c)if(d.parentMessagePath){let p=a.get(d.parentMessagePath)||[];p.push(d),a.set(d.parentMessagePath,p)}else l.push(d);return{messages:o,activityMessages:nr(s.activity_messages||[]),messageCards:a,siblingCards:l,mode:s.mode||"top_level"}}catch(n){return console.error(`[gateway] Failed to fetch channel messages with cards for ${e}:`,n),{messages:[],messageCards:new Map,siblingCards:[],mode:"top_level"}}}async function or(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 S("get-channel-messages",n),i=s.messages||[],o=_a(i),c=new Map,a=[];for(let l of o)if(l.parentMessagePath){let d=c.get(l.parentMessagePath)||[];d.push(l),c.set(l.parentMessagePath,d)}else a.push(l);return{messages:nr(i),activityMessages:nr(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 Wr(e){P().invalidateQueries({queryKey:R.children(e)})}function ai(e){P().invalidateQueries({queryKey:R.item(e)})}function ba(e,t){ai(e),Wr(e);let n=e.split("/");n.pop();let r=n.join("/")||t;r&&Wr(r)}function wa(e){let t=e+"/";P().invalidateQueries({predicate:n=>{let r=n.queryKey;return r[0]!=="vfs"?!1:r.some(s=>typeof s=="string"&&(s===e||s.startsWith(t)))}})}function Sa(){P().invalidateQueries({queryKey:R.all()})}function Ra(e){P().invalidateQueries({queryKey:R.types(e)})}function Ca(e,t){e?P().invalidateQueries({queryKey:R.channelMessages(e,t)}):P().invalidateQueries({queryKey:R.allChannelMessages()})}function xa(e,t){e&&t?P().invalidateQueries({queryKey:R.openEnvelope(e,t)}):e?P().invalidateQueries({predicate:n=>{let r=n.queryKey;return r[0]==="vfs"&&r[2]==="open"&&r[3]===e}}):P().invalidateQueries({queryKey:R.allOpenEnvelopes()})}function je(e){return{id:e.accountId,path:e.path,kind:e.isSpace?"space":"account",name:e.name,grantedUnderAccountId:e.grantedUnderAccountId??void 0}}async function ts(){return((await S("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 bn=new Map,ar=null,ns=null,ht=new Map,Pa=250;function Ot(e){if(ar){wn(e);return}wn(e),ar=re("vfs_change",t=>dl(t)),ns=re("ccm_change",t=>fl(t))}function wn(e){if(bn.has(e))return;let t=yn(e,["vfs_change","ccm_change"]);bn.set(e,t)}function rs(e){let t=bn.get(e);t&&(t(),bn.delete(e))}function ci(){for(let[,e]of bn)e();bn.clear(),ar&&(ar(),ar=null),ns&&(ns(),ns=null),ht.forEach(e=>clearTimeout(e)),ht.clear()}ie(ci);function dl(e){let t=e.path,n=e.action;if(!t)return;let r=t.split("/");r.pop();let s=r.join("/")||"/root",i=ht.get(s);i&&clearTimeout(i);let o=setTimeout(()=>{ht.delete(s),pl(n,t,e,s)},Pa);ht.set(s,o)}function fl(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=ht.get(s);i&&clearTimeout(i);let o=setTimeout(()=>{ht.delete(s),t&&P().invalidateQueries({queryKey:R.edges(t)}),n&&P().invalidateQueries({queryKey:R.edges(n)})},Pa);ht.set(s,o)}function pl(e,t,n,r){if((e||"").toUpperCase()==="DELETE")P().removeQueries({queryKey:R.item(t)}),P().removeQueries({queryKey:R.children(t)}),P().removeQueries({queryKey:R.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=ye(i);o&&o.id&&P().setQueryData(R.item(t),o)}catch{}P().invalidateQueries({queryKey:R.children(r)}),P().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&&P().invalidateQueries({queryKey:R.itemById(n.item_id)})}var Sn=null;ie(()=>{Sn=null});function gt(e){if(e!==Sn||e.generation!==se())throw new Error("Workspace session changed")}function ml(e){return e instanceof Te&&e.payload?.error==="item_not_found"}function cr(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 ur(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 Ta(e,t){return JSON.stringify({mounts:e.map(n=>n.id),last_anchor:t.id})}async function Ea(e,t,n){gt(e);let r=Ta(t,n);if(e.saved===r)return;let s=JSON.parse(r);await S(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}),gt(e),e.exists=!0,e.saved=r}function Ia(e,t){let n=Pe();Ot(fe().id);for(let r of n)e.some(s=>s.id===r.id)||rs(r.id);for(let r of e)wn(r.id);Io(e,t)}async function Ft(e,t,n={}){let r=fe();if(!r)throw new Error("Elect a home account before loading mounts");let s=`${e}/settings/mounts`;if(Sn&&Sn.path!==s)throw new Error("Reset the session before changing the mount declaration owner");let i=Sn??(Sn={generation:se(),path:s,scope:r.path,resolve:t,exists:!1,ready:!1,saved:null,queue:Promise.resolve()});return gt(i),i.loading?i.loading:i.ready?Pe():(i.resolve=t,i.loading=(async()=>{let o=null;try{let d=await S("read",{path:s,_scope_path:i.scope});if(gt(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(gt(i),!ml(d))throw d;i.exists=!1}let c=n.initialAnchor?cr(i,n.initialAnchor):r,a=ur(o?o.mounts.map(t).filter(d=>d!==null):[c]),l=o?a.find(d=>d.id===o.last_anchor)??a.find(d=>d.kind==="space")??r:c;return o?i.saved=Ta(a,l):n.initialAnchor&&await Ea(i,a,l),gt(i),i.ready=!0,Ia(a,l),a})().finally(()=>{i.loading=void 0}),i.loading)}function ss(e){let t=Sn;if(!t?.ready)return Promise.reject(new Error("Workspace mounts are not loaded"));let n=t.queue.then(async()=>{gt(t);let{refs:r,anchor:s}=e(t);await Ea(t,r,s),gt(t),Ia(r,s)});return t.queue=n.catch(()=>{}),n}function ui(e){return ss(t=>({refs:ur([...Pe(),cr(t,e)]),anchor:ge()}))}function Aa(e){return ss(()=>{if(e===fe().id)throw new Error("The home account cannot be unmounted");let t=ur(Pe().filter(r=>r.id!==e)),n=t.find(r=>r.id===ge()?.id)??t.find(r=>r.kind==="space")??fe();return{refs:t,anchor:n}})}function lr(e){return ss(t=>{let n=cr(t,e);return{refs:ur([...Pe(),n]),anchor:n}})}function is(e,t){return ss(n=>{let r=ur(e.map(i=>cr(n,i))),s=cr(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 os(e){if(typeof e.path!="string")return!1;let t=[...Pe().map(n=>n.path),ge()?.path].filter(n=>!!n);return!t.length&&H()&&t.push(H()),t.some(n=>Ke(e.path,n))}function li(e,t,n,r){return!["message","card"].includes(e?.item_type)||!Ke(e.path,t)?!1:!n||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&&Ke(e.path,i)})}var ka=new WeakMap;function Ma(e,t,n){let r=ka.get(e);r||(r=new Map,ka.set(e,r));let s=JSON.stringify(t),i=r.get(s);if(!i){let c=!1,a,l=!1,d=!1,p=new Set,m=new Set,f=()=>e.getQueryData(t)??[],y=()=>{c||l||a||(a=setTimeout(()=>{a=void 0,h()},250))},h=async()=>{if(c)return;l=!0;let F=d;d=!1;let C=[...p],k=new Set(m);m.clear(),p.clear();try{if(F)await Ee(e,t,{exact:!0});else{let N=(await Promise.allSettled(C.map(async I=>{let $=e.getQueryCache().find({queryKey:t,exact:!0});if(!$)return;let M=await S("read",{id:I});if(M.success===!1)throw new Error("Channel refresh failed");if(c||!$||e.getQueryCache().find({queryKey:t,exact:!0})!==$)return;let E=ye(M.item??M);if(E.id!==I||E.item_type!=="channel")return;let Q=f().find(V=>V.id===I);if(!Q)return;let O=n({...E}),ue={...Q,path:O.path,name:O.name,displayName:O.displayName,messageCount:O.messageCount,aiMode:O.aiMode,isPrivate:O.isPrivate,isDm:O.isDm,autoPilot:O.autoPilot,updatedAt:O.updatedAt};k.has(I)&&(Q.name!==ue.name||Q.displayName!==ue.displayName||Q.path!==ue.path)&&(d=!0),e.setQueryData(t,V=>V?.map(Oe=>Oe.id===I?ue:Oe))}))).find(I=>I.status==="rejected");if(N?.status==="rejected")throw N.reason}}catch(U){console.warn("[channels] refresh failed",U)}finally{l=!1,(d||p.size)&&y()}},g=F=>f().some(C=>C.id===F.item_id||C.path===F.path)?!0:os(F),v=F=>{if(!g(F))return;let C=String(F.action??"").toLowerCase();if(["insert","delete","rename","move"].includes(C))d=!0;else if(C==="update"){let k=f().find(U=>U.id===F.item_id||U.path===F.path);k&&(p.add(k.id),m.add(k.id))}(d||p.size)&&y()},x=F=>{let C=f().find(k=>k.id===F.parent_id);C&&(p.add(C.id),y())},q=["vfs_change","ccm_change"].flatMap(F=>[re(F,v,C=>C.item_type==="channel"),re(F,x,C=>C.item_type==="message")]);i={users:0,stop:()=>{c=!0,a&&clearTimeout(a),q.forEach(F=>F())}},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)(be,Z,Z)}function Qa(){return Y(),Or()}function Da(e){return Y(),j({queryKey:R.item(e),queryFn:()=>$r(e),enabled:!!e,staleTime:1/0})}function Ua(e){return Y(),j({queryKey:R.itemById(e),queryFn:()=>Br(e),enabled:!!e,staleTime:1/0})}function fi(e){return Y(),j({queryKey:R.children(e),queryFn:()=>sr(e),enabled:!!e})}function Na(e){let t=fi(e);return{...t,children:t.data??[]}}function Ka(e,t=1){return Y(),j({queryKey:R.tree(e,t),queryFn:()=>zr(e,t),enabled:!!e})}function La(e,t){return Y(),j({queryKey:R.search(e,t),queryFn:async()=>{let n={query:e};t?.length&&(n.item_types=t);let r=await S("search",n);return(r.content?.items||r.items||r.results||[]).map(ye)},enabled:!!e&&e.length>0})}function ja(e){Y();let t=(0,_.useMemo)(()=>e,[JSON.stringify(e)]);return j({queryKey:["vfs",H()??"__unscoped__","resolve",JSON.stringify(t??{})],queryFn:async()=>await S("resolve",t),enabled:!!t?.query&&t.query.length>0})}function Wa(e){Y();let t=kt(e),n=(0,_.useMemo)(()=>t,[JSON.stringify(t)]),r=j({queryKey:R.items(n?.type??"",n),queryFn:()=>vn(n),enabled:_n(n),...n?.spaceIds!==void 0?{retry:(s,i)=>!dn(i)&&s<1}:{},select:s=>s.items});return n?.spaceIds!==void 0&&dn(r.error)?{...r,data:void 0}:r}function Ba(e,t={}){let n=Y(),{realtime:r=!1}=t,s=kt(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=Vn({queryKey:c,queryFn:async({pageParam:p=0})=>vn({...o,limit:i,offset:p},{throwOnError:!0}),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:_n(o),...o?.spaceIds!==void 0?{retry:(p,m)=>!dn(m)&&p<1}:{},staleTime:r?1/0:void 0,meta:r&&o?{infiniteItemsRealtime:{filter:o}}:{}}),l=(0,_.useMemo)(()=>{if(o?.spaceIds!==void 0&&dn(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&&dn(a.error);return{allItems:l,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 $a(e){Y();let t=20,n=Vn({queryKey:["vfs",H()??"__unscoped__","infinite-children",e??""],queryFn:async({pageParam:s=0})=>Vr(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 Va(e){return Y(),j({queryKey:R.edges(e),queryFn:()=>Gr(e),enabled:!!e})}function as(e){return Y(),j({queryKey:R.types(e),queryFn:()=>Hr(e)})}function Ha(e,t){let n=as(t);return{...n,data:n.data?.get(e)??void 0}}function Ga(e,t){Y();let n=(0,_.useMemo)(()=>t?.arguments,[JSON.stringify(t?.arguments)]),r=t?.mode,s=t?.strategy,i=t?.width;return j({queryKey:[...R.openEnvelope(e,s),i],queryFn:async()=>{let o=await Zr(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 Oa={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 za(e){let t=as(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(Oa).map(([f,y])=>({key:f,label:y})),getEdgeTypeLabel:f=>Oa[f]??f.replace(/_/g," "),allTypes:n,loading:t.isLoading}),[n,t.isLoading])}function Ja(e,t,n){return Y(),j({queryKey:R.memberFocus(e),queryFn:()=>Xr(e,t,n),enabled:!!e})}function Ya(e,t={}){let{limit:n=50,offset:r=0,include_snapshots:s=!1}=t;return j({queryKey:R.itemVersions(e,String(n),String(r),String(s)),queryFn:()=>ir(e,{limit:n,offset:r,include_snapshots:s}),enabled:!!e})}function Xa(e,t=50,n=0){return j({queryKey:R.itemHistory(e,String(t),String(n)),queryFn:()=>Yr(e,t,n),enabled:!!e})}function Za(e,t=50,n=0){return Y(),j({queryKey:R.recentActivity(e,String(t),String(n)),queryFn:()=>Jr(e,t,n),enabled:!!e})}function ec(){let[e,t]=(0,_.useState)(null),[n,r]=(0,_.useState)(!0),[s,i]=(0,_.useState)(null);return(0,_.useEffect)(()=>{let o=!1;return pt().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 yl=[];function tc(){let{user:e}=cs(),t=(0,_.useRef)(null),[n,r]=(0,_.useState)(null),s=j({queryKey:R.memberships(e?.id??"anonymous"),queryFn:ts,enabled:!!e?.id,staleTime:1e3*60*2}),i=s.data??yl,o=(0,_.useMemo)(()=>i.filter(m=>m.isAccount!==!1&&!m.isSpace),[i]),c=(0,_.useMemo)(()=>{let m=new Set(o.map(y=>y.accountId)),f=y=>!y.subordinateTo||!m.has(y.subordinateTo);return[...o].sort((y,h)=>Number(f(h))-Number(f(y)))},[o]),a=(0,_.useSyncExternalStore)(be,Z,Z),l=(0,_.useMemo)(()=>{let m=ge();return m?i.find(f=>f.accountId===m.id)??null:null},[a,i]);(0,_.useEffect)(()=>{if(!e?.id){t.current=null;return}if(t.current!==e.id)if(r(null),c.length===1){let m=c[0];fe()||Et(je(m)),Ot(m.accountId),m.personalSpacePath&&Ft(m.personalSpacePath,f=>{let y=i.find(h=>h.accountId===f);return y?je(y):null}).catch(r),t.current=e.id}else c.length>1&&(t.current=e.id)},[e?.id,c,i]);let d=(0,_.useCallback)(async m=>{let f=i.find(g=>g.path===m);if(!f)throw new Error("Account membership is unavailable");let y=je(f);fe()||Et(y);let h=i.find(g=>g.accountId===fe()?.id);if(!h?.personalSpacePath)throw new Error("The home membership has no mount declaration location");await Ft(h.personalSpacePath,g=>{let v=i.find(x=>x.accountId===g);return v?je(v):null}),await lr(y),r(null),Ot(f.accountId)},[i]),p=(0,_.useCallback)(async m=>{let f=i.find(y=>y.path===m);if(!f)throw new Error("Scope membership is unavailable");await ui(je(f))},[i]);return{accounts:c,allMemberships:i,currentAccount:l,mountedScope:null,switchAccount:d,mountScope:p,loading:s.isLoading,error:s.error??n}}function nc(){Y();let e=(0,_.useSyncExternalStore)(Mr,Xn,Xn),t=(0,_.useMemo)(()=>Pe(),[e]),n=ge(),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:lr,replaceMounts:is,mount:ui,unmount:Aa}}function cs(){let[e,t]=(0,_.useState)(null),[n,r]=(0,_.useState)(null),[s,i]=(0,_.useState)(!0),o=(0,_.useRef)(null);(0,_.useEffect)(()=>{B.auth.getSession().then(({data:f,error:y})=>{if(y){console.warn("[useAuth] getSession error, clearing stale session:",y.message),B.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),B.auth.signOut().catch(()=>{}),r(null),t(null),i(!1)});let{data:{subscription:m}}=B.auth.onAuthStateChange((f,y)=>{if(f==="TOKEN_REFRESHED"&&!y){console.warn("[useAuth] TOKEN_REFRESHED with null session \u2014 signing out"),B.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?B.auth.signInWithOAuth({provider:m.provider,options:m.redirectTo?{redirectTo:m.redirectTo}:{redirectTo:window.location.href}}):B.auth.signInWithPassword({email:m.email,password:m.password}),[]),a=(0,_.useCallback)(async m=>B.auth.signUp({email:m.email,password:m.password,options:{data:m.metadata||{}}}),[]),l=(0,_.useCallback)(async()=>{await B.auth.signOut(),ln(),P().clear()},[]),d=(0,_.useCallback)(async m=>{let{error:f}=await B.auth.resetPasswordForEmail(m);if(f)throw f},[]),p=(0,_.useCallback)(async(m,f)=>{let{error:y}=await B.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:l,resetPassword:d,signInWithMagicLink:p}}function rc(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),S("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 l=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"";n({url:l+e}),s(!1)}},[e]),{data:t,loading:r,error:i}}var dr={},Fa={};ie(()=>{for(let e of Object.keys(dr))delete dr[e]});var sc=null;function ic(e){sc=e,typeof window<"u"&&!window.__FSAOS_GATEWAY__&&(window.__FSAOS_GATEWAY__=e)}function _l(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||hl;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}:gl;case"@fsaos/gateway":case"@fsaos/react":return typeof window<"u"&&window.__FSAOS_GATEWAY__||sc||{};case"@fsaos/ui":return typeof window<"u"&&window.__FSAOS_UI__||{};case"@fsaos/theme":return{};default:return console.warn(`[useComponent] Unknown module requested: ${e}`),{}}}function vl(e,t){return e.replace(/^(\s*)(:root|body)(\s*[{,])/gm,(n,r,s,i)=>`${r}.${t}${i}`)}async function bl(e,t){if(!Fa[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=vl(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),Fa[e]=s}catch{}}function wl(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)(_l),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 l=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"";return(async()=>{try{let d=1,p=e+"@v1",m=l+e+"/__bundle.js";try{let v=await fetch(l+e+"/__meta",{cache:"no-store"});v.ok&&(d=(await v.json()).version||1,p=e+"@v"+d,m=l+e+"/__bundle.v"+d+".js")}catch{m=l+e+"/__bundle.js?v="+Date.now()}if(c)return;if(dr[p]){n(()=>dr[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 h=m.replace(/__bundle(\.v\d+)?\.js(\?.*)?$/,"__bundle$1.css");bl(h).catch(()=>{});let g=wl(y);if(!g)throw new Error("Bundle did not export a component. Expected window.__FSAOS_COMPONENT__ (FSAOS build) or a __FSAOS_REGISTER__(Component) call.");if(typeof g!="function")throw new Error(`Bundle export is not a React component (got ${typeof g})`);dr[p]=g,c||(n(()=>g),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 Sl=["--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 oc(){return{data:(0,_.useMemo)(()=>{if(typeof document>"u")return{tokens:{}};let t={},n=getComputedStyle(document.documentElement);return Sl.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 cc(e,t){let n={};return(t||[]).forEach(r=>{n[r]=!0}),{data:n,loading:!1,error:null}}var ce=null,Rn=null,di=new Set;function Rl(){di.forEach(e=>e())}ie(()=>{ce=null,Rn=null});async function uc(e){let t={principalId:null,displayName:null,createdAt:null,metadata:null,vfsPath:null},n=It()?.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 B.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 Rn||(Rn=(async()=>{try{let{data:s,error:i}=await B.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:l}=await B.from("os_items").select("path").eq("owner_principal_id",o).eq("item_type","principal").eq("is_active",!0).like("path","/root/principals/%"),d=(l??[]).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{Rn=null}})(),Rn)}async function lc(e){return(await uc(e)).principalId}function dc(){let e=cs(),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 di.add(o),()=>{di.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,uc(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 fc(){return{data:null,loading:!1,error:null}}function pc(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 mc(e){return e.children}function hc(e){let t=Y(),{channelPath:n,parentMessageId:r,realtime:s=!0,enabled:i}=e,o=i!==void 0?i&&!!n:!!n,c=(0,_.useMemo)(()=>R.channelMessages(n??"",r),[n,r,t]),a=W(),l=(0,_.useRef)(null),d=j({queryKey:c,queryFn:()=>es(n,r),enabled:o});(0,_.useEffect)(()=>{if(!s||!o)return;let h=re("vfs_change",()=>{l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{Ee(a,c,{exact:!0})},500)},g=>{let v=a.getQueryData(c);return li(g,n,r,[...v?.messages??[],...v?.activityMessages??[]])});return()=>{h(),l.current&&clearTimeout(l.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(h=>h.reply_count>0),[m]),isLoading:d.isLoading,isFetching:d.isFetching,error:d.error,refetch:d.refetch}}function gc(e){Y();let{channelPath:t,parentMessageId:n,limit:r=50,realtime:s=!0,enabled:i=!0}=e,o=!!n,c=i&&!!t,a=Vn({queryKey:[...R.channelMessages(t||"",n),"infinite",r],queryFn:async({pageParam:h})=>or(t,{parentMessageId:n,limit:r,before_seq:o?void 0:h,after_seq:o?h:void 0}),initialPageParam:void 0,getNextPageParam:h=>!o||h.messages.length<r?void 0:h.messages[h.messages.length-1]?.seq,getPreviousPageParam:h=>o||h.messages.length<r?void 0:h.messages[0]?.seq,enabled:c}),l=(0,_.useMemo)(()=>{if(!a.data?.pages)return[];let h=new Set,g=[];for(let v of a.data.pages)for(let x of v.messages)h.has(x.id)||(h.add(x.id),g.push(x));return g.sort((v,x)=>v.seq-x.seq)},[a.data?.pages]),{messageCards:d,siblingCards:p}=(0,_.useMemo)(()=>{let h=new Map,g=[];if(!a.data?.pages)return{messageCards:h,siblingCards:g};let v=new Set;for(let x of a.data.pages){for(let[q,F]of x.messageCards)for(let C of F){if(v.has(C.id))continue;v.add(C.id);let k=h.get(q)||[];k.push(C),h.set(q,k)}for(let q of x.siblingCards)v.has(q.id)||(v.add(q.id),g.push(q))}return{messageCards:h,siblingCards:g}},[a.data?.pages]),m=W(),f=(0,_.useRef)(null),y=(0,_.useMemo)(()=>[...R.channelMessages(t||"",n),"infinite",r],[t,n,r]);return(0,_.useEffect)(()=>{if(!s||!t||!c)return;let h=()=>void Ee(m,y,{exact:!0}),g=!1,v=!1,x=!1,q=async()=>{let k=m.getQueryData(y);if(!k?.pages?.length){h();return}let U=0;for(let N of k.pages)for(let I of N.messages)I.seq>U&&(U=I.seq);if(U===0){h();return}try{let N=await or(t,{parentMessageId:n,limit:r,after_seq:U});if(N.messages.length===0&&N.siblingCards.length===0){h();return}if(N.messages.length>0){let I=Math.min(...N.messages.map($=>$.seq));if(I>U+1){console.warn(`[useInfiniteChannelMessages] sequence gap detected: maxSeq=${U}, minNewSeq=${I}. Triggering full refetch.`),h();return}}m.setQueryData(y,I=>{if(!I)return I;let $=[...I.pages],M=$.length-1,E=$[M],Q=new Set(E.messages.map(Se=>Se.id)),O=N.messages.filter(Se=>!Q.has(Se.id)),ue=[...E.messages,...O].sort((Se,ys)=>Se.seq-ys.seq),V=new Map(E.messageCards);for(let[Se,ys]of N.messageCards){let Pi=V.get(Se)||[],Su=new Set(Pi.map(_s=>_s.id)),Ru=ys.filter(_s=>!Su.has(_s.id));V.set(Se,[...Pi,...Ru])}let Oe=new Set(E.siblingCards.map(Se=>Se.id)),bu=N.siblingCards.filter(Se=>!Oe.has(Se.id)),wu=[...E.siblingCards,...bu];return $[M]={...E,activityMessages:N.activityMessages??[],messages:ue,messageCards:V,siblingCards:wu},{...I,pages:$}})}catch(N){console.warn("[useInfiniteChannelMessages] live tail fetch failed, falling back to full invalidation:",N),h()}},F=async()=>{if(g){v=!0;return}g=!0;try{do v=!1,await q();while(v&&!x)}finally{g=!1}},C=re("vfs_change",()=>{f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{F()},500)},k=>li(k,t,n,m.getQueryData(y)?.pages.flatMap(U=>U.messages)??[]));return()=>{x=!0,C(),f.current&&clearTimeout(f.current)}},[s,t,c,y,m,n,r]),{messages:l,activityMessages:a.data?.pages.at(-1)?.activityMessages??[],messageCards:d,siblingCards:p,threads:l.filter(h=>h.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}}function Cl(e){return e==="on"||e==="auto"?"on":"off"}function qa(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:Cl(t.ai_mode),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}}function us(e={}){let t=Y(),{realtime:n=!0,enabled:r=!0}=e,s=W(),i=(0,_.useMemo)(()=>R.channels("all"),[t]),o=j({queryKey:i,queryFn:async()=>((await S("query",{item_type:"channel",include_reader:!0,limit:500})).items||[]).map(qa),enabled:r});return(0,_.useEffect)(()=>{if(!(!n||!r))return Ma(s,i,qa)},[n,r,i,s]),{channels:o.data??[],isLoading:o.isLoading,isFetching:o.isFetching,error:o.error,refetch:o.refetch}}function yc(e={}){let t=us(e),n=(0,_.useMemo)(()=>t.channels.filter(r=>!r.isDm),[t.channels]);return{...t,channels:n}}function _c(e={}){let t=us(e),n=(0,_.useMemo)(()=>t.channels.filter(r=>r.isDm),[t.channels]);return{...t,channels:n}}function mi(e={}){let t=Y(),{filter:n="all",limit:r=200,realtime:s=!0,enabled:i=!0}=e,o=W(),c=(0,_.useRef)(null),a=(0,_.useMemo)(()=>R.notifications(n,r),[n,r,t]),l=j({queryKey:a,queryFn:async()=>{let p={limit:r};return n==="unread"&&(p.filter="unread"),(await S("get-notifications",p)).notifications||[]},enabled:i});return(0,_.useEffect)(()=>{if(!s||!i)return;let p=["vfs_change","ccm_change"].map(m=>re(m,()=>{c.current&&clearTimeout(c.current),c.current=setTimeout(()=>{o.invalidateQueries({queryKey:a})},2e3)},f=>f.item_type==="notification"&&os(f)));return()=>{p.forEach(m=>m()),c.current&&clearTimeout(c.current)}},[s,i,a,o]),{notifications:l.data??[],isLoading:l.isLoading,isFetching:l.isFetching,error:l.error,refetch:l.refetch}}function vc(e={}){let{channels:t,realtime:n=!0,enabled:r=!0}=e,{notifications:s,isLoading:i,isFetching:o,error:c,refetch:a}=mi({filter:"unread",limit:200,realtime:n,enabled:r}),l=(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 l.forEach(y=>{f+=y}),f},[l]),{dmUnread:p,channelUnread:m}=(0,_.useMemo)(()=>{if(!t)return{dmUnread:0,channelUnread:0};let f=new Set(t.filter(g=>g.isDm).map(g=>g.id)),y=0,h=0;return l.forEach((g,v)=>{f.has(v)?y+=g:h+=g}),{dmUnread:y,channelUnread:h}},[t,l]);return{unreadByChannel:l,totalUnread:d,dmUnread:p,channelUnread:m,isLoading:i,isFetching:o,error:c,refetch:a}}function bc(){let e=W();return de({mutationFn:t=>S("create",t),onSuccess:(t,n)=>{let r=n.parent_path;r&&e.invalidateQueries({queryKey:R.children(r)})}})}function wc(){let e=W();return de({mutationFn:t=>S("update",t),onSuccess:(t,n)=>{let r=n.path;if(r){e.invalidateQueries({queryKey:R.item(r)});let s=r.split("/");s.pop();let i=s.join("/");i&&e.invalidateQueries({queryKey:R.children(i)})}}})}function Sc(){return de({mutationFn:e=>S("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},Rl()}})}function Rc(){let e=W();return de({mutationFn:t=>S("delete",t),onSuccess:(t,n)=>{let r=n.path;if(r){e.removeQueries({queryKey:R.item(r)});let s=r.split("/");s.pop();let i=s.join("/");i&&e.invalidateQueries({queryKey:R.children(i)})}}})}function Cc(){let e=W();return de({mutationFn:t=>S("move",t),onSuccess:(t,n)=>{let r=n.path,s=n.new_parent_path;if(r){e.invalidateQueries({queryKey:R.item(r)});let i=r.split("/");i.pop();let o=i.join("/");o&&e.invalidateQueries({queryKey:R.children(o)})}s&&e.invalidateQueries({queryKey:R.children(s)})}})}function xc(){let e=W();return de({mutationFn:t=>S("link",t),onSuccess:(t,n)=>{let r=n.source_id,s=n.target_id;r&&e.invalidateQueries({queryKey:R.edges(r)}),s&&e.invalidateQueries({queryKey:R.edges(s)})}})}function Pc(e,t){let n=W(),{optimistic:r,...s}=t??{};return de({mutationFn:i=>S(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 Tc(e,t,n){let r,s,i,o=!0;if(typeof e=="string")r=e,s=t,i=n;else{s=e;let l=t;r=l.eventType,i=l.filter,o=l.enabled??!0}let c=(0,_.useRef)(s),a=(0,_.useRef)(i);(0,_.useEffect)(()=>{c.current=s,a.current=i},[s,i]),(0,_.useEffect)(()=>o?re(r,d=>c.current(d),a.current?d=>a.current(d):void 0):void 0,[r,o])}function Ec(e){let{queryKey:t,queryFn:n,eventType:r,filter:s,enabled:i=!0,debounceMs:o=500}=e,c=W(),a=(0,_.useRef)(s);a.current=s;let l=(0,_.useRef)(null),d=j({queryKey:t,queryFn:n,enabled:i});return(0,_.useEffect)(()=>{if(!i)return;let p=re(r,()=>{l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{Ee(c,t,{exact:!0})},o)},m=>a.current?.(m)??!0);return()=>{p(),l.current&&clearTimeout(l.current)}},[r,i,o,c,JSON.stringify(t)]),d}function Cn(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=j({queryKey:i,staleTime:1/0,retry:!1,meta:{arrangementRealtime:!0},queryFn:async()=>{if(!n)return null;let m=await S("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]),l=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,x)=>[v,x])),h=[],g=[];for(let v of m)(y.has(f(v))?h:g).push(v);return h.sort((v,x)=>y.get(f(v))-y.get(f(x))),[...h,...g]},[d]);return{...o,arrangement:c,resolvedChildren:a,resolutionLevel:l,order:d,sourceScopeId:c?.scope_item_id??null,arrangementQueryKey:i,applyTo:p}}function Ic(e){let{origin:t,originField:n,fallbackUrl:r,mintError:s,scopeId:i,scopePath:o}=e,c=Y(),a=It(),l=i??a?.scope_id??null,d=(0,_.useMemo)(()=>{if(!t)return null;let C="/accounts/",k=t.indexOf(C);if(k===-1)return null;let U=t.indexOf("/",k+C.length);return U===-1?t:t.slice(0,U)},[t]),p=o??d??a?.scope_path??null,m=n?.trim()||null,f=`${c}
4
- ${l??""}
1
+ /* @fsaos/gateway v2.0.0 — Unified FSAOS Edge Runtime — 2026-10-14T06:13:57.506Z */
2
+ "use strict";var __FSAOS_GATEWAY__=(()=>{var Pu=Object.create;var An=Object.defineProperty;var Tu=Object.getOwnPropertyDescriptor;var Eu=Object.getOwnPropertyNames;var Iu=Object.getPrototypeOf,Au=Object.prototype.hasOwnProperty;var Ii=e=>{throw TypeError(e)};var ku=(e,t,n)=>t in e?An(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var kn=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Mu=(e,t)=>{for(var n in t)An(e,n,{get:t[n],enumerable:!0})},Ai=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Eu(t))!Au.call(e,s)&&s!==n&&An(e,s,{get:()=>t[s],enumerable:!(r=Tu(t,s))||r.enumerable});return e};var X=(e,t,n)=>(n=e!=null?Pu(Iu(e)):{},Ai(t||!e||!e.__esModule?An(n,"default",{value:e,enumerable:!0}):n,e)),Ou=e=>Ai(An({},"__esModule",{value:!0}),e);var ee=(e,t,n)=>ku(e,typeof t!="symbol"?t+"":t,n),bs=(e,t,n)=>t.has(e)||Ii("Cannot "+n);var l=(e,t,n)=>(bs(e,t,"read from private field"),n?n.call(e):t.get(e)),R=(e,t,n)=>t.has(e)?Ii("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),b=(e,t,n,r)=>(bs(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n),k=(e,t,n)=>(bs(e,t,"access private method"),n);var Mn=(e,t,n,r)=>({set _(s){b(e,t,s,n)},get _(){return l(e,t,r)}});var oe=kn((Gl,ki)=>{ki.exports=React});var Pr=kn(($f,fo)=>{fo.exports={jsx:React.createElement,jsxs:React.createElement,Fragment:React.Fragment}});var xo=kn((Rp,Co)=>{Co.exports={createClient:window.supabase.createClient}});var Wo=kn((Fp,Vo)=>{Vo.exports=ReactDOM});var Gc=kn((Eh,Hc)=>{Hc.exports=ReactDOM});var Ti={};Mu(Ti,{ComponentRenderer:()=>hc,EnforcementDeniedError:()=>tt,FormSubmissionError:()=>In,GatewayRequestError:()=>Ee,InteractionTrackingError:()=>Pn,KernelProvider:()=>gc,QueryClientProvider:()=>Wn,assignPersonalSection:()=>vu,auth:()=>su,awaitAnchorReady:()=>Yn,awaitScopeReady:()=>Fo,callTool:()=>tu,cancelQueuedTurn:()=>Bc,cancelTurn:()=>Vc,clearCachedToken:()=>Hs,clearSession:()=>ei,createItem:()=>Xc,disconnectSSE:()=>ai,disposeVfsRealtimeWs:()=>ui,electHomeAnchor:()=>It,emitEvent:()=>la,fetchChannelMessages:()=>ba,fetchChannelMessagesPage:()=>ar,fetchChannelMessagesWithCards:()=>ts,fetchEdgesForItem:()=>zr,fetchItemHistory:()=>Xr,fetchItemVersions:()=>or,fetchItems:()=>vn,fetchMemberFocus:()=>Zr,fetchOpenEnvelope:()=>es,fetchRecentActivity:()=>Yr,fetchResolvedItems:()=>Ri,fetchTimelineHistory:()=>Ci,fetchTurnQueueEntries:()=>ya,fetchTypeDefinitions:()=>Gr,fetchVfsChildren:()=>ir,fetchVfsChildrenPage:()=>Hr,fetchVfsItem:()=>sr,fetchVfsItemById:()=>$r,fetchVfsTree:()=>Jr,gatewayCall:()=>C,getAccessToken:()=>Je,getAnchor:()=>un,getAnchorRef:()=>ge,getAnchorVersion:()=>Js,getAssetUrl:()=>ru,getDefaultSort:()=>cu,getHomeAnchor:()=>fe,getMountVersion:()=>Xn,getMounts:()=>Te,getPathSubscriptionState:()=>fa,getQueryClient:()=>A,getRequiredFormFields:()=>uu,getScope:()=>H,getScopeVersion:()=>Z,getServerClockOffsetMs:()=>No,getServerClockSyncedAt:()=>Ko,getSessionEntry:()=>At,hasServerClock:()=>Uo,initSession:()=>pt,initVfsRealtimeWs:()=>Ot,initializeFsaos:()=>jc,initializeWorkspace:()=>ps,interpretSchema:()=>Si,invalidateAllVfs:()=>Ra,invalidateChannelMessages:()=>xa,invalidateChildren:()=>Br,invalidateItem:()=>ci,invalidateOpenEnvelope:()=>Pa,invalidatePathAndParent:()=>wa,invalidateSubtree:()=>Sa,invalidateTypes:()=>Ca,isAnchorReady:()=>Xs,isChannelPath:()=>we,isListableItemsFilter:()=>_n,isScopeReady:()=>Fr,itemsFilterFromQueryFilter:()=>_a,listChildren:()=>Yc,loadMounts:()=>Ft,mount:()=>iu,mountRealtimeScope:()=>wn,normalizeItem:()=>ye,onConnectionStateChange:()=>Wr,pathSubscriptionMatches:()=>si,personalSectionsKey:()=>gr,ping:()=>da,pushChanges:()=>eu,queryClient:()=>Yo,readItem:()=>Jc,refreshQuery:()=>Ie,registerCleanup:()=>ie,replaceMounts:()=>os,resetAllSdkState:()=>ln,resolvePrincipalId:()=>fc,resubscribePath:()=>ma,selectMount:()=>dr,serverDeadlinePassed:()=>Lo,serverMsUntil:()=>jo,serverNow:()=>qr,setAnchor:()=>Mr,setCachedToken:()=>Eo,setQueryClient:()=>Jo,setScope:()=>Oo,setupRequireShim:()=>ou,signal:()=>nu,startTracking:()=>fs,steerTurn:()=>Wc,submitForm:()=>$c,subscribeAnchor:()=>Ys,subscribeArtifactStream:()=>ms,subscribeMounts:()=>Or,subscribeScope:()=>be,subscribeToEvents:()=>te,subscribeToPath:()=>Vr,subscribeToScope:()=>yn,trackAction:()=>Nc,trackEvent:()=>qt,trackPageView:()=>Uc,unmountRealtimeScope:()=>ss,updateItem:()=>Zc,uploadFile:()=>lu,useAccounts:()=>rc,useAgentTimeline:()=>gu,useAllChannels:()=>ls,useArrangement:()=>Cn,useArtifactStream:()=>hu,useAsset:()=>ic,useAuth:()=>us,useChannelMessages:()=>yc,useChannels:()=>vc,useChildren:()=>La,useComponent:()=>hi,useCreate:()=>Sc,useDelete:()=>xc,useDmChannels:()=>bc,useEdges:()=>Ga,useEventStream:()=>Ic,useFileUpload:()=>fu,useIncrementalItems:()=>$a,useInfiniteChannelMessages:()=>_c,useInfiniteChildren:()=>Ha,useInfiniteItems:()=>mi,useItem:()=>Na,useItemById:()=>Ka,useItemHistory:()=>ec,useItemVersions:()=>Za,useItems:()=>Ba,useLink:()=>Tc,useList:()=>pi,useMemberFocus:()=>Xa,useMintedAsset:()=>kc,useMounts:()=>sc,useMove:()=>Pc,useMutation:()=>Ec,useNotifications:()=>gi,useOpen:()=>Ja,usePermission:()=>uc,usePermissions:()=>lc,usePersonalItemOrder:()=>Mc,usePersonalSections:()=>wu,usePinnedItems:()=>_u,usePrincipal:()=>pc,useRealtimeQuery:()=>Ac,useRecentActivity:()=>tc,useResolve:()=>Wa,useResolvedItems:()=>mu,useScope:()=>nc,useScopeReady:()=>Ua,useSearch:()=>Va,useTheme:()=>cc,useTimelineHistory:()=>yu,useTool:()=>mc,useTree:()=>ja,useType:()=>za,useTypeHelpers:()=>Ya,useTypes:()=>cs,useUnreadCounts:()=>wc,useUpdate:()=>Rc,useUpdatePrincipal:()=>Cc,vfsKeys:()=>x,waitForPathReady:()=>pa});var tt=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 xn=X(oe(),1);var Ce=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}};var _t,nt,Dt,Mi,Fu=(Mi=class extends Ce{constructor(){super();R(this,_t);R(this,nt);R(this,Dt);b(this,Dt,t=>{if(typeof window<"u"&&window.addEventListener){let n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){l(this,nt)||this.setEventListener(l(this,Dt))}onUnsubscribe(){var t;this.hasListeners()||((t=l(this,nt))==null||t.call(this),b(this,nt,void 0))}setEventListener(t){var n;b(this,Dt,t),(n=l(this,nt))==null||n.call(this),b(this,nt,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){l(this,_t)!==t&&(b(this,_t,t),this.onFocus())}onFocus(){let t=this.isFocused();this.listeners.forEach(n=>{n(t)})}isFocused(){return typeof l(this,_t)=="boolean"?l(this,_t):globalThis.document?.visibilityState!=="hidden"}},_t=new WeakMap,nt=new WeakMap,Dt=new WeakMap,Mi),Ut=new Fu;var qu={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},rt,ws,Oi,Qu=(Oi=class{constructor(){R(this,rt,qu);R(this,ws,!1)}setTimeoutProvider(e){b(this,rt,e)}setTimeout(e,t){return l(this,rt).setTimeout(e,t)}clearTimeout(e){l(this,rt).clearTimeout(e)}setInterval(e,t){return l(this,rt).setInterval(e,t)}clearInterval(e){l(this,rt).clearInterval(e)}},rt=new WeakMap,ws=new WeakMap,Oi),qe=new Qu;function Fi(e){setTimeout(e,0)}var Rs=typeof window>"u"||"Deno"in globalThis;function G(){}function Di(e,t){return typeof e=="function"?e(t):e}function On(e){return typeof e=="number"&&e>=0&&e!==1/0}function yr(e,t){return Math.max(e+(t||0)-Date.now(),0)}function ke(e,t){return typeof e=="function"?e(t):e}function pe(e,t){return typeof e=="function"?e(t):e}function _r(e,t){let{type:n="all",exact:r,fetchStatus:s,predicate:i,queryKey:o,stale:c}=e;if(o){if(r){if(t.queryHash!==Fn(o,t.options))return!1}else if(!vt(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 vr(e,t){let{exact:n,status:r,predicate:s,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(Qe(t.options.mutationKey)!==Qe(i))return!1}else if(!vt(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||s&&!s(t))}function Fn(e,t){return(t?.queryKeyHashFn||Qe)(e)}function Qe(e){return JSON.stringify(e,(t,n)=>Ss(n)?Object.keys(n).sort().reduce((r,s)=>(r[s]=n[s],r),{}):n)}function vt(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>vt(e[n],t[n])):!1}var Du=Object.prototype.hasOwnProperty;function Cs(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=qi(e)&&qi(t);if(!r&&!(Ss(e)&&Ss(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:Du.call(e,p))&&u++;continue}if(m===null||f===null||typeof m!="object"||typeof f!="object"){a[p]=f;continue}let y=Cs(m,f,n+1);a[p]=y,y===m&&u++}return i===c&&u===i?e:a}function Nt(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 qi(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Ss(e){if(!Qi(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!Qi(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function Qi(e){return Object.prototype.toString.call(e)==="[object Object]"}function Ui(e){return new Promise(t=>{qe.setTimeout(t,e)})}function qn(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?Cs(e,t):t}function Ni(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function Ki(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var Kt=Symbol();function br(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===Kt?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function Lt(e,t){return typeof e=="function"?e(...t):!!e}function Li(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 De=(()=>{let e=()=>Rs;return{isServer(){return e()},setIsServer(t){e=t}}})();function Qn(){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 ji=Fi;function Uu(){let e=[],t=0,n=c=>{c()},r=c=>{c()},s=ji,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=Uu();var jt,st,Vt,Vi,Nu=(Vi=class extends Ce{constructor(){super();R(this,jt,!0);R(this,st);R(this,Vt);b(this,Vt,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,st)||this.setEventListener(l(this,Vt))}onUnsubscribe(){var t;this.hasListeners()||((t=l(this,st))==null||t.call(this),b(this,st,void 0))}setEventListener(t){var n;b(this,Vt,t),(n=l(this,st))==null||n.call(this),b(this,st,t(this.setOnline.bind(this)))}setOnline(t){l(this,jt)!==t&&(b(this,jt,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return l(this,jt)}},jt=new WeakMap,st=new WeakMap,Vt=new WeakMap,Vi),Wt=new Nu;function Ku(e){return Math.min(1e3*2**e,3e4)}function xs(e){return(e??"online")==="online"?Wt.isOnline():!0}var wr=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function Sr(e){let t=!1,n=0,r,s=Qn(),i=()=>s.status!=="pending",o=h=>{if(!i()){let g=new wr(h);m(g),e.onCancel?.(g)}},c=()=>{t=!0},a=()=>{t=!1},u=()=>Ut.isFocused()&&(e.networkMode==="always"||Wt.isOnline())&&e.canRun(),d=()=>xs(e.networkMode)&&e.canRun(),p=h=>{i()||(r?.(),s.resolve(h))},m=h=>{i()||(r?.(),s.reject(h))},f=()=>new Promise(h=>{r=g=>{(i()||u())&&h(g)},e.onPause?.()}).then(()=>{r=void 0,i()||e.onContinue?.()}),y=()=>{if(i())return;let h,g=n===0?e.initialPromise:void 0;try{h=g??e.fn()}catch(v){h=Promise.reject(v)}Promise.resolve(h).then(p).catch(v=>{if(i())return;let w=e.retry??(De.isServer()?0:3),O=e.retryDelay??Ku,F=typeof O=="function"?O(n,v):O,S=w===!0||typeof w=="number"&&n<w||typeof w=="function"&&w(n,v);if(t||!S){m(v);return}n++,e.onFail?.(n,v),Ui(F).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 bt,Wi,Rr=(Wi=class{constructor(){R(this,bt)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),On(this.gcTime)&&b(this,bt,qe.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(De.isServer()?1/0:5*60*1e3))}clearGcTimeout(){l(this,bt)!==void 0&&(qe.clearTimeout(l(this,bt)),b(this,bt,void 0))}},bt=new WeakMap,Wi);var wt,Bt,xe,St,ne,Dn,Rt,ve,zi,Ve,Hi,Gi=(Hi=class extends Rr{constructor(t){super();R(this,ve);R(this,wt);R(this,Bt);R(this,xe);R(this,St);R(this,ne);R(this,Dn);R(this,Rt);b(this,Rt,!1),b(this,Dn,t.defaultOptions),this.setOptions(t.options),this.observers=[],b(this,St,t.client),b(this,xe,l(this,St).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,b(this,wt,$i(this.options)),this.state=t.state??l(this,wt),this.scheduleGc()}get meta(){return this.options.meta}get promise(){return l(this,ne)?.promise}setOptions(t){if(this.options={...l(this,Dn),...t},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let n=$i(this.options);n.data!==void 0&&(this.setState(Bi(n.data,n.dataUpdatedAt)),b(this,wt,n))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&l(this,xe).remove(this)}setData(t,n){let r=qn(this.state.data,t,this.options);return k(this,ve,Ve).call(this,{data:r,type:"success",dataUpdatedAt:n?.updatedAt,manual:n?.manual}),r}setState(t,n){k(this,ve,Ve).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){let n=l(this,ne)?.promise;return l(this,ne)?.cancel(t),n?n.then(G).catch(G):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return l(this,wt)}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(t=>pe(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Kt||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>ke(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:!yr(this.state.dataUpdatedAt,t)}onFocus(){this.observers.find(n=>n.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),l(this,ne)?.continue()}onOnline(){this.observers.find(n=>n.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),l(this,ne)?.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),l(this,xe).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,ne)&&(l(this,Rt)||k(this,ve,zi).call(this)?l(this,ne).cancel({revert:!0}):l(this,ne).cancelRetry()),this.scheduleGc()),l(this,xe).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||k(this,ve,Ve).call(this,{type:"invalidate"})}async fetch(t,n){if(this.state.fetchStatus!=="idle"&&l(this,ne)?.status()!=="rejected"){if(this.state.data!==void 0&&n?.cancelRefetch)this.cancel({silent:!0});else if(l(this,ne))return l(this,ne).continueRetry(),l(this,ne).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:()=>(b(this,Rt,!0),r.signal)})},i=()=>{let a=br(this.options,n),d=(()=>{let p={client:l(this,St),queryKey:this.queryKey,meta:this.meta};return s(p),p})();return b(this,Rt,!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,St),state:this.state,fetchFn:i};return s(a),a})();this.options.behavior?.onFetch(c,this),b(this,Bt,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==c.fetchOptions?.meta)&&k(this,ve,Ve).call(this,{type:"fetch",meta:c.fetchOptions?.meta}),b(this,ne,Sr({initialPromise:n?.initialPromise,fn:c.fetchFn,onCancel:a=>{a instanceof wr&&a.revert&&this.setState({...l(this,Bt),fetchStatus:"idle"}),r.abort()},onFail:(a,u)=>{k(this,ve,Ve).call(this,{type:"failed",failureCount:a,error:u})},onPause:()=>{k(this,ve,Ve).call(this,{type:"pause"})},onContinue:()=>{k(this,ve,Ve).call(this,{type:"continue"})},retry:c.options.retry,retryDelay:c.options.retryDelay,networkMode:c.options.networkMode,canRun:()=>!0}));try{let a=await l(this,ne).start();if(a===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(a),l(this,xe).config.onSuccess?.(a,this),l(this,xe).config.onSettled?.(a,this.state.error,this),a}catch(a){if(a instanceof wr){if(a.silent)return l(this,ne).promise;if(a.revert){if(this.state.data===void 0)throw a;return this.state.data}}throw k(this,ve,Ve).call(this,{type:"error",error:a}),l(this,xe).config.onError?.(a,this),l(this,xe).config.onSettled?.(this.state.data,a,this),a}finally{this.scheduleGc()}}},wt=new WeakMap,Bt=new WeakMap,xe=new WeakMap,St=new WeakMap,ne=new WeakMap,Dn=new WeakMap,Rt=new WeakMap,ve=new WeakSet,zi=function(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"},Ve=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,...Ps(r.data,this.options),fetchMeta:t.meta??null};case"success":let s={...r,...Bi(t.data,t.dataUpdatedAt),dataUpdateCount:r.dataUpdateCount+1,...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return b(this,Bt,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,xe).notify({query:this,type:"updated",action:t})})},Hi);function Ps(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:xs(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function Bi(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function $i(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 me,N,Nn,le,Ct,$t,We,it,Kn,Ht,Gt,xt,Pt,ot,zt,L,Un,Ts,Es,Is,As,ks,Ms,Os,Zi,Xi,Ln=(Xi=class extends Ce{constructor(t,n){super();R(this,L);R(this,me);R(this,N);R(this,Nn);R(this,le);R(this,Ct);R(this,$t);R(this,We);R(this,it);R(this,Kn);R(this,Ht);R(this,Gt);R(this,xt);R(this,Pt);R(this,ot);R(this,zt,new Set);this.options=n,b(this,me,t),b(this,it,null),b(this,We,Qn()),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(l(this,N).addObserver(this),Ji(l(this,N),this.options)?k(this,L,Un).call(this):this.updateResult(),k(this,L,As).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Fs(l(this,N),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Fs(l(this,N),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,k(this,L,ks).call(this),k(this,L,Ms).call(this),l(this,N).removeObserver(this)}setOptions(t){let n=this.options,r=l(this,N);if(this.options=l(this,me).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof pe(this.options.enabled,l(this,N))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");k(this,L,Os).call(this),l(this,N).setOptions(this.options),n._defaulted&&!Nt(this.options,n)&&l(this,me).getQueryCache().notify({type:"observerOptionsUpdated",query:l(this,N),observer:this});let s=this.hasListeners();s&&Yi(l(this,N),r,this.options,n)&&k(this,L,Un).call(this),this.updateResult(),s&&(l(this,N)!==r||pe(this.options.enabled,l(this,N))!==pe(n.enabled,l(this,N))||ke(this.options.staleTime,l(this,N))!==ke(n.staleTime,l(this,N)))&&k(this,L,Ts).call(this);let i=k(this,L,Es).call(this);s&&(l(this,N)!==r||pe(this.options.enabled,l(this,N))!==pe(n.enabled,l(this,N))||i!==l(this,ot))&&k(this,L,Is).call(this,i)}getOptimisticResult(t){let n=l(this,me).getQueryCache().build(l(this,me),t),r=this.createResult(n,t);return ju(this,r)&&(b(this,le,r),b(this,$t,this.options),b(this,Ct,l(this,N).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,N)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){let n=l(this,me).defaultQueryOptions(t),r=l(this,me).getQueryCache().build(l(this,me),n);return r.fetch().then(()=>this.createResult(r,n))}fetch(t){return k(this,L,Un).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),l(this,le)))}createResult(t,n){let r=l(this,N),s=this.options,i=l(this,le),o=l(this,Ct),c=l(this,$t),u=t!==r?t.state:l(this,Nn),{state:d}=t,p={...d},m=!1,f;if(n._optimisticResults){let T=this.hasListeners(),Q=!T&&Ji(t,n),I=T&&Yi(t,r,n,s);(Q||I)&&(p={...p,...Ps(d.data,t.options)}),n._optimisticResults==="isRestoring"&&(p.fetchStatus="idle")}let{error:y,errorUpdatedAt:h,status:g}=p;f=p.data;let v=!1;if(n.placeholderData!==void 0&&f===void 0&&g==="pending"){let T;i?.isPlaceholderData&&n.placeholderData===c?.placeholderData?(T=i.data,v=!0):T=typeof n.placeholderData=="function"?n.placeholderData(l(this,Gt)?.state.data,l(this,Gt)):n.placeholderData,T!==void 0&&(g="success",f=qn(i?.data,T,n),m=!0)}if(n.select&&f!==void 0&&!v)if(i&&f===o?.data&&n.select===l(this,Kn))f=l(this,Ht);else try{b(this,Kn,n.select),f=n.select(f),f=qn(i?.data,f,n),b(this,Ht,f),b(this,it,null)}catch(T){b(this,it,T)}l(this,it)&&(y=l(this,it),f=l(this,Ht),h=Date.now(),g="error");let w=p.fetchStatus==="fetching",O=g==="pending",F=g==="error",S=O&&w,M=f!==void 0,P={status:g,fetchStatus:p.fetchStatus,isPending:O,isSuccess:g==="success",isError:F,isInitialLoading:S,isLoading:S,data:f,dataUpdatedAt:p.dataUpdatedAt,error:y,errorUpdatedAt:h,failureCount:p.fetchFailureCount,failureReason:p.fetchFailureReason,errorUpdateCount:p.errorUpdateCount,isFetched:t.isFetched(),isFetchedAfterMount:p.dataUpdateCount>u.dataUpdateCount||p.errorUpdateCount>u.errorUpdateCount,isFetching:w,isRefetching:w&&!O,isLoadingError:F&&!M,isPaused:p.fetchStatus==="paused",isPlaceholderData:m,isRefetchError:F&&M,isStale:qs(t,n),refetch:this.refetch,promise:l(this,We),isEnabled:pe(n.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){let T=P.data!==void 0,Q=P.status==="error"&&!T,I=D=>{Q?D.reject(P.error):T&&D.resolve(P.data)},E=()=>{let D=b(this,We,P.promise=Qn());I(D)},U=l(this,We);switch(U.status){case"pending":t.queryHash===r.queryHash&&I(U);break;case"fulfilled":(Q||P.data!==U.value)&&E();break;case"rejected":(!Q||P.error!==U.reason)&&E();break}}return P}updateResult(){let t=l(this,le),n=this.createResult(l(this,N),this.options);if(b(this,Ct,l(this,N).state),b(this,$t,this.options),l(this,Ct).data!==void 0&&b(this,Gt,l(this,N)),Nt(n,t))return;b(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)})};k(this,L,Zi).call(this,{listeners:r()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&k(this,L,As).call(this)}},me=new WeakMap,N=new WeakMap,Nn=new WeakMap,le=new WeakMap,Ct=new WeakMap,$t=new WeakMap,We=new WeakMap,it=new WeakMap,Kn=new WeakMap,Ht=new WeakMap,Gt=new WeakMap,xt=new WeakMap,Pt=new WeakMap,ot=new WeakMap,zt=new WeakMap,L=new WeakSet,Un=function(t){k(this,L,Os).call(this);let n=l(this,N).fetch(this.options,t);return t?.throwOnError||(n=n.catch(G)),n},Ts=function(){k(this,L,ks).call(this);let t=ke(this.options.staleTime,l(this,N));if(De.isServer()||l(this,le).isStale||!On(t))return;let r=yr(l(this,le).dataUpdatedAt,t)+1;b(this,xt,qe.setTimeout(()=>{l(this,le).isStale||this.updateResult()},r))},Es=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(l(this,N)):this.options.refetchInterval)??!1},Is=function(t){k(this,L,Ms).call(this),b(this,ot,t),!(De.isServer()||pe(this.options.enabled,l(this,N))===!1||!On(l(this,ot))||l(this,ot)===0)&&b(this,Pt,qe.setInterval(()=>{(this.options.refetchIntervalInBackground||Ut.isFocused())&&k(this,L,Un).call(this)},l(this,ot)))},As=function(){k(this,L,Ts).call(this),k(this,L,Is).call(this,k(this,L,Es).call(this))},ks=function(){l(this,xt)!==void 0&&(qe.clearTimeout(l(this,xt)),b(this,xt,void 0))},Ms=function(){l(this,Pt)!==void 0&&(qe.clearInterval(l(this,Pt)),b(this,Pt,void 0))},Os=function(){let t=l(this,me).getQueryCache().build(l(this,me),this.options);if(t===l(this,N))return;let n=l(this,N);b(this,N,t),b(this,Nn,t.state),this.hasListeners()&&(n?.removeObserver(this),t.addObserver(this))},Zi=function(t){j.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(l(this,le))}),l(this,me).getQueryCache().notify({query:l(this,N),type:"observerResultsUpdated"})})},Xi);function Lu(e,t){return pe(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function Ji(e,t){return Lu(e,t)||e.state.data!==void 0&&Fs(e,t,t.refetchOnMount)}function Fs(e,t,n){if(pe(t.enabled,e)!==!1&&ke(t.staleTime,e)!=="static"){let r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&qs(e,t)}return!1}function Yi(e,t,n,r){return(e!==t||pe(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&qs(e,n)}function qs(e,t){return pe(t.enabled,e)!==!1&&e.isStaleByTime(ke(t.staleTime,e))}function ju(e,t){return!Nt(e.getCurrentResult(),t)}function Jt(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=>{Li(y,()=>t.signal,()=>d=!0)},m=br(t.options,t.fetchOptions),f=async(y,h,g)=>{if(d)return Promise.reject();if(h==null&&y.pages.length)return Promise.resolve(y);let w=(()=>{let M={client:t.client,queryKey:t.queryKey,pageParam:h,direction:g?"backward":"forward",meta:t.options.meta};return p(M),M})(),O=await m(w),{maxPages:F}=t.options,S=g?Ki:Ni;return{pages:S(y.pages,O,F),pageParams:S(y.pageParams,h,F)}};if(s&&i.length){let y=s==="backward",h=y?eo:Qs,g={pages:i,pageParams:o},v=h(r,g);c=await f(g,v,y)}else{let y=e??i.length;do{let h=a===0?o[0]??r.initialPageParam:Qs(r,c);if(a>0&&h==null)break;c=await f(c,h),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 Qs(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 eo(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function to(e,t){return t?Qs(e,t)!=null:!1}function no(e,t){return!t||!e.getPreviousPageParam?!1:eo(e,t)!=null}var Ds=class extends Ln{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:Jt()})}getOptimisticResult(e){return e.behavior=Jt(),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:to(t,n.data),hasPreviousPage:no(t,n.data),isFetchNextPageError:u,isFetchingNextPage:d,isFetchPreviousPageError:p,isFetchingPreviousPage:m,isRefetchError:c&&!u&&!p,isRefetching:i&&!d&&!m}}};var jn,Ue,ae,Tt,Ne,at,ro,so=(ro=class extends Rr{constructor(t){super();R(this,Ne);R(this,jn);R(this,Ue);R(this,ae);R(this,Tt);b(this,jn,t.client),this.mutationId=t.mutationId,b(this,ae,t.mutationCache),b(this,Ue,[]),this.state=t.state||Us(),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,Ue).includes(t)||(l(this,Ue).push(t),this.clearGcTimeout(),l(this,ae).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){b(this,Ue,l(this,Ue).filter(n=>n!==t)),this.scheduleGc(),l(this,ae).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){l(this,Ue).length||(this.state.status==="pending"?this.scheduleGc():l(this,ae).remove(this))}continue(){return l(this,Tt)?.continue()??this.execute(this.state.variables)}async execute(t){let n=()=>{k(this,Ne,at).call(this,{type:"continue"})},r={client:l(this,jn),meta:this.options.meta,mutationKey:this.options.mutationKey};b(this,Tt,Sr({fn:()=>this.options.mutationFn?this.options.mutationFn(t,r):Promise.reject(new Error("No mutationFn found")),onFail:(o,c)=>{k(this,Ne,at).call(this,{type:"failed",failureCount:o,error:c})},onPause:()=>{k(this,Ne,at).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,Tt).canStart();try{if(s)n();else{k(this,Ne,at).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&&k(this,Ne,at).call(this,{type:"pending",context:c,variables:t,isPaused:i})}let o=await l(this,Tt).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),k(this,Ne,at).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 k(this,Ne,at).call(this,{type:"error",error:o}),o}finally{l(this,ae).runNext(this)}}},jn=new WeakMap,Ue=new WeakMap,ae=new WeakMap,Tt=new WeakMap,Ne=new WeakSet,at=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,Ue).forEach(r=>{r.onMutationUpdate(t)}),l(this,ae).notify({mutation:this,type:"updated",action:t})})},ro);function Us(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Be,Me,Vn,io,oo=(io=class extends Ce{constructor(t={}){super();R(this,Be);R(this,Me);R(this,Vn);this.config=t,b(this,Be,new Set),b(this,Me,new Map),b(this,Vn,0)}build(t,n,r){let s=new so({client:t,mutationCache:this,mutationId:++Mn(this,Vn)._,options:t.defaultMutationOptions(n),state:r});return this.add(s),s}add(t){l(this,Be).add(t);let n=Cr(t);if(typeof n=="string"){let r=l(this,Me).get(n);r?r.push(t):l(this,Me).set(n,[t])}this.notify({type:"added",mutation:t})}remove(t){if(l(this,Be).delete(t)){let n=Cr(t);if(typeof n=="string"){let r=l(this,Me).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,Me).delete(n)}}this.notify({type:"removed",mutation:t})}canRun(t){let n=Cr(t);if(typeof n=="string"){let s=l(this,Me).get(n)?.find(i=>i.state.status==="pending");return!s||s===t}else return!0}runNext(t){let n=Cr(t);return typeof n=="string"?l(this,Me).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,Me).clear()})}getAll(){return Array.from(l(this,Be))}find(t){let n={exact:!0,...t};return this.getAll().find(r=>vr(n,r))}findAll(t={}){return this.getAll().filter(n=>vr(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,Me=new WeakMap,Vn=new WeakMap,io);function Cr(e){return e.options.scope?.id}var $e,ct,he,He,Ge,xr,Ns,ao,Ks=(ao=class extends Ce{constructor(t,n){super();R(this,Ge);R(this,$e);R(this,ct);R(this,he);R(this,He);b(this,$e,t),this.setOptions(n),this.bindMethods(),k(this,Ge,xr).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,$e).defaultMutationOptions(t),Nt(this.options,n)||l(this,$e).getMutationCache().notify({type:"observerOptionsUpdated",mutation:l(this,he),observer:this}),n?.mutationKey&&this.options.mutationKey&&Qe(n.mutationKey)!==Qe(this.options.mutationKey)?this.reset():l(this,he)?.state.status==="pending"&&l(this,he).setOptions(this.options)}onUnsubscribe(){this.hasListeners()||l(this,he)?.removeObserver(this)}onMutationUpdate(t){k(this,Ge,xr).call(this),k(this,Ge,Ns).call(this,t)}getCurrentResult(){return l(this,ct)}reset(){l(this,he)?.removeObserver(this),b(this,he,void 0),k(this,Ge,xr).call(this),k(this,Ge,Ns).call(this)}mutate(t,n){return b(this,He,n),l(this,he)?.removeObserver(this),b(this,he,l(this,$e).getMutationCache().build(l(this,$e),this.options)),l(this,he).addObserver(this),l(this,he).execute(t)}},$e=new WeakMap,ct=new WeakMap,he=new WeakMap,He=new WeakMap,Ge=new WeakSet,xr=function(){let t=l(this,he)?.state??Us();b(this,ct,{...t,isPending:t.status==="pending",isSuccess:t.status==="success",isError:t.status==="error",isIdle:t.status==="idle",mutate:this.mutate,reset:this.reset})},Ns=function(t){j.batch(()=>{if(l(this,He)&&this.hasListeners()){let n=l(this,ct).variables,r=l(this,ct).context,s={client:l(this,$e),meta:this.options.meta,mutationKey:this.options.mutationKey};if(t?.type==="success"){try{l(this,He).onSuccess?.(t.data,n,r,s)}catch(i){Promise.reject(i)}try{l(this,He).onSettled?.(t.data,null,n,r,s)}catch(i){Promise.reject(i)}}else if(t?.type==="error"){try{l(this,He).onError?.(t.error,n,r,s)}catch(i){Promise.reject(i)}try{l(this,He).onSettled?.(void 0,t.error,n,r,s)}catch(i){Promise.reject(i)}}}this.listeners.forEach(n=>{n(l(this,ct))})})},ao);var Ke,co,uo=(co=class extends Ce{constructor(t={}){super();R(this,Ke);this.config=t,b(this,Ke,new Map)}build(t,n,r){let s=n.queryKey,i=n.queryHash??Fn(s,n),o=this.get(i);return o||(o=new Gi({client:t,queryKey:s,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(s)}),this.add(o)),o}add(t){l(this,Ke).has(t.queryHash)||(l(this,Ke).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){let n=l(this,Ke).get(t.queryHash);n&&(t.destroy(),n===t&&l(this,Ke).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){j.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return l(this,Ke).get(t)}getAll(){return[...l(this,Ke).values()]}find(t){let n={exact:!0,...t};return this.getAll().find(r=>_r(n,r))}findAll(t={}){let n=this.getAll();return Object.keys(t).length>0?n.filter(r=>_r(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()})})}},Ke=new WeakMap,co);var z,ut,lt,Yt,Xt,dt,Zt,en,lo,Ls=(lo=class{constructor(e={}){R(this,z);R(this,ut);R(this,lt);R(this,Yt);R(this,Xt);R(this,dt);R(this,Zt);R(this,en);b(this,z,e.queryCache||new uo),b(this,ut,e.mutationCache||new oo),b(this,lt,e.defaultOptions||{}),b(this,Yt,new Map),b(this,Xt,new Map),b(this,dt,0)}mount(){Mn(this,dt)._++,l(this,dt)===1&&(b(this,Zt,Ut.subscribe(async e=>{e&&(await this.resumePausedMutations(),l(this,z).onFocus())})),b(this,en,Wt.subscribe(async e=>{e&&(await this.resumePausedMutations(),l(this,z).onOnline())})))}unmount(){var e,t;Mn(this,dt)._--,l(this,dt)===0&&((e=l(this,Zt))==null||e.call(this),b(this,Zt,void 0),(t=l(this,en))==null||t.call(this),b(this,en,void 0))}isFetching(e){return l(this,z).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return l(this,ut).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(ke(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=Di(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(ke(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=Jt(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(G).catch(G)}ensureInfiniteQueryData(e){return e.behavior=Jt(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return Wt.isOnline()?l(this,ut).resumePausedMutations():Promise.resolve()}getQueryCache(){return l(this,z)}getMutationCache(){return l(this,ut)}getDefaultOptions(){return l(this,lt)}setDefaultOptions(e){b(this,lt,e)}setQueryDefaults(e,t){l(this,Yt).set(Qe(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){let t=[...l(this,Yt).values()],n={};return t.forEach(r=>{vt(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){l(this,Xt).set(Qe(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){let t=[...l(this,Xt).values()],n={};return t.forEach(r=>{vt(e,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;let t={...l(this,lt).queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Fn(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===Kt&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...l(this,lt).mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){l(this,z).clear(),l(this,ut).clear()}},z=new WeakMap,ut=new WeakMap,lt=new WeakMap,Yt=new WeakMap,Xt=new WeakMap,dt=new WeakMap,Zt=new WeakMap,en=new WeakMap,lo);var tn=X(oe(),1),po=X(Pr(),1),js=tn.createContext(void 0),W=e=>{let t=tn.useContext(js);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},Wn=({client:e,children:t})=>(tn.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,po.jsx)(js.Provider,{value:e,children:t}));var Tr=X(oe(),1),mo=Tr.createContext(!1),ho=()=>Tr.useContext(mo),Gf=mo.Provider;var Bn=X(oe(),1),Vu=X(Pr(),1);function Wu(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Bu=Bn.createContext(Wu()),go=()=>Bn.useContext(Bu);var yo=X(oe(),1);var _o=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError=="function"?Lt(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},vo=e=>{yo.useEffect(()=>{e.clearReset()},[e])},bo=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:s})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(s&&e.data===void 0||Lt(n,[e.error,r]));var wo=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))}},So=(e,t)=>e.isLoading&&e.isFetching&&!t,Ro=(e,t)=>e?.suspense&&t.isPending,Vs=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});var ft=X(oe(),1);function Er(e,t,n){let r=ho(),s=go(),i=W(n),o=i.defaultQueryOptions(e);i.getDefaultOptions().queries?._experimental_beforeQuery?.(o);let c=i.getQueryCache().get(o.queryHash);o._optimisticResults=r?"isRestoring":"optimistic",wo(o),_o(o,s,c),vo(s);let a=!i.getQueryCache().get(o.queryHash),[u]=ft.useState(()=>new t(i,o)),d=u.getOptimisticResult(o),p=!r&&e.subscribed!==!1;if(ft.useSyncExternalStore(ft.useCallback(m=>{let f=p?u.subscribe(j.batchCalls(m)):G;return u.updateResult(),f},[u,p]),()=>u.getCurrentResult(),()=>u.getCurrentResult()),ft.useEffect(()=>{u.setOptions(o)},[o,u]),Ro(o,d))throw Vs(o,u,s);if(bo({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&&!De.isServer()&&So(d,r)&&(a?Vs(o,u,s):c?.promise)?.catch(G).finally(()=>{u.updateResult()}),o.notifyOnChangeProps?d:u.trackResult(d)}function V(e,t){return Er(e,Ln,t)}var ze=X(oe(),1);function de(e,t){let n=W(t),[r]=ze.useState(()=>new Ks(n,e));ze.useEffect(()=>{r.setOptions(e)},[r,e]);let s=ze.useSyncExternalStore(ze.useCallback(o=>r.subscribe(j.batchCalls(o)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),i=ze.useCallback((o,c)=>{r.mutate(o,c).catch(G)},[r]);if(s.error&&Lt(r.options.throwOnError,[s.error]))throw s.error;return{...s,mutate:i,mutateAsync:s.mutate}}function $n(e,t){return Er(e,Ds,t)}var Po=X(xo(),1),Hn=typeof window<"u"&&window.__FSAOS_CONFIG__||{},Gn=Array.isArray(Hn.sources)?Hn.sources:[],$u=Hn.supabaseUrl||"https://vahbmsslxuustnlvsrkg.supabase.co",Hu=Hn.supabaseAnonKey||"sb_publishable_ZjosozAjfpZ4InMNElTr6Q_hHB-f5nc",Pe=Hn.gatewayUrl||"https://fsaos-mcp-gw-rust.fly.dev",B=(0,Po.createClient)($u,Hu,{auth:{persistSession:!0,autoRefreshToken:!0,detectSessionInUrl:!1}});var zn=null,Ir=0,To,$s,Ar=!1;To=new Promise(e=>{$s=e});B.auth.onAuthStateChange((e,t)=>{t?.access_token?(zn=t.access_token,Ir=t.expires_at??Math.floor(Date.now()/1e3)+3600):(zn=null,Ir=0),Ar||(Ar=!0,$s())});setTimeout(()=>{Ar||(Ar=!0,$s())},5e3);function Eo(e,t){zn=e,Ir=t??Math.floor(Date.now()/1e3)+3600}function Hs(){zn=null,Ir=0}async function Je(){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 To,zn}var on=null,an=null,Io=0,Ws=new Set,Gs,Jn,cn=!1;Gs=new Promise(e=>{Jn=e});function zs(){Io++,Ws.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Anchor listener error:",t)}})}function Mr(e){let t=typeof e=="string"?e:e.path,n=on!==t||an?.id!==(typeof e=="string"?void 0:e.id);on=t,an=typeof e=="string"?null:e,typeof e!="string"&&!Et.some(r=>r.id===e.id)&&(Et=[...Et,e],Zs()),cn||(cn=!0,Jn()),n&&zs()}function un(){return on}function ge(){return an}function Js(){return Io}function Ys(e){return Ws.add(e),()=>{Ws.delete(e)}}function Yn(){return Gs}function Xs(){return cn}var kr=null;function It(e,t={}){if(kr){console.warn("[SDK] electHomeAnchor called twice; ignoring (logout to re-elect).");return}kr=e,t.activate!==!1&&Mr(e)}function fe(){return kr}var Et=[],Bs=new Set,Ao=0;function Zs(){Ao++,Bs.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Mount listener error:",t)}})}function Te(){return Et}function Xn(){return Ao}function Or(e){return Bs.add(e),()=>{Bs.delete(e)}}function ko(e,t){let n=JSON.stringify(Et)!==JSON.stringify(e),r=on!==t.path||an?.id!==t.id;Et=e,on=t.path,an=t,cn||(cn=!0,Jn()),n&&Zs(),r&&zs()}var rn=null,nn=null,sn=0;function se(){return sn}async function pt(){if(rn)return rn;if(nn)return nn;let e=sn;return nn=(async()=>{let t=kt(),n=await Je();if(e!==sn)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!==sn)throw new Error("Session changed during initialization");let o=i.entry||i;return rn={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},rn})().catch(t=>{throw e===sn&&(nn=null),t}),nn}function At(){return rn}function ei(){sn++,rn=null,nn=null,on=null,an=null,kr=null,Et=[]}var Mo=[];function ie(e){Mo.push(e)}function ln(){ei(),Hs(),Jn(),cn=!1,Gs=new Promise(e=>{Jn=e}),zs(),Zs();for(let e of Mo)try{e()}catch(t){console.warn("[SDK] Cleanup function failed:",t)}}function kt(){if(typeof window<"u"){let e=window.__FSAOS_CONFIG__;return e?.hostname?e.hostname:window.location.hostname}return"localhost"}var Oo=Mr,H=un,Z=Js,be=Ys,Fo=Yn,Fr=Xs;var ti=0,qo=!1,Qo=0;function Do(e){if(typeof e!="string")return;let t=Date.parse(e);Number.isNaN(t)||(ti=t-Date.now(),qo=!0,Qo=Date.now())}function qr(){return Date.now()+ti}function Uo(){return qo}function No(){return ti}function Ko(){return Qo}function Lo(e){if(typeof e!="string")return null;let t=Date.parse(e);return Number.isNaN(t)?null:qr()>=t}function jo(e){if(typeof e!="string")return null;let t=Date.parse(e);return Number.isNaN(t)?null:Math.max(0,t-qr())}var Gu=new Set(["list-memberships","init"]),Ee=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={}){let n=se(),r=un(),s=kt(),i=`${Pe}/d/${s}`,o={"Content-Type":"application/json"},c=await Je();if(n!==se())throw new Error("Session changed before gateway request");if(c&&(o.Authorization=`Bearer ${c}`),!Gu.has(e)&&!t._scope_path&&await Yn(),n!==se())throw new Error("Session changed before gateway request");let a={...t},u=At();!a.domain_scope_id&&u?.scope_id&&(a.domain_scope_id=u.scope_id);let d=r??un();!a._scope_path&&d&&(a._scope_path=d);let p=await fetch(i,{method:"POST",headers:o,body:JSON.stringify({method:e,params:a})}),m=await p.text();if(n!==se())throw new Error("Session changed during gateway request");let f=null;if(m)try{f=JSON.parse(m)}catch{}if(!p.ok||!f)throw new Ee({method:e,status:p.status,statusText:p.statusText,payload:f,responseBody:m});if(f.success===!1){let y=f.error||"",h=f.denied_by||f.error_type||"";throw h==="rule"||h==="access"||h==="entitlement"||y==="RULE_DENIED"||y==="ACCESS_DENIED"||y==="PERMISSION_DENIED"||y==="ENTITLEMENT_REQUIRED"?new tt(f):new Ee({method:e,status:p.status,statusText:p.statusText,payload:f,responseBody:m})}return f&&f.server_now!==void 0&&Do(f.server_now),f}var _=X(oe(),1),yl=X(Wo(),1),_l=X(Pr(),1);var Bo=new WeakMap;function Ie(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=Bo.get(e);c||(c=new Map,Bo.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 we(e,t){return typeof e=="string"&&(e===t||e.startsWith(`${t}/`))}var Qr=new WeakMap,$o=e=>e.meta?.arrangementRealtime===!0;function Ye(e,t){let n=e.getQueryCache().find({queryKey:t,exact:!0});if(!n)return;let r=Qr.get(e);r||(r=new Map,Qr.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&&Ie(e,t,{exact:!0})},250))}function Ho(e,t){if(!(!t||typeof t!="object"))for(let n of e.getQueryCache().getAll()){if(!$o(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")&&Ye(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)))&&Ye(e,n.queryKey)}}function Go(e){for(let t of e.getQueryCache().getAll())$o(t)&&t.state.data!==void 0&&Ye(e,t.queryKey)}function zo(e){Qr.get(e)?.forEach(clearTimeout),Qr.delete(e)}var Xe=null;ie(()=>{Xe&&(Xe.cancelQueries({queryKey:["vfs"]}),Xe.removeQueries({queryKey:["vfs"]}))});function Jo(e){if(Xe&&Xe!==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.");Xe=e}function A(){return Xe||(Xe=new Ls({defaultOptions:{queries:{staleTime:1e3*60*2,gcTime:1e3*60*10,refetchOnWindowFocus:!1,retry:1}}})),Xe}var Yo=new Proxy({},{get(e,t,n){let r=A(),s=r[t];return typeof s=="function"?s.bind(r):s}});var Dr=new WeakMap;function ni(e){return e.meta?.infiniteItemsRealtime?.filter}function zu(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 Ju(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 Yu(e,t,n){if(zu(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&&!we(n.path,r)&&!we(n.old_path,r))return!1;if(n.item_type==="symlink"&&s&&i)return!0;let o=Ju(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 Xo(e,t){let n=Dr.get(e);n||(n=new Map,Dr.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||!ni(t))&&Ie(e,t.queryKey,{exact:!0})},500))}function Zo(e,t){if(!(!t||typeof t!="object"))for(let n of e.getQueryCache().getAll()){let r=ni(n);r&&Yu(n,r,t)&&Xo(e,n)}}function ea(e){for(let t of e.getQueryCache().getAll())ni(t)&&t.state.data!==void 0&&Xo(e,t)}function ta(e){Dr.get(e)?.forEach(clearTimeout),Dr.delete(e)}var Ur=class extends Error{constructor(){super("The server did not confirm the selected-Space listing contract")}};function na(e,t){if(!Array.isArray(t)||t.some(n=>typeof n!="string")||JSON.stringify([...new Set(t)].sort())!==JSON.stringify(e))throw new Ur}function mt(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 dn(e){return e instanceof Ur||e instanceof tt||e instanceof Ee&&(e.payload?.error==="SPACE_SELECTION_UNAVAILABLE"||e.payload?.error==="QUERY_PARAMS_INVALID"||e.status===401||e.status===403)}function re(){return H()??"__unscoped__"}var x={all:()=>["vfs",re()],item:e=>["vfs",re(),"item",e],itemById:e=>["vfs","item-by-id",e],children:e=>["vfs",re(),"children",e],allChildren:()=>["vfs",re(),"children"],types:e=>["vfs","types",e??"default"],edges:e=>["vfs","edges",e],search:(e,t)=>["vfs",re(),"search",e,...t??[]],items:(e,t)=>["vfs",re(),"items",e,JSON.stringify(mt(t??{}))],allItems:()=>["vfs",re(),"items"],tree:(e,t)=>["vfs",re(),"tree",e,t??1],openEnvelope:(e,t)=>["vfs",re(),"open",e,t??"__default__"],allOpenEnvelopes:()=>["vfs",re(),"open"],memberFocus:e=>["vfs","member-focus",e],fractalInstances:()=>["vfs","fractal-instances"],recentActivity:(e,t,n)=>["vfs",re(),"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",re(),"channel-messages",e,t??"__top__"],allChannelMessages:()=>["vfs",re(),"channel-messages"],channels:e=>["vfs",re(),"channels",e??"all"],allChannels:()=>["vfs",re(),"channels"],notifications:(e,t)=>["vfs",re(),"notifications",e??"all",t??200],allNotifications:()=>["vfs",re(),"notifications"],unreadCounts:()=>["vfs",re(),"unread-counts"],memberships:e=>["memberships",e]};var Xu=typeof window<"u"&&(window.location?.hostname==="localhost"||window.location?.hostname==="127.0.0.1"||window.__FSAOS_WS_DEBUG__);function J(...e){Xu&&console.log("[WS]",...e)}var q=null,fn=null,mn=null,Zn=0,Zu=3e4,ra=1e4,gn=!1,sa=!1,ua=3e4,el=ua*2+5e3,Nr=0,Kr=null,ia=!1;function tl(){tr(),Nr=Date.now(),Kr=setInterval(()=>{if(q&&q.readyState===WebSocket.OPEN&&Date.now()-Nr>el){J("ping: no inbound traffic for",Date.now()-Nr,"ms \u2014 closing half-open socket");try{q.close(4e3,"liveness timeout")}catch{}return}et({type:"ping"})},ua)}function tr(){Kr&&(clearInterval(Kr),Kr=null)}function nl(){typeof document>"u"||(document.hidden?tr():er()&&(J("Tab visible, reconnecting..."),Mt()))}function rl(){ia||typeof document>"u"||(document.addEventListener("visibilitychange",nl),ia=!0)}var Se={};function si(e,t){let n=e.replace(/\/+$/,""),r=t.replace(/\/+$/,"");return!n||!r?n===r:r===n||r.startsWith(`${n}/`)}var hn=[],Ze=new Map,pn=new Map,Ae=new Map;function sl(e){let t=pn.get(e);return t?Array.from(new Set(Array.from(t.values()).flatMap(n=>n.event_types))).sort():[]}function oa(e,t){return e?e.length===t.length&&e.every((n,r)=>n===t[r]):!1}function aa(e){let t=sl(e);if(t.length===0)return Ze.delete(e),null;let n={scope_id:e,event_types:t};return Ze.set(e,n),n}var Le=new Map,ht=new Map,ri="disconnected",Lr=[];function jr(e){if(ri!==e){ri=e;for(let t of[...Lr])try{t(e)}catch{}}}function il(e){Le.set(e,"ready");let t=ht.get(e);if(t){ht.delete(e);for(let n of t)n()}}function ol(){for(let e of Le.keys())Le.set(e,"disconnected")}function ii(e,t){Le.set(e,"pending"),et({type:"subscribe_path",path:e,event_types:t})}function al(){return Object.keys(Se).some(t=>Se[t]&&Se[t].length>0)||hn.length>0}function er(){return Ze.size>0||Ae.size>0}async function Mt(){if(!er()){J("ensureConnection: no active subscriptions, skipping");return}if(q&&q.readyState===WebSocket.OPEN){J("ensureConnection: already open");return}if(fn)return J("ensureConnection: connection already in flight, waiting..."),fn;if(q){J("ensureConnection: killing stale WS in state",q.readyState);try{q.close()}catch{}q=null}return gn=!1,fn=(async()=>{try{let e=typeof window<"u"&&window.__FSAOS_CONFIG__||{},t=Pe,n=await Je();if(!n){J("ensureConnection: no token available, will retry"),ca();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)+"..."),jr("connecting"),q=new WebSocket(i);let o=q;await new Promise((c,a)=>{if(!q)return a(new Error("WebSocket not created"));let u=setTimeout(()=>{if(q===o){if(J("ensureConnection: TIMEOUT after",ra,"ms"),q&&q.readyState!==WebSocket.OPEN){try{q.close()}catch{}q=null}a(new Error("WebSocket connection timeout"))}},ra);o.onopen=()=>{if(q!==o)return;clearTimeout(u),J("ensureConnection: CONNECTED");let d=sa;sa=!0,Zn=0,jr("connected"),cl(d),(typeof document>"u"||!document.hidden)&&tl(),rl(),c()},o.onmessage=d=>{q===o&&ul(d.data)},o.onerror=()=>{J("ensureConnection: WS error event")},o.onclose=d=>{clearTimeout(u),q===o&&(J("ensureConnection: WS closed, code:",d.code,"reason:",d.reason),q=null,tr(),ol(),jr("disconnected"),!gn&&er()&&ca(),a(new Error(`WebSocket closed: ${d.code}`)))}})}catch(e){J("ensureConnection: failed -",e?.message||e)}finally{fn=null}})(),fn}function ca(){if(mn||typeof document<"u"&&document.hidden)return;let e=Math.min(1e3*Math.pow(2,Zn)+Math.random()*1e3,Zu);Zn++,J("scheduleReconnect: attempt",Zn,"in",Math.round(e),"ms"),mn=setTimeout(()=>{mn=null,er()&&Mt()},e)}function cl(e=!1){for(let t of Ze.values())J("resubscribeAll: scope",t.scope_id),et({type:"subscribe",scope_id:t.scope_id,event_types:t.event_types});for(let t of Ae.values())J("resubscribeAll: path",t.path),ii(t.path,t.event_types);if(e)try{let t=A();ea(t),Go(t);for(let n of Ae.values())t.invalidateQueries({queryKey:x.item(n.path)}),t.invalidateQueries({queryKey:x.children(n.path)});J("resubscribeAll: invalidated",Ae.size,"paths after reconnect")}catch(t){J("resubscribeAll: cache invalidation skipped",t)}}function et(e){q&&q.readyState===WebSocket.OPEN&&q.send(JSON.stringify(e))}function ul(e){Nr=Date.now();try{let t=JSON.parse(e);if(t.type==="subscribed_path"){typeof t.path=="string"&&il(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"&&(Zo(A(),r),Ho(A(),r)),typeof r.path=="string")for(let[s,i]of Object.entries(Se))s!=="*"&&si(s,r.path)&&i.forEach(o=>o(r));Se["*"]&&Se["*"].forEach(s=>s(r));for(let s of hn)s.eventType!=="*"&&s.eventType!==n||s.filter&&!s.filter(r)||s.callback(r)}}catch{}}function oi(){!al()&&Ze.size===0&&Ae.size===0&&q&&(gn=!0,tr(),q.close(),q=null,gn=!1)}function Vr(e,t){return Se[e]||(Se[e]=[]),Se[e].push(t),Ae.has(e)||(Ae.set(e,{path:e,event_types:["token_stream"]}),q&&q.readyState===WebSocket.OPEN?ii(e,["token_stream"]):Le.set(e,"pending")),Mt(),()=>{let n=Se[e];if(n){let r=n.indexOf(t);r!==-1&&n.splice(r,1),n.length===0&&(delete Se[e],Ae.delete(e),Le.delete(e),ht.delete(e),et({type:"unsubscribe_path",path:e}))}oi()}}function te(e,t,n){let s=(Array.isArray(e)?e:[e]).map(i=>({eventType:i,callback:t,filter:n}));return hn.push(...s),er()&&Mt(),()=>{for(let i of s){let o=hn.indexOf(i);o!==-1&&hn.splice(o,1)}oi()}}function yn(e,t=["vfs_change","ccm_change"]){let n=Symbol(e),r=Array.from(new Set(t)).sort();if(r.length===0)return()=>{};let s=pn.get(e)??new Map,i=Ze.get(e)?.event_types;s.set(n,{event_types:r}),pn.set(e,s);let o=aa(e);if(!o)return()=>{};J("subscribeToScope:",e,o.event_types),q&&q.readyState===WebSocket.OPEN&&!oa(i,o.event_types)&&et({type:"subscribe",scope_id:e,event_types:o.event_types}),Mt();let c=!0;return()=>{if(!c)return;c=!1;let a=pn.get(e);if(!a?.delete(n))return;let u=Ze.get(e)?.event_types;if(a.size===0)pn.delete(e),Ze.delete(e),et({type:"unsubscribe",scope_id:e});else{let d=aa(e);d&&q&&q.readyState===WebSocket.OPEN&&!oa(u,d.event_types)&&et({type:"subscribe",scope_id:e,event_types:d.event_types})}oi()}}function la(e,t,n={}){et({type:"emit",scope_id:e,event_type:t,payload:n})}function ai(){J("disconnectSSE: tearing down"),ta(A()),zo(A()),gn=!0,tr(),q&&(q.close(),q=null),mn&&(clearTimeout(mn),mn=null),fn=null,gn=!1,Zn=0;for(let e of Object.keys(Se))delete Se[e];hn.length=0,Ze.clear(),pn.clear(),Ae.clear(),Le.clear(),ht.clear(),jr("disconnected")}function da(){et({type:"ping"})}function fa(e){return Ae.has(e)?Le.get(e)??"pending":"unsubscribed"}function pa(e,t=5e3){return Ae.has(e)?Le.get(e)==="ready"&&q&&q.readyState===WebSocket.OPEN?Promise.resolve(!0):(Mt(),new Promise(n=>{let r=!1,s=ht.get(e)??[],i=()=>{r||(r=!0,clearTimeout(o),n(!0))};s.push(i),ht.set(e,s);let o=setTimeout(()=>{if(r)return;r=!0;let c=ht.get(e);if(c){let a=c.indexOf(i);a!==-1&&c.splice(a,1),c.length===0&&ht.delete(e)}n(!1)},t)})):Promise.resolve(!1)}function ma(e){let t=Ae.get(e);if(!t){J("resubscribePath: no active subscription for",e);return}q&&q.readyState===WebSocket.OPEN?(J("resubscribePath: re-sending frame for",e),ii(t.path,t.event_types)):(Le.set(e,"pending"),Mt())}function Wr(e){Lr.push(e);try{e(ri)}catch{}return()=>{let t=Lr.indexOf(e);t!==-1&&Lr.splice(t,1)}}ie(ai);function ha(){return new Date().toISOString()}function ga(){return crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function ye(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||ha(),updated_at:e.updated_at||ha(),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 rr(e){return(e.content?.items||e.items||[]).map(ye)}async function $r(e){try{let t=await C("read",{id:e});if(t.item_name||t.item_path){let r=ye(t);return r.path&&A().setQueryData(x.item(r.path),r),r}let n=t.item;if(n){let r=ye(n);return r.path&&A().setQueryData(x.item(r.path),r),r}return null}catch{return null}}async function sr(e){try{let t=await C("read",{path:e});if(t.item_name||t.item_path)return ye(t);let n=t.item;return n?ye(n):null}catch{return null}}async function ir(e){try{let t=await C("list",{path:e,limit:200}),n=rr(t);for(let r of n)A().setQueryData(x.item(r.path),r);return n}catch(t){return console.error(`[gateway] Failed to fetch children of ${e}:`,t),[]}}async function ya(e,t){let{items:n}=await vn({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 Hr(e,t,n){try{let r=await C("list",{path:e,limit:t,offset:n}),s=rr(r);for(let i of s)A().setQueryData(x.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 Gr(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 zr(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||ga(),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||ga(),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 Jr(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=rr(i);for(let c of o)A().setQueryData(x.item(c.path),c);return o}catch(s){return console.error(`[gateway] Failed to fetch tree at ${e}:`,s),[]}}async function Yr(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 or(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 Xr(e,t=50,n=0){return or(e,{limit:t,offset:n})}async function Zr(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=rr(s);for(let o of i)A().setQueryData(x.item(o.path),o);return i}catch(r){return console.error(`[gateway] Failed to fetch member focus for scope ${e}:`,r),[]}}async function es(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 _n(e){return!!e&&(!!e.type||Array.isArray(e.any_of)&&e.any_of.length>0)}function ll(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 dl=["catalog","parent_only","internal"];function _a(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"&&dl.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 _n(s)?{...s,...t}:null}async function vn(e,t={}){if(e=mt(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(ll)),Object.keys(r).length>0&&(n.filters=r),e.limit!=null&&(n.limit=e.limit);try{let s=await C("query",n);e.spaceIds!==void 0&&na(e.spaceIds,s.selected_space_ids??s.content?.selected_space_ids);let i=rr(s);for(let o of i)A().setQueryData(x.item(o.path),o);return{items:i,total_hint:s.total??s.content?.total??i.length}}catch(s){if(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 fl(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 va(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:fl(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 nr(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,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 ba(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 nr(i)}catch(n){return console.error(`[gateway] Failed to fetch channel messages for ${e}:`,n),[]}}async function ts(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=nr(i),c=va(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:nr(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 ar(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=va(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:nr(i),activityMessages:nr(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 Br(e){A().invalidateQueries({queryKey:x.children(e)})}function ci(e){A().invalidateQueries({queryKey:x.item(e)})}function wa(e,t){ci(e),Br(e);let n=e.split("/");n.pop();let r=n.join("/")||t;r&&Br(r)}function Sa(e){let t=e+"/";A().invalidateQueries({predicate:n=>{let r=n.queryKey;return r[0]!=="vfs"?!1:r.some(s=>typeof s=="string"&&(s===e||s.startsWith(t)))}})}function Ra(){A().invalidateQueries({queryKey:x.all()})}function Ca(e){A().invalidateQueries({queryKey:x.types(e)})}function xa(e,t){e?A().invalidateQueries({queryKey:x.channelMessages(e,t)}):A().invalidateQueries({queryKey:x.allChannelMessages()})}function Pa(e,t){e&&t?A().invalidateQueries({queryKey:x.openEnvelope(e,t)}):e?A().invalidateQueries({predicate:n=>{let r=n.queryKey;return r[0]==="vfs"&&r[2]==="open"&&r[3]===e}}):A().invalidateQueries({queryKey:x.allOpenEnvelopes()})}function je(e){return{id:e.accountId,path:e.path,kind:e.isSpace?"space":"account",name:e.name,grantedUnderAccountId:e.grantedUnderAccountId??void 0}}async function ns(){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 bn=new Map,cr=null,rs=null,gt=new Map,Ta=250;function Ot(e){if(cr){wn(e);return}wn(e),cr=te("vfs_change",t=>pl(t)),rs=te("ccm_change",t=>ml(t))}function wn(e){if(bn.has(e))return;let t=yn(e,["vfs_change","ccm_change"]);bn.set(e,t)}function ss(e){let t=bn.get(e);t&&(t(),bn.delete(e))}function ui(){for(let[,e]of bn)e();bn.clear(),cr&&(cr(),cr=null),rs&&(rs(),rs=null),gt.forEach(e=>clearTimeout(e)),gt.clear()}ie(ui);function pl(e){let t=e.path,n=e.action;if(!t)return;let r=t.split("/");r.pop();let s=r.join("/")||"/root",i=gt.get(s);i&&clearTimeout(i);let o=setTimeout(()=>{gt.delete(s),hl(n,t,e,s)},Ta);gt.set(s,o)}function ml(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=gt.get(s);i&&clearTimeout(i);let o=setTimeout(()=>{gt.delete(s),t&&A().invalidateQueries({queryKey:x.edges(t)}),n&&A().invalidateQueries({queryKey:x.edges(n)})},Ta);gt.set(s,o)}function hl(e,t,n,r){if((e||"").toUpperCase()==="DELETE")A().removeQueries({queryKey:x.item(t)}),A().removeQueries({queryKey:x.children(t)}),A().removeQueries({queryKey:x.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=ye(i);o&&o.id&&A().setQueryData(x.item(t),o)}catch{}A().invalidateQueries({queryKey:x.children(r)}),A().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&&A().invalidateQueries({queryKey:x.itemById(n.item_id)})}var Sn=null;ie(()=>{Sn=null});function yt(e){if(e!==Sn||e.generation!==se())throw new Error("Workspace session changed")}function gl(e){return e instanceof Ee&&e.payload?.error==="item_not_found"}function ur(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 lr(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 Ea(e,t){return JSON.stringify({mounts:e.map(n=>n.id),last_anchor:t.id})}async function Ia(e,t,n){yt(e);let r=Ea(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}),yt(e),e.exists=!0,e.saved=r}function Aa(e,t){let n=Te();Ot(fe().id);for(let r of n)e.some(s=>s.id===r.id)||ss(r.id);for(let r of e)wn(r.id);ko(e,t)}async function Ft(e,t,n={}){let r=fe();if(!r)throw new Error("Elect a home account before loading mounts");let s=`${e}/settings/mounts`;if(Sn&&Sn.path!==s)throw new Error("Reset the session before changing the mount declaration owner");let i=Sn??(Sn={generation:se(),path:s,scope:r.path,resolve:t,exists:!1,ready:!1,saved:null,queue:Promise.resolve()});return yt(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(yt(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(yt(i),!gl(d))throw d;i.exists=!1}let c=n.initialAnchor?ur(i,n.initialAnchor):r,a=lr(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=Ea(a,u):n.initialAnchor&&await Ia(i,a,u),yt(i),i.ready=!0,Aa(a,u),a})().finally(()=>{i.loading=void 0}),i.loading)}function is(e){let t=Sn;if(!t?.ready)return Promise.reject(new Error("Workspace mounts are not loaded"));let n=t.queue.then(async()=>{yt(t);let{refs:r,anchor:s}=e(t);await Ia(t,r,s),yt(t),Aa(r,s)});return t.queue=n.catch(()=>{}),n}function li(e){return is(t=>({refs:lr([...Te(),ur(t,e)]),anchor:ge()}))}function ka(e){return is(()=>{if(e===fe().id)throw new Error("The home account cannot be unmounted");let t=lr(Te().filter(r=>r.id!==e)),n=t.find(r=>r.id===ge()?.id)??t.find(r=>r.kind==="space")??fe();return{refs:t,anchor:n}})}function dr(e){return is(t=>{let n=ur(t,e);return{refs:lr([...Te(),n]),anchor:n}})}function os(e,t){return is(n=>{let r=lr(e.map(i=>ur(n,i))),s=ur(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 as(e){if(typeof e.path!="string")return!1;let t=[...Te().map(n=>n.path),ge()?.path].filter(n=>!!n);return!t.length&&H()&&t.push(H()),t.some(n=>we(e.path,n))}function di(e,t,n,r){if(!["message","card"].includes(e?.item_type)||!we(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&&we(e.path,i)})}var Ma=new WeakMap;function Oa(e,t,n){let r=Ma.get(e);r||(r=new Map,Ma.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,h()},250))},h=async()=>{if(c)return;u=!0;let F=d;d=!1;let S=[...p],M=new Set(m);m.clear(),p.clear();try{if(F)await Ie(e,t,{exact:!0});else{let P=(await Promise.allSettled(S.map(async T=>{let Q=e.getQueryCache().find({queryKey:t,exact:!0});if(!Q)return;let I=await C("read",{id:T});if(I.success===!1)throw new Error("Channel refresh failed");if(c||!Q||e.getQueryCache().find({queryKey:t,exact:!0})!==Q)return;let E=ye(I.item??I);if(E.id!==T||E.item_type!=="channel")return;let U=f().find($=>$.id===T);if(!U)return;let D=n({...E}),ue={...U,path:D.path,name:D.name,displayName:D.displayName,messageCount:D.messageCount,aiMode:D.aiMode,isPrivate:D.isPrivate,isDm:D.isDm,autoPilot:D.autoPilot,updatedAt:D.updatedAt};M.has(T)&&(U.name!==ue.name||U.displayName!==ue.displayName||U.path!==ue.path)&&(d=!0),e.setQueryData(t,$=>$?.map(Fe=>Fe.id===T?ue:Fe))}))).find(T=>T.status==="rejected");if(P?.status==="rejected")throw P.reason}}catch(K){console.warn("[channels] refresh failed",K)}finally{u=!1,(d||p.size)&&y()}},g=F=>f().some(S=>S.id===F.item_id||S.path===F.path)?!0:as(F),v=F=>{if(!g(F))return;let S=String(F.action??"").toLowerCase();if(["insert","delete","rename","move"].includes(S))d=!0;else if(S==="update"){let M=f().find(K=>K.id===F.item_id||K.path===F.path);M&&(p.add(M.id),m.add(M.id))}(d||p.size)&&y()},w=F=>{let S=f().find(M=>M.id===F.parent_id);S&&(p.add(S.id),y())},O=["vfs_change","ccm_change"].flatMap(F=>[te(F,v,S=>S.item_type==="channel"),te(F,w,S=>S.item_type==="message")]);i={users:0,stop:()=>{c=!0,a&&clearTimeout(a),O.forEach(F=>F())}},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)(be,Z,Z)}function Ua(){return Y(),Fr()}function Na(e){return Y(),V({queryKey:x.item(e),queryFn:()=>sr(e),enabled:!!e,staleTime:1/0})}function Ka(e){return Y(),V({queryKey:x.itemById(e),queryFn:()=>$r(e),enabled:!!e,staleTime:1/0})}function pi(e){return Y(),V({queryKey:x.children(e),queryFn:()=>ir(e),enabled:!!e})}function La(e){let t=pi(e);return{...t,children:t.data??[]}}function ja(e,t=1){return Y(),V({queryKey:x.tree(e,t),queryFn:()=>Jr(e,t),enabled:!!e})}function Va(e,t){return Y(),V({queryKey:x.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(ye)},enabled:!!e&&e.length>0})}function Wa(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 Ba(e){Y();let t=mt(e),n=(0,_.useMemo)(()=>t,[JSON.stringify(t)]),r=V({queryKey:x.items(n?.type??"",n),queryFn:()=>vn(n),enabled:_n(n),...n?.spaceIds!==void 0?{retry:(s,i)=>!dn(i)&&s<1}:{},select:s=>s.items});return n?.spaceIds!==void 0&&dn(r.error)?{...r,data:void 0}:r}function mi(e,t={}){let n=Y(),{realtime:r=!1}=t,s=mt(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=$n({queryKey:c,queryFn:async({pageParam:p=0})=>vn({...o,limit:i,offset:p},{throwOnError:!0}),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:_n(o),...o?.spaceIds!==void 0?{retry:(p,m)=>!dn(m)&&p<1}:{},staleTime:r?1/0:t.staleTime,meta:r&&o?{infiniteItemsRealtime:{filter:o}}:{}}),u=(0,_.useMemo)(()=>{if(o?.spaceIds!==void 0&&dn(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&&dn(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 Fa(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 vl(e,t){if(e.is_active===!1||e.item_type!==t.type||!we(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 $a(e,t={}){let n=Fa(e),r=mi(e,n?{realtime:!1,staleTime:3e4}:{realtime:!0}),s=W(),i=JSON.stringify([H(),mt(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(w=>w.id)),h=[...f,...r.allItems.filter(w=>!y.has(w.id))].filter(w=>!a.deleted.has(w.path)),g=e.sort_by??"updated_at",v=e.sort_dir==="asc"?1:-1;return h.sort((w,O)=>v*String(w[g]??"").localeCompare(String(O[g]??"")))},[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(!Fa(e))return;let f=e,y=!1,h=!1,g=!1,v=0,w=new Map,O=()=>{let P=v;m.current().then(T=>{!y&&!T.isError&&v===P&&c({identity:i,upserts:{},deleted:new Set})})},F=P=>{v++,c(Q=>{let I=Q.identity===i?Q:{identity:i,upserts:{},deleted:new Set},E={...I.upserts};return delete E[P],{identity:i,upserts:E,deleted:new Set(I.deleted).add(P)}});let T=w.get("__reconcile__");T&&clearTimeout(T),w.set("__reconcile__",setTimeout(()=>{w.delete("__reconcile__"),O()},250))},S=P=>{let T=w.get(P);T&&clearTimeout(T),w.set(P,setTimeout(()=>{w.delete(P),s.fetchQuery({queryKey:x.item(P),queryFn:()=>sr(P),staleTime:0}).then(Q=>{if(!y){if(!Q||!vl(Q,f)){let I=d.current.find(E=>E.path===P||E.id===Q?.id);I&&F(I.path);return}c(I=>{let E=I.identity===i?I:{identity:i,upserts:{},deleted:new Set},U=new Set(E.deleted);return U.delete(P),{identity:i,upserts:{...E.upserts,[P]:Q},deleted:U}})}}).catch(Q=>console.warn("[useIncrementalItems] item read failed:",Q))},250))},M=te("vfs_change",P=>{if(!P||typeof P.path!="string")return;let T=d.current.find(I=>I.path===P.path||P.item_id&&I.id===P.item_id),Q=!!T;if(!(!we(P.path,f.scope)&&!Q)&&!(P.item_type&&P.item_type!==f.type)&&!(f.parent_id&&P.parent_id&&P.parent_id!==f.parent_id&&!Q))if(P.action==="insert")v++,S(P.path);else if(P.action==="update"){if(!p.current?.(P,d.current))return;v++,S(P.path)}else P.action==="delete"&&F(T?.path??P.path)}),K=Wr(P=>{if(P!=="connected"){h&&(g=!0);return}h=!0,g&&(g=!1,O())});return()=>{y=!0,M(),K(),w.forEach(clearTimeout)}},[s,i]),{...r,allItems:u}}function Ha(e){Y();let t=20,n=$n({queryKey:["vfs",H()??"__unscoped__","infinite-children",e??""],queryFn:async({pageParam:s=0})=>Hr(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 Ga(e){return Y(),V({queryKey:x.edges(e),queryFn:()=>zr(e),enabled:!!e})}function cs(e){return Y(),V({queryKey:x.types(e),queryFn:()=>Gr(e)})}function za(e,t){let n=cs(t);return{...n,data:n.data?.get(e)??void 0}}function Ja(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:[...x.openEnvelope(e,s),i],queryFn:async()=>{let o=await es(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 qa={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 Ya(e){let t=cs(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(qa).map(([f,y])=>({key:f,label:y})),getEdgeTypeLabel:f=>qa[f]??f.replace(/_/g," "),allTypes:n,loading:t.isLoading}),[n,t.isLoading])}function Xa(e,t,n){return Y(),V({queryKey:x.memberFocus(e),queryFn:()=>Zr(e,t,n),enabled:!!e})}function Za(e,t={}){let{limit:n=50,offset:r=0,include_snapshots:s=!1}=t;return V({queryKey:x.itemVersions(e,String(n),String(r),String(s)),queryFn:()=>or(e,{limit:n,offset:r,include_snapshots:s}),enabled:!!e})}function ec(e,t=50,n=0){return V({queryKey:x.itemHistory(e,String(t),String(n)),queryFn:()=>Xr(e,t,n),enabled:!!e})}function tc(e,t=50,n=0){return Y(),V({queryKey:x.recentActivity(e,String(t),String(n)),queryFn:()=>Yr(e,t,n),enabled:!!e})}function nc(){let[e,t]=(0,_.useState)(null),[n,r]=(0,_.useState)(!0),[s,i]=(0,_.useState)(null);return(0,_.useEffect)(()=>{let o=!1;return pt().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 bl=[];function rc(){let{user:e}=us(),t=(0,_.useRef)(null),[n,r]=(0,_.useState)(null),s=V({queryKey:x.memberships(e?.id??"anonymous"),queryFn:ns,enabled:!!e?.id,staleTime:1e3*60*2}),i=s.data??bl,o=(0,_.useMemo)(()=>i.filter(m=>m.isAccount!==!1&&!m.isSpace),[i]),c=(0,_.useMemo)(()=>{let m=new Set(o.map(y=>y.accountId)),f=y=>!y.subordinateTo||!m.has(y.subordinateTo);return[...o].sort((y,h)=>Number(f(h))-Number(f(y)))},[o]),a=(0,_.useSyncExternalStore)(be,Z,Z),u=(0,_.useMemo)(()=>{let m=ge();return m?i.find(f=>f.accountId===m.id)??null:null},[a,i]);(0,_.useEffect)(()=>{if(!e?.id){t.current=null;return}if(t.current!==e.id)if(r(null),c.length===1){let m=c[0];fe()||It(je(m)),Ot(m.accountId),m.personalSpacePath&&Ft(m.personalSpacePath,f=>{let y=i.find(h=>h.accountId===f);return y?je(y):null}).catch(r),t.current=e.id}else c.length>1&&(t.current=e.id)},[e?.id,c,i]);let d=(0,_.useCallback)(async m=>{let f=i.find(g=>g.path===m);if(!f)throw new Error("Account membership is unavailable");let y=je(f);fe()||It(y);let h=i.find(g=>g.accountId===fe()?.id);if(!h?.personalSpacePath)throw new Error("The home membership has no mount declaration location");await Ft(h.personalSpacePath,g=>{let v=i.find(w=>w.accountId===g);return v?je(v):null}),await dr(y),r(null),Ot(f.accountId)},[i]),p=(0,_.useCallback)(async m=>{let f=i.find(y=>y.path===m);if(!f)throw new Error("Scope membership is unavailable");await li(je(f))},[i]);return{accounts:c,allMemberships:i,currentAccount:u,mountedScope:null,switchAccount:d,mountScope:p,loading:s.isLoading,error:s.error??n}}function sc(){Y();let e=(0,_.useSyncExternalStore)(Or,Xn,Xn),t=(0,_.useMemo)(()=>Te(),[e]),n=ge(),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:dr,replaceMounts:os,mount:li,unmount:ka}}function us(){let[e,t]=(0,_.useState)(null),[n,r]=(0,_.useState)(null),[s,i]=(0,_.useState)(!0),o=(0,_.useRef)(null);(0,_.useEffect)(()=>{B.auth.getSession().then(({data:f,error:y})=>{if(y){console.warn("[useAuth] getSession error, clearing stale session:",y.message),B.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),B.auth.signOut().catch(()=>{}),r(null),t(null),i(!1)});let{data:{subscription:m}}=B.auth.onAuthStateChange((f,y)=>{if(f==="TOKEN_REFRESHED"&&!y){console.warn("[useAuth] TOKEN_REFRESHED with null session \u2014 signing out"),B.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?B.auth.signInWithOAuth({provider:m.provider,options:m.redirectTo?{redirectTo:m.redirectTo}:{redirectTo:window.location.href}}):B.auth.signInWithPassword({email:m.email,password:m.password}),[]),a=(0,_.useCallback)(async m=>B.auth.signUp({email:m.email,password:m.password,options:{data:m.metadata||{}}}),[]),u=(0,_.useCallback)(async()=>{await B.auth.signOut(),ln(),A().clear()},[]),d=(0,_.useCallback)(async m=>{let{error:f}=await B.auth.resetPasswordForEmail(m);if(f)throw f},[]),p=(0,_.useCallback)(async(m,f)=>{let{error:y}=await B.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 ic(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 fr={},Qa={};ie(()=>{for(let e of Object.keys(fr))delete fr[e]});var oc=null;function ac(e){oc=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||yl;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}:_l;case"@fsaos/gateway":case"@fsaos/react":return typeof window<"u"&&window.__FSAOS_GATEWAY__||oc||{};case"@fsaos/ui":return typeof window<"u"&&window.__FSAOS_UI__||{};case"@fsaos/theme":return{};default:return console.warn(`[useComponent] Unknown module requested: ${e}`),{}}}function Sl(e,t){return e.replace(/^(\s*)(:root|body)(\s*[{,])/gm,(n,r,s,i)=>`${r}.${t}${i}`)}async function Rl(e,t){if(!Qa[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=Sl(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),Qa[e]=s}catch{}}function Cl(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 hi(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(fr[p]){n(()=>fr[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 h=m.replace(/__bundle(\.v\d+)?\.js(\?.*)?$/,"__bundle$1.css");Rl(h).catch(()=>{});let g=Cl(y);if(!g)throw new Error("Bundle did not export a component. Expected window.__FSAOS_COMPONENT__ (FSAOS build) or a __FSAOS_REGISTER__(Component) call.");if(typeof g!="function")throw new Error(`Bundle export is not a React component (got ${typeof g})`);fr[p]=g,c||(n(()=>g),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 xl=["--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 cc(){return{data:(0,_.useMemo)(()=>{if(typeof document>"u")return{tokens:{}};let t={},n=getComputedStyle(document.documentElement);return xl.forEach(r=>{t[r]=n.getPropertyValue(r).trim()}),{tokens:t}},[]),loading:!1,error:null}}function uc(e,t){return{data:{allowed:!0},loading:!1,error:null}}function lc(e,t){let n={};return(t||[]).forEach(r=>{n[r]=!0}),{data:n,loading:!1,error:null}}var ce=null,Rn=null,fi=new Set;function Pl(){fi.forEach(e=>e())}ie(()=>{ce=null,Rn=null});async function dc(e){let t={principalId:null,displayName:null,createdAt:null,metadata:null,vfsPath:null},n=At()?.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 B.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 Rn||(Rn=(async()=>{try{let{data:s,error:i}=await B.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 B.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{Rn=null}})(),Rn)}async function fc(e){return(await dc(e)).principalId}function pc(){let e=us(),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 fi.add(o),()=>{fi.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,dc(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 mc(){return{data:null,loading:!1,error:null}}function hc(e){let{path:t,...n}=e,r=hi(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 gc(e){return e.children}function yc(e){let t=Y(),{channelPath:n,parentMessageId:r,realtime:s=!0,enabled:i}=e,o=i!==void 0?i&&!!n:!!n,c=(0,_.useMemo)(()=>x.channelMessages(n??"",r),[n,r,t]),a=W(),u=(0,_.useRef)(null),d=V({queryKey:c,queryFn:()=>ts(n,r),enabled:o});(0,_.useEffect)(()=>{if(!s||!o)return;let h=te("vfs_change",()=>{u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{Ie(a,c,{exact:!0})},500)},g=>{let v=a.getQueryData(c);return di(g,n,r,[...v?.messages??[],...v?.activityMessages??[]])});return()=>{h(),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(h=>h.reply_count>0),[m]),isLoading:d.isLoading,isFetching:d.isFetching,error:d.error,refetch:d.refetch}}function _c(e){Y();let{channelPath:t,parentMessageId:n,limit:r=50,realtime:s=!0,enabled:i=!0}=e,o=!!n,c=i&&!!t,a=$n({queryKey:[...x.channelMessages(t||"",n),"infinite",r],queryFn:async({pageParam:h})=>ar(t,{parentMessageId:n,limit:r,before_seq:o?void 0:h,after_seq:o?h:void 0}),initialPageParam:void 0,getNextPageParam:h=>!o||h.messages.length<r?void 0:h.messages[h.messages.length-1]?.seq,getPreviousPageParam:h=>o||h.messages.length<r?void 0:h.messages[0]?.seq,enabled:c}),u=(0,_.useMemo)(()=>{if(!a.data?.pages)return[];let h=new Set,g=[];for(let v of a.data.pages)for(let w of v.messages)h.has(w.id)||(h.add(w.id),g.push(w));return g.sort((v,w)=>v.seq-w.seq)},[a.data?.pages]),{messageCards:d,siblingCards:p}=(0,_.useMemo)(()=>{let h=new Map,g=[];if(!a.data?.pages)return{messageCards:h,siblingCards:g};let v=new Set;for(let w of a.data.pages){for(let[O,F]of w.messageCards)for(let S of F){if(v.has(S.id))continue;v.add(S.id);let M=h.get(O)||[];M.push(S),h.set(O,M)}for(let O of w.siblingCards)v.has(O.id)||(v.add(O.id),g.push(O))}return{messageCards:h,siblingCards:g}},[a.data?.pages]),m=W(),f=(0,_.useRef)(null),y=(0,_.useMemo)(()=>[...x.channelMessages(t||"",n),"infinite",r],[t,n,r]);return(0,_.useEffect)(()=>{if(!s||!t||!c)return;let h=()=>void Ie(m,y,{exact:!0}),g=!1,v=!1,w=!1,O=async()=>{let M=m.getQueryData(y);if(!M?.pages?.length){h();return}let K=0;for(let P of M.pages)for(let T of P.messages)T.seq>K&&(K=T.seq);if(K===0){h();return}try{let P=await ar(t,{parentMessageId:n,limit:r,after_seq:K});if(P.messages.length===0&&P.siblingCards.length===0){h();return}if(P.messages.length>0){let T=Math.min(...P.messages.map(Q=>Q.seq));if(T>K+1){console.warn(`[useInfiniteChannelMessages] sequence gap detected: maxSeq=${K}, minNewSeq=${T}. Triggering full refetch.`),h();return}}m.setQueryData(y,T=>{if(!T)return T;let Q=[...T.pages],I=Q.length-1,E=Q[I],U=new Set(E.messages.map(Re=>Re.id)),D=P.messages.filter(Re=>!U.has(Re.id)),ue=[...E.messages,...D].sort((Re,_s)=>Re.seq-_s.seq),$=new Map(E.messageCards);for(let[Re,_s]of P.messageCards){let Ei=$.get(Re)||[],Cu=new Set(Ei.map(vs=>vs.id)),xu=_s.filter(vs=>!Cu.has(vs.id));$.set(Re,[...Ei,...xu])}let Fe=new Set(E.siblingCards.map(Re=>Re.id)),Su=P.siblingCards.filter(Re=>!Fe.has(Re.id)),Ru=[...E.siblingCards,...Su];return Q[I]={...E,activityMessages:P.activityMessages??[],messages:ue,messageCards:$,siblingCards:Ru},{...T,pages:Q}})}catch(P){console.warn("[useInfiniteChannelMessages] live tail fetch failed, falling back to full invalidation:",P),h()}},F=async()=>{if(g){v=!0;return}g=!0;try{do v=!1,await O();while(v&&!w)}finally{g=!1}},S=te("vfs_change",()=>{f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{F()},500)},M=>di(M,t,n,m.getQueryData(y)?.pages.flatMap(K=>K.messages)??[]));return()=>{w=!0,S(),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(h=>h.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}}function Tl(e){return e==="on"||e==="auto"?"on":"off"}function Da(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:Tl(t.ai_mode),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}}function ls(e={}){let t=Y(),{realtime:n=!0,enabled:r=!0}=e,s=W(),i=(0,_.useMemo)(()=>x.channels("all"),[t]),o=V({queryKey:i,queryFn:async()=>((await C("query",{item_type:"channel",include_reader:!0,limit:500})).items||[]).map(Da),enabled:r});return(0,_.useEffect)(()=>{if(!(!n||!r))return Oa(s,i,Da)},[n,r,i,s]),{channels:o.data??[],isLoading:o.isLoading,isFetching:o.isFetching,error:o.error,refetch:o.refetch}}function vc(e={}){let t=ls(e),n=(0,_.useMemo)(()=>t.channels.filter(r=>!r.isDm),[t.channels]);return{...t,channels:n}}function bc(e={}){let t=ls(e),n=(0,_.useMemo)(()=>t.channels.filter(r=>r.isDm),[t.channels]);return{...t,channels:n}}function gi(e={}){let t=Y(),{filter:n="all",limit:r=200,realtime:s=!0,enabled:i=!0}=e,o=W(),c=(0,_.useRef)(null),a=(0,_.useMemo)(()=>x.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=>te(m,()=>{c.current&&clearTimeout(c.current),c.current=setTimeout(()=>{o.invalidateQueries({queryKey:a})},2e3)},f=>f.item_type==="notification"&&as(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 wc(e={}){let{channels:t,realtime:n=!0,enabled:r=!0}=e,{notifications:s,isLoading:i,isFetching:o,error:c,refetch:a}=gi({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(g=>g.isDm).map(g=>g.id)),y=0,h=0;return u.forEach((g,v)=>{f.has(v)?y+=g:h+=g}),{dmUnread:y,channelUnread:h}},[t,u]);return{unreadByChannel:u,totalUnread:d,dmUnread:p,channelUnread:m,isLoading:i,isFetching:o,error:c,refetch:a}}function Sc(){let e=W();return de({mutationFn:t=>C("create",t),onSuccess:(t,n)=>{let r=n.parent_path;r&&e.invalidateQueries({queryKey:x.children(r)})}})}function Rc(){let e=W();return de({mutationFn:t=>C("update",t),onSuccess:(t,n)=>{let r=n.path;if(r){e.invalidateQueries({queryKey:x.item(r)});let s=r.split("/");s.pop();let i=s.join("/");i&&e.invalidateQueries({queryKey:x.children(i)})}}})}function Cc(){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},Pl()}})}function xc(){let e=W();return de({mutationFn:t=>C("delete",t),onSuccess:(t,n)=>{let r=n.path;if(r){e.removeQueries({queryKey:x.item(r)});let s=r.split("/");s.pop();let i=s.join("/");i&&e.invalidateQueries({queryKey:x.children(i)})}}})}function Pc(){let e=W();return de({mutationFn:t=>C("move",t),onSuccess:(t,n)=>{let r=n.path,s=n.new_parent_path;if(r){e.invalidateQueries({queryKey:x.item(r)});let i=r.split("/");i.pop();let o=i.join("/");o&&e.invalidateQueries({queryKey:x.children(o)})}s&&e.invalidateQueries({queryKey:x.children(s)})}})}function Tc(){let e=W();return de({mutationFn:t=>C("link",t),onSuccess:(t,n)=>{let r=n.source_id,s=n.target_id;r&&e.invalidateQueries({queryKey:x.edges(r)}),s&&e.invalidateQueries({queryKey:x.edges(s)})}})}function Ec(e,t){let n=W(),{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 Ic(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?te(r,d=>c.current(d),a.current?d=>a.current(d):void 0):void 0,[r,o])}function Ac(e){let{queryKey:t,queryFn:n,eventType:r,filter:s,enabled:i=!0,debounceMs:o=500}=e,c=W(),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=te(r,()=>{u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{Ie(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 Cn(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,w)=>[v,w])),h=[],g=[];for(let v of m)(y.has(f(v))?h:g).push(v);return h.sort((v,w)=>y.get(f(v))-y.get(f(w))),[...h,...g]},[d]);return{...o,arrangement:c,resolvedChildren:a,resolutionLevel:u,order:d,sourceScopeId:c?.scope_item_id??null,arrangementQueryKey:i,applyTo:p}}function kc(e){let{origin:t,originField:n,fallbackUrl:r,mintError:s,scopeId:i,scopePath:o}=e,c=Y(),a=At(),u=i??a?.scope_id??null,d=(0,_.useMemo)(()=>{if(!t)return null;let S="/accounts/",M=t.indexOf(S);if(M===-1)return null;let K=t.indexOf("/",M+S.length);return K===-1?t:t.slice(0,K)},[t]),p=o??d??a?.scope_path??null,m=n?.trim()||null,f=`${c}
4
+ ${u??""}
5
5
  ${p??""}
6
6
  ${m??""}
7
- ${t??""}`,[y,h]=(0,_.useState)(null),g=(0,_.useRef)({key:f,found:null,earlyContentPaths:new Set}),v=y?.key===f?y:null;(0,_.useLayoutEffect)(()=>{g.current={key:f,found:v,earlyContentPaths:new Set}},[f]);let x=j({queryKey:["vfs",p??"__unscoped__","minted-asset",m??"",t??""],queryFn:async()=>{let C=await S("query",{scope_path:p,filters:{[`field.${m}`]:t},limit:1}),k=C.content?.items??C.items??[],U=k[0]?ye(k[0]):null;if(!U)return null;let I=(await sr(U.path)).some($=>$.item_type==="file"&&!!$.type_data?.file_ref);return{asset:U,hasBytes:I}},enabled:!!(t&&p&&m&&!s),refetchInterval:C=>g.current.key===f&&g.current.found?.hasBytes||C.state.data?.hasBytes?!1:1500});(0,_.useEffect)(()=>{let C=x.data;if(!C||g.current.key!==f)return;let k=g.current.found,U={key:f,itemId:C.asset.id,itemPath:C.asset.path,displayName:typeof C.asset.type_data?.display_name=="string"?C.asset.type_data.display_name:C.asset.name,hasBytes:C.hasBytes||!!(k?.itemId===C.asset.id&&k.hasBytes)};g.current.found=U,h(U)},[x.data,f]);let q=!!(t&&l)&&!s&&!v?.hasBytes;return(0,_.useEffect)(()=>{if(!(!q||!l))return yn(l,["asset.materialized","content.written"])},[q,l]),(0,_.useEffect)(()=>{if(!q||!t||!l)return;let C=f,k=M=>M?.payload??M,U=M=>{let Q=k(M)?.scope_id??M?.scope_id;return typeof Q=="string"?Q:void 0},N=M=>{let Q=k(M)?.item_path??M?.item_path;return typeof Q=="string"&&Q?Q:void 0},I=(M,E)=>{let Q=E.replace(/\/+$/,"");return M===Q||M.startsWith(`${Q}/`)},$=[re("asset.materialized",M=>{if(g.current.key!==C)return;let E=k(M);if(typeof E?.item_id!="string"||!E.item_id)return;let Q=g.current.found,O=typeof E.item_path=="string"?E.item_path:void 0,ue=!!E.has_bytes||!!(O&&Array.from(g.current.earlyContentPaths).some(Oe=>I(Oe,O)))||!!(Q&&Q.itemId===E.item_id&&Q.hasBytes),V={key:C,itemId:E.item_id,itemPath:O,displayName:typeof E.display_name=="string"?E.display_name:void 0,hasBytes:ue};g.current.found=V,h(V)},M=>{let E=U(M);return(!E||E===l)&&k(M)?.origin===t}),re("content.written",M=>{if(g.current.key!==C)return;let E=N(M);if(!E)return;let Q=g.current.found;if(!Q?.itemPath||!I(E,Q.itemPath)){if(g.current.earlyContentPaths.add(E),g.current.earlyContentPaths.size>128){let ue=g.current.earlyContentPaths.values().next().value;ue&&g.current.earlyContentPaths.delete(ue)}return}if(Q.hasBytes)return;let O={...Q,hasBytes:!0};g.current.found=O,h(O)},M=>{let E=U(M);return(!E||E===l)&&!!N(M)})];return()=>$.forEach(M=>M())},[q,t,l,f]),{state:s?"failed":t?v?v.hasBytes?"ready":"materializing":"pending":"idle",itemId:v?.itemId,itemPath:v?.itemPath,displayName:v?.displayName,fallbackUrl:r??void 0,error:s??void 0}}function Ac(e,t){let n=(0,xn.useSyncExternalStore)(be,Z,Z),r=ge(),s=H(),i=r?.kind==="space",o=Cn(i&&s?{key:e,scope_id:r.id}:null),c=(0,xn.useMemo)(()=>{let f=o.applyTo([...t]);if(e!=="channel-order")return f;let y=new Set(o.order??[]),h=f.filter(v=>!y.has(v.id)),g=v=>Date.parse(v.createdAt??"")||0;return h.sort((v,x)=>g(x)-g(v)),[...h,...f.filter(v=>y.has(v.id))]},[e,t,o.applyTo,o.order]),a=W(),l=(0,xn.useRef)(!1),d=!!(i&&!o.error&&o.arrangement?.item_id&&o.resolutionLevel==="member"&&o.arrangement.write_target_id===o.arrangement.item_id),p=de({mutationFn:async f=>{let y=await S("update",{_scope_path:f.scopePath,id:f.arrangementId,type_data:{order:f.ids}});if(y?.success===!1)throw new Error(y.error||"Order could not be saved");return y},onSettled:(f,y,h)=>Ye(a,h.queryKey)});async function m(f){if(!d||!s||n!==Z()||H()!==s)throw new Error("Personal order is not available in this Space");if(l.current)throw new Error("An order change is already being saved");let y=t.map(C=>C.id);if(f.length!==y.length||new Set(f).size!==y.length||y.some(C=>!f.includes(C)))throw new Error("Order must include each displayed item exactly once");let h=a.getQueryData(o.arrangementQueryKey);if(h?.item_id!==o.arrangement.item_id||JSON.stringify(h?.type_data?.order??[])!==JSON.stringify(o.order??[]))throw new Error("The saved order changed. Try dragging again");let g=c.map(C=>C.id);if(f.every((C,k)=>g[k]===C))return;let v=new Set(y),x=0,F=[...(o.order??[]).map(C=>v.has(C)?f[x++]:C),...f.slice(x)];l.current=!0;try{return await p.mutateAsync({ids:F,scopePath:s,arrangementId:o.arrangement.item_id,queryKey:o.arrangementQueryKey})}finally{l.current=!1}}return{items:c,ready:d,supported:i,contextKey:`${n}:${s}:${e}`,isLoading:i&&o.isLoading,error:o.error,refetch:o.refetch,isSaving:p.isPending,saveError:p.error,reorder:m}}var hi=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,xl=/^[A-Za-z_:][A-Za-z0-9_:.-]{0,127}$/,kc=new Map,Mc=new Map,Pn=class extends Error{constructor(n,r,s,i){super(n);ee(this,"code");ee(this,"status");ee(this,"eventId");this.name="InteractionTrackingError",this.code=r,this.status=s,this.eventId=i}};function Tn(e){let t=e?Gn.find(n=>n.id===e):Gn.find(n=>n.default===!0)??(Gn.length===1?Gn[0]:void 0);if(!t)throw new TypeError("No unambiguous source is declared for this release");if(!t.id||!Number.isInteger(t.version)||t.version<1)throw new TypeError("The release source declaration is invalid");return t}function ls(e,t){let n=t.adapters?.find(r=>r.type===e);if(!n)throw new TypeError(`The source does not declare a ${e} adapter`);return n}function Pl(e){return e.length>0&&e.length<=128&&!/[\u0000-\u001f\u007f]/.test(e)}function Tl(e,t){if(!Pl(t)||!e.observations?.includes(t))throw new TypeError("The observation is not declared by this release source")}function gi(e){if(!(typeof window>"u"||e.storage==="memory"))try{return e.storage==="session"?window.sessionStorage:window.localStorage}catch{return}}function El(e){try{let t=gi(e)?.getItem(e.key)??void 0;return t&&hi.test(t)?t:void 0}catch{return}}function Oc(e,t){try{gi(e)?.setItem(e.key,t)}catch{}}function Fc(e){let t=e.identity?.visitor;if(!t?.key)throw new TypeError("The source visitor identity policy is invalid");let n=El(t)??kc.get(e.id);if(n)return n;let r=crypto.randomUUID();return kc.set(e.id,r),Oc(t,r),r}function qc(e,t=Date.now()){let n=e.identity?.session;if(!n?.key||!Number.isInteger(n.idle_seconds)||n.idle_seconds<1)throw new TypeError("The source session identity policy is invalid");let r;try{let l=gi(n)?.getItem(n.key);r=l?JSON.parse(l):void 0}catch{r=void 0}let s=Mc.get(e.id),i=r&&typeof r.id=="string"&&hi.test(r.id)&&typeof r.lastSeenAt=="number"?{id:r.id,lastSeenAt:r.lastSeenAt}:s,o=n.idle_seconds*1e3,a=i&&t-i.lastSeenAt>=0&&t-i.lastSeenAt<o?{id:i.id,lastSeenAt:t}:{id:crypto.randomUUID(),lastSeenAt:t};return Mc.set(e.id,a),Oc(n,JSON.stringify(a)),a.id}function Il(e,t){let n=e.source_keys?.query;if(!Array.isArray(n)||n.length===0)return;let r;try{r=new URL(t)}catch{return}let s=e.source_keys?.max_value_length,i=Number.isInteger(s)?Math.min(Math.max(s??1,1),4096):512,o=Object.fromEntries(n.flatMap(c=>{if(typeof c!="string"||c.length===0||c.length>128)return[];let a=r.searchParams.get(c);return a?[[c,a.slice(0,i)]]:[]}));return Object.keys(o).length>0?o:void 0}async function qt(e,t={},n={}){let r=Tn(n.source);if(Tl(r,e),!t||typeof t!="object"||Array.isArray(t))throw new TypeError("properties must be an object");let s=n.eventId??crypto.randomUUID(),i=n.visitorId??Fc(r),o=n.sessionId??qc(r);if(![s,i,o].every(g=>hi.test(g)))throw new TypeError("event, visitor, and session IDs must be UUIDs");let c=n.pageUrl??(typeof window<"u"?window.location.href:void 0);if(!c)throw new TypeError("pageUrl is required outside a browser");let a=n.occurredAt??new Date().toISOString();if(Number.isNaN(Date.parse(a)))throw new TypeError("occurredAt is invalid");let l=n.referrer??(typeof document<"u"&&document.referrer||void 0),d=Il(r,c),p=d?{...t,source_keys:d}:t,m=At(),f=`${xe.replace(/\/+$/,"")}/d/${encodeURIComponent(m)}/interactions`,y;try{y=await fetch(f,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({source:r.id,page_url:c,visitor_id:i,session_id:o,referrer:l,events:[{id:s,event_type:e,occurred_at:a,properties:p}]}),signal:n.signal,credentials:"omit",keepalive:n.keepalive??!1})}catch(g){throw new Pn(g instanceof Error?g.message:"Observation transport network error","OBSERVATION_NETWORK_ERROR",0,s)}let h=null;try{h=await y.json()}catch{}if(!y.ok||h?.success!==!0){let g=h;throw new Pn(g?.message||g?.error||`Observation transport failed (${y.status})`,g?.error||"OBSERVATION_TRANSPORT_FAILED",y.status,s)}return h}function Qc(e={},t={}){let n=Tn(t.source),r=ls("page_view",n),s=typeof document>"u"||!r.title_property?{}:{[r.title_property]:document.title.slice(0,512)};return qt(r.observation,{...s,...e},{...t,source:n.id})}function Dc(e,t={},n={}){if(!e||e.length>128)throw new TypeError("actionId is invalid");let r=Tn(n.source),s=ls("declared_action",r),i=s.id_property?{[s.id_property]:e}:{};return qt(s.observation,{...t,...i},{...n,source:r.id})}function Uc(){try{let e=Tn();return ls("form_receipt",e),{visitor_id:Fc(e),session_id:qc(e),source:e.id}}catch{return}}function Nc(e,t={}){let n=Tn(t.source),r=ls("form_receipt",n);return qt(r.observation,e,{...t,source:n.id})}var fr;function ds(e={}){if(typeof window>"u"||typeof document>"u")return()=>{};if(fr)return fr;if(window.__FSAOS_CONFIG__?.tracking?.enabled===!1)return()=>{};let t;try{t=Tn(e.source)}catch{return()=>{}}let n=e.pageViews===!1?[]:t.adapters.filter(m=>m.type==="page_view"),r=e.declaredActions===!1?[]:t.adapters.filter(m=>m.type==="declared_action"),s="",i=()=>{if(window.location.href!==s){s=window.location.href;for(let m of n){let f=m.title_property?{[m.title_property]:document.title.slice(0,512)}:{};qt(m.observation,f,{source:t.id,keepalive:!0}).catch(()=>{})}}},o=m=>{if(m.target instanceof Element)for(let f of r){let y=f.attribute;if(!y||!xl.test(y))continue;let h=m.target.closest(`[${y}]`);if(!h)continue;let g=h.getAttribute(y)?.trim();if(!g||g.length>128)continue;let v={};f.id_property&&(v[f.id_property]=g),f.element_property&&(v[f.element_property]=h.tagName.toLowerCase()),qt(f.observation,v,{source:t.id,keepalive:!0}).catch(()=>{})}},c=window.history.pushState,a=window.history.replaceState,l=()=>queueMicrotask(i),d=n.some(m=>m.history===!0),p=n.some(m=>m.pageshow===!0);return d&&(window.history.pushState=function(...f){c.apply(this,f),l()},window.history.replaceState=function(...f){a.apply(this,f),l()},window.addEventListener("popstate",i)),p&&window.addEventListener("pageshow",i),r.length>0&&document.addEventListener("click",o,{capture:!0}),n.length>0&&queueMicrotask(i),fr=()=>{window.removeEventListener("popstate",i),window.removeEventListener("pageshow",i),document.removeEventListener("click",o,{capture:!0}),d&&(window.history.pushState=c,window.history.replaceState=a),fr=void 0},fr}var En;ie(()=>{En=void 0});function fs(e){if(En)return En.accountPath!==e.accountPath?Promise.reject(new Error("Reset the session before changing accounts")):En.promise;let t=se(),n=()=>{if(t!==se())throw new Error("Workspace session changed")},r=(async()=>{let s=await pt();if(n(),!s.principal_id)throw new Error("Workspace initialization requires an authenticated principal");let i=await P().fetchQuery({queryKey:R.memberships(s.principal_id),queryFn:ts,staleTime:12e4,retry:!1});n();let o=i.find(p=>p.path===e.accountPath&&p.isAccount&&!p.isSpace);if(!o)throw new Error("Authenticated account membership is unavailable");let c=i.find(p=>p.isSpace&&p.accountId===o.personalSpaceId&&p.path===o.personalSpacePath);if(!c||!o.personalSpacePath)throw new Error("A provisioned default Space membership is required");let a=je(o),l=je(c),d=fe();if(d&&d.id!==a.id)throw new Error("Reset the session before changing accounts");return d||Et(a,{activate:!1}),await Ft(o.personalSpacePath,p=>{let m=i.find(f=>f.accountId===p&&(f.isAccount||f.isSpace));return m?je(m):null},{initialAnchor:l}),n(),{home:a,defaultSpace:l,memberships:i}})().catch(s=>{throw t===se()&&(En=void 0),s});return En={accountPath:e.accountPath,promise:r},r}var Qt,mr,pr;ie(()=>{mr?.(),mr=void 0,Qt=void 0,pr=void 0});function Kc(e={}){if(Qt)return e.workspace&&e.workspace.accountPath!==pr?Promise.reject(new Error("Initialize workspace through initializeWorkspace, or dispose the existing runtime first")):Qt;pr=e.workspace?.accountPath;let t=se();return Qt=(async()=>{let n=e.tracking??!0,r=n===!1?()=>{}:ds(typeof n=="object"?n:{});mr=r;try{let s=e.session===!1?null:await pt(),i=e.workspace?await fs(e.workspace):void 0;if(t!==se())throw new Error("Session changed during initialization");let o=!1;return{session:s,workspace:i,dispose(){o||(o=!0,r(),t===se()&&(Qt=void 0,pr=void 0,mr=void 0))}}}catch(s){throw r(),t===se()&&(Qt=void 0,pr=void 0,mr=void 0),s}})(),Qt}async function yi(e){try{return await S("execution-control-transition",e)}catch(t){if(!(t instanceof Te)||t.status<500)throw t;return await new Promise(n=>setTimeout(n,250)),S("execution-control-transition",e)}}function _i(e){let t=e.conversation_anchor_item_id??e.conversation_root_id;return t?{...e,conversation_anchor_item_id:t,conversation_root_id:e.conversation_root_id??t}:e}async function Lc(e,t={}){let n=e.trim();if(!n)throw new TypeError("cancelTurn requires a request message id");let r=(t.idempotencyKey??`cancel:${n}`).trim();if(!r)throw new TypeError("cancelTurn requires a non-empty idempotency key");if(r.length>128)throw new TypeError("cancelTurn idempotency key must be 128 characters or fewer");let s=await yi({op:"request",command:"cancel",delivery:"immediate",request_message_id:n,idempotency_key:r,...t.scopePath?{_scope_path:t.scopePath}:{}}),i=s.outcome??s.state??s.status;return _i(i?{...s,state:i}:s)}async function jc(e,t,n={}){let r=e.trim(),s=t.trim();if(!r)throw new TypeError("steerTurn requires an active request message id");if(!s)throw new TypeError("steerTurn requires a selected queue entry id");if(r===s)throw new TypeError("steerTurn cannot target the active request message");let i=(n.idempotencyKey??`steer:${r}:${s}`).trim();if(!i)throw new TypeError("steerTurn requires a non-empty idempotency key");if(i.length>128)throw new TypeError("steerTurn idempotency key must be 128 characters or fewer");let o=await yi({op:"request",command:"steer",delivery:"immediate",request_message_id:r,selected_queue_entry_id:s,idempotency_key:i,...n.scopePath?{_scope_path:n.scopePath}:{}}),c=o.outcome??o.state??o.status;return _i(c?{...o,state:c}:o)}async function Wc(e,t={}){let n=e.trim();if(!n)throw new TypeError("cancelQueuedTurn requires a queue entry id");let r=(t.idempotencyKey??`cancel-queue:${n}`).trim();if(!r)throw new TypeError("cancelQueuedTurn requires a non-empty idempotency key");if(r.length>128)throw new TypeError("cancelQueuedTurn idempotency key must be 128 characters or fewer");let s=await yi({op:"cancel_queue_entry",queue_entry_id:n,idempotency_key:r,...t.scopePath?{_scope_path:t.scopePath}:{}}),i=s.outcome??s.state??s.status;return _i(i?{...s,outcome:i}:s)}var Al=/^[a-z][a-z0-9_-]{0,63}$/,kl=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,In=class extends Error{constructor(n,r,s,i){super(n);ee(this,"code");ee(this,"status");ee(this,"fillId");this.name="FormSubmissionError",this.code=r,this.status=s,this.fillId=i}};async function Bc(e,t,n={}){if(!Al.test(e))throw new TypeError("capabilityId is invalid");if(!t||typeof t!="object"||Array.isArray(t))throw new TypeError("fields must be an object");let r=n.fillId??crypto.randomUUID();if(!kl.test(r))throw new TypeError("fillId must be a UUID");let s=At(),i=n.pageUrl??(typeof window<"u"?window.location.href:void 0);if(!i)throw new TypeError("pageUrl is required outside a browser");let o=`${xe.replace(/\/+$/,"")}/d/${encodeURIComponent(s)}/actions/${encodeURIComponent(e)}`,c=Uc(),a=c?{visitor_id:c.visitor_id,session_id:c.session_id}:void 0,l;try{l=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({fill_id:r,page_url:i,fields:t,...a?{attribution:a}:{}}),signal:n.signal,credentials:"omit"})}catch(p){throw new In(p instanceof Error?p.message:"Form submission network error","FORM_NETWORK_ERROR",0,r)}let d=null;try{d=await l.json()}catch{}if(!l.ok||d?.success!==!0){let p=d;throw new In(p?.message||p?.error||`Form submission failed (${l.status})`,p?.error||"FORM_SUBMISSION_FAILED",l.status,r)}try{await Nc({fill_id:r,action_id:e,release_id:d.release_id},{eventId:r,pageUrl:i,signal:n.signal,keepalive:!0,...c?{source:c.source,visitorId:c.visitor_id,sessionId:c.session_id}:{}})}catch{}return d}var vi=X(oe(),1),Hc=X(Vc(),1);function Gc(e){return S("read",{path:e})}function zc(e,t){return S("list",{path:e,...t})}function Jc(e){return S("create",e)}function Yc(e){return S("update",e)}function Xc(e){return S("create",e)}function Zc(e,t){let r=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).scopePath||"";return S("tools/call",{name:e,instance_path:r,...t||{}})}function eu(e,t,n){return S("signal",{target_id:e,event_name:t,payload:n||{}})}function tu(e){return((typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"")+e}var nu={signIn:e=>e.provider?B.auth.signInWithOAuth({provider:e.provider,options:{redirectTo:e.redirectTo||window.location.href}}):B.auth.signInWithPassword({email:e.email,password:e.password}),signUp:e=>B.auth.signUp({email:e.email,password:e.password,options:{data:e.metadata||{}}}),signOut:async()=>{await B.auth.signOut(),ln(),P().clear()},getSession:()=>B.auth.getSession().then(e=>e.data.session),getUser:()=>B.auth.getUser().then(e=>e.data.user),onAuthStateChange:e=>{let{data:{subscription:t}}=B.auth.onAuthStateChange((n,r)=>{e({event:n,session:r,user:r?.user??null})});return()=>t?.unsubscribe()},resetPassword:e=>B.auth.resetPasswordForEmail(e),signInWithMagicLink:(e,t)=>B.auth.signInWithOtp({email:e,options:{emailRedirectTo:t||window.location.href}})};function ru(){let e=document.getElementById("root");if(e)try{let t=window.__FSAOS_COMPONENT__;if(!t){e.innerHTML='<div style="padding:2rem;color:#ef4444;font-family:system-ui"><h2>Component Error</h2><pre>No component found. The bundle may have failed to load.</pre></div>';return}let n=t.default||t,r=window.__FSAOS_ITEM_DATA__||null,s=r?{item:r,...r}:{};(0,Hc.createRoot)(e).render((0,vi.createElement)(Bn,{client:P()},(0,vi.createElement)(n,s)))}catch(t){console.error("[FSAOS] Failed to mount root component:",t),e.innerHTML='<div style="padding:2rem;color:#ef4444;font-family:system-ui"><h2>Component Error</h2><pre>'+(t.message||t)+"</pre></div>"}}function su(){let e=window.React,t=window.ReactDOM,n=window.__FSAOS_GATEWAY__,r=window.__FSAOS_UI__;if(!n){console.error("[FSAOS] Cannot set up require shim: __FSAOS_GATEWAY__ not found");return}let s={react:e,"react-dom":t,"react-dom/client":t,"react/jsx-runtime":{jsx:e?.createElement,jsxs:e?.createElement,Fragment:e?.Fragment},"@fsaos/kernel":n,"@fsaos/react":n,"@fsaos/gateway":n,"@fsaos/ui":r||{}};window.require=function(o){if(s[o])return s[o];throw new Error("[FSAOS] Module not found: "+o)},window.__FSAOS_MOUNT__=n.mount}function Ml(e){return e.split("_").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function Ol(e,t){return t&&t.length>0?"select":e==="boolean"?"toggle":e==="integer"||e==="number"?"range":e==="string"?"text":"none"}function Fl(e,t){return!(e==="object"||e==="array")}function ql(e){return["string","number","integer","boolean"].includes(e)}function Ql(e){return e!=="object"&&e!=="array"}function iu(e,t,n,r){let s=e?.properties;if(!s||typeof s!="object")return[];let i=[];for(let[o,c]of Object.entries(s)){let a=c.type||"string",l=c.enum,d=Fl(a,l),p=ql(a),m=Ol(a,l);i.push({key:o,label:c.title||Ml(o),type:a,description:c.description,enum_values:l,default_value:n[o]??r[o]??c.default,editable:t,filterable:d,sortable:p,filter_widget:m})}return i}function bi(e){let t=e.default_data||{},n=e.field_defaults||{},r=iu(e.input_schema,!0,t,n),s=iu(e.system_schema,!1,t,n),i=[...r,...s],o=i.filter(l=>Ql(l.type)),c=i.filter(l=>l.filterable),a=i.filter(l=>l.sortable);return{fields:i,columns:o,filterable:c,sortable:a,form_fields:r,system_fields:s}}function ou(e){return{field:"updated_at",direction:"desc"}}function au(e){let t=bi(e),n=new Set(e.input_schema?.required||[]);return t.form_fields.filter(r=>n.has(r.key)||r.default_value===void 0)}var _e=X(oe(),1);var Dl=0;function Ul(){return`upload_${Date.now()}_${++Dl}`}async function cu(e,t,n,r){let s=t.name||(e instanceof File?e.name:`file-${Date.now()}`),i=e.type||"application/octet-stream",o=t.itemType||"file",c={parent_path:t.parentPath,item_type:o,name:s,type_data:{...t.typeData||{},file_source:{type:"upload",content_type:i}}};t.cardParentPath&&(c.card_parent_path=t.cardParentPath);let l=await S("create",c);if(!l.id)throw new Error(l.error||l.message||"Failed to create file item");let d=l.id,p=l.path;if(l.storage_completed&&l.file_ref)return{itemId:d,itemPath:p,fileRef:l.file_ref};let m=l.storage_key,f=l.upload_token,y=l.storage_worker_url||"https://fsaos-storage.radns.workers.dev";if(!m)throw new Error("Gateway returned no storage_key \u2014 file_source may not be supported for this item type");await Nl(y,m,f,e,i,n,r);let h=await uu(d,m,i);return{itemId:d,itemPath:p,fileRef:h}}function Nl(e,t,n,r,s,i,o){return new Promise((c,a)=>{let l=new XMLHttpRequest;if(l.open("PUT",`${e}/upload`),l.setRequestHeader("X-Storage-Key",t),l.setRequestHeader("Content-Type",s),n&&l.setRequestHeader("X-Upload-Token",n),l.upload.onprogress=d=>{d.lengthComputable&&i&&i(Math.round(d.loaded/d.total*100))},l.onload=()=>{l.status>=200&&l.status<300?c():a(new Error(`Storage upload failed: HTTP ${l.status} \u2014 ${l.responseText?.slice(0,300)}`))},l.onerror=()=>a(new Error("Storage upload network error")),l.ontimeout=()=>a(new Error("Storage upload timed out")),o){if(o.aborted){a(new Error("Upload cancelled"));return}o.addEventListener("abort",()=>{l.abort(),a(new Error("Upload cancelled"))})}l.send(r)})}async function uu(e,t,n){let r=await Je(),s=await fetch(`${xe}/storage/upload-complete`,{method:"POST",headers:{"Content-Type":"application/json",...r?{Authorization:`Bearer ${r}`}:{}},body:JSON.stringify({item_id:e,storage_key:t,content_type:n})});if(!s.ok){let o=await s.text().catch(()=>"");throw new Error(`Upload confirmation failed: HTTP ${s.status} \u2014 ${o.slice(0,300)}`)}let i=await s.json();if(!i.success)throw new Error(i.error||i.message||"Upload confirmation rejected");return i.file_ref}function lu(){let[e,t]=(0,_e.useState)([]),n=W(),r=(0,_e.useRef)(e);r.current=e;let s=(0,_e.useCallback)((h,g)=>{t(v=>v.map(x=>x.id===h?{...x,...g}:x))},[]),i=(0,_e.useCallback)(h=>{t(g=>[...g,h])},[]),o=(0,_e.useCallback)(async(h,g,v,x,q)=>{let F=v.name||g.name,C=g.type||"application/octet-stream",k=v.itemType||"file",U=q?.itemId||null,N=q?.itemPath||null,I=q?.storageKey||null,$=q?.uploadToken||null,M=q?.storageWorkerUrl||null;try{if(!x||x==="create"){s(h,{status:"creating",error:null,_failedAt:null});let O=await S("create",{parent_path:v.parentPath,item_type:k,name:F,type_data:{...v.typeData||{},file_source:{type:"upload",content_type:C}}});if(!O.id)throw Object.assign(new Error(O.error||O.message||"Failed to create file item"),{_step:"create"});if(U=O.id,N=O.path,s(h,{itemId:U,itemPath:N}),O.storage_completed&&O.file_ref){s(h,{status:"complete",progress:100,fileRef:O.file_ref}),n.invalidateQueries({queryKey:R.children(v.parentPath)});return}if(I=O.storage_key,$=O.upload_token||"",M=O.storage_worker_url||"https://fsaos-storage.radns.workers.dev",s(h,{_storageKey:I,_uploadToken:$,_storageWorkerUrl:M}),!I)throw Object.assign(new Error("Gateway returned no storage_key"),{_step:"create"})}(!x||x==="create"||x==="upload")&&(s(h,{status:"uploading",progress:0,error:null,_failedAt:null}),await new Promise((O,ue)=>{let V=new XMLHttpRequest;s(h,{_xhr:V}),V.open("PUT",`${M}/upload`),V.setRequestHeader("X-Storage-Key",I),V.setRequestHeader("Content-Type",C),$&&V.setRequestHeader("X-Upload-Token",$),V.upload.onprogress=Oe=>{Oe.lengthComputable&&s(h,{progress:Math.round(Oe.loaded/Oe.total*100)})},V.onload=()=>{V.status>=200&&V.status<300?O():ue(Object.assign(new Error(`Storage upload failed: HTTP ${V.status}`),{_step:"upload"}))},V.onerror=()=>ue(Object.assign(new Error("Storage upload network error"),{_step:"upload"})),V.ontimeout=()=>ue(Object.assign(new Error("Storage upload timed out"),{_step:"upload"})),V.send(g)}),s(h,{progress:100,_xhr:null})),s(h,{status:"confirming",error:null,_failedAt:null});let E=await uu(U,I,C);s(h,{status:"complete",fileRef:E}),n.invalidateQueries({queryKey:R.children(v.parentPath)})}catch(E){let Q=E?.message||String(E),O=E?._step||"create";s(h,{status:"error",error:Q,_failedAt:O,_xhr:null})}},[s,n]),c=(0,_e.useCallback)((h,g)=>{let v=Ul();i({id:v,file:h,status:"creating",progress:0,error:null,itemId:null,itemPath:null,fileRef:null,options:g,_storageKey:null,_uploadToken:null,_storageWorkerUrl:null,_xhr:null,_failedAt:null}),o(v,h,g)},[i,o]),a=(0,_e.useCallback)((h,g)=>{for(let v of h)c(v,g)},[c]),l=(0,_e.useCallback)(h=>{let g=r.current.find(q=>q.id===h);if(!g||g.status!=="error")return;let v=g._failedAt||"create",x=g._storageKey&&g.itemId?{storageKey:g._storageKey,uploadToken:g._uploadToken||"",storageWorkerUrl:g._storageWorkerUrl||"https://fsaos-storage.radns.workers.dev",itemId:g.itemId,itemPath:g.itemPath||""}:void 0;o(h,g.file,g.options,v,x)},[o]),d=(0,_e.useCallback)(h=>{let g=r.current.find(v=>v.id===h);g&&(g._xhr&&g._xhr.abort(),s(h,{status:"error",error:"Cancelled",_xhr:null,_failedAt:null}))},[s]),p=(0,_e.useCallback)(h=>{t(g=>g.filter(v=>v.id!==h))},[]),m=(0,_e.useCallback)(()=>{t(h=>h.filter(g=>g.status!=="complete"))},[]),f=e.some(h=>h.status==="creating"||h.status==="uploading"||h.status==="confirming"),y=e.map(({_storageKey:h,_uploadToken:g,_storageWorkerUrl:v,_xhr:x,_failedAt:q,...F})=>F);return{upload:c,uploadMultiple:a,uploads:y,retryUpload:l,cancelUpload:d,removeUpload:p,clearCompleted:m,isUploading:f}}var du=X(oe(),1);async function wi(e,t){return await S("resolve-items",{context_id:e,item_type:t})}function fu(e,t){return(0,du.useSyncExternalStore)(be,Z,Z),j({queryKey:["vfs",H()??"__unscoped__","resolved-items",e??"",t],queryFn:()=>wi(e,t),enabled:!!(e&&t)})}var Me=X(oe(),1);function ps(e,t){let n={artifacts:new Map,timeline:[]},r=new Map;function s(o){if(!o.action?.startsWith("artifact_"))return;let a,l=o.name;if(typeof l=="string"&&l.startsWith("{"))try{a=JSON.parse(l)}catch{return}else if(o.artifact_id)a=o;else return;switch(a.type){case"artifact_opened":{let d=Date.now();if(n.artifacts.set(a.artifact_id,{artifact_id:a.artifact_id,surface_type:a.surface_type,tool_id:a.tool_id,tool_name:a.tool_name,target_uri:a.target_uri,status:"streaming",content:"",total_chars:0,delta_count:0,artifact_item_uri:null,evidence_uri:null,meta:a.meta,started_at:d,completed_at:null}),r.has(a.tool_id)){let p=r.get(a.tool_id);n.timeline[p].artifact_ids.push(a.artifact_id)}else{let p=n.timeline.length;n.timeline.push({tool_id:a.tool_id,tool_name:a.tool_name,status:"started",target_uri:a.target_uri,started_at:d,completed_at:null,artifact_ids:[a.artifact_id]}),r.set(a.tool_id,p)}break}case"artifact_delta":{let d=n.artifacts.get(a.artifact_id);d&&(d.content+=a.content_delta,d.total_chars+=a.content_delta.length,d.delta_count+=1,a.target_uri&&!d.target_uri&&(d.target_uri=a.target_uri));break}case"artifact_done":{let d=n.artifacts.get(a.artifact_id);d&&(d.status=a.status,d.total_chars=a.total_chars,d.artifact_item_uri=a.artifact_item_uri,d.evidence_uri=a.evidence_uri,a.target_uri&&(d.target_uri=a.target_uri),(a.status==="completed"||a.status==="failed")&&(d.completed_at=Date.now()));let p=r.get(a.tool_id);if(p!==void 0){let m=n.timeline[p];a.status==="executing"?m.status="executing":a.status==="completed"?(m.status="completed",m.completed_at=Date.now()):a.status==="failed"&&(m.status="failed",m.completed_at=Date.now()),a.target_uri&&!m.target_uri&&(m.target_uri=a.target_uri)}break}}t(n)}return jr(e,s)}function pu(e,t=!0){let[n,r]=(0,Me.useState)(new Map),[s,i]=(0,Me.useState)([]),o=(0,Me.useRef)({artifacts:new Map,timeline:[]});(0,Me.useEffect)(()=>!e||!t?void 0:ps(e,p=>{o.current=p,r(new Map(p.artifacts)),i([...p.timeline])}),[e,t]);let c=(0,Me.useCallback)(()=>{r(new Map),i([]),o.current={artifacts:new Map,timeline:[]}},[]),a=Array.from(n.values()).find(d=>d.surface_type==="file_editor"&&d.status==="streaming")??null,l=Array.from(n.values()).filter(d=>d.surface_type==="activity"&&(d.status==="streaming"||d.status==="executing"));return{artifacts:n,timeline:s,activeEditor:a,activeActivities:l,reset:c}}function mu(e,t=!0){let[n,r]=(0,Me.useState)([]);(0,Me.useEffect)(()=>!e||!t?void 0:ps(e,o=>{r([...o.timeline])}),[e,t]);let s=n.length>0?n[n.length-1]:null;return{timeline:n,latestActivity:s}}var ms=X(oe(),1);function Kl(e,t,n,r){return["vfs","timeline-history",e,t??"__all__",n??500,r??0]}async function Si(e,t){let n=`${e}/datasets/agent-events`,r=t?.limit??500,s=t?.offset??0,i={limit:r,offset:s,sort:[{key:"seq",direction:"asc"}]};t?.turnId&&(i.filters=[{key:"turn_id",operator:"eq",value:t.turnId}]);try{let c=(await S("open",{path:n,mode:"extract",strategy:"rows",arguments:i}))?.content;return c?(c.rows??c.items??c.data??[]).map(Ll).sort((l,d)=>l.seq-d.seq):[]}catch(o){if(o?.status===404||o?.message?.includes("not found"))return[];throw o}}function hu(e,t){let{turnId:n,limit:r=500,offset:s=0,enabled:i=!0,debounceMs:o=300}=t??{},c=e?`${e}/datasets/agent-events`:null,a=W(),l=(0,ms.useRef)(null),d=c?Kl(c,n,r,s):["vfs","timeline-history","__disabled__"],p=j({queryKey:d,queryFn:()=>Si(e,{turnId:n,limit:r,offset:s}),enabled:!!e&&i});return(0,ms.useEffect)(()=>{if(!c||!i)return;let m=re("vfs_change",()=>{l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{a.invalidateQueries({queryKey:d})},o)},f=>{let y=f?.path;return y?y===c&&f.item_type==="dataset":!1});return()=>{m(),l.current&&clearTimeout(l.current)}},[c,i,o,a,JSON.stringify(d)]),{events:p.data??[],isLoading:p.isLoading,error:p.error,isFetching:p.isFetching,refetch:()=>{p.refetch()}}}function Ll(e){return{turn_id:String(e.turn_id??""),seq:Number(e.seq??0),kind:String(e.kind??""),status:String(e.status??""),title:String(e.title??""),tool_name:e.tool_name!=null?String(e.tool_name):void 0,tool_id:e.tool_id!=null?String(e.tool_id):void 0,evidence_uri:e.evidence_uri!=null?String(e.evidence_uri):void 0,artifact_item_uri:e.artifact_item_uri!=null?String(e.artifact_item_uri):void 0,preview:e.preview!=null?String(e.preview):void 0,duration_ms:e.duration_ms!=null?Number(e.duration_ms):void 0,started_at:String(e.started_at??""),completed_at:e.completed_at!=null?String(e.completed_at):void 0,error_type:e.error_type!=null?String(e.error_type):void 0,meta:e.meta!=null?e.meta:void 0}}var hs=X(oe(),1);function gu(){(0,hs.useSyncExternalStore)(be,Z,Z);let e=H(),t=ge(),n=Cn(e?{key:"pinned",...t?{scope_id:t.id}:{}}:null),r=W(),s=n.resolvedChildren,i=!!(!n.error&&n.arrangement?.item_id&&n.resolutionLevel==="member"&&n.arrangement.write_target_id===n.arrangement.item_id),o=de({mutationFn:async a=>{let l,d={_scope_path:a.scopePath};if(a.operation==="pin"?l=await S("create",{...d,parent_id:a.arrangementId,name:`pin-${a.target.id}`,item_type:"symlink",type_data:{target_item_id:a.target.id,target_type:a.target.item_type}}):a.operation==="unpin"?l=await S("delete",{...d,id:a.entry.id}):l=await S("update",{...d,id:a.arrangementId,type_data:{order:a.ids}}),l?.success===!1)throw new Error(l.error||"Pins could not be saved");return l},onSettled:(a,l,d)=>Ye(r,d.queryKey)}),c=(0,hs.useCallback)(a=>!i||!e||H()!==e?Promise.reject(new Error("Personal pins are not available in this context")):a.operation==="unpin"&&!s.some(l=>l.id===a.entry.id)?Promise.reject(new Error("Pin is outside this arrangement")):a.operation==="reorder"&&(new Set(a.ids).size!==s.length||a.ids.length!==s.length||s.some(l=>!a.ids.includes(l.id)))?Promise.reject(new Error("Order must include each pin exactly once")):a.operation==="pin"&&s.some(l=>l.symlink_type_data?.target_item_id===a.target.id)?Promise.resolve(null):o.mutateAsync({...a,scopePath:e,arrangementId:n.arrangement.item_id,arrangementPath:n.arrangement.item_path,queryKey:n.arrangementQueryKey}),[i,e,s,n.arrangement,n.arrangementQueryKey,o.mutateAsync]);return{entries:s,isLoading:n.isLoading,error:n.error,refetch:n.refetch,ready:i,isSaving:o.isPending,saveError:o.error,isPinned:a=>s.some(l=>l.symlink_type_data?.target_item_id===a),pin:a=>c({operation:"pin",target:a}),unpin:a=>{let l=s.find(d=>d.symlink_type_data?.target_item_id===a||d.id===a);return l?c({operation:"unpin",entry:l}):Promise.resolve(null)},reorder:a=>c({operation:"reorder",ids:a})}}var gs=X(oe(),1);var hr=(e,t,n)=>["vfs",e,"personal-sections",t,n];function Ri(e,t){return e&&e.item_id===t.item_id&&e.version>t.version?e:t}async function Ci(e,t,n,r){let s=await S("personal-sections",{...r,context_item_id:t,collection:n,_scope_path:e});if(!s||s.success===!1)throw new Error(s?.message||s?.error||"Sections could not be saved");if(!Array.isArray(s.sections)||s.context_item_id!==t||s.collection!==n)throw new Error("Invalid sections response");return s}async function yu(e,t){let n=await Ci(e.scopePath,e.contextId,e.collection,{operation:"assign",section_id:e.sectionId,target_id:t}),r=P();return r.setQueryData(hr(e.scopePath,e.contextId,e.collection),s=>Ri(s,n)),_u(r,e.scopePath),n}function _u(e,t){for(let n of e.getQueryCache().getAll())n.queryKey[0]==="vfs"&&n.queryKey[1]===t&&n.queryKey[2]==="personal-sections"&&Ye(e,n.queryKey)}function vu(e,t){let n=(0,gs.useSyncExternalStore)(be,Z,Z),r=H(),s=W(),i=hr(r,e,t),o=j({queryKey:i,enabled:!!r&&!!e,queryFn:()=>Ci(r,e,t,{operation:"list"}),staleTime:1/0,retry:!1,meta:{arrangementRealtime:!0,personalSections:!0},structuralSharing:(p,m)=>Ri(p,m)}),c=(0,gs.useRef)(!1),a=de({mutationFn:async p=>{let m=await Ci(p.scope,p.context,p.collection,{...p.change,...p.change.operation.startsWith("reorder")?{expected_version:p.version}:{}});return s.setQueryData(hr(p.scope,p.context,p.collection),f=>Ri(f,m)),m},onSettled:(p,m,f)=>_u(s,f.scope)});async function l(p){if(!r||!e||n!==Z()||H()!==r||!o.data||o.error)throw new Error("Select the Space again before changing sections");if(c.current)throw new Error("A section change is still being saved");c.current=!0;try{return await a.mutateAsync({change:p,scope:r,context:e,collection:t,version:o.data.version})}finally{c.current=!1}}function d(p){if(!r||!e||!o.data?.sections.some(m=>m.id===p))throw new Error("Section is unavailable");return{scopePath:r,contextId:e,collection:t,sectionId:p}}return{sections:o.data?.sections??[],ready:!!o.data&&!o.error,isLoading:o.isLoading,error:o.error,refetch:o.refetch,isSaving:a.isPending,change:l,destination:d,contextKey:`${n}:${r}:${e}:${t}`}}ic(xi);return ku(xi);})();
7
+ ${t??""}`,[y,h]=(0,_.useState)(null),g=(0,_.useRef)({key:f,found:null,earlyContentPaths:new Set}),v=y?.key===f?y:null;(0,_.useLayoutEffect)(()=>{g.current={key:f,found:v,earlyContentPaths:new Set}},[f]);let w=V({queryKey:["vfs",p??"__unscoped__","minted-asset",m??"",t??""],queryFn:async()=>{let S=await C("query",{scope_path:p,filters:{[`field.${m}`]:t},limit:1}),M=S.content?.items??S.items??[],K=M[0]?ye(M[0]):null;if(!K)return null;let T=(await ir(K.path)).some(Q=>Q.item_type==="file"&&!!Q.type_data?.file_ref);return{asset:K,hasBytes:T}},enabled:!!(t&&p&&m&&!s),refetchInterval:S=>g.current.key===f&&g.current.found?.hasBytes||S.state.data?.hasBytes?!1:1500});(0,_.useEffect)(()=>{let S=w.data;if(!S||g.current.key!==f)return;let M=g.current.found,K={key:f,itemId:S.asset.id,itemPath:S.asset.path,displayName:typeof S.asset.type_data?.display_name=="string"?S.asset.type_data.display_name:S.asset.name,hasBytes:S.hasBytes||!!(M?.itemId===S.asset.id&&M.hasBytes)};g.current.found=K,h(K)},[w.data,f]);let O=!!(t&&u)&&!s&&!v?.hasBytes;return(0,_.useEffect)(()=>{if(!(!O||!u))return yn(u,["asset.materialized","content.written"])},[O,u]),(0,_.useEffect)(()=>{if(!O||!t||!u)return;let S=f,M=I=>I?.payload??I,K=I=>{let U=M(I)?.scope_id??I?.scope_id;return typeof U=="string"?U:void 0},P=I=>{let U=M(I)?.item_path??I?.item_path;return typeof U=="string"&&U?U:void 0},T=(I,E)=>{let U=E.replace(/\/+$/,"");return I===U||I.startsWith(`${U}/`)},Q=[te("asset.materialized",I=>{if(g.current.key!==S)return;let E=M(I);if(typeof E?.item_id!="string"||!E.item_id)return;let U=g.current.found,D=typeof E.item_path=="string"?E.item_path:void 0,ue=!!E.has_bytes||!!(D&&Array.from(g.current.earlyContentPaths).some(Fe=>T(Fe,D)))||!!(U&&U.itemId===E.item_id&&U.hasBytes),$={key:S,itemId:E.item_id,itemPath:D,displayName:typeof E.display_name=="string"?E.display_name:void 0,hasBytes:ue};g.current.found=$,h($)},I=>{let E=K(I);return(!E||E===u)&&M(I)?.origin===t}),te("content.written",I=>{if(g.current.key!==S)return;let E=P(I);if(!E)return;let U=g.current.found;if(!U?.itemPath||!T(E,U.itemPath)){if(g.current.earlyContentPaths.add(E),g.current.earlyContentPaths.size>128){let ue=g.current.earlyContentPaths.values().next().value;ue&&g.current.earlyContentPaths.delete(ue)}return}if(U.hasBytes)return;let D={...U,hasBytes:!0};g.current.found=D,h(D)},I=>{let E=K(I);return(!E||E===u)&&!!P(I)})];return()=>Q.forEach(I=>I())},[O,t,u,f]),{state:s?"failed":t?v?v.hasBytes?"ready":"materializing":"pending":"idle",itemId:v?.itemId,itemPath:v?.itemPath,displayName:v?.displayName,fallbackUrl:r??void 0,error:s??void 0}}function Mc(e,t){let n=(0,xn.useSyncExternalStore)(be,Z,Z),r=ge(),s=H(),i=r?.kind==="space",o=Cn(i&&s?{key:e,scope_id:r.id}:null),c=(0,xn.useMemo)(()=>{let f=o.applyTo([...t]);if(e!=="channel-order")return f;let y=new Set(o.order??[]),h=f.filter(v=>!y.has(v.id)),g=v=>Date.parse(v.createdAt??"")||0;return h.sort((v,w)=>g(w)-g(v)),[...h,...f.filter(v=>y.has(v.id))]},[e,t,o.applyTo,o.order]),a=W(),u=(0,xn.useRef)(!1),d=!!(i&&!o.error&&o.arrangement?.item_id&&o.resolutionLevel==="member"&&o.arrangement.write_target_id===o.arrangement.item_id),p=de({mutationFn:async f=>{let y=await C("update",{_scope_path:f.scopePath,id:f.arrangementId,type_data:{order:f.ids}});if(y?.success===!1)throw new Error(y.error||"Order could not be saved");return y},onSettled:(f,y,h)=>Ye(a,h.queryKey)});async function m(f){if(!d||!s||n!==Z()||H()!==s)throw new Error("Personal order is not available in this Space");if(u.current)throw new Error("An order change is already being saved");let y=t.map(S=>S.id);if(f.length!==y.length||new Set(f).size!==y.length||y.some(S=>!f.includes(S)))throw new Error("Order must include each displayed item exactly once");let h=a.getQueryData(o.arrangementQueryKey);if(h?.item_id!==o.arrangement.item_id||JSON.stringify(h?.type_data?.order??[])!==JSON.stringify(o.order??[]))throw new Error("The saved order changed. Try dragging again");let g=c.map(S=>S.id);if(f.every((S,M)=>g[M]===S))return;let v=new Set(y),w=0,F=[...(o.order??[]).map(S=>v.has(S)?f[w++]:S),...f.slice(w)];u.current=!0;try{return await p.mutateAsync({ids:F,scopePath:s,arrangementId:o.arrangement.item_id,queryKey:o.arrangementQueryKey})}finally{u.current=!1}}return{items:c,ready:d,supported:i,contextKey:`${n}:${s}:${e}`,isLoading:i&&o.isLoading,error:o.error,refetch:o.refetch,isSaving:p.isPending,saveError:p.error,reorder:m}}var yi=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,El=/^[A-Za-z_:][A-Za-z0-9_:.-]{0,127}$/,Oc=new Map,Fc=new Map,Pn=class extends Error{constructor(n,r,s,i){super(n);ee(this,"code");ee(this,"status");ee(this,"eventId");this.name="InteractionTrackingError",this.code=r,this.status=s,this.eventId=i}};function Tn(e){let t=e?Gn.find(n=>n.id===e):Gn.find(n=>n.default===!0)??(Gn.length===1?Gn[0]:void 0);if(!t)throw new TypeError("No unambiguous source is declared for this release");if(!t.id||!Number.isInteger(t.version)||t.version<1)throw new TypeError("The release source declaration is invalid");return t}function ds(e,t){let n=t.adapters?.find(r=>r.type===e);if(!n)throw new TypeError(`The source does not declare a ${e} adapter`);return n}function Il(e){return e.length>0&&e.length<=128&&!/[\u0000-\u001f\u007f]/.test(e)}function Al(e,t){if(!Il(t)||!e.observations?.includes(t))throw new TypeError("The observation is not declared by this release source")}function _i(e){if(!(typeof window>"u"||e.storage==="memory"))try{return e.storage==="session"?window.sessionStorage:window.localStorage}catch{return}}function kl(e){try{let t=_i(e)?.getItem(e.key)??void 0;return t&&yi.test(t)?t:void 0}catch{return}}function qc(e,t){try{_i(e)?.setItem(e.key,t)}catch{}}function Qc(e){let t=e.identity?.visitor;if(!t?.key)throw new TypeError("The source visitor identity policy is invalid");let n=kl(t)??Oc.get(e.id);if(n)return n;let r=crypto.randomUUID();return Oc.set(e.id,r),qc(t,r),r}function Dc(e,t=Date.now()){let n=e.identity?.session;if(!n?.key||!Number.isInteger(n.idle_seconds)||n.idle_seconds<1)throw new TypeError("The source session identity policy is invalid");let r;try{let u=_i(n)?.getItem(n.key);r=u?JSON.parse(u):void 0}catch{r=void 0}let s=Fc.get(e.id),i=r&&typeof r.id=="string"&&yi.test(r.id)&&typeof r.lastSeenAt=="number"?{id:r.id,lastSeenAt:r.lastSeenAt}:s,o=n.idle_seconds*1e3,a=i&&t-i.lastSeenAt>=0&&t-i.lastSeenAt<o?{id:i.id,lastSeenAt:t}:{id:crypto.randomUUID(),lastSeenAt:t};return Fc.set(e.id,a),qc(n,JSON.stringify(a)),a.id}function Ml(e,t){let n=e.source_keys?.query;if(!Array.isArray(n)||n.length===0)return;let r;try{r=new URL(t)}catch{return}let s=e.source_keys?.max_value_length,i=Number.isInteger(s)?Math.min(Math.max(s??1,1),4096):512,o=Object.fromEntries(n.flatMap(c=>{if(typeof c!="string"||c.length===0||c.length>128)return[];let a=r.searchParams.get(c);return a?[[c,a.slice(0,i)]]:[]}));return Object.keys(o).length>0?o:void 0}async function qt(e,t={},n={}){let r=Tn(n.source);if(Al(r,e),!t||typeof t!="object"||Array.isArray(t))throw new TypeError("properties must be an object");let s=n.eventId??crypto.randomUUID(),i=n.visitorId??Qc(r),o=n.sessionId??Dc(r);if(![s,i,o].every(g=>yi.test(g)))throw new TypeError("event, visitor, and session IDs must be UUIDs");let c=n.pageUrl??(typeof window<"u"?window.location.href:void 0);if(!c)throw new TypeError("pageUrl is required outside a browser");let a=n.occurredAt??new Date().toISOString();if(Number.isNaN(Date.parse(a)))throw new TypeError("occurredAt is invalid");let u=n.referrer??(typeof document<"u"&&document.referrer||void 0),d=Ml(r,c),p=d?{...t,source_keys:d}:t,m=kt(),f=`${Pe.replace(/\/+$/,"")}/d/${encodeURIComponent(m)}/interactions`,y;try{y=await fetch(f,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({source:r.id,page_url:c,visitor_id:i,session_id:o,referrer:u,events:[{id:s,event_type:e,occurred_at:a,properties:p}]}),signal:n.signal,credentials:"omit",keepalive:n.keepalive??!1})}catch(g){throw new Pn(g instanceof Error?g.message:"Observation transport network error","OBSERVATION_NETWORK_ERROR",0,s)}let h=null;try{h=await y.json()}catch{}if(!y.ok||h?.success!==!0){let g=h;throw new Pn(g?.message||g?.error||`Observation transport failed (${y.status})`,g?.error||"OBSERVATION_TRANSPORT_FAILED",y.status,s)}return h}function Uc(e={},t={}){let n=Tn(t.source),r=ds("page_view",n),s=typeof document>"u"||!r.title_property?{}:{[r.title_property]:document.title.slice(0,512)};return qt(r.observation,{...s,...e},{...t,source:n.id})}function Nc(e,t={},n={}){if(!e||e.length>128)throw new TypeError("actionId is invalid");let r=Tn(n.source),s=ds("declared_action",r),i=s.id_property?{[s.id_property]:e}:{};return qt(s.observation,{...t,...i},{...n,source:r.id})}function Kc(){try{let e=Tn();return ds("form_receipt",e),{visitor_id:Qc(e),session_id:Dc(e),source:e.id}}catch{return}}function Lc(e,t={}){let n=Tn(t.source),r=ds("form_receipt",n);return qt(r.observation,e,{...t,source:n.id})}var pr;function fs(e={}){if(typeof window>"u"||typeof document>"u")return()=>{};if(pr)return pr;if(window.__FSAOS_CONFIG__?.tracking?.enabled===!1)return()=>{};let t;try{t=Tn(e.source)}catch{return()=>{}}let n=e.pageViews===!1?[]:t.adapters.filter(m=>m.type==="page_view"),r=e.declaredActions===!1?[]:t.adapters.filter(m=>m.type==="declared_action"),s="",i=()=>{if(window.location.href!==s){s=window.location.href;for(let m of n){let f=m.title_property?{[m.title_property]:document.title.slice(0,512)}:{};qt(m.observation,f,{source:t.id,keepalive:!0}).catch(()=>{})}}},o=m=>{if(m.target instanceof Element)for(let f of r){let y=f.attribute;if(!y||!El.test(y))continue;let h=m.target.closest(`[${y}]`);if(!h)continue;let g=h.getAttribute(y)?.trim();if(!g||g.length>128)continue;let v={};f.id_property&&(v[f.id_property]=g),f.element_property&&(v[f.element_property]=h.tagName.toLowerCase()),qt(f.observation,v,{source:t.id,keepalive:!0}).catch(()=>{})}},c=window.history.pushState,a=window.history.replaceState,u=()=>queueMicrotask(i),d=n.some(m=>m.history===!0),p=n.some(m=>m.pageshow===!0);return d&&(window.history.pushState=function(...f){c.apply(this,f),u()},window.history.replaceState=function(...f){a.apply(this,f),u()},window.addEventListener("popstate",i)),p&&window.addEventListener("pageshow",i),r.length>0&&document.addEventListener("click",o,{capture:!0}),n.length>0&&queueMicrotask(i),pr=()=>{window.removeEventListener("popstate",i),window.removeEventListener("pageshow",i),document.removeEventListener("click",o,{capture:!0}),d&&(window.history.pushState=c,window.history.replaceState=a),pr=void 0},pr}var En;ie(()=>{En=void 0});function ps(e){if(En)return En.accountPath!==e.accountPath?Promise.reject(new Error("Reset the session before changing accounts")):En.promise;let t=se(),n=()=>{if(t!==se())throw new Error("Workspace session changed")},r=(async()=>{let s=await pt();if(n(),!s.principal_id)throw new Error("Workspace initialization requires an authenticated principal");let i=await A().fetchQuery({queryKey:x.memberships(s.principal_id),queryFn:ns,staleTime:12e4,retry:!1});n();let o=i.find(p=>p.path===e.accountPath&&p.isAccount&&!p.isSpace);if(!o)throw new Error("Authenticated account membership is unavailable");let c=i.find(p=>p.isSpace&&p.accountId===o.personalSpaceId&&p.path===o.personalSpacePath);if(!c||!o.personalSpacePath)throw new Error("A provisioned default Space membership is required");let a=je(o),u=je(c),d=fe();if(d&&d.id!==a.id)throw new Error("Reset the session before changing accounts");return d||It(a,{activate:!1}),await Ft(o.personalSpacePath,p=>{let m=i.find(f=>f.accountId===p&&(f.isAccount||f.isSpace));return m?je(m):null},{initialAnchor:u}),n(),{home:a,defaultSpace:u,memberships:i}})().catch(s=>{throw t===se()&&(En=void 0),s});return En={accountPath:e.accountPath,promise:r},r}var Qt,hr,mr;ie(()=>{hr?.(),hr=void 0,Qt=void 0,mr=void 0});function jc(e={}){if(Qt)return e.workspace&&e.workspace.accountPath!==mr?Promise.reject(new Error("Initialize workspace through initializeWorkspace, or dispose the existing runtime first")):Qt;mr=e.workspace?.accountPath;let t=se();return Qt=(async()=>{let n=e.tracking??!0,r=n===!1?()=>{}:fs(typeof n=="object"?n:{});hr=r;try{let s=e.session===!1?null:await pt(),i=e.workspace?await ps(e.workspace):void 0;if(t!==se())throw new Error("Session changed during initialization");let o=!1;return{session:s,workspace:i,dispose(){o||(o=!0,r(),t===se()&&(Qt=void 0,mr=void 0,hr=void 0))}}}catch(s){throw r(),t===se()&&(Qt=void 0,mr=void 0,hr=void 0),s}})(),Qt}async function vi(e){try{return await C("execution-control-transition",e)}catch(t){if(!(t instanceof Ee)||t.status<500)throw t;return await new Promise(n=>setTimeout(n,250)),C("execution-control-transition",e)}}function bi(e){let t=e.conversation_anchor_item_id??e.conversation_root_id;return t?{...e,conversation_anchor_item_id:t,conversation_root_id:e.conversation_root_id??t}:e}async function Vc(e,t={}){let n=e.trim();if(!n)throw new TypeError("cancelTurn requires a request message id");let r=(t.idempotencyKey??`cancel:${n}`).trim();if(!r)throw new TypeError("cancelTurn requires a non-empty idempotency key");if(r.length>128)throw new TypeError("cancelTurn idempotency key must be 128 characters or fewer");let s=await vi({op:"request",command:"cancel",delivery:"immediate",request_message_id:n,idempotency_key:r,...t.scopePath?{_scope_path:t.scopePath}:{}}),i=s.outcome??s.state??s.status;return bi(i?{...s,state:i}:s)}async function Wc(e,t,n={}){let r=e.trim(),s=t.trim();if(!r)throw new TypeError("steerTurn requires an active request message id");if(!s)throw new TypeError("steerTurn requires a selected queue entry id");if(r===s)throw new TypeError("steerTurn cannot target the active request message");let i=(n.idempotencyKey??`steer:${r}:${s}`).trim();if(!i)throw new TypeError("steerTurn requires a non-empty idempotency key");if(i.length>128)throw new TypeError("steerTurn idempotency key must be 128 characters or fewer");let o=await vi({op:"request",command:"steer",delivery:"immediate",request_message_id:r,selected_queue_entry_id:s,idempotency_key:i,...n.scopePath?{_scope_path:n.scopePath}:{}}),c=o.outcome??o.state??o.status;return bi(c?{...o,state:c}:o)}async function Bc(e,t={}){let n=e.trim();if(!n)throw new TypeError("cancelQueuedTurn requires a queue entry id");let r=(t.idempotencyKey??`cancel-queue:${n}`).trim();if(!r)throw new TypeError("cancelQueuedTurn requires a non-empty idempotency key");if(r.length>128)throw new TypeError("cancelQueuedTurn idempotency key must be 128 characters or fewer");let s=await vi({op:"cancel_queue_entry",queue_entry_id:n,idempotency_key:r,...t.scopePath?{_scope_path:t.scopePath}:{}}),i=s.outcome??s.state??s.status;return bi(i?{...s,outcome:i}:s)}var Ol=/^[a-z][a-z0-9_-]{0,63}$/,Fl=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,In=class extends Error{constructor(n,r,s,i){super(n);ee(this,"code");ee(this,"status");ee(this,"fillId");this.name="FormSubmissionError",this.code=r,this.status=s,this.fillId=i}};async function $c(e,t,n={}){if(!Ol.test(e))throw new TypeError("capabilityId is invalid");if(!t||typeof t!="object"||Array.isArray(t))throw new TypeError("fields must be an object");let r=n.fillId??crypto.randomUUID();if(!Fl.test(r))throw new TypeError("fillId must be a UUID");let s=kt(),i=n.pageUrl??(typeof window<"u"?window.location.href:void 0);if(!i)throw new TypeError("pageUrl is required outside a browser");let o=`${Pe.replace(/\/+$/,"")}/d/${encodeURIComponent(s)}/actions/${encodeURIComponent(e)}`,c=Kc(),a=c?{visitor_id:c.visitor_id,session_id:c.session_id}:void 0,u;try{u=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({fill_id:r,page_url:i,fields:t,...a?{attribution:a}:{}}),signal:n.signal,credentials:"omit"})}catch(p){throw new In(p instanceof Error?p.message:"Form submission network error","FORM_NETWORK_ERROR",0,r)}let d=null;try{d=await u.json()}catch{}if(!u.ok||d?.success!==!0){let p=d;throw new In(p?.message||p?.error||`Form submission failed (${u.status})`,p?.error||"FORM_SUBMISSION_FAILED",u.status,r)}try{await Lc({fill_id:r,action_id:e,release_id:d.release_id},{eventId:r,pageUrl:i,signal:n.signal,keepalive:!0,...c?{source:c.source,visitorId:c.visitor_id,sessionId:c.session_id}:{}})}catch{}return d}var wi=X(oe(),1),zc=X(Gc(),1);function Jc(e){return C("read",{path:e})}function Yc(e,t){return C("list",{path:e,...t})}function Xc(e){return C("create",e)}function Zc(e){return C("update",e)}function eu(e){return C("create",e)}function tu(e,t){let r=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).scopePath||"";return C("tools/call",{name:e,instance_path:r,...t||{}})}function nu(e,t,n){return C("signal",{target_id:e,event_name:t,payload:n||{}})}function ru(e){return((typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"")+e}var su={signIn:e=>e.provider?B.auth.signInWithOAuth({provider:e.provider,options:{redirectTo:e.redirectTo||window.location.href}}):B.auth.signInWithPassword({email:e.email,password:e.password}),signUp:e=>B.auth.signUp({email:e.email,password:e.password,options:{data:e.metadata||{}}}),signOut:async()=>{await B.auth.signOut(),ln(),A().clear()},getSession:()=>B.auth.getSession().then(e=>e.data.session),getUser:()=>B.auth.getUser().then(e=>e.data.user),onAuthStateChange:e=>{let{data:{subscription:t}}=B.auth.onAuthStateChange((n,r)=>{e({event:n,session:r,user:r?.user??null})});return()=>t?.unsubscribe()},resetPassword:e=>B.auth.resetPasswordForEmail(e),signInWithMagicLink:(e,t)=>B.auth.signInWithOtp({email:e,options:{emailRedirectTo:t||window.location.href}})};function iu(){let e=document.getElementById("root");if(e)try{let t=window.__FSAOS_COMPONENT__;if(!t){e.innerHTML='<div style="padding:2rem;color:#ef4444;font-family:system-ui"><h2>Component Error</h2><pre>No component found. The bundle may have failed to load.</pre></div>';return}let n=t.default||t,r=window.__FSAOS_ITEM_DATA__||null,s=r?{item:r,...r}:{};(0,zc.createRoot)(e).render((0,wi.createElement)(Wn,{client:A()},(0,wi.createElement)(n,s)))}catch(t){console.error("[FSAOS] Failed to mount root component:",t),e.innerHTML='<div style="padding:2rem;color:#ef4444;font-family:system-ui"><h2>Component Error</h2><pre>'+(t.message||t)+"</pre></div>"}}function ou(){let e=window.React,t=window.ReactDOM,n=window.__FSAOS_GATEWAY__,r=window.__FSAOS_UI__;if(!n){console.error("[FSAOS] Cannot set up require shim: __FSAOS_GATEWAY__ not found");return}let s={react:e,"react-dom":t,"react-dom/client":t,"react/jsx-runtime":{jsx:e?.createElement,jsxs:e?.createElement,Fragment:e?.Fragment},"@fsaos/kernel":n,"@fsaos/react":n,"@fsaos/gateway":n,"@fsaos/ui":r||{}};window.require=function(o){if(s[o])return s[o];throw new Error("[FSAOS] Module not found: "+o)},window.__FSAOS_MOUNT__=n.mount}function ql(e){return e.split("_").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function Ql(e,t){return t&&t.length>0?"select":e==="boolean"?"toggle":e==="integer"||e==="number"?"range":e==="string"?"text":"none"}function Dl(e,t){return!(e==="object"||e==="array")}function Ul(e){return["string","number","integer","boolean"].includes(e)}function Nl(e){return e!=="object"&&e!=="array"}function au(e,t,n,r){let s=e?.properties;if(!s||typeof s!="object")return[];let i=[];for(let[o,c]of Object.entries(s)){let a=c.type||"string",u=c.enum,d=Dl(a,u),p=Ul(a),m=Ql(a,u);i.push({key:o,label:c.title||ql(o),type:a,description:c.description,enum_values:u,default_value:n[o]??r[o]??c.default,editable:t,filterable:d,sortable:p,filter_widget:m})}return i}function Si(e){let t=e.default_data||{},n=e.field_defaults||{},r=au(e.input_schema,!0,t,n),s=au(e.system_schema,!1,t,n),i=[...r,...s],o=i.filter(u=>Nl(u.type)),c=i.filter(u=>u.filterable),a=i.filter(u=>u.sortable);return{fields:i,columns:o,filterable:c,sortable:a,form_fields:r,system_fields:s}}function cu(e){return{field:"updated_at",direction:"desc"}}function uu(e){let t=Si(e),n=new Set(e.input_schema?.required||[]);return t.form_fields.filter(r=>n.has(r.key)||r.default_value===void 0)}var _e=X(oe(),1);var Kl=0;function Ll(){return`upload_${Date.now()}_${++Kl}`}async function lu(e,t,n,r){let s=t.name||(e instanceof File?e.name:`file-${Date.now()}`),i=e.type||"application/octet-stream",o=t.itemType||"file",c={parent_path:t.parentPath,item_type:o,name:s,type_data:{...t.typeData||{},file_source:{type:"upload",content_type:i}}};t.cardParentPath&&(c.card_parent_path=t.cardParentPath);let u=await C("create",c);if(!u.id)throw new Error(u.error||u.message||"Failed to create file item");let d=u.id,p=u.path;if(u.storage_completed&&u.file_ref)return{itemId:d,itemPath:p,fileRef:u.file_ref};let m=u.storage_key,f=u.upload_token,y=u.storage_worker_url||"https://fsaos-storage.radns.workers.dev";if(!m)throw new Error("Gateway returned no storage_key \u2014 file_source may not be supported for this item type");await jl(y,m,f,e,i,n,r);let h=await du(d,m,i);return{itemId:d,itemPath:p,fileRef:h}}function jl(e,t,n,r,s,i,o){return new Promise((c,a)=>{let u=new XMLHttpRequest;if(u.open("PUT",`${e}/upload`),u.setRequestHeader("X-Storage-Key",t),u.setRequestHeader("Content-Type",s),n&&u.setRequestHeader("X-Upload-Token",n),u.upload.onprogress=d=>{d.lengthComputable&&i&&i(Math.round(d.loaded/d.total*100))},u.onload=()=>{u.status>=200&&u.status<300?c():a(new Error(`Storage upload failed: HTTP ${u.status} \u2014 ${u.responseText?.slice(0,300)}`))},u.onerror=()=>a(new Error("Storage upload network error")),u.ontimeout=()=>a(new Error("Storage upload timed out")),o){if(o.aborted){a(new Error("Upload cancelled"));return}o.addEventListener("abort",()=>{u.abort(),a(new Error("Upload cancelled"))})}u.send(r)})}async function du(e,t,n){let r=await Je(),s=await fetch(`${Pe}/storage/upload-complete`,{method:"POST",headers:{"Content-Type":"application/json",...r?{Authorization:`Bearer ${r}`}:{}},body:JSON.stringify({item_id:e,storage_key:t,content_type:n})});if(!s.ok){let o=await s.text().catch(()=>"");throw new Error(`Upload confirmation failed: HTTP ${s.status} \u2014 ${o.slice(0,300)}`)}let i=await s.json();if(!i.success)throw new Error(i.error||i.message||"Upload confirmation rejected");return i.file_ref}function fu(){let[e,t]=(0,_e.useState)([]),n=W(),r=(0,_e.useRef)(e);r.current=e;let s=(0,_e.useCallback)((h,g)=>{t(v=>v.map(w=>w.id===h?{...w,...g}:w))},[]),i=(0,_e.useCallback)(h=>{t(g=>[...g,h])},[]),o=(0,_e.useCallback)(async(h,g,v,w,O)=>{let F=v.name||g.name,S=g.type||"application/octet-stream",M=v.itemType||"file",K=O?.itemId||null,P=O?.itemPath||null,T=O?.storageKey||null,Q=O?.uploadToken||null,I=O?.storageWorkerUrl||null;try{if(!w||w==="create"){s(h,{status:"creating",error:null,_failedAt:null});let D=await C("create",{parent_path:v.parentPath,item_type:M,name:F,type_data:{...v.typeData||{},file_source:{type:"upload",content_type:S}}});if(!D.id)throw Object.assign(new Error(D.error||D.message||"Failed to create file item"),{_step:"create"});if(K=D.id,P=D.path,s(h,{itemId:K,itemPath:P}),D.storage_completed&&D.file_ref){s(h,{status:"complete",progress:100,fileRef:D.file_ref}),n.invalidateQueries({queryKey:x.children(v.parentPath)});return}if(T=D.storage_key,Q=D.upload_token||"",I=D.storage_worker_url||"https://fsaos-storage.radns.workers.dev",s(h,{_storageKey:T,_uploadToken:Q,_storageWorkerUrl:I}),!T)throw Object.assign(new Error("Gateway returned no storage_key"),{_step:"create"})}(!w||w==="create"||w==="upload")&&(s(h,{status:"uploading",progress:0,error:null,_failedAt:null}),await new Promise((D,ue)=>{let $=new XMLHttpRequest;s(h,{_xhr:$}),$.open("PUT",`${I}/upload`),$.setRequestHeader("X-Storage-Key",T),$.setRequestHeader("Content-Type",S),Q&&$.setRequestHeader("X-Upload-Token",Q),$.upload.onprogress=Fe=>{Fe.lengthComputable&&s(h,{progress:Math.round(Fe.loaded/Fe.total*100)})},$.onload=()=>{$.status>=200&&$.status<300?D():ue(Object.assign(new Error(`Storage upload failed: HTTP ${$.status}`),{_step:"upload"}))},$.onerror=()=>ue(Object.assign(new Error("Storage upload network error"),{_step:"upload"})),$.ontimeout=()=>ue(Object.assign(new Error("Storage upload timed out"),{_step:"upload"})),$.send(g)}),s(h,{progress:100,_xhr:null})),s(h,{status:"confirming",error:null,_failedAt:null});let E=await du(K,T,S);s(h,{status:"complete",fileRef:E}),n.invalidateQueries({queryKey:x.children(v.parentPath)})}catch(E){let U=E?.message||String(E),D=E?._step||"create";s(h,{status:"error",error:U,_failedAt:D,_xhr:null})}},[s,n]),c=(0,_e.useCallback)((h,g)=>{let v=Ll();i({id:v,file:h,status:"creating",progress:0,error:null,itemId:null,itemPath:null,fileRef:null,options:g,_storageKey:null,_uploadToken:null,_storageWorkerUrl:null,_xhr:null,_failedAt:null}),o(v,h,g)},[i,o]),a=(0,_e.useCallback)((h,g)=>{for(let v of h)c(v,g)},[c]),u=(0,_e.useCallback)(h=>{let g=r.current.find(O=>O.id===h);if(!g||g.status!=="error")return;let v=g._failedAt||"create",w=g._storageKey&&g.itemId?{storageKey:g._storageKey,uploadToken:g._uploadToken||"",storageWorkerUrl:g._storageWorkerUrl||"https://fsaos-storage.radns.workers.dev",itemId:g.itemId,itemPath:g.itemPath||""}:void 0;o(h,g.file,g.options,v,w)},[o]),d=(0,_e.useCallback)(h=>{let g=r.current.find(v=>v.id===h);g&&(g._xhr&&g._xhr.abort(),s(h,{status:"error",error:"Cancelled",_xhr:null,_failedAt:null}))},[s]),p=(0,_e.useCallback)(h=>{t(g=>g.filter(v=>v.id!==h))},[]),m=(0,_e.useCallback)(()=>{t(h=>h.filter(g=>g.status!=="complete"))},[]),f=e.some(h=>h.status==="creating"||h.status==="uploading"||h.status==="confirming"),y=e.map(({_storageKey:h,_uploadToken:g,_storageWorkerUrl:v,_xhr:w,_failedAt:O,...F})=>F);return{upload:c,uploadMultiple:a,uploads:y,retryUpload:u,cancelUpload:d,removeUpload:p,clearCompleted:m,isUploading:f}}var pu=X(oe(),1);async function Ri(e,t){return await C("resolve-items",{context_id:e,item_type:t})}function mu(e,t){return(0,pu.useSyncExternalStore)(be,Z,Z),V({queryKey:["vfs",H()??"__unscoped__","resolved-items",e??"",t],queryFn:()=>Ri(e,t),enabled:!!(e&&t)})}var Oe=X(oe(),1);function ms(e,t){let n={artifacts:new Map,timeline:[]},r=new Map;function s(o){if(!o.action?.startsWith("artifact_"))return;let a,u=o.name;if(typeof u=="string"&&u.startsWith("{"))try{a=JSON.parse(u)}catch{return}else if(o.artifact_id)a=o;else return;switch(a.type){case"artifact_opened":{let d=Date.now();if(n.artifacts.set(a.artifact_id,{artifact_id:a.artifact_id,surface_type:a.surface_type,tool_id:a.tool_id,tool_name:a.tool_name,target_uri:a.target_uri,status:"streaming",content:"",total_chars:0,delta_count:0,artifact_item_uri:null,evidence_uri:null,meta:a.meta,started_at:d,completed_at:null}),r.has(a.tool_id)){let p=r.get(a.tool_id);n.timeline[p].artifact_ids.push(a.artifact_id)}else{let p=n.timeline.length;n.timeline.push({tool_id:a.tool_id,tool_name:a.tool_name,status:"started",target_uri:a.target_uri,started_at:d,completed_at:null,artifact_ids:[a.artifact_id]}),r.set(a.tool_id,p)}break}case"artifact_delta":{let d=n.artifacts.get(a.artifact_id);d&&(d.content+=a.content_delta,d.total_chars+=a.content_delta.length,d.delta_count+=1,a.target_uri&&!d.target_uri&&(d.target_uri=a.target_uri));break}case"artifact_done":{let d=n.artifacts.get(a.artifact_id);d&&(d.status=a.status,d.total_chars=a.total_chars,d.artifact_item_uri=a.artifact_item_uri,d.evidence_uri=a.evidence_uri,a.target_uri&&(d.target_uri=a.target_uri),(a.status==="completed"||a.status==="failed")&&(d.completed_at=Date.now()));let p=r.get(a.tool_id);if(p!==void 0){let m=n.timeline[p];a.status==="executing"?m.status="executing":a.status==="completed"?(m.status="completed",m.completed_at=Date.now()):a.status==="failed"&&(m.status="failed",m.completed_at=Date.now()),a.target_uri&&!m.target_uri&&(m.target_uri=a.target_uri)}break}}t(n)}return Vr(e,s)}function hu(e,t=!0){let[n,r]=(0,Oe.useState)(new Map),[s,i]=(0,Oe.useState)([]),o=(0,Oe.useRef)({artifacts:new Map,timeline:[]});(0,Oe.useEffect)(()=>!e||!t?void 0:ms(e,p=>{o.current=p,r(new Map(p.artifacts)),i([...p.timeline])}),[e,t]);let c=(0,Oe.useCallback)(()=>{r(new Map),i([]),o.current={artifacts:new Map,timeline:[]}},[]),a=Array.from(n.values()).find(d=>d.surface_type==="file_editor"&&d.status==="streaming")??null,u=Array.from(n.values()).filter(d=>d.surface_type==="activity"&&(d.status==="streaming"||d.status==="executing"));return{artifacts:n,timeline:s,activeEditor:a,activeActivities:u,reset:c}}function gu(e,t=!0){let[n,r]=(0,Oe.useState)([]);(0,Oe.useEffect)(()=>!e||!t?void 0:ms(e,o=>{r([...o.timeline])}),[e,t]);let s=n.length>0?n[n.length-1]:null;return{timeline:n,latestActivity:s}}var hs=X(oe(),1);function Vl(e,t,n,r){return["vfs","timeline-history",e,t??"__all__",n??500,r??0]}async function Ci(e,t){let n=`${e}/datasets/agent-events`,r=t?.limit??500,s=t?.offset??0,i={limit:r,offset:s,sort:[{key:"seq",direction:"asc"}]};t?.turnId&&(i.filters=[{key:"turn_id",operator:"eq",value:t.turnId}]);try{let c=(await C("open",{path:n,mode:"extract",strategy:"rows",arguments:i}))?.content;return c?(c.rows??c.items??c.data??[]).map(Wl).sort((u,d)=>u.seq-d.seq):[]}catch(o){if(o?.status===404||o?.message?.includes("not found"))return[];throw o}}function yu(e,t){let{turnId:n,limit:r=500,offset:s=0,enabled:i=!0,debounceMs:o=300}=t??{},c=e?`${e}/datasets/agent-events`:null,a=W(),u=(0,hs.useRef)(null),d=c?Vl(c,n,r,s):["vfs","timeline-history","__disabled__"],p=V({queryKey:d,queryFn:()=>Ci(e,{turnId:n,limit:r,offset:s}),enabled:!!e&&i});return(0,hs.useEffect)(()=>{if(!c||!i)return;let m=te("vfs_change",()=>{u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{a.invalidateQueries({queryKey:d})},o)},f=>{let y=f?.path;return y?y===c&&f.item_type==="dataset":!1});return()=>{m(),u.current&&clearTimeout(u.current)}},[c,i,o,a,JSON.stringify(d)]),{events:p.data??[],isLoading:p.isLoading,error:p.error,isFetching:p.isFetching,refetch:()=>{p.refetch()}}}function Wl(e){return{turn_id:String(e.turn_id??""),seq:Number(e.seq??0),kind:String(e.kind??""),status:String(e.status??""),title:String(e.title??""),tool_name:e.tool_name!=null?String(e.tool_name):void 0,tool_id:e.tool_id!=null?String(e.tool_id):void 0,evidence_uri:e.evidence_uri!=null?String(e.evidence_uri):void 0,artifact_item_uri:e.artifact_item_uri!=null?String(e.artifact_item_uri):void 0,preview:e.preview!=null?String(e.preview):void 0,duration_ms:e.duration_ms!=null?Number(e.duration_ms):void 0,started_at:String(e.started_at??""),completed_at:e.completed_at!=null?String(e.completed_at):void 0,error_type:e.error_type!=null?String(e.error_type):void 0,meta:e.meta!=null?e.meta:void 0}}var gs=X(oe(),1);function _u(){(0,gs.useSyncExternalStore)(be,Z,Z);let e=H(),t=ge(),n=Cn(e?{key:"pinned",...t?{scope_id:t.id}:{}}:null),r=W(),s=n.resolvedChildren,i=!!(!n.error&&n.arrangement?.item_id&&n.resolutionLevel==="member"&&n.arrangement.write_target_id===n.arrangement.item_id),o=de({mutationFn:async a=>{let u,d={_scope_path:a.scopePath};if(a.operation==="pin"?u=await C("create",{...d,parent_id:a.arrangementId,name:`pin-${a.target.id}`,item_type:"symlink",type_data:{target_item_id:a.target.id,target_type:a.target.item_type}}):a.operation==="unpin"?u=await C("delete",{...d,id:a.entry.id}):u=await C("update",{...d,id:a.arrangementId,type_data:{order:a.ids}}),u?.success===!1)throw new Error(u.error||"Pins could not be saved");return u},onSettled:(a,u,d)=>Ye(r,d.queryKey)}),c=(0,gs.useCallback)(a=>!i||!e||H()!==e?Promise.reject(new Error("Personal pins are not available in this context")):a.operation==="unpin"&&!s.some(u=>u.id===a.entry.id)?Promise.reject(new Error("Pin is outside this arrangement")):a.operation==="reorder"&&(new Set(a.ids).size!==s.length||a.ids.length!==s.length||s.some(u=>!a.ids.includes(u.id)))?Promise.reject(new Error("Order must include each pin exactly once")):a.operation==="pin"&&s.some(u=>u.symlink_type_data?.target_item_id===a.target.id)?Promise.resolve(null):o.mutateAsync({...a,scopePath:e,arrangementId:n.arrangement.item_id,arrangementPath:n.arrangement.item_path,queryKey:n.arrangementQueryKey}),[i,e,s,n.arrangement,n.arrangementQueryKey,o.mutateAsync]);return{entries:s,isLoading:n.isLoading,error:n.error,refetch:n.refetch,ready:i,isSaving:o.isPending,saveError:o.error,isPinned:a=>s.some(u=>u.symlink_type_data?.target_item_id===a),pin:a=>c({operation:"pin",target:a}),unpin:a=>{let u=s.find(d=>d.symlink_type_data?.target_item_id===a||d.id===a);return u?c({operation:"unpin",entry:u}):Promise.resolve(null)},reorder:a=>c({operation:"reorder",ids:a})}}var ys=X(oe(),1);var gr=(e,t,n)=>["vfs",e,"personal-sections",t,n];function xi(e,t){return e&&e.item_id===t.item_id&&e.version>t.version?e:t}async function Pi(e,t,n,r){let s=await C("personal-sections",{...r,context_item_id:t,collection:n,_scope_path:e});if(!s||s.success===!1)throw new Error(s?.message||s?.error||"Sections could not be saved");if(!Array.isArray(s.sections)||s.context_item_id!==t||s.collection!==n)throw new Error("Invalid sections response");return s}async function vu(e,t){let n=await Pi(e.scopePath,e.contextId,e.collection,{operation:"assign",section_id:e.sectionId,target_id:t}),r=A();return r.setQueryData(gr(e.scopePath,e.contextId,e.collection),s=>xi(s,n)),bu(r,e.scopePath),n}function bu(e,t){for(let n of e.getQueryCache().getAll())n.queryKey[0]==="vfs"&&n.queryKey[1]===t&&n.queryKey[2]==="personal-sections"&&Ye(e,n.queryKey)}function wu(e,t){let n=(0,ys.useSyncExternalStore)(be,Z,Z),r=H(),s=W(),i=gr(r,e,t),o=V({queryKey:i,enabled:!!r&&!!e,queryFn:()=>Pi(r,e,t,{operation:"list"}),staleTime:1/0,retry:!1,meta:{arrangementRealtime:!0,personalSections:!0},structuralSharing:(p,m)=>xi(p,m)}),c=(0,ys.useRef)(!1),a=de({mutationFn:async p=>{let m=await Pi(p.scope,p.context,p.collection,{...p.change,...p.change.operation.startsWith("reorder")?{expected_version:p.version}:{}});return s.setQueryData(gr(p.scope,p.context,p.collection),f=>xi(f,m)),m},onSettled:(p,m,f)=>bu(s,f.scope)});async function u(p){if(!r||!e||n!==Z()||H()!==r||!o.data||o.error)throw new Error("Select the Space again before changing sections");if(c.current)throw new Error("A section change is still being saved");c.current=!0;try{return await a.mutateAsync({change:p,scope:r,context:e,collection:t,version:o.data.version})}finally{c.current=!1}}function d(p){if(!r||!e||!o.data?.sections.some(m=>m.id===p))throw new Error("Section is unavailable");return{scopePath:r,contextId:e,collection:t,sectionId:p}}return{sections:o.data?.sections??[],ready:!!o.data&&!o.error,isLoading:o.isLoading,error:o.error,refetch:o.refetch,isSaving:a.isPending,change:u,destination:d,contextKey:`${n}:${r}:${e}:${t}`}}ac(Ti);return Ou(Ti);})();
8
8
 
9
9
  /* ── Auto-setup: require shim + mount + backward compat globals ── */
10
10
  (function() {