@ai4b-team/fsaos-gateway-sdk 5.8.0 → 5.9.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -0
- package/dist/iife/gateway.js +9 -6
- package/dist/iife/gateway.js.map +4 -4
- package/dist/iife/ui.js +1 -1
- package/dist/index.cjs +562 -398
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +17 -46
- package/dist/index.d.ts +17 -46
- package/dist/index.js +562 -399
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/iife/gateway.js
CHANGED
|
@@ -1,10 +1,13 @@
|
|
|
1
|
-
/* @fsaos/gateway v2.0.0 — Unified FSAOS Edge Runtime — 2026-11-
|
|
2
|
-
"use strict";var __FSAOS_GATEWAY__=(()=>{var qd=Object.create;var dr=Object.defineProperty;var Qd=Object.getOwnPropertyDescriptor;var Nd=Object.getOwnPropertyNames;var Dd=Object.getPrototypeOf,Ud=Object.prototype.hasOwnProperty;var ea=e=>{throw TypeError(e)};var Kd=(e,t,n)=>t in e?dr(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var pr=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),ta=(e,t)=>{for(var n in t)dr(e,n,{get:t[n],enumerable:!0})},na=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Nd(t))!Ud.call(e,s)&&s!==n&&dr(e,s,{get:()=>t[s],enumerable:!(r=Qd(t,s))||r.enumerable});return e};var J=(e,t,n)=>(n=e!=null?qd(Dd(e)):{},na(t||!e||!e.__esModule?dr(n,"default",{value:e,enumerable:!0}):n,e)),Ld=e=>na(dr({},"__esModule",{value:!0}),e);var ee=(e,t,n)=>Kd(e,typeof t!="symbol"?t+"":t,n),_i=(e,t,n)=>t.has(e)||ea("Cannot "+n);var p=(e,t,n)=>(_i(e,t,"read from private field"),n?n.call(e):t.get(e)),E=(e,t,n)=>t.has(e)?ea("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),S=(e,t,n,r)=>(_i(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n),q=(e,t,n)=>(_i(e,t,"access private method"),n);var fr=(e,t,n,r)=>({set _(s){S(e,t,s,n)},get _(){return p(e,t,r)}});var ue=pr((Bf,ra)=>{ra.exports=React});var ps=pr((zg,Ua)=>{Ua.exports={jsx:React.createElement,jsxs:React.createElement,Fragment:React.Fragment}});var $a=pr((Fh,Ba)=>{Ba.exports={createClient:window.supabase.createClient}});var vc=pr((Xh,bc)=>{bc.exports=ReactDOM});var Xl=pr((yb,Yl)=>{Yl.exports=ReactDOM});var Xo={};ta(Xo,{CHANNEL_AI_MODES:()=>hl,ComponentRenderer:()=>dl,EnforcementDeniedError:()=>Be,FormSubmissionError:()=>lr,GatewayRequestError:()=>Re,HostSessionUnavailableError:()=>tn,InteractionTrackingError:()=>cr,KernelProvider:()=>pl,QueryClientProvider:()=>Tr,acceptInvitation:()=>If,acceptInvite:()=>Ho,answerInput:()=>$o,assignPersonalSection:()=>Ad,auth:()=>cd,awaitAnchorReady:()=>qr,awaitScopeReady:()=>nc,callTool:()=>id,cancelInvitation:()=>Af,cancelQueuedTurn:()=>$l,cancelTurn:()=>jl,clearCachedToken:()=>Yi,clearSession:()=>so,configureGatewayReads:()=>mc,connectHostSession:()=>sc,createAgent:()=>Bo,createInvitation:()=>Pf,createItem:()=>nd,disconnectSSE:()=>yo,disposeVfsRealtimeWs:()=>bo,electHomeAnchor:()=>Zt,emitEvent:()=>$c,fetchChannelMessages:()=>su,fetchChannelMessagesPage:()=>an,fetchChannelMessagesWithCards:()=>Ys,fetchEdgesForItem:()=>$s,fetchItemHistory:()=>Gs,fetchItemVersions:()=>jr,fetchItems:()=>on,fetchMemberFocus:()=>zs,fetchMessageReplies:()=>Js,fetchMessageReplyContexts:()=>nu,fetchOpenEnvelope:()=>Br,fetchRecentActivity:()=>Ws,fetchResolvedItems:()=>Go,fetchTimelineHistory:()=>zo,fetchTurnQueueEntries:()=>Xc,fetchTypeDefinitions:()=>Bs,fetchVfsChildren:()=>Hr,fetchVfsChildrenPage:()=>js,fetchVfsItem:()=>Lr,fetchVfsItemById:()=>Kr,fetchVfsTree:()=>Vs,filePurchaseNextUrl:()=>Jl,funnelCheckoutLink:()=>zl,gatewayCall:()=>C,getAccessToken:()=>mt,getAnchor:()=>Ot,getAnchorRef:()=>fe,getAnchorVersion:()=>eo,getAssetUrl:()=>ad,getDefaultSort:()=>yd,getFilePurchase:()=>Gl,getHomeAnchor:()=>Se,getInvitation:()=>Ef,getMountVersion:()=>Ft,getMounts:()=>Me,getPathSubscriptionState:()=>Wc,getQueryClient:()=>N,getRequiredFormFields:()=>_d,getScope:()=>z,getScopeVersion:()=>W,getServerClockOffsetMs:()=>uc,getServerClockSyncedAt:()=>lc,getSessionEntry:()=>nt,hasServerClock:()=>cc,initSession:()=>gt,initVfsRealtimeWs:()=>cn,initializeFsaos:()=>Ll,initializeWorkspace:()=>pi,interpretSchema:()=>Vo,invalidateAllVfs:()=>au,invalidateChannelMessages:()=>uu,invalidateChildren:()=>Hs,invalidateItem:()=>_o,invalidateOpenEnvelope:()=>lu,invalidatePathAndParent:()=>iu,invalidateSubtree:()=>ou,invalidateTypes:()=>cu,inviteMember:()=>Lo,isAnchorReady:()=>no,isChannelPath:()=>ie,isListableItemsFilter:()=>tr,isScopeReady:()=>Cs,itemsFilterFromQueryFilter:()=>Zc,listChildren:()=>td,listInvitations:()=>kf,loadCompiledBundle:()=>Fo,loadMounts:()=>un,loadPublishedBundle:()=>rl,mount:()=>ud,mountRealtimeScope:()=>rr,normalizeItem:()=>He,onConnectionStateChange:()=>Ls,pathSubscriptionMatches:()=>mo,personalSectionsKey:()=>ns,ping:()=>Vc,pushChanges:()=>sd,queryClient:()=>Mc,readItem:()=>ed,refreshQuery:()=>ce,registerCleanup:()=>ae,rejectInvitation:()=>Tf,replaceMounts:()=>ni,resendInvitation:()=>Mf,resetAllSdkState:()=>$n,resolvePrincipalId:()=>ul,resubscribePath:()=>zc,seatMember:()=>jo,selectMount:()=>zr,sendMessage:()=>tu,serveHostSession:()=>Hl,serverDeadlinePassed:()=>dc,serverMsUntil:()=>pc,serverNow:()=>Is,setAnchor:()=>Hn,setCachedToken:()=>Ga,setQueryClient:()=>Ac,setScope:()=>tc,setupRequireShim:()=>ld,signal:()=>od,startFileCheckout:()=>Wl,startTracking:()=>di,steerTurn:()=>Bl,submitForm:()=>Vl,subscribeAnchor:()=>to,subscribeArtifactStream:()=>fi,subscribeMounts:()=>jn,subscribeScope:()=>xe,subscribeToEvents:()=>X,subscribeToPath:()=>Ks,subscribeToScope:()=>Zn,trackAction:()=>Dl,trackEvent:()=>dn,trackPageView:()=>Nl,unmountRealtimeScope:()=>ei,updateItem:()=>rd,uploadFile:()=>wd,useAcceptInvite:()=>pd,useAccounts:()=>Ju,useAgentTimeline:()=>Ed,useAllChannels:()=>ui,useAnswerInput:()=>gd,useArrangement:()=>ar,useArtifactStream:()=>Pd,useAsset:()=>Xu,useAuth:()=>ci,useChannelMessages:()=>fl,useChannels:()=>yl,useChildren:()=>Fu,useCompiledComponent:()=>ol,useComponent:()=>Oo,useCreate:()=>vl,useCreateAgent:()=>md,useDelete:()=>xl,useDmChannels:()=>_l,useEdges:()=>Lu,useEventStream:()=>El,useFileUpload:()=>xd,useIncrementalItems:()=>Uu,useInfiniteChannelMessages:()=>gl,useInfiniteChildren:()=>Ku,useInfiniteItems:()=>Ao,useInviteMember:()=>dd,useItem:()=>ku,useItemById:()=>Ou,useItemHistory:()=>Wu,useItemVersions:()=>Vu,useItems:()=>Du,useLink:()=>Cl,useList:()=>To,useMemberFocus:()=>$u,useMessageReplies:()=>ml,useMintedAsset:()=>Tl,useMounts:()=>Yu,useMove:()=>Rl,useMutation:()=>Pl,useNotifications:()=>qo,useOpen:()=>ju,usePermission:()=>Co,usePermissions:()=>ii,usePersonalItemOrder:()=>Ml,usePersonalSections:()=>kd,usePinnedItems:()=>Td,usePrincipal:()=>ll,usePublishedComponent:()=>sl,useRealtimeQuery:()=>Il,useRecentActivity:()=>Gu,useResolve:()=>Nu,useResolvedItems:()=>Cd,useScope:()=>zu,useScopeReady:()=>Mu,useSearch:()=>Qu,useSeatMember:()=>fd,useTheme:()=>al,useTimelineHistory:()=>Id,useTree:()=>qu,useType:()=>Hu,useTypeHelpers:()=>Bu,useTypes:()=>ai,useUnreadCounts:()=>bl,useUpdate:()=>wl,useUpdatePrincipal:()=>Sl,vfsKeys:()=>T,waitForPathReady:()=>Gc});var Be=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");ee(this,"payload");this.payload=n,this.deniedBy=n.denied_by||n.error_type||n.error||"unknown";let s=n.enforcement;this.ruleKey=s?.rule_key??void 0,this.displayName=s?.display_name??void 0}static fallbackMessage(n){let r=n.error||"",s=n.denied_by||"";return s==="rule"||r==="RULE_DENIED"?"This feature is not enabled for this workspace.":s==="entitlement"||r==="ENTITLEMENT_REQUIRED"?"This feature requires a plan upgrade.":s==="access"||r==="ACCESS_DENIED"||r==="PERMISSION_DENIED"?"You don't have permission to do this.":"This action is not allowed."}get isRuleDenial(){return this.deniedBy==="rule"||this.deniedBy==="RULE_DENIED"}get isAccessDenial(){return this.deniedBy==="access"||this.deniedBy==="ACCESS_DENIED"}get isEntitlementDenial(){return this.deniedBy==="entitlement"||this.deniedBy==="ENTITLEMENT_REQUIRED"}};var Ut=J(ue(),1);var Ee=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}};var Lt,vt,fn,sa,Hd=(sa=class extends Ee{constructor(){super();E(this,Lt);E(this,vt);E(this,fn);S(this,fn,t=>{if(typeof window<"u"&&window.addEventListener){let n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){p(this,vt)||this.setEventListener(p(this,fn))}onUnsubscribe(){var t;this.hasListeners()||((t=p(this,vt))==null||t.call(this),S(this,vt,void 0))}setEventListener(t){var n;S(this,fn,t),(n=p(this,vt))==null||n.call(this),S(this,vt,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){p(this,Lt)!==t&&(S(this,Lt,t),this.onFocus())}onFocus(){let t=this.isFocused();this.listeners.forEach(n=>{n(t)})}isFocused(){return typeof p(this,Lt)=="boolean"?p(this,Lt):globalThis.document?.visibilityState!=="hidden"}},Lt=new WeakMap,vt=new WeakMap,fn=new WeakMap,sa),mn=new Hd;var jd={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},wt,bi,ia,Bd=(ia=class{constructor(){E(this,wt,jd);E(this,bi,!1)}setTimeoutProvider(e){S(this,wt,e)}setTimeout(e,t){return p(this,wt).setTimeout(e,t)}clearTimeout(e){p(this,wt).clearTimeout(e)}setInterval(e,t){return p(this,wt).setInterval(e,t)}clearInterval(e){p(this,wt).clearInterval(e)}},wt=new WeakMap,bi=new WeakMap,ia),ze=new Bd;function oa(e){setTimeout(e,0)}var wi=typeof window>"u"||"Deno"in globalThis;function Y(){}function ua(e,t){return typeof e=="function"?e(t):e}function mr(e){return typeof e=="number"&&e>=0&&e!==1/0}function rs(e,t){return Math.max(e+(t||0)-Date.now(),0)}function $e(e,t){return typeof e=="function"?e(t):e}function Ie(e,t){return typeof e=="function"?e(t):e}function ss(e,t){let{type:n="all",exact:r,fetchStatus:s,predicate:i,queryKey:o,stale:a}=e;if(o){if(r){if(t.queryHash!==gr(o,t.options))return!1}else if(!Ht(t.queryKey,o))return!1}if(n!=="all"){let c=t.isActive();if(n==="active"&&!c||n==="inactive"&&c)return!1}return!(typeof a=="boolean"&&t.isStale()!==a||s&&s!==t.state.fetchStatus||i&&!i(t))}function is(e,t){let{exact:n,status:r,predicate:s,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(Je(t.options.mutationKey)!==Je(i))return!1}else if(!Ht(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||s&&!s(t))}function gr(e,t){return(t?.queryKeyHashFn||Je)(e)}function Je(e){return JSON.stringify(e,(t,n)=>vi(n)?Object.keys(n).sort().reduce((r,s)=>(r[s]=n[s],r),{}):n)}function Ht(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>Ht(e[n],t[n])):!1}var $d=Object.prototype.hasOwnProperty;function hr(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=aa(e)&&aa(t);if(!r&&!(vi(e)&&vi(t)))return t;let i=(r?e:Object.keys(e)).length,o=r?t:Object.keys(t),a=o.length,c=r?new Array(a):{},u=0;for(let d=0;d<a;d++){let l=r?d:o[d],h=e[l],f=t[l];if(h===f){c[l]=h,(r?d<i:$d.call(e,l))&&u++;continue}if(h===null||f===null||typeof h!="object"||typeof f!="object"){c[l]=f;continue}let m=hr(h,f,n+1);c[l]=m,m===h&&u++}return i===a&&u===i?e:c}function St(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 aa(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function vi(e){if(!ca(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!ca(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function ca(e){return Object.prototype.toString.call(e)==="[object Object]"}function la(e){return new Promise(t=>{ze.setTimeout(t,e)})}function yr(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?hr(e,t):t}function da(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function pa(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var gn=Symbol();function os(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===gn?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function hn(e,t){return typeof e=="function"?e(...t):!!e}function fa(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 Ye=(()=>{let e=()=>wi;return{isServer(){return e()},setIsServer(t){e=t}}})();function _r(){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 ma=oa;function Vd(){let e=[],t=0,n=a=>{a()},r=a=>{a()},s=ma,i=a=>{t?e.push(a):s(()=>{n(a)})},o=()=>{let a=e;e=[],a.length&&s(()=>{r(()=>{a.forEach(c=>{n(c)})})})};return{batch:a=>{let c;t++;try{c=a()}finally{t--,t||o()}return c},batchCalls:a=>(...c)=>{i(()=>{a(...c)})},schedule:i,setNotifyFunction:a=>{n=a},setBatchNotifyFunction:a=>{r=a},setScheduler:a=>{s=a}}}var H=Vd();var yn,xt,_n,ga,Wd=(ga=class extends Ee{constructor(){super();E(this,yn,!0);E(this,xt);E(this,_n);S(this,_n,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(){p(this,xt)||this.setEventListener(p(this,_n))}onUnsubscribe(){var t;this.hasListeners()||((t=p(this,xt))==null||t.call(this),S(this,xt,void 0))}setEventListener(t){var n;S(this,_n,t),(n=p(this,xt))==null||n.call(this),S(this,xt,t(this.setOnline.bind(this)))}setOnline(t){p(this,yn)!==t&&(S(this,yn,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return p(this,yn)}},yn=new WeakMap,xt=new WeakMap,_n=new WeakMap,ga),bn=new Wd;function Gd(e){return Math.min(1e3*2**e,3e4)}function Si(e){return(e??"online")==="online"?bn.isOnline():!0}var as=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function cs(e){let t=!1,n=0,r,s=_r(),i=()=>s.status!=="pending",o=_=>{if(!i()){let g=new as(_);h(g),e.onCancel?.(g)}},a=()=>{t=!0},c=()=>{t=!1},u=()=>mn.isFocused()&&(e.networkMode==="always"||bn.isOnline())&&e.canRun(),d=()=>Si(e.networkMode)&&e.canRun(),l=_=>{i()||(r?.(),s.resolve(_))},h=_=>{i()||(r?.(),s.reject(_))},f=()=>new Promise(_=>{r=g=>{(i()||u())&&_(g)},e.onPause?.()}).then(()=>{r=void 0,i()||e.onContinue?.()}),m=()=>{if(i())return;let _,g=n===0?e.initialPromise:void 0;try{_=g??e.fn()}catch(b){_=Promise.reject(b)}Promise.resolve(_).then(l).catch(b=>{if(i())return;let y=e.retry??(Ye.isServer()?0:3),v=e.retryDelay??Gd,x=typeof v=="function"?v(n,b):v,R=y===!0||typeof y=="number"&&n<y||typeof y=="function"&&y(n,b);if(t||!R){h(b);return}n++,e.onFail?.(n,b),la(x).then(()=>u()?void 0:f()).then(()=>{t?h(b):m()})})};return{promise:s,status:()=>s.status,cancel:o,continue:()=>(r?.(),s),cancelRetry:a,continueRetry:c,canStart:d,start:()=>(d()?m():f().then(m),s)}}var jt,ha,us=(ha=class{constructor(){E(this,jt)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),mr(this.gcTime)&&S(this,jt,ze.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Ye.isServer()?1/0:5*60*1e3))}clearGcTimeout(){p(this,jt)!==void 0&&(ze.clearTimeout(p(this,jt)),S(this,jt,void 0))}},jt=new WeakMap,ha);var Bt,vn,Ne,$t,pe,br,Vt,ke,wa,it,ba,va=(ba=class extends us{constructor(t){super();E(this,ke);E(this,Bt);E(this,vn);E(this,Ne);E(this,$t);E(this,pe);E(this,br);E(this,Vt);S(this,Vt,!1),S(this,br,t.defaultOptions),this.setOptions(t.options),this.observers=[],S(this,$t,t.client),S(this,Ne,p(this,$t).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,S(this,Bt,_a(this.options)),this.state=t.state??p(this,Bt),this.scheduleGc()}get meta(){return this.options.meta}get promise(){return p(this,pe)?.promise}setOptions(t){if(this.options={...p(this,br),...t},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let n=_a(this.options);n.data!==void 0&&(this.setState(ya(n.data,n.dataUpdatedAt)),S(this,Bt,n))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&p(this,Ne).remove(this)}setData(t,n){let r=yr(this.state.data,t,this.options);return q(this,ke,it).call(this,{data:r,type:"success",dataUpdatedAt:n?.updatedAt,manual:n?.manual}),r}setState(t,n){q(this,ke,it).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){let n=p(this,pe)?.promise;return p(this,pe)?.cancel(t),n?n.then(Y).catch(Y):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return p(this,Bt)}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(t=>Ie(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===gn||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>$e(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:!rs(this.state.dataUpdatedAt,t)}onFocus(){this.observers.find(n=>n.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),p(this,pe)?.continue()}onOnline(){this.observers.find(n=>n.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),p(this,pe)?.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),p(this,Ne).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(n=>n!==t),this.observers.length||(p(this,pe)&&(p(this,Vt)||q(this,ke,wa).call(this)?p(this,pe).cancel({revert:!0}):p(this,pe).cancelRetry()),this.scheduleGc()),p(this,Ne).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||q(this,ke,it).call(this,{type:"invalidate"})}async fetch(t,n){if(this.state.fetchStatus!=="idle"&&p(this,pe)?.status()!=="rejected"){if(this.state.data!==void 0&&n?.cancelRefetch)this.cancel({silent:!0});else if(p(this,pe))return p(this,pe).continueRetry(),p(this,pe).promise}if(t&&this.setOptions(t),!this.options.queryFn){let c=this.observers.find(u=>u.options.queryFn);c&&this.setOptions(c.options)}let r=new AbortController,s=c=>{Object.defineProperty(c,"signal",{enumerable:!0,get:()=>(S(this,Vt,!0),r.signal)})},i=()=>{let c=os(this.options,n),d=(()=>{let l={client:p(this,$t),queryKey:this.queryKey,meta:this.meta};return s(l),l})();return S(this,Vt,!1),this.options.persister?this.options.persister(c,d,this):c(d)},a=(()=>{let c={fetchOptions:n,options:this.options,queryKey:this.queryKey,client:p(this,$t),state:this.state,fetchFn:i};return s(c),c})();this.options.behavior?.onFetch(a,this),S(this,vn,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==a.fetchOptions?.meta)&&q(this,ke,it).call(this,{type:"fetch",meta:a.fetchOptions?.meta}),S(this,pe,cs({initialPromise:n?.initialPromise,fn:a.fetchFn,onCancel:c=>{c instanceof as&&c.revert&&this.setState({...p(this,vn),fetchStatus:"idle"}),r.abort()},onFail:(c,u)=>{q(this,ke,it).call(this,{type:"failed",failureCount:c,error:u})},onPause:()=>{q(this,ke,it).call(this,{type:"pause"})},onContinue:()=>{q(this,ke,it).call(this,{type:"continue"})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0}));try{let c=await p(this,pe).start();if(c===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(c),p(this,Ne).config.onSuccess?.(c,this),p(this,Ne).config.onSettled?.(c,this.state.error,this),c}catch(c){if(c instanceof as){if(c.silent)return p(this,pe).promise;if(c.revert){if(this.state.data===void 0)throw c;return this.state.data}}throw q(this,ke,it).call(this,{type:"error",error:c}),p(this,Ne).config.onError?.(c,this),p(this,Ne).config.onSettled?.(this.state.data,c,this),c}finally{this.scheduleGc()}}},Bt=new WeakMap,vn=new WeakMap,Ne=new WeakMap,$t=new WeakMap,pe=new WeakMap,br=new WeakMap,Vt=new WeakMap,ke=new WeakSet,wa=function(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"},it=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,...xi(r.data,this.options),fetchMeta:t.meta??null};case"success":let s={...r,...ya(t.data,t.dataUpdatedAt),dataUpdateCount:r.dataUpdateCount+1,...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return S(this,vn,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),H.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),p(this,Ne).notify({query:this,type:"updated",action:t})})},ba);function xi(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Si(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function ya(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function _a(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 Te,L,wr,we,Wt,wn,ot,Rt,Sr,Sn,xn,Gt,zt,Ct,Rn,V,vr,Ri,Ci,Pi,Ei,Ii,Ti,Ai,Ca,Ra,at=(Ra=class extends Ee{constructor(t,n){super();E(this,V);E(this,Te);E(this,L);E(this,wr);E(this,we);E(this,Wt);E(this,wn);E(this,ot);E(this,Rt);E(this,Sr);E(this,Sn);E(this,xn);E(this,Gt);E(this,zt);E(this,Ct);E(this,Rn,new Set);this.options=n,S(this,Te,t),S(this,Rt,null),S(this,ot,_r()),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(p(this,L).addObserver(this),Sa(p(this,L),this.options)?q(this,V,vr).call(this):this.updateResult(),q(this,V,Ei).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Mi(p(this,L),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Mi(p(this,L),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,q(this,V,Ii).call(this),q(this,V,Ti).call(this),p(this,L).removeObserver(this)}setOptions(t){let n=this.options,r=p(this,L);if(this.options=p(this,Te).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof Ie(this.options.enabled,p(this,L))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");q(this,V,Ai).call(this),p(this,L).setOptions(this.options),n._defaulted&&!St(this.options,n)&&p(this,Te).getQueryCache().notify({type:"observerOptionsUpdated",query:p(this,L),observer:this});let s=this.hasListeners();s&&xa(p(this,L),r,this.options,n)&&q(this,V,vr).call(this),this.updateResult(),s&&(p(this,L)!==r||Ie(this.options.enabled,p(this,L))!==Ie(n.enabled,p(this,L))||$e(this.options.staleTime,p(this,L))!==$e(n.staleTime,p(this,L)))&&q(this,V,Ri).call(this);let i=q(this,V,Ci).call(this);s&&(p(this,L)!==r||Ie(this.options.enabled,p(this,L))!==Ie(n.enabled,p(this,L))||i!==p(this,Ct))&&q(this,V,Pi).call(this,i)}getOptimisticResult(t){let n=p(this,Te).getQueryCache().build(p(this,Te),t),r=this.createResult(n,t);return Jd(this,r)&&(S(this,we,r),S(this,wn,this.options),S(this,Wt,p(this,L).state)),r}getCurrentResult(){return p(this,we)}trackResult(t,n){return new Proxy(t,{get:(r,s)=>(this.trackProp(s),n?.(s),s==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&p(this,ot).status==="pending"&&p(this,ot).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(r,s))})}trackProp(t){p(this,Rn).add(t)}getCurrentQuery(){return p(this,L)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){let n=p(this,Te).defaultQueryOptions(t),r=p(this,Te).getQueryCache().build(p(this,Te),n);return r.fetch().then(()=>this.createResult(r,n))}fetch(t){return q(this,V,vr).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),p(this,we)))}createResult(t,n){let r=p(this,L),s=this.options,i=p(this,we),o=p(this,Wt),a=p(this,wn),u=t!==r?t.state:p(this,wr),{state:d}=t,l={...d},h=!1,f;if(n._optimisticResults){let A=this.hasListeners(),M=!A&&Sa(t,n),I=A&&xa(t,r,n,s);(M||I)&&(l={...l,...xi(d.data,t.options)}),n._optimisticResults==="isRestoring"&&(l.fetchStatus="idle")}let{error:m,errorUpdatedAt:_,status:g}=l;f=l.data;let b=!1;if(n.placeholderData!==void 0&&f===void 0&&g==="pending"){let A;i?.isPlaceholderData&&n.placeholderData===a?.placeholderData?(A=i.data,b=!0):A=typeof n.placeholderData=="function"?n.placeholderData(p(this,xn)?.state.data,p(this,xn)):n.placeholderData,A!==void 0&&(g="success",f=yr(i?.data,A,n),h=!0)}if(n.select&&f!==void 0&&!b)if(i&&f===o?.data&&n.select===p(this,Sr))f=p(this,Sn);else try{S(this,Sr,n.select),f=n.select(f),f=yr(i?.data,f,n),S(this,Sn,f),S(this,Rt,null)}catch(A){S(this,Rt,A)}p(this,Rt)&&(m=p(this,Rt),f=p(this,Sn),_=Date.now(),g="error");let y=l.fetchStatus==="fetching",v=g==="pending",x=g==="error",R=v&&y,k=f!==void 0,P={status:g,fetchStatus:l.fetchStatus,isPending:v,isSuccess:g==="success",isError:x,isInitialLoading:R,isLoading:R,data:f,dataUpdatedAt:l.dataUpdatedAt,error:m,errorUpdatedAt:_,failureCount:l.fetchFailureCount,failureReason:l.fetchFailureReason,errorUpdateCount:l.errorUpdateCount,isFetched:t.isFetched(),isFetchedAfterMount:l.dataUpdateCount>u.dataUpdateCount||l.errorUpdateCount>u.errorUpdateCount,isFetching:y,isRefetching:y&&!v,isLoadingError:x&&!k,isPaused:l.fetchStatus==="paused",isPlaceholderData:h,isRefetchError:x&&k,isStale:ki(t,n),refetch:this.refetch,promise:p(this,ot),isEnabled:Ie(n.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){let A=P.data!==void 0,M=P.status==="error"&&!A,I=K=>{M?K.reject(P.error):A&&K.resolve(P.data)},F=()=>{let K=S(this,ot,P.promise=_r());I(K)},Q=p(this,ot);switch(Q.status){case"pending":t.queryHash===r.queryHash&&I(Q);break;case"fulfilled":(M||P.data!==Q.value)&&F();break;case"rejected":(!M||P.error!==Q.reason)&&F();break}}return P}updateResult(){let t=p(this,we),n=this.createResult(p(this,L),this.options);if(S(this,Wt,p(this,L).state),S(this,wn,this.options),p(this,Wt).data!==void 0&&S(this,xn,p(this,L)),St(n,t))return;S(this,we,n);let r=()=>{if(!t)return!0;let{notifyOnChangeProps:s}=this.options,i=typeof s=="function"?s():s;if(i==="all"||!i&&!p(this,Rn).size)return!0;let o=new Set(i??p(this,Rn));return this.options.throwOnError&&o.add("error"),Object.keys(p(this,we)).some(a=>{let c=a;return p(this,we)[c]!==t[c]&&o.has(c)})};q(this,V,Ca).call(this,{listeners:r()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&q(this,V,Ei).call(this)}},Te=new WeakMap,L=new WeakMap,wr=new WeakMap,we=new WeakMap,Wt=new WeakMap,wn=new WeakMap,ot=new WeakMap,Rt=new WeakMap,Sr=new WeakMap,Sn=new WeakMap,xn=new WeakMap,Gt=new WeakMap,zt=new WeakMap,Ct=new WeakMap,Rn=new WeakMap,V=new WeakSet,vr=function(t){q(this,V,Ai).call(this);let n=p(this,L).fetch(this.options,t);return t?.throwOnError||(n=n.catch(Y)),n},Ri=function(){q(this,V,Ii).call(this);let t=$e(this.options.staleTime,p(this,L));if(Ye.isServer()||p(this,we).isStale||!mr(t))return;let r=rs(p(this,we).dataUpdatedAt,t)+1;S(this,Gt,ze.setTimeout(()=>{p(this,we).isStale||this.updateResult()},r))},Ci=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(p(this,L)):this.options.refetchInterval)??!1},Pi=function(t){q(this,V,Ti).call(this),S(this,Ct,t),!(Ye.isServer()||Ie(this.options.enabled,p(this,L))===!1||!mr(p(this,Ct))||p(this,Ct)===0)&&S(this,zt,ze.setInterval(()=>{(this.options.refetchIntervalInBackground||mn.isFocused())&&q(this,V,vr).call(this)},p(this,Ct)))},Ei=function(){q(this,V,Ri).call(this),q(this,V,Pi).call(this,q(this,V,Ci).call(this))},Ii=function(){p(this,Gt)!==void 0&&(ze.clearTimeout(p(this,Gt)),S(this,Gt,void 0))},Ti=function(){p(this,zt)!==void 0&&(ze.clearInterval(p(this,zt)),S(this,zt,void 0))},Ai=function(){let t=p(this,Te).getQueryCache().build(p(this,Te),this.options);if(t===p(this,L))return;let n=p(this,L);S(this,L,t),S(this,wr,t.state),this.hasListeners()&&(n?.removeObserver(this),t.addObserver(this))},Ca=function(t){H.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(p(this,we))}),p(this,Te).getQueryCache().notify({query:p(this,L),type:"observerResultsUpdated"})})},Ra);function zd(e,t){return Ie(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function Sa(e,t){return zd(e,t)||e.state.data!==void 0&&Mi(e,t,t.refetchOnMount)}function Mi(e,t,n){if(Ie(t.enabled,e)!==!1&&$e(t.staleTime,e)!=="static"){let r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&ki(e,t)}return!1}function xa(e,t,n,r){return(e!==t||Ie(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&ki(e,n)}function ki(e,t){return Ie(t.enabled,e)!==!1&&e.isStaleByTime($e(t.staleTime,e))}function Jd(e,t){return!St(e.getCurrentResult(),t)}function Cn(e){return{onFetch:(t,n)=>{let r=t.options,s=t.fetchOptions?.meta?.fetchMore?.direction,i=t.state.data?.pages||[],o=t.state.data?.pageParams||[],a={pages:[],pageParams:[]},c=0,u=async()=>{let d=!1,l=m=>{fa(m,()=>t.signal,()=>d=!0)},h=os(t.options,t.fetchOptions),f=async(m,_,g)=>{if(d)return Promise.reject();if(_==null&&m.pages.length)return Promise.resolve(m);let y=(()=>{let k={client:t.client,queryKey:t.queryKey,pageParam:_,direction:g?"backward":"forward",meta:t.options.meta};return l(k),k})(),v=await h(y),{maxPages:x}=t.options,R=g?pa:da;return{pages:R(m.pages,v,x),pageParams:R(m.pageParams,_,x)}};if(s&&i.length){let m=s==="backward",_=m?Pa:Oi,g={pages:i,pageParams:o},b=_(r,g);a=await f(g,b,m)}else{let m=e??i.length;do{let _=c===0?o[0]??r.initialPageParam:Oi(r,a);if(c>0&&_==null)break;a=await f(a,_),c++}while(c<m)}return a};t.options.persister?t.fetchFn=()=>t.options.persister?.(u,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=u}}}function Oi(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 Pa(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function Ea(e,t){return t?Oi(e,t)!=null:!1}function Ia(e,t){return!t||!e.getPreviousPageParam?!1:Pa(e,t)!=null}var Fi=class extends at{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:Cn()})}getOptimisticResult(e){return e.behavior=Cn(),super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"backward"}}})}createResult(e,t){let{state:n}=e,r=super.createResult(e,t),{isFetching:s,isRefetching:i,isError:o,isRefetchError:a}=r,c=n.fetchMeta?.fetchMore?.direction,u=o&&c==="forward",d=s&&c==="forward",l=o&&c==="backward",h=s&&c==="backward";return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:Ea(t,n.data),hasPreviousPage:Ia(t,n.data),isFetchNextPageError:u,isFetchingNextPage:d,isFetchPreviousPageError:l,isFetchingPreviousPage:h,isRefetchError:a&&!u&&!l,isRefetching:i&&!d&&!h}}};var xr,Xe,_e,Jt,Ze,Pt,Ta,Aa=(Ta=class extends us{constructor(t){super();E(this,Ze);E(this,xr);E(this,Xe);E(this,_e);E(this,Jt);S(this,xr,t.client),this.mutationId=t.mutationId,S(this,_e,t.mutationCache),S(this,Xe,[]),this.state=t.state||qi(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){p(this,Xe).includes(t)||(p(this,Xe).push(t),this.clearGcTimeout(),p(this,_e).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){S(this,Xe,p(this,Xe).filter(n=>n!==t)),this.scheduleGc(),p(this,_e).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){p(this,Xe).length||(this.state.status==="pending"?this.scheduleGc():p(this,_e).remove(this))}continue(){return p(this,Jt)?.continue()??this.execute(this.state.variables)}async execute(t){let n=()=>{q(this,Ze,Pt).call(this,{type:"continue"})},r={client:p(this,xr),meta:this.options.meta,mutationKey:this.options.mutationKey};S(this,Jt,cs({fn:()=>this.options.mutationFn?this.options.mutationFn(t,r):Promise.reject(new Error("No mutationFn found")),onFail:(o,a)=>{q(this,Ze,Pt).call(this,{type:"failed",failureCount:o,error:a})},onPause:()=>{q(this,Ze,Pt).call(this,{type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>p(this,_e).canRun(this)}));let s=this.state.status==="pending",i=!p(this,Jt).canStart();try{if(s)n();else{q(this,Ze,Pt).call(this,{type:"pending",variables:t,isPaused:i}),p(this,_e).config.onMutate&&await p(this,_e).config.onMutate(t,this,r);let a=await this.options.onMutate?.(t,r);a!==this.state.context&&q(this,Ze,Pt).call(this,{type:"pending",context:a,variables:t,isPaused:i})}let o=await p(this,Jt).start();return await p(this,_e).config.onSuccess?.(o,t,this.state.context,this,r),await this.options.onSuccess?.(o,t,this.state.context,r),await p(this,_e).config.onSettled?.(o,null,this.state.variables,this.state.context,this,r),await this.options.onSettled?.(o,null,t,this.state.context,r),q(this,Ze,Pt).call(this,{type:"success",data:o}),o}catch(o){try{await p(this,_e).config.onError?.(o,t,this.state.context,this,r)}catch(a){Promise.reject(a)}try{await this.options.onError?.(o,t,this.state.context,r)}catch(a){Promise.reject(a)}try{await p(this,_e).config.onSettled?.(void 0,o,this.state.variables,this.state.context,this,r)}catch(a){Promise.reject(a)}try{await this.options.onSettled?.(void 0,o,t,this.state.context,r)}catch(a){Promise.reject(a)}throw q(this,Ze,Pt).call(this,{type:"error",error:o}),o}finally{p(this,_e).runNext(this)}}},xr=new WeakMap,Xe=new WeakMap,_e=new WeakMap,Jt=new WeakMap,Ze=new WeakSet,Pt=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),H.batch(()=>{p(this,Xe).forEach(r=>{r.onMutationUpdate(t)}),p(this,_e).notify({mutation:this,type:"updated",action:t})})},Ta);function qi(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var ct,Ve,Rr,Ma,ka=(Ma=class extends Ee{constructor(t={}){super();E(this,ct);E(this,Ve);E(this,Rr);this.config=t,S(this,ct,new Set),S(this,Ve,new Map),S(this,Rr,0)}build(t,n,r){let s=new Aa({client:t,mutationCache:this,mutationId:++fr(this,Rr)._,options:t.defaultMutationOptions(n),state:r});return this.add(s),s}add(t){p(this,ct).add(t);let n=ls(t);if(typeof n=="string"){let r=p(this,Ve).get(n);r?r.push(t):p(this,Ve).set(n,[t])}this.notify({type:"added",mutation:t})}remove(t){if(p(this,ct).delete(t)){let n=ls(t);if(typeof n=="string"){let r=p(this,Ve).get(n);if(r)if(r.length>1){let s=r.indexOf(t);s!==-1&&r.splice(s,1)}else r[0]===t&&p(this,Ve).delete(n)}}this.notify({type:"removed",mutation:t})}canRun(t){let n=ls(t);if(typeof n=="string"){let s=p(this,Ve).get(n)?.find(i=>i.state.status==="pending");return!s||s===t}else return!0}runNext(t){let n=ls(t);return typeof n=="string"?p(this,Ve).get(n)?.find(s=>s!==t&&s.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){H.batch(()=>{p(this,ct).forEach(t=>{this.notify({type:"removed",mutation:t})}),p(this,ct).clear(),p(this,Ve).clear()})}getAll(){return Array.from(p(this,ct))}find(t){let n={exact:!0,...t};return this.getAll().find(r=>is(n,r))}findAll(t={}){return this.getAll().filter(n=>is(t,n))}notify(t){H.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){let t=this.getAll().filter(n=>n.state.isPaused);return H.batch(()=>Promise.all(t.map(n=>n.continue().catch(Y))))}},ct=new WeakMap,Ve=new WeakMap,Rr=new WeakMap,Ma);function ls(e){return e.options.scope?.id}var ut,Et,Ae,lt,dt,ds,Qi,Oa,Ni=(Oa=class extends Ee{constructor(t,n){super();E(this,dt);E(this,ut);E(this,Et);E(this,Ae);E(this,lt);S(this,ut,t),this.setOptions(n),this.bindMethods(),q(this,dt,ds).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(t){let n=this.options;this.options=p(this,ut).defaultMutationOptions(t),St(this.options,n)||p(this,ut).getMutationCache().notify({type:"observerOptionsUpdated",mutation:p(this,Ae),observer:this}),n?.mutationKey&&this.options.mutationKey&&Je(n.mutationKey)!==Je(this.options.mutationKey)?this.reset():p(this,Ae)?.state.status==="pending"&&p(this,Ae).setOptions(this.options)}onUnsubscribe(){this.hasListeners()||p(this,Ae)?.removeObserver(this)}onMutationUpdate(t){q(this,dt,ds).call(this),q(this,dt,Qi).call(this,t)}getCurrentResult(){return p(this,Et)}reset(){p(this,Ae)?.removeObserver(this),S(this,Ae,void 0),q(this,dt,ds).call(this),q(this,dt,Qi).call(this)}mutate(t,n){return S(this,lt,n),p(this,Ae)?.removeObserver(this),S(this,Ae,p(this,ut).getMutationCache().build(p(this,ut),this.options)),p(this,Ae).addObserver(this),p(this,Ae).execute(t)}},ut=new WeakMap,Et=new WeakMap,Ae=new WeakMap,lt=new WeakMap,dt=new WeakSet,ds=function(){let t=p(this,Ae)?.state??qi();S(this,Et,{...t,isPending:t.status==="pending",isSuccess:t.status==="success",isError:t.status==="error",isIdle:t.status==="idle",mutate:this.mutate,reset:this.reset})},Qi=function(t){H.batch(()=>{if(p(this,lt)&&this.hasListeners()){let n=p(this,Et).variables,r=p(this,Et).context,s={client:p(this,ut),meta:this.options.meta,mutationKey:this.options.mutationKey};if(t?.type==="success"){try{p(this,lt).onSuccess?.(t.data,n,r,s)}catch(i){Promise.reject(i)}try{p(this,lt).onSettled?.(t.data,null,n,r,s)}catch(i){Promise.reject(i)}}else if(t?.type==="error"){try{p(this,lt).onError?.(t.error,n,r,s)}catch(i){Promise.reject(i)}try{p(this,lt).onSettled?.(void 0,t.error,n,r,s)}catch(i){Promise.reject(i)}}}this.listeners.forEach(n=>{n(p(this,Et))})})},Oa);function Fa(e,t){let n=new Set(t);return e.filter(r=>!n.has(r))}function Yd(e,t,n){let r=e.slice(0);return r[t]=n,r}var Pn,Oe,En,In,De,It,Cr,Pr,Er,Ir,ge,Di,Ui,Ki,Li,Hi,qa,ji=(qa=class extends Ee{constructor(t,n,r){super();E(this,ge);E(this,Pn);E(this,Oe);E(this,En);E(this,In);E(this,De);E(this,It);E(this,Cr);E(this,Pr);E(this,Er);E(this,Ir,[]);S(this,Pn,t),S(this,In,r),S(this,En,[]),S(this,De,[]),S(this,Oe,[]),this.setQueries(n)}onSubscribe(){this.listeners.size===1&&p(this,De).forEach(t=>{t.subscribe(n=>{q(this,ge,Li).call(this,t,n)})})}onUnsubscribe(){this.listeners.size||this.destroy()}destroy(){this.listeners=new Set,p(this,De).forEach(t=>{t.destroy()})}setQueries(t,n){S(this,En,t),S(this,In,n),H.batch(()=>{let r=p(this,De),s=q(this,ge,Ki).call(this,p(this,En));s.forEach(l=>l.observer.setOptions(l.defaultedQueryOptions));let i=s.map(l=>l.observer),o=i.map(l=>l.getCurrentResult()),a=r.length!==i.length,c=i.some((l,h)=>l!==r[h]),u=a||c,d=u?!0:o.some((l,h)=>{let f=p(this,Oe)[h];return!f||!St(l,f)});!u&&!d||(u&&(S(this,Ir,s),S(this,De,i)),S(this,Oe,o),this.hasListeners()&&(u&&(Fa(r,i).forEach(l=>{l.destroy()}),Fa(i,r).forEach(l=>{l.subscribe(h=>{q(this,ge,Li).call(this,l,h)})})),q(this,ge,Hi).call(this)))})}getCurrentResult(){return p(this,Oe)}getQueries(){return p(this,De).map(t=>t.getCurrentQuery())}getObservers(){return p(this,De)}getOptimisticResult(t,n){let r=q(this,ge,Ki).call(this,t),s=r.map(o=>o.observer.getOptimisticResult(o.defaultedQueryOptions)),i=r.map(o=>o.defaultedQueryOptions.queryHash);return[s,o=>q(this,ge,Ui).call(this,o??s,n,i),()=>q(this,ge,Di).call(this,s,r)]}},Pn=new WeakMap,Oe=new WeakMap,En=new WeakMap,In=new WeakMap,De=new WeakMap,It=new WeakMap,Cr=new WeakMap,Pr=new WeakMap,Er=new WeakMap,Ir=new WeakMap,ge=new WeakSet,Di=function(t,n){return n.map((r,s)=>{let i=t[s];return r.defaultedQueryOptions.notifyOnChangeProps?i:r.observer.trackResult(i,o=>{n.forEach(a=>{a.observer.trackProp(o)})})})},Ui=function(t,n,r){if(n){let s=p(this,Er),i=r!==void 0&&s!==void 0&&(s.length!==r.length||r.some((o,a)=>o!==s[a]));return(!p(this,It)||p(this,Oe)!==p(this,Pr)||i||n!==p(this,Cr))&&(S(this,Cr,n),S(this,Pr,p(this,Oe)),r!==void 0&&S(this,Er,r),S(this,It,hr(p(this,It),n(t)))),p(this,It)}return t},Ki=function(t){let n=new Map;p(this,De).forEach(s=>{let i=s.options.queryHash;if(!i)return;let o=n.get(i);o?o.push(s):n.set(i,[s])});let r=[];return t.forEach(s=>{let i=p(this,Pn).defaultQueryOptions(s),a=n.get(i.queryHash)?.shift()??new at(p(this,Pn),i);r.push({defaultedQueryOptions:i,observer:a})}),r},Li=function(t,n){let r=p(this,De).indexOf(t);r!==-1&&(S(this,Oe,Yd(p(this,Oe),r,n)),q(this,ge,Hi).call(this))},Hi=function(){if(this.hasListeners()){let t=p(this,It),n=q(this,ge,Di).call(this,p(this,Oe),p(this,Ir)),r=q(this,ge,Ui).call(this,n,p(this,In)?.combine);t!==r&&H.batch(()=>{this.listeners.forEach(s=>{s(p(this,Oe))})})}},qa);var et,Qa,Na=(Qa=class extends Ee{constructor(t={}){super();E(this,et);this.config=t,S(this,et,new Map)}build(t,n,r){let s=n.queryKey,i=n.queryHash??gr(s,n),o=this.get(i);return o||(o=new va({client:t,queryKey:s,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(s)}),this.add(o)),o}add(t){p(this,et).has(t.queryHash)||(p(this,et).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){let n=p(this,et).get(t.queryHash);n&&(t.destroy(),n===t&&p(this,et).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){H.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return p(this,et).get(t)}getAll(){return[...p(this,et).values()]}find(t){let n={exact:!0,...t};return this.getAll().find(r=>ss(n,r))}findAll(t={}){let n=this.getAll();return Object.keys(t).length>0?n.filter(r=>ss(t,r)):n}notify(t){H.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){H.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){H.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},et=new WeakMap,Qa);var se,Tt,At,Tn,An,Mt,Mn,kn,Da,Bi=(Da=class{constructor(e={}){E(this,se);E(this,Tt);E(this,At);E(this,Tn);E(this,An);E(this,Mt);E(this,Mn);E(this,kn);S(this,se,e.queryCache||new Na),S(this,Tt,e.mutationCache||new ka),S(this,At,e.defaultOptions||{}),S(this,Tn,new Map),S(this,An,new Map),S(this,Mt,0)}mount(){fr(this,Mt)._++,p(this,Mt)===1&&(S(this,Mn,mn.subscribe(async e=>{e&&(await this.resumePausedMutations(),p(this,se).onFocus())})),S(this,kn,bn.subscribe(async e=>{e&&(await this.resumePausedMutations(),p(this,se).onOnline())})))}unmount(){var e,t;fr(this,Mt)._--,p(this,Mt)===0&&((e=p(this,Mn))==null||e.call(this),S(this,Mn,void 0),(t=p(this,kn))==null||t.call(this),S(this,kn,void 0))}isFetching(e){return p(this,se).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return p(this,Tt).findAll({...e,status:"pending"}).length}getQueryData(e){let t=this.defaultQueryOptions({queryKey:e});return p(this,se).get(t.queryHash)?.state.data}ensureQueryData(e){let t=this.defaultQueryOptions(e),n=p(this,se).build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime($e(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return p(this,se).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=p(this,se).get(r.queryHash)?.state.data,o=ua(t,i);if(o!==void 0)return p(this,se).build(this,r).setData(o,{...n,manual:!0})}setQueriesData(e,t,n){return H.batch(()=>p(this,se).findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){let t=this.defaultQueryOptions({queryKey:e});return p(this,se).get(t.queryHash)?.state}removeQueries(e){let t=p(this,se);H.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){let n=p(this,se);return H.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){let n={revert:!0,...t},r=H.batch(()=>p(this,se).findAll(e).map(s=>s.cancel(n)));return Promise.all(r).then(Y).catch(Y)}invalidateQueries(e,t={}){return H.batch(()=>(p(this,se).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=H.batch(()=>p(this,se).findAll(e).filter(s=>!s.isDisabled()&&!s.isStatic()).map(s=>{let i=s.fetch(void 0,n);return n.throwOnError||(i=i.catch(Y)),s.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(Y)}fetchQuery(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=p(this,se).build(this,t);return n.isStaleByTime($e(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Y).catch(Y)}fetchInfiniteQuery(e){return e.behavior=Cn(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Y).catch(Y)}ensureInfiniteQueryData(e){return e.behavior=Cn(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return bn.isOnline()?p(this,Tt).resumePausedMutations():Promise.resolve()}getQueryCache(){return p(this,se)}getMutationCache(){return p(this,Tt)}getDefaultOptions(){return p(this,At)}setDefaultOptions(e){S(this,At,e)}setQueryDefaults(e,t){p(this,Tn).set(Je(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){let t=[...p(this,Tn).values()],n={};return t.forEach(r=>{Ht(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){p(this,An).set(Je(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){let t=[...p(this,An).values()],n={};return t.forEach(r=>{Ht(e,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;let t={...p(this,At).queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=gr(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===gn&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...p(this,At).mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){p(this,se).clear(),p(this,Tt).clear()}},se=new WeakMap,Tt=new WeakMap,At=new WeakMap,Tn=new WeakMap,An=new WeakMap,Mt=new WeakMap,Mn=new WeakMap,kn=new WeakMap,Da);var tt=J(ue(),1);var On=J(ue(),1),Ka=J(ps(),1),$i=On.createContext(void 0),U=e=>{let t=On.useContext($i);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},Tr=({client:e,children:t})=>(On.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,Ka.jsx)($i.Provider,{value:e,children:t}));var fs=J(ue(),1),La=fs.createContext(!1),ms=()=>fs.useContext(La),Yg=La.Provider;var Ar=J(ue(),1),Xd=J(ps(),1);function Zd(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var ep=Ar.createContext(Zd()),gs=()=>Ar.useContext(ep);var Ha=J(ue(),1);var hs=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError=="function"?hn(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},ys=e=>{Ha.useEffect(()=>{e.clearReset()},[e])},_s=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:s})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(s&&e.data===void 0||hn(n,[e.error,r]));var bs=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))}},ja=(e,t)=>e.isLoading&&e.isFetching&&!t,Mr=(e,t)=>e?.suspense&&t.isPending,kr=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function Vi({queries:e,...t},n){let r=U(n),s=ms(),i=gs(),o=tt.useMemo(()=>e.map(_=>{let g=r.defaultQueryOptions(_);return g._optimisticResults=s?"isRestoring":"optimistic",g}),[e,r,s]);o.forEach(_=>{bs(_);let g=r.getQueryCache().get(_.queryHash);hs(_,i,g)}),ys(i);let[a]=tt.useState(()=>new ji(r,o,t)),[c,u,d]=a.getOptimisticResult(o,t.combine),l=!s&&t.subscribed!==!1;tt.useSyncExternalStore(tt.useCallback(_=>l?a.subscribe(H.batchCalls(_)):Y,[a,l]),()=>a.getCurrentResult(),()=>a.getCurrentResult()),tt.useEffect(()=>{a.setQueries(o,t)},[o,t,a]);let f=c.some((_,g)=>Mr(o[g],_))?c.flatMap((_,g)=>{let b=o[g];if(b&&Mr(b,_)){let y=new at(r,b);return kr(b,y,i)}return[]}):[];if(f.length>0)throw Promise.all(f);let m=c.find((_,g)=>{let b=o[g];return b&&_s({result:_,errorResetBoundary:i,throwOnError:b.throwOnError,query:r.getQueryCache().get(b.queryHash),suspense:b.suspense})});if(m?.error)throw m.error;return u(d())}var kt=J(ue(),1);function vs(e,t,n){let r=ms(),s=gs(),i=U(n),o=i.defaultQueryOptions(e);i.getDefaultOptions().queries?._experimental_beforeQuery?.(o);let a=i.getQueryCache().get(o.queryHash);o._optimisticResults=r?"isRestoring":"optimistic",bs(o),hs(o,s,a),ys(s);let c=!i.getQueryCache().get(o.queryHash),[u]=kt.useState(()=>new t(i,o)),d=u.getOptimisticResult(o),l=!r&&e.subscribed!==!1;if(kt.useSyncExternalStore(kt.useCallback(h=>{let f=l?u.subscribe(H.batchCalls(h)):Y;return u.updateResult(),f},[u,l]),()=>u.getCurrentResult(),()=>u.getCurrentResult()),kt.useEffect(()=>{u.setOptions(o)},[o,u]),Mr(o,d))throw kr(o,u,s);if(_s({result:d,errorResetBoundary:s,throwOnError:o.throwOnError,query:a,suspense:o.suspense}))throw d.error;return i.getDefaultOptions().queries?._experimental_afterQuery?.(o,d),o.experimental_prefetchInRender&&!Ye.isServer()&&ja(d,r)&&(c?kr(o,u,s):a?.promise)?.catch(Y).finally(()=>{u.updateResult()}),o.notifyOnChangeProps?d:u.trackResult(d)}function $(e,t){return vs(e,at,t)}var pt=J(ue(),1);function oe(e,t){let n=U(t),[r]=pt.useState(()=>new Ni(n,e));pt.useEffect(()=>{r.setOptions(e)},[r,e]);let s=pt.useSyncExternalStore(pt.useCallback(o=>r.subscribe(H.batchCalls(o)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),i=pt.useCallback((o,a)=>{r.mutate(o,a).catch(Y)},[r]);if(s.error&&hn(r.options.throwOnError,[s.error]))throw s.error;return{...s,mutate:i,mutateAsync:s.mutate}}function Fn(e,t){return vs(e,Fi,t)}var Va=J($a(),1),qn=typeof window<"u"&&window.__FSAOS_CONFIG__||{},Yt=Array.isArray(qn.sources)?qn.sources:[],ft=qn.hostSession===!0,tp=qn.supabaseUrl||"https://vahbmsslxuustnlvsrkg.supabase.co",np=qn.supabaseAnonKey||"sb_publishable_ZjosozAjfpZ4InMNElTr6Q_hHB-f5nc",Ue=qn.gatewayUrl||"https://fsaos-mcp-gw-rust.fly.dev",G=(0,Va.createClient)(tp,np,{auth:{persistSession:!0,autoRefreshToken:!0,detectSessionInUrl:!1}});var Or=null,ws=0,Wa,Ji,Ss=!1;Wa=new Promise(e=>{Ji=e});G.auth.onAuthStateChange((e,t)=>{t?.access_token?(Or=t.access_token,ws=t.expires_at??Math.floor(Date.now()/1e3)+3600):(Or=null,ws=0),Ss||(Ss=!0,Ji())});setTimeout(()=>{Ss||(Ss=!0,Ji())},5e3);function Ga(e,t){Or=e,ws=t??Math.floor(Date.now()/1e3)+3600}function Yi(){Or=null,ws=0}async function mt(){let e=typeof window<"u"&&window.__FSAOS_CONFIG__||{};if(ft)return null;if(e.embedToken){if(typeof e.embedToken=="function")try{return await e.embedToken()??null}catch{return null}return e.embedToken}return await Wa,Or}var Un=null,Kn=null,za=0,Wi=new Set,Xi,Fr,Ln=!1;Xi=new Promise(e=>{Fr=e});function Zi(){za++,Wi.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Anchor listener error:",t)}})}function Hn(e){let t=typeof e=="string"?e:e.path,n=Un!==t||Kn?.id!==(typeof e=="string"?void 0:e.id);Un=t,Kn=typeof e=="string"?null:e,typeof e!="string"&&!Xt.some(r=>r.id===e.id)&&(Xt=[...Xt,e],ro()),Ln||(Ln=!0,Fr()),n&&Zi()}function Ot(){return Un}function fe(){return Kn}function eo(){return za}function to(e){return Wi.add(e),()=>{Wi.delete(e)}}function qr(){return Xi}function no(){return Ln}var xs=null;function Zt(e,t={}){if(xs){console.warn("[SDK] electHomeAnchor called twice; ignoring (logout to re-elect).");return}xs=e,t.activate!==!1&&Hn(e)}function Se(){return xs}var Xt=[],Gi=new Set,Ja=0;function ro(){Ja++,Gi.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Mount listener error:",t)}})}function Me(){return Xt}function Ft(){return Ja}function jn(e){return Gi.add(e),()=>{Gi.delete(e)}}function Ya(e,t){let n=JSON.stringify(Xt)!==JSON.stringify(e),r=Un!==t.path||Kn?.id!==t.id;Xt=e,Un=t.path,Kn=t,Ln||(Ln=!0,Fr()),n&&ro(),r&&Zi()}var Nn=null,Qn=null,Dn=0,zi=new Set,Xa=0;function Za(){Xa++,zi.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Session listener error:",t)}})}function te(){return Dn}function Bn(){return Xa}function Rs(e){return zi.add(e),()=>{zi.delete(e)}}async function gt(){if(Nn)return Nn;if(Qn)return Qn;let e=Dn;return Qn=(async()=>{let t=en(),n=await mt();if(e!==Dn)throw new Error("Session changed during initialization");let r={};n&&(r.Authorization=`Bearer ${n}`);let s=await fetch(`${Ue}/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!==Dn)throw new Error("Session changed during initialization");let o=i.entry||i;return Nn={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},Za(),Nn})().catch(t=>{throw e===Dn&&(Qn=null),t}),Qn}function nt(){return Nn}function so(){Dn++,Nn=null,Qn=null,Un=null,Kn=null,xs=null,Xt=[],Za()}var ec=[];function ae(e){ec.push(e)}function $n(){so(),Yi(),Fr(),Ln=!1,Xi=new Promise(e=>{Fr=e}),Zi(),ro();for(let e of ec)try{e()}catch(t){console.warn("[SDK] Cleanup function failed:",t)}}function en(){if(typeof window<"u"){let e=window.__FSAOS_CONFIG__;return e?.hostname?e.hostname:window.location.hostname}return"localhost"}var tc=Hn,z=Ot,W=eo,xe=to,nc=qr,Cs=no;var nn="host-session",rp=5e3;function io(e){return typeof e=="object"&&e!==null&&e.fsaos===nn&&typeof e.kind=="string"}var tn=class extends Error{constructor(){super(...arguments);ee(this,"name","HostSessionUnavailableError")}},Ps=null,sp=0,Es=new Map;function rc(){return Ps||(Ps=new Promise((e,t)=>{if(!ft){t(new tn("This page was not started with hostSession."));return}if(typeof window>"u"||!window.parent||window.parent===window){t(new tn("This page is signed in only inside the app that frames it. Open it from there."));return}let n=window.parent,r=null,s=setTimeout(()=>{r===null&&(window.removeEventListener("message",i),t(new tn("The window around this page did not sign it in. Open it from the app that owns it.")))},rp);function i(o){if(o.source!==n||!io(o.data))return;let a=o.data;if(r===null){if(a.kind!=="welcome")return;r=o.origin,clearTimeout(s),a.anchor&&Hn(a.anchor),e({host:n,origin:r,item:a.item??null});return}if(o.origin!==r||a.kind!=="result")return;let c=Es.get(a.id);c&&(Es.delete(a.id),c.resolve(a.ok?{ok:!0,response:a.response}:{ok:!1,error:a.error}))}window.addEventListener("message",i),n.postMessage({fsaos:nn,kind:"hello"},"*")}),Ps)}async function sc(){let{item:e}=await rc();return{item:e}}async function ic(e,t,n){if(n?.aborted)throw new DOMException("Read cancelled","AbortError");let{host:r,origin:s}=await rc();if(n?.aborted)throw new DOMException("Read cancelled","AbortError");let i=JSON.parse(JSON.stringify(t??{}));return new Promise((o,a)=>{let c=`${Date.now().toString(36)}-${(++sp).toString(36)}`,u=()=>{Es.delete(c),a(new DOMException("Read cancelled","AbortError"))};Es.set(c,{resolve:d=>{n?.removeEventListener("abort",u),o(d)}}),n?.addEventListener("abort",u,{once:!0}),r.postMessage({fsaos:nn,kind:"call",id:c,method:e,params:i},s)})}var oo=0,oc=!1,ac=0;function ao(e){if(typeof e!="string")return;let t=Date.parse(e);Number.isNaN(t)||(oo=t-Date.now(),oc=!0,ac=Date.now())}function Is(){return Date.now()+oo}function cc(){return oc}function uc(){return oo}function lc(){return ac}function dc(e){if(typeof e!="string")return null;let t=Date.parse(e);return Number.isNaN(t)?null:Is()>=t}function pc(e){if(typeof e!="string")return null;let t=Date.parse(e);return Number.isNaN(t)?null:Math.max(0,t-Is())}var Vn,Ke=new Map,rn=[],co=0,uo={foreground:0,normal:1,background:2},Ts=()=>performance.now(),lo=()=>new DOMException("Read cancelled","AbortError");function mc(e={}){Vn={concurrency:Math.max(1,Math.min(16,Math.floor(e.concurrency??6))),timeoutMs:Math.max(1e3,e.timeoutMs??15e3),onTiming:e.onTiming},Ms()}function gc(){for(let e of Ke.values()){e.controller.abort();for(let t of e.consumers)t.detach(),t.reject(lo());e.consumers.clear(),e.timer&&clearTimeout(e.timer)}Ke.clear(),rn.length=0}function hc(e,t){return e==="query"?!("materialize"in t):["read","list","search","resolve","resolve-items","get-channel-messages","list-memberships","message-replies","check-item-access"].includes(e)}function As(e){return Array.isArray(e)?`[${e.map(As).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>`${JSON.stringify(t)}:${As(n)}`).join(",")}}`:JSON.stringify(e)}function yc(e,t,n,r){if(n.signal?.aborted)return Promise.reject(lo());if(!Vn)return r(n.signal);let s=Ke.get(e);if(s)uo[n.priority??"normal"]<uo[s.priority]&&(s.priority=n.priority??"normal");else{s={key:e,method:t,priority:n.priority??"normal",queuedAt:Ts(),controller:new AbortController,consumers:new Set,run:r},Ke.set(e,s),rn.push(s);let a=s;s.timer=setTimeout(()=>{a.controller.abort();let c=new Error("The read timed out. Please retry.");c.name="TimeoutError";for(let u of a.consumers)u.detach(),u.reject(c);a.consumers.clear(),Ke.get(a.key)===a&&Ke.delete(a.key),fc(a)},Vn.timeoutMs)}let i=s,o=new Promise((a,c)=>{let u=()=>{d.detach(),i.consumers.delete(d),c(lo()),i.consumers.size||(i.controller.abort(),Ke.get(i.key)===i&&Ke.delete(i.key),fc(i))},d={resolve:l=>a(structuredClone(l)),reject:c,detach:()=>n.signal?.removeEventListener("abort",u)};i.consumers.add(d),n.signal?.addEventListener("abort",u,{once:!0})});return Ms(),o}function fc(e){let t=rn.indexOf(e);t>=0&&(rn.splice(t,1),Ke.get(e.key)===e&&Ke.delete(e.key),e.timer&&clearTimeout(e.timer)),Ms()}function Ms(){if(Vn)for(;co<Vn.concurrency&&rn.length;){let e=r=>uo[r.priority]-Math.floor((Ts()-r.queuedAt)/2e3);rn.sort((r,s)=>e(r)-e(s)||r.queuedAt-s.queuedAt);let t=rn.shift();if(!t.consumers.size)continue;co++,t.startedAt=Ts();let n="success";Promise.resolve().then(()=>t.run(t.controller.signal)).then(r=>{for(let s of t.consumers)s.detach(),s.resolve(r)},r=>{n=t.controller.signal.aborted?"aborted":"error";for(let s of t.consumers)s.detach(),s.reject(r)}).finally(()=>{t.timer&&clearTimeout(t.timer),t.consumers.clear(),Ke.get(t.key)===t&&Ke.delete(t.key),co--;try{Vn?.onTiming?.({method:t.method,priority:t.priority,queueMs:Math.round(t.startedAt-t.queuedAt),requestMs:Math.round(Ts()-t.startedAt),outcome:n})}catch{}Ms()})}}ae(gc);var ip=new Set(["list-memberships","init"]),Re=class extends Error{constructor(n){let r=typeof n.payload?.error=="string"?n.payload.error.trim():"",s=typeof n.payload?.message=="string"?n.payload.message.trim():"",i=n.responseBody.trim()||`Gateway HTTP error: ${n.status} ${n.statusText}`.trim(),o=r&&s?`${r}: ${s}`:s||r||i;super(o);ee(this,"name","GatewayRequestError");ee(this,"method");ee(this,"status");ee(this,"statusText");ee(this,"payload");ee(this,"responseBody");this.method=n.method,this.status=n.status,this.statusText=n.statusText,this.payload=n.payload,this.responseBody=n.responseBody}};async function C(e,t={},n={}){if(ft)return op(e,t,n);let r=te(),s=Ot(),i=en(),o=`${Ue}/d/${i}`,a={"Content-Type":"application/json"},c=await _c(mt(),n.signal);if(r!==te())throw new Error("Session changed before gateway request");if(c&&(a.Authorization=`Bearer ${c}`),!ip.has(e)&&!t._scope_path&&await _c(qr(),n.signal),r!==te())throw new Error("Session changed before gateway request");let u={...t},d=nt();!u.domain_scope_id&&d?.scope_id&&(u.domain_scope_id=d.scope_id);let l=s??Ot();!u._scope_path&&l&&(u._scope_path=l);let h=async f=>{if(r!==te())throw new Error("Session changed before queued gateway request");let m=await fetch(o,{method:"POST",signal:f,headers:a,body:JSON.stringify({method:e,params:u})}),_=await m.text();if(r!==te())throw new Error("Session changed during gateway request");let g=null;if(_)try{g=JSON.parse(_)}catch{}if(!m.ok||!g)throw new Re({method:e,status:m.status,statusText:m.statusText,payload:g,responseBody:_});if(g.success===!1){let b=g.error||"",y=g.denied_by||g.error_type||"";throw y==="rule"||y==="access"||y==="entitlement"||b==="RULE_DENIED"||b==="ACCESS_DENIED"||b==="PERMISSION_DENIED"||b==="ENTITLEMENT_REQUIRED"?new Be(g):new Re({method:e,status:m.status,statusText:m.statusText,payload:g,responseBody:_})}return g&&g.server_now!==void 0&&ao(g.server_now),g};return hc(e,u)?yc(As([r,i,c,e,u]),e,n,h):h(n.signal)}async function op(e,t,n){let r=await ic(e,t,n.signal);if(r.ok){let o=r.response?.server_now;return o!==void 0&&ao(o),r.response}let s=r.error;if(s.kind==="denied")throw new Be(s.payload);if(s.kind==="gateway")throw new Re({method:s.method,status:s.status,statusText:s.statusText,payload:s.payload,responseBody:s.responseBody});let i=new Error(s.message);throw i.name=s.name,i}function _c(e,t){return t?t.aborted?Promise.reject(new DOMException("Read cancelled","AbortError")):new Promise((n,r)=>{let s=()=>r(new DOMException("Read cancelled","AbortError"));t.addEventListener("abort",s,{once:!0}),e.then(n,r).finally(()=>t.removeEventListener("abort",s))}):e}var w=J(ue(),1),Zp=J(vc(),1),ef=J(ps(),1);var wc=new WeakMap;function ce(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(l=>l.promise?[l.promise]:[]);if(i.length===0)return s();let o=`${r?"=":"^"}${JSON.stringify(t)}`,a=wc.get(e);a||(a=new Map,wc.set(e,a));let c=a.get(o);if(c)return c;let u=a,d=Promise.allSettled(i).then(()=>(u.delete(o),s()));return u.set(o,d),d}function ie(e,t){return typeof e=="string"&&(e===t||e.startsWith(`${t}/`))}var ks=new WeakMap,Sc=e=>e.meta?.arrangementRealtime===!0;function ht(e,t){let n=e.getQueryCache().find({queryKey:t,exact:!0});if(!n)return;let r=ks.get(e);r||(r=new Map,ks.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&&ce(e,t,{exact:!0})},250))}function xc(e,t){if(!(!t||typeof t!="object"))for(let n of e.getQueryCache().getAll()){if(!Sc(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")&&ht(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)))&&ht(e,n.queryKey)}}function Rc(e){for(let t of e.getQueryCache().getAll())Sc(t)&&t.state.data!==void 0&&ht(e,t.queryKey)}function Cc(e){ks.get(e)?.forEach(clearTimeout),ks.delete(e)}var Os=new WeakMap,ap=new Set(["shared_with","has_member","member_of","owned_by"]);function Pc(e,t){let n=Os.get(e);n||(n=new Map,Os.set(e,n)),!n.has(t)&&(e.cancelQueries({queryKey:t.queryKey,exact:!0}),e.invalidateQueries({queryKey:t.queryKey,exact:!0,refetchType:"none"}),t.isActive()&&n.set(t,setTimeout(()=>{n.delete(t),!(e.getQueryCache().get(t.queryHash)!==t||!t.isActive())&&ce(e,t.queryKey,{exact:!0})},250)))}function Ec(e,t,n){let r=n==="ccm_change";if(r&&!ap.has(t.edge_type))return;let s=[t.path,t.old_path,t.source_path].filter(o=>typeof o=="string"),i=[t.item_id,t.source_item_id,t.source_id,t.target_item_id,t.target_id].filter(Boolean);if(!(!s.length&&!i.length))for(let o of e.getQueryCache().findAll({queryKey:["vfs"]})){let a=o.meta?.permissionQuery;if(!a?.scope)continue;let c=!!(a.itemId&&i.includes(a.itemId)),u=!!(a.path&&s.some(f=>ie(a.path,f))),d=a.scope,h=(s.some(f=>ie(f,d)||ie(d,f))||[t.scope_item_id,t.account_item_id,t.space_item_id].some(f=>f&&a.scopeIds.includes(f)))&&(t.item_type==="member"||t.item_type==="principal"||r);(c||u||!a.targetLookup&&h)&&Pc(e,o)}}function Ic(e){for(let t of e.getQueryCache().findAll({queryKey:["vfs"]}))t.meta?.permissionQuery&&Pc(e,t)}function Tc(e){Os.get(e)?.forEach(t=>clearTimeout(t)),Os.delete(e)}var yt=null;ae(()=>{yt&&(yt.cancelQueries({queryKey:["vfs"]}),yt.removeQueries({queryKey:["vfs"]}))});function Ac(e){if(yt&&yt!==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.");yt=e}function N(){return yt||(yt=new Bi({defaultOptions:{queries:{staleTime:1e3*60*2,gcTime:1e3*60*10,refetchOnWindowFocus:!1,retry:1}}})),yt}var Mc=new Proxy({},{get(e,t,n){let r=N(),s=r[t];return typeof s=="function"?s.bind(r):s}});var Fs=new WeakMap;function po(e){return e.meta?.infiniteItemsRealtime?.filter}function cp(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 up(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 lp(e,t,n){if(cp(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&&!ie(n.path,r)&&!ie(n.old_path,r))return!1;if(n.item_type==="symlink"&&s&&i)return!0;let o=up(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 kc(e,t){let n=Fs.get(e);n||(n=new Map,Fs.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||!po(t))&&ce(e,t.queryKey,{exact:!0})},500))}function Oc(e,t){if(!(!t||typeof t!="object"))for(let n of e.getQueryCache().getAll()){let r=po(n);r&&lp(n,r,t)&&kc(e,n)}}function Fc(e){for(let t of e.getQueryCache().getAll())po(t)&&t.state.data!==void 0&&kc(e,t)}function qc(e){Fs.get(e)?.forEach(clearTimeout),Fs.delete(e)}var qs=class extends Error{constructor(){super("The server did not confirm the selected-Space listing contract")}};function Qc(e,t){if(!Array.isArray(t)||t.some(n=>typeof n!="string")||JSON.stringify([...new Set(t)].sort())!==JSON.stringify(e))throw new qs}function qt(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 Wn(e){return e instanceof qs||e instanceof Be||e instanceof Re&&(e.payload?.error==="SPACE_SELECTION_UNAVAILABLE"||e.payload?.error==="QUERY_PARAMS_INVALID"||e.status===401||e.status===403)}function le(){return z()??"__unscoped__"}var T={all:()=>["vfs",le()],item:e=>["vfs",le(),"item",e],itemById:e=>["vfs","item-by-id",e],children:e=>["vfs",le(),"children",e],allChildren:()=>["vfs",le(),"children"],types:e=>["vfs","types",e??"default"],edges:e=>["vfs","edges",e],search:(e,t)=>["vfs",le(),"search",e,...t??[]],items:(e,t)=>["vfs",le(),"items",e,JSON.stringify(qt(t??{}))],allItems:()=>["vfs",le(),"items"],tree:(e,t)=>["vfs",le(),"tree",e,t??1],openEnvelope:(e,t)=>["vfs",le(),"open",e,t??"__default__"],allOpenEnvelopes:()=>["vfs",le(),"open"],memberFocus:e=>["vfs","member-focus",e],fractalInstances:()=>["vfs","fractal-instances"],recentActivity:(e,t,n)=>["vfs",le(),"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",le(),"channel-messages",e,t??"__top__"],allChannelMessages:()=>["vfs",le(),"channel-messages"],channels:e=>["vfs",le(),"channels",e??"all"],messageReplies:(e,t,n,r=25)=>["vfs",le(),"channel-messages",e,n??"__top__","contextual-replies",t,r],allChannels:()=>["vfs",le(),"channels"],notifications:(e,t)=>["vfs",le(),"notifications",e??"all",t??200],allNotifications:()=>["vfs",le(),"notifications"],unreadCounts:()=>["vfs",le(),"unread-counts"],memberships:e=>["memberships",e]};var dp=typeof window<"u"&&(window.location?.hostname==="localhost"||window.location?.hostname==="127.0.0.1"||window.__FSAOS_WS_DEBUG__);function ne(...e){dp&&console.log("[WS]",...e)}var D=null,Gn=null,Jn=null,Qr=0,pp=3e4,Nc=1e4,Xn=!1,Dc=!1,jc=3e4,fp=jc*2+5e3,Qs=0,Ns=null,Uc=!1;function mp(){Dr(),Qs=Date.now(),Ns=setInterval(()=>{if(D&&D.readyState===WebSocket.OPEN&&Date.now()-Qs>fp){ne("ping: no inbound traffic for",Date.now()-Qs,"ms \u2014 closing half-open socket");try{D.close(4e3,"liveness timeout")}catch{}return}bt({type:"ping"})},jc)}function Dr(){Ns&&(clearInterval(Ns),Ns=null)}function gp(){typeof document>"u"||(document.hidden?Dr():Nr()&&(ne("Tab visible, reconnecting..."),sn()))}function hp(){Uc||typeof document>"u"||(document.addEventListener("visibilitychange",gp),Uc=!0)}var Fe={};function mo(e,t){let n=e.replace(/\/+$/,""),r=t.replace(/\/+$/,"");return!n||!r?n===r:r===n||r.startsWith(`${n}/`)}var Yn=[],_t=new Map,zn=new Map,Le=new Map;function yp(e){let t=zn.get(e);return t?Array.from(new Set(Array.from(t.values()).flatMap(n=>n.event_types))).sort():[]}function Kc(e,t){return e?e.length===t.length&&e.every((n,r)=>n===t[r]):!1}function Lc(e){let t=yp(e);if(t.length===0)return _t.delete(e),null;let n={scope_id:e,event_types:t};return _t.set(e,n),n}var rt=new Map,Qt=new Map,fo="disconnected",Ds=[];function Us(e){if(fo!==e){fo=e;for(let t of[...Ds])try{t(e)}catch{}}}function _p(e){rt.set(e,"ready");let t=Qt.get(e);if(t){Qt.delete(e);for(let n of t)n()}}function bp(){for(let e of rt.keys())rt.set(e,"disconnected")}function go(e,t){rt.set(e,"pending"),bt({type:"subscribe_path",path:e,event_types:t})}function vp(){return Object.keys(Fe).some(t=>Fe[t]&&Fe[t].length>0)||Yn.length>0}function Nr(){return _t.size>0||Le.size>0}async function sn(){if(ft){ne("ensureConnection: the host holds the session, no realtime connection");return}if(!Nr()){ne("ensureConnection: no active subscriptions, skipping");return}if(D&&D.readyState===WebSocket.OPEN){ne("ensureConnection: already open");return}if(Gn)return ne("ensureConnection: connection already in flight, waiting..."),Gn;if(D){ne("ensureConnection: killing stale WS in state",D.readyState);try{D.close()}catch{}D=null}return Xn=!1,Gn=(async()=>{try{let e=typeof window<"u"&&window.__FSAOS_CONFIG__||{},t=Ue,n=await mt();if(!n){ne("ensureConnection: no token available, will retry"),Hc();return}let r=t.startsWith("https")?"wss":"ws",s=t.replace(/^https?:\/\//,""),i=`${r}://${s}/ws`;i+=`?token=${encodeURIComponent(n)}`,ne("ensureConnection: opening WS to",i.substring(0,50)+"..."),Us("connecting"),D=new WebSocket(i);let o=D;await new Promise((a,c)=>{if(!D)return c(new Error("WebSocket not created"));let u=setTimeout(()=>{if(D===o){if(ne("ensureConnection: TIMEOUT after",Nc,"ms"),D&&D.readyState!==WebSocket.OPEN){try{D.close()}catch{}D=null}c(new Error("WebSocket connection timeout"))}},Nc);o.onopen=()=>{if(D!==o)return;clearTimeout(u),ne("ensureConnection: CONNECTED");let d=Dc;Dc=!0,Qr=0,Us("connected"),wp(d),(typeof document>"u"||!document.hidden)&&mp(),hp(),a()},o.onmessage=d=>{D===o&&Sp(d.data)},o.onerror=()=>{ne("ensureConnection: WS error event")},o.onclose=d=>{clearTimeout(u),D===o&&(ne("ensureConnection: WS closed, code:",d.code,"reason:",d.reason),D=null,Dr(),bp(),Us("disconnected"),!Xn&&Nr()&&Hc(),c(new Error(`WebSocket closed: ${d.code}`)))}})}catch(e){ne("ensureConnection: failed -",e?.message||e)}finally{Gn=null}})(),Gn}function Hc(){if(Jn||typeof document<"u"&&document.hidden)return;let e=Math.min(1e3*Math.pow(2,Qr)+Math.random()*1e3,pp);Qr++,ne("scheduleReconnect: attempt",Qr,"in",Math.round(e),"ms"),Jn=setTimeout(()=>{Jn=null,Nr()&&sn()},e)}function wp(e=!1){for(let t of _t.values())ne("resubscribeAll: scope",t.scope_id),bt({type:"subscribe",scope_id:t.scope_id,event_types:t.event_types});for(let t of Le.values())ne("resubscribeAll: path",t.path),go(t.path,t.event_types);e&&Bc("reconnect")}function Bc(e){try{let t=N();Fc(t),Rc(t),Ic(t);for(let n of Le.values())t.invalidateQueries({queryKey:T.item(n.path)}),t.invalidateQueries({queryKey:T.children(n.path)});t.invalidateQueries({queryKey:T.allChannelMessages()}),ne("catchUpAfterGap:",e,"- invalidated",Le.size,"paths and the transcripts on screen")}catch(t){ne("catchUpAfterGap: cache invalidation skipped",t)}}function bt(e){D&&D.readyState===WebSocket.OPEN&&D.send(JSON.stringify(e))}function Sp(e){Qs=Date.now();try{let t=JSON.parse(e);if(t.type==="subscribed_path"){typeof t.path=="string"&&_p(t.path);return}if(t.type==="subscribed"||t.type==="unsubscribed"||t.type==="unsubscribed_path"||t.type==="pong")return;if(t.type==="error"){console.warn("[WS] Server error:",t.message);return}if(t.type==="resync"){Bc(typeof t.reason=="string"?t.reason:"resync");return}if(t.type==="event"||t.event_type){let n=t.event_type||"message",r=t.data||t;if((n==="vfs_change"||n==="ccm_change")&&Ec(N(),r,n),n==="vfs_change"&&(Oc(N(),r),xc(N(),r)),typeof r.path=="string")for(let[s,i]of Object.entries(Fe))s!=="*"&&mo(s,r.path)&&i.forEach(o=>o(r));Fe["*"]&&Fe["*"].forEach(s=>s(r));for(let s of Yn)s.eventType!=="*"&&s.eventType!==n||s.filter&&!s.filter(r)||s.callback(r)}}catch{}}function ho(){!vp()&&_t.size===0&&Le.size===0&&D&&(Xn=!0,Dr(),D.close(),D=null,Xn=!1)}function Ks(e,t){return Fe[e]||(Fe[e]=[]),Fe[e].push(t),Le.has(e)||(Le.set(e,{path:e,event_types:["token_stream"]}),D&&D.readyState===WebSocket.OPEN?go(e,["token_stream"]):rt.set(e,"pending")),sn(),()=>{let n=Fe[e];if(n){let r=n.indexOf(t);r!==-1&&n.splice(r,1),n.length===0&&(delete Fe[e],Le.delete(e),rt.delete(e),Qt.delete(e),bt({type:"unsubscribe_path",path:e}))}ho()}}function X(e,t,n){let s=(Array.isArray(e)?e:[e]).map(i=>({eventType:i,callback:t,filter:n}));return Yn.push(...s),Nr()&&sn(),()=>{for(let i of s){let o=Yn.indexOf(i);o!==-1&&Yn.splice(o,1)}ho()}}function Zn(e,t=["vfs_change","ccm_change"]){let n=Symbol(e),r=Array.from(new Set(t)).sort();if(r.length===0)return()=>{};let s=zn.get(e)??new Map,i=_t.get(e)?.event_types;s.set(n,{event_types:r}),zn.set(e,s);let o=Lc(e);if(!o)return()=>{};ne("subscribeToScope:",e,o.event_types),D&&D.readyState===WebSocket.OPEN&&!Kc(i,o.event_types)&&bt({type:"subscribe",scope_id:e,event_types:o.event_types}),sn();let a=!0;return()=>{if(!a)return;a=!1;let c=zn.get(e);if(!c?.delete(n))return;let u=_t.get(e)?.event_types;if(c.size===0)zn.delete(e),_t.delete(e),bt({type:"unsubscribe",scope_id:e});else{let d=Lc(e);d&&D&&D.readyState===WebSocket.OPEN&&!Kc(u,d.event_types)&&bt({type:"subscribe",scope_id:e,event_types:d.event_types})}ho()}}function $c(e,t,n={}){bt({type:"emit",scope_id:e,event_type:t,payload:n})}function yo(){ne("disconnectSSE: tearing down"),qc(N()),Cc(N()),Tc(N()),Xn=!0,Dr(),D&&(D.close(),D=null),Jn&&(clearTimeout(Jn),Jn=null),Gn=null,Xn=!1,Qr=0;for(let e of Object.keys(Fe))delete Fe[e];Yn.length=0,_t.clear(),zn.clear(),Le.clear(),rt.clear(),Qt.clear(),Us("disconnected")}function Vc(){bt({type:"ping"})}function Wc(e){return Le.has(e)?rt.get(e)??"pending":"unsubscribed"}function Gc(e,t=5e3){return!Le.has(e)||ft?Promise.resolve(!1):rt.get(e)==="ready"&&D&&D.readyState===WebSocket.OPEN?Promise.resolve(!0):(sn(),new Promise(n=>{let r=!1,s=Qt.get(e)??[],i=()=>{r||(r=!0,clearTimeout(o),n(!0))};s.push(i),Qt.set(e,s);let o=setTimeout(()=>{if(r)return;r=!0;let a=Qt.get(e);if(a){let c=a.indexOf(i);c!==-1&&a.splice(c,1),a.length===0&&Qt.delete(e)}n(!1)},t)}))}function zc(e){let t=Le.get(e);if(!t){ne("resubscribePath: no active subscription for",e);return}D&&D.readyState===WebSocket.OPEN?(ne("resubscribePath: re-sending frame for",e),go(t.path,t.event_types)):(rt.set(e,"pending"),sn())}function Ls(e){Ds.push(e);try{e(fo)}catch{}return()=>{let t=Ds.indexOf(e);t!==-1&&Ds.splice(t,1)}}ae(yo);function Jc(){return new Date().toISOString()}function Yc(){return crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function He(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||Jc(),updated_at:e.updated_at||Jc(),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 Ur(e){return(e.content?.items||e.items||[]).map(He)}async function Kr(e){try{let t=await C("read",{id:e});if(t.item_name||t.item_path){let r=He(t);return r.path&&N().setQueryData(T.item(r.path),r),r}let n=t.item;if(n){let r=He(n);return r.path&&N().setQueryData(T.item(r.path),r),r}return null}catch{return null}}async function Lr(e){try{let t=await C("read",{path:e});if(t.item_name||t.item_path)return He(t);let n=t.item;return n?He(n):null}catch{return null}}async function Hr(e){try{let t=await C("list",{path:e,limit:200}),n=Ur(t);for(let r of n)N().setQueryData(T.item(r.path),r);return n}catch(t){return console.error(`[gateway] Failed to fetch children of ${e}:`,t),[]}}async function Xc(e,t){let{items:n}=await on({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 js(e,t,n){try{let r=await C("list",{path:e,limit:t,offset:n}),s=Ur(r);for(let i of s)N().setQueryData(T.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 Bs(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,a=i.type_data;!o||!a||s.set(o,{type_key:o,display_name:a.display_name||o,display_name_plural:a.display_name_plural||o+"s",icon:a.icon||"File",color:a.color||"gray",description:a.description||"",input_schema:a.input_schema||{},system_schema:a.system_schema||{},json_schema:a.input_schema||a.json_schema||{},default_data:a.default_data||{},field_defaults:a.field_defaults||{},renderer_config:a.renderer_config||{},is_system:a.is_system??!1,is_active:a.is_active??!0,is_container:a.is_container??!1,is_scope:a.is_scope??!1,render_mode:a.render_mode||"none",placement_mode:a.placement_mode,direct_parent_types:a.direct_parent_types,allowed_parent_types:a.allowed_parent_types,governed_create:a.governed_create,create_method:a.create_method,dedup:a.dedup,edges:a.edges,events:a.events})}return s}async function $s(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||Yc(),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||Yc(),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 Vs(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=Ur(i);for(let a of o)N().setQueryData(T.item(a.path),a);return o}catch(s){return console.error(`[gateway] Failed to fetch tree at ${e}:`,s),[]}}async function Ws(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 jr(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 Gs(e,t=50,n=0){return jr(e,{limit:t,offset:n})}async function zs(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=Ur(s);for(let o of i)N().setQueryData(T.item(o.path),o);return i}catch(r){return console.error(`[gateway] Failed to fetch member focus for scope ${e}:`,r),[]}}async function Br(e,t){let n={path:e};t?.mode&&(n.mode=t.mode),t?.strategy&&(n.strategy=t.strategy),t?.arguments&&(n.arguments=t.arguments);let s=await 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 tr(e){return!!e&&(!!e.type||Array.isArray(e.any_of)&&e.any_of.length>0)}function xp(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 Rp=["catalog","parent_only","internal"];function Zc(e,t={}){if(!e||typeof e!="object")return null;let n=o=>typeof o=="string"||typeof o=="number"||typeof o=="boolean",r=o=>{let a={},c={};for(let[u,d]of Object.entries(o))u.startsWith("field.")&&u.length>6&&n(d)?a[u.slice(6)]=d:u.startsWith("field_in.")&&u.length>9&&Array.isArray(d)&&(c[u.slice(9)]=d.filter(n));return{fields:a,field_in:c}},s={};typeof e.type=="string"&&e.type&&(s.type=e.type),typeof e.sort_by=="string"&&(s.sort_by=e.sort_by),(e.sort_dir==="asc"||e.sort_dir==="desc")&&(s.sort_dir=e.sort_dir),typeof e.name=="string"&&e.name&&(s.name=e.name),typeof e.tag=="string"&&e.tag&&(s.tag=e.tag),typeof e.discovery=="string"&&Rp.includes(e.discovery)&&(s.discovery=e.discovery);let i=r(e);if(Object.keys(i.fields).length&&(s.fields=i.fields),Object.keys(i.field_in).length&&(s.field_in=i.field_in),Array.isArray(e.any_of)){let o=[];for(let a of e.any_of){if(!a||typeof a!="object"||Array.isArray(a))continue;let c=a,u={};typeof c.item_type=="string"&&c.item_type&&(u.item_type=c.item_type);let d=r(c);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 tr(s)?{...s,...t}:null}async function on(e,t={}){if(e=qt(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(xp)),Object.keys(r).length>0&&(n.filters=r),e.limit!=null&&(n.limit=e.limit);try{let s=await C("query",n,t);e.spaceIds!==void 0&&Qc(e.spaceIds,s.selected_space_ids??s.content?.selected_space_ids);let i=Ur(s);for(let o of i)N().setQueryData(T.item(o.path),o);return{items:i,total_hint:s.total??s.content?.total??i.length}}catch(s){if(t.signal?.aborted||s instanceof Error&&s.name==="AbortError"||(console.error(`[gateway] Failed to fetch items of type ${e.type??"(any_of)"}:`,s),t.throwOnError||e.spaceIds!==void 0))throw s;return{items:[],total_hint:0}}}function eu(e){if(!e||typeof e!="object")return;let t=e;if(t.state==="unavailable")return{state:"unavailable"};if(!(t.state!=="available"||typeof t.message_id!="string"||typeof t.path!="string"||typeof t.excerpt!="string"))return{state:"available",message_id:t.message_id,path:t.path,role:typeof t.role=="string"?t.role:void 0,sender_principal_id:typeof t.sender_principal_id=="string"?t.sender_principal_id:void 0,sender_display_name:typeof t.sender_display_name=="string"?t.sender_display_name:void 0,excerpt:t.excerpt,truncated:t.truncated===!0}}async function tu(e){if(!e.channel_id&&!e.channel_path)throw new Error("A message requires a channel.");let t=e.reply_to_message_id!==void 0;if(t&&(typeof e.reply_to_message_id!="string"||!e.reply_to_message_id.trim()))throw new Error("A contextual reply requires a target message ID.");if(t&&(e.conversation_mode==="new_thread"||e.hand_off_to))throw new Error("A contextual reply stays in the current conversation.");return await C(t?"reply-message":"send-message",e)}async function nu(e,t){let n=new Set(e),r=[...n];if(!r.length)return{};if(r.length>200)throw new Error("Reply context supports at most 200 messages per batch.");let i=(await C("message-replies",{operation:"context",message_ids:r},t)).replies;if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Invalid reply-context response.");return Object.fromEntries(Object.entries(i).flatMap(([o,a])=>{let c=eu(a);return c&&n.has(o)?[[o,c]]:[]}))}async function Js(e,t={},n){let r=t.limit??25;if(!Number.isInteger(r)||r<1||r>100)throw new Error("Reply page size must be between 1 and 100.");let s=await C("message-replies",{operation:"list",message_id:e,limit:r,...t.cursor?{cursor:t.cursor}:{},...t.conversationRootId?{conversation_root_id:t.conversationRootId}:{}},n);if(!Array.isArray(s.messages))throw new Error("Invalid reply-list response.");let i=s.next_cursor;if(i&&(typeof i.updated_at!="string"||typeof i.edge_id!="string"))throw new Error("Invalid reply-list cursor.");let o=new Map(er(s.messages).map(a=>[a.id,a]));return{messages:s.messages.flatMap(a=>{let c=o.get(a.id);return c?[c]:[]}),next_cursor:i??null}}function Cp(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 ru(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:Cp(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 er(e){return e.filter(t=>t.item_type==="message").map(t=>{let n=t.type_data||{},r="user";n.role==="assistant"?r="assistant":n.role==="system"&&(r="system");let s=n.metadata||{};return{id:t.id||"",path:t.path||"",content:n.message||n.content||"",created_at:t.created_at||"",role:r,status:typeof n.status=="string"?n.status:void 0,delivery_state:typeof n.delivery_state=="string"?n.delivery_state:void 0,cognition_event_id:typeof n.cognition_event_id=="string"?n.cognition_event_id:void 0,seq:n.seq||0,principal_id:n.principal_id,member_id:typeof n.member_id=="string"?n.member_id:void 0,sender_display_name:typeof n.sender_display_name=="string"?n.sender_display_name:void 0,sender_is_ai:typeof n.sender_is_ai=="boolean"?n.sender_is_ai:void 0,sender_role_display_name:typeof n.sender_role_display_name=="string"?n.sender_role_display_name:void 0,reply_count:n.reply_count||0,member_count:n.member_count||0,parent_message_id:n.parent_message_id,reply_to:eu(t.reply_to),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 su(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 er(i)}catch(n){throw console.error(`[gateway] Failed to fetch channel messages for ${e}:`,n),n}}async function Ys(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=er(i),a=ru(i),c=new Map,u=[];for(let d of a)if(d.parentMessagePath){let l=c.get(d.parentMessagePath)||[];l.push(d),c.set(d.parentMessagePath,l)}else u.push(d);return{messages:o,activityMessages:er(s.activity_messages||[]),messageCards:c,siblingCards:u,mode:s.mode||"top_level"}}catch(n){throw console.error(`[gateway] Failed to fetch channel messages with cards for ${e}:`,n),n}}async function an(e,t){try{let n={channel_path:e};t?.parentMessageId&&(n.parent_message_id=t.parentMessageId),t?.conversationsOnly&&(n.conversations_only=!0),t?.transcriptOnly&&(n.transcript_only=!0),t?.limit&&(n.limit=t.limit),t?.before_seq!=null&&(n.before_seq=t.before_seq),t?.after_seq!=null&&(n.after_seq=t.after_seq);let s=await C("get-channel-messages",n);if(t?.conversationsOnly&&s.conversations_only!==!0)throw new Error("This server does not support conversation history lists yet. Update the message reader.");if(t?.transcriptOnly&&s.transcript_only!==!0)throw new Error("This server does not support channel transcript pages yet. Update the message reader.");let i=s.messages||[],o=ru(i),a=new Map,c=[];for(let u of o)if(u.parentMessagePath){let d=a.get(u.parentMessagePath)||[];d.push(u),a.set(u.parentMessagePath,d)}else c.push(u);return{messages:er(i),activityMessages:er(s.activity_messages||[]),messageCards:a,siblingCards:c,mode:s.mode||"top_level"}}catch(n){throw console.error(`[gateway] Failed to fetch channel messages page for ${e}:`,n),n}}function Hs(e){N().invalidateQueries({queryKey:T.children(e)})}function _o(e){N().invalidateQueries({queryKey:T.item(e)})}function iu(e,t){_o(e),Hs(e);let n=e.split("/");n.pop();let r=n.join("/")||t;r&&Hs(r)}function ou(e){let t=e+"/";N().invalidateQueries({predicate:n=>{let r=n.queryKey;return r[0]!=="vfs"?!1:r.some(s=>typeof s=="string"&&(s===e||s.startsWith(t)))}})}function au(){N().invalidateQueries({queryKey:T.all()})}function cu(e){N().invalidateQueries({queryKey:T.types(e)})}function uu(e,t){e?N().invalidateQueries({queryKey:T.channelMessages(e,t)}):N().invalidateQueries({queryKey:T.allChannelMessages()})}function lu(e,t){e&&t?N().invalidateQueries({queryKey:T.openEnvelope(e,t)}):e?N().invalidateQueries({predicate:n=>{let r=n.queryKey;return r[0]==="vfs"&&r[2]==="open"&&r[3]===e}}):N().invalidateQueries({queryKey:T.allOpenEnvelopes()})}function st(e){return{id:e.accountId,path:e.path,kind:e.isSpace?"space":"account",name:e.name,grantedUnderAccountId:e.grantedUnderAccountId??void 0}}async function Xs(){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,invitationAccepted:n.invitation_accepted===!0,grantedUnderAccountId:n.granted_under_account_id??null,membershipPath:n.membership_path??null,personalSpaceId:n.personal_space_id??null,personalSpacePath:n.personal_space_path??null}))}var nr=new Map,Vr=null,Zs=null,Nt=new Map,du=250,$r=new Map;function cn(e){if(Vr){rr(e);return}rr(e),Vr=X("vfs_change",t=>Pp(t)),Zs=X("ccm_change",t=>Ep(t))}function rr(e){if(nr.has(e))return;let t=Zn(e,["vfs_change","ccm_change"]);nr.set(e,t)}function ei(e){let t=nr.get(e);t&&(t(),nr.delete(e))}function bo(){for(let[,e]of nr)e();nr.clear(),Vr&&(Vr(),Vr=null),Zs&&(Zs(),Zs=null),Nt.forEach(e=>clearTimeout(e)),Nt.clear(),$r.clear()}ae(bo);function Pp(e){let t=e.path,n=e.action;if(!t)return;let r=t.split("/");r.pop();let s=r.join("/")||"/root",i=$r.get(s);i||(i=new Map,$r.set(s,i)),i.set(t,{action:n,itemId:typeof e.item_id=="string"?e.item_id:void 0});let o=Nt.get(s);o&&clearTimeout(o);let a=setTimeout(()=>{Nt.delete(s);let c=$r.get(s);$r.delete(s),c&&Ip(s,c)},du);Nt.set(s,a)}function Ep(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=Nt.get(s);i&&clearTimeout(i);let o=setTimeout(()=>{Nt.delete(s),t&&N().invalidateQueries({queryKey:T.edges(t)}),n&&N().invalidateQueries({queryKey:T.edges(n)})},du);Nt.set(s,o)}function Ip(e,t){let n=N();for(let[s,i]of t)(i.action||"").toUpperCase()==="DELETE"?(n.removeQueries({queryKey:T.item(s)}),n.removeQueries({queryKey:T.children(s)}),n.removeQueries({queryKey:T.tree(s)})):ce(n,T.item(s),{exact:!0}),i.itemId&&n.invalidateQueries({queryKey:T.itemById(i.itemId)});n.invalidateQueries({queryKey:T.children(e)});let r=[...t.keys()];n.invalidateQueries({predicate:s=>{let i=s.queryKey;if(i[0]!=="vfs"||i[1]!=="tree")return!1;let o=i[2];return r.some(a=>a.startsWith(o+"/")||a===o)}})}var sr=null;ae(()=>{sr=null});function Dt(e){if(e!==sr||e.generation!==te())throw new Error("Workspace session changed")}function Tp(e){return e instanceof Re&&e.payload?.error==="item_not_found"}function Wr(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 Gr(e){let t=Se();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 pu(e,t){return JSON.stringify({mounts:e.map(n=>n.id),last_anchor:t.id})}async function fu(e,t,n){Dt(e);let r=pu(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}),Dt(e),e.exists=!0,e.saved=r}function mu(e,t){let n=Me();cn(Se().id);for(let r of n)e.some(s=>s.id===r.id)||ei(r.id);for(let r of e)rr(r.id);Ya(e,t)}async function un(e,t,n={}){let r=Se();if(!r)throw new Error("Elect a home account before loading mounts");let s=`${e}/settings/mounts`;if(sr&&sr.path!==s)throw new Error("Reset the session before changing the mount declaration owner");let i=sr??(sr={generation:te(),path:s,scope:r.path,resolve:t,exists:!1,ready:!1,saved:null,queue:Promise.resolve()});return Dt(i),i.resolve=t,i.loading?i.loading:i.ready?Me():(i.loading=(async()=>{let o=null;try{let d=await C("read",{path:s,_scope_path:i.scope});if(Dt(i),o=d.type_data??d.item?.type_data,!o||!Array.isArray(o.mounts)||!o.mounts.every(l=>typeof l=="string"))throw new Error("Invalid saved mount declaration");i.exists=!0}catch(d){if(Dt(i),!Tp(d))throw d;i.exists=!1}let a=n.initialAnchor?Wr(i,n.initialAnchor):r,c=Gr(o?o.mounts.map(d=>i.resolve(d)).filter(d=>d!==null):[a]),u=o?c.find(d=>d.id===o.last_anchor)??c.find(d=>d.kind==="space")??r:a;return o?i.saved=pu(c,u):n.initialAnchor&&await fu(i,c,u),Dt(i),i.ready=!0,mu(c,u),c})().finally(()=>{i.loading=void 0}),i.loading)}function ti(e){let t=sr;if(!t?.ready)return Promise.reject(new Error("Workspace mounts are not loaded"));let n=t.queue.then(async()=>{Dt(t);let{refs:r,anchor:s}=e(t);await fu(t,r,s),Dt(t),mu(r,s)});return t.queue=n.catch(()=>{}),n}function vo(e){return ti(t=>({refs:Gr([...Me(),Wr(t,e)]),anchor:fe()}))}function gu(e){return ti(()=>{if(e===Se().id)throw new Error("The home account cannot be unmounted");let t=Gr(Me().filter(r=>r.id!==e)),n=t.find(r=>r.id===fe()?.id)??t.find(r=>r.kind==="space")??Se();return{refs:t,anchor:n}})}function zr(e){return ti(t=>{let n=Wr(t,e);return{refs:Gr([...Me(),n]),anchor:n}})}function ni(e,t){return ti(n=>{let r=Gr(e.map(i=>Wr(n,i))),s=Wr(n,t);if(!r.some(i=>i.id===s.id))throw new Error("Selected mount must be in the working set");return{refs:r,anchor:s}})}var wo={};ta(wo,{Badge:()=>qp,Breadcrumbs:()=>Vp,Button:()=>Np,Card:()=>Fp,DataView:()=>Up,Detail:()=>Hp,Empty:()=>Dp,FilePreview:()=>zp,Form:()=>Lp,Grid:()=>kp,Image:()=>Wp,Link:()=>Bp,Page:()=>Ap,Router:()=>jp,Sidebar:()=>Op,Spinner:()=>Qp,Stack:()=>Mp,Table:()=>Kp,Tabs:()=>$p,Video:()=>Gp});var Z=J(ue(),1);function hu(){return(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||""}function Ap(e){return(0,Z.createElement)("div",{style:{minHeight:"100vh",display:"flex",flexDirection:"column"},className:e.className||""},e.children)}function Mp(e){let t=e.direction||"vertical";return(0,Z.createElement)("div",{style:{display:"flex",flexDirection:t==="horizontal"?"row":"column",gap:e.gap||"0.5rem",padding:e.padding||"0",alignItems:e.align||"stretch",justifyContent:e.justify||"flex-start",flex:e.flex||"initial"},className:e.className||""},e.children)}function kp(e){return(0,Z.createElement)("div",{style:{display:"grid",gridTemplateColumns:"repeat("+(e.columns||3)+", 1fr)",gap:e.gap||"1rem",padding:e.padding||"0"},className:e.className||""},e.children)}function Op(e){return(0,Z.createElement)("div",{style:{display:"flex",flexDirection:"row",minHeight:"100vh"},className:e.className||""},e.children)}function Fp(e){return(0,Z.createElement)("div",{style:{border:"1px solid var(--color-border, #e5e7eb)",borderRadius:"var(--border-radius, 0.5rem)",padding:e.padding||"1rem",background:"var(--color-surface, #fff)"},className:e.className||"",onClick:e.onClick},e.children)}function qp(e){return(0,Z.createElement)("span",{style:{display:"inline-flex",alignItems:"center",padding:"0.125rem 0.5rem",fontSize:"0.75rem",fontWeight:"500",borderRadius:"9999px",background:e.color||"#e5e7eb",color:e.textColor||"#374151"},className:e.className||""},e.children||e.label)}function Qp(e){let t=e.size||"1.5rem";return(0,Z.createElement)("div",{style:{width:t,height:t,border:"2px solid #e5e7eb",borderTopColor:"var(--color-primary, #3b82f6)",borderRadius:"50%",animation:"fsaos-spin 0.6s linear infinite"}})}function Np(e){return(0,Z.createElement)("button",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",padding:"0.5rem 1rem",fontSize:"0.875rem",fontWeight:"500",borderRadius:"var(--border-radius, 0.375rem)",border:e.variant==="outline"?"1px solid var(--color-border, #d1d5db)":"none",background:e.variant==="outline"||e.variant==="ghost"?"transparent":"var(--color-primary, #3b82f6)",color:e.variant==="outline"||e.variant==="ghost"?"var(--color-text, #1a1a1a)":"#fff",cursor:e.disabled?"not-allowed":"pointer",opacity:e.disabled?"0.5":"1",gap:"0.5rem"},className:e.className||"",onClick:e.onClick,disabled:e.disabled},e.children||e.label)}function Dp(e){return(0,Z.createElement)("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:"3rem",color:"var(--color-text-secondary, #6b7280)",textAlign:"center"}},e.icon?(0,Z.createElement)("div",{style:{fontSize:"2rem",marginBottom:"0.5rem"}},e.icon):null,(0,Z.createElement)("div",{style:{fontWeight:500,marginBottom:"0.25rem"}},e.title||e.message||e.children||"No items"),e.description?(0,Z.createElement)("div",{style:{fontSize:"0.875rem",opacity:.7}},e.description):null)}function Up(e){return(0,Z.createElement)("div",{className:e.className||""},e.children)}function Kp(e){return(0,Z.createElement)("table",{className:e.className||""},e.children)}function Lp(e){return(0,Z.createElement)("form",{className:e.className||"",onSubmit:e.onSubmit},e.children)}function Hp(e){return(0,Z.createElement)("div",{className:e.className||""},e.children)}function jp(e){return(0,Z.createElement)("div",null,e.children)}function Bp(e){return(0,Z.createElement)("a",{href:e.href||e.to,className:e.className||"",onClick:e.onClick},e.children)}function $p(e){return(0,Z.createElement)("div",{className:e.className||""},e.children)}function Vp(e){return(0,Z.createElement)("nav",{className:e.className||""},e.children)}function Wp(e){return(0,Z.createElement)("img",{src:e.src||(e.path?hu()+e.path:""),alt:e.alt||"",className:e.className||"",style:e.style})}function Gp(e){return(0,Z.createElement)("video",{src:e.src||(e.path?hu()+e.path:""),controls:!0,className:e.className||""})}function zp(e){return(0,Z.createElement)("div",{className:e.className||""},e.children||"File preview")}function ri(e){if(typeof e.path!="string")return!1;let t=[...Me().map(n=>n.path),fe()?.path].filter(n=>!!n);return!t.length&&z()&&t.push(z()),t.some(n=>ie(e.path,n))}function ir(e,t,n,r){if(!["message","card"].includes(e?.item_type)||!ie(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&&ie(e.path,i)})}var yu=new WeakMap,So=e=>e.slice(0,e.lastIndexOf("/")),xo=e=>e.action?.toLowerCase();function _u(e,t){return e.item_type==="message"&&xo(e)==="insert"&&So(e.path)===t&&!e.old_path}function Jp(e,t,n){return e.messages.filter(r=>t.has(r.id)||n.has(r.path))}function Yp(e,t,n,r){let s=e.pages.slice(),i=new Map(n?.messages.map(u=>[u.id,u]));for(let[u,d]of t){let l=s[u],h=new Set(d.map(m=>m.id)),f=new Map(l.messageCards);for(let m of d){f.delete(m.path);let _=i.get(m.id),g=_&&n?.messageCards.get(_.path);_&&g?.length&&f.set(_.path,g)}s[u]={...l,messages:l.messages.flatMap(m=>{if(!h.has(m.id))return[m];let _=i.get(m.id);return _?[_]:[]}),messageCards:f}}let o=r??n,a=s[0],c=new Map(a.messageCards);for(let u of a.activityMessages??[])c.delete(u.path);for(let u of[...o.activityMessages??[],...r?.messages??[]]){let d=o.messageCards.get(u.path);d?.length&&c.set(u.path,d)}return s[0]={...a,messages:r?[...a.messages,...r.messages]:a.messages,activityMessages:o.activityMessages,siblingCards:o.siblingCards,messageCards:c},{...e,pages:s}}function bu(e,t,n,r){let s=yu.get(e);s||(s=new Map,yu.set(e,s));let i=JSON.stringify(t),o=s.get(i);if(!o){let c,u=!1,d=!1,l=new Map,h=()=>e.getQueryData(t),f=()=>e.getQueryCache().find({queryKey:t,exact:!0}),m=()=>ce(e,t,{exact:!0}),_=(v,x)=>an(n,{transcriptOnly:!0,limit:r,after_seq:v,before_seq:x}),g=()=>{d||u||c||!l.size||(c=setTimeout(()=>{c=void 0,b()},500))},b=async()=>{u=!0;let v=[...l.values()];l.clear();let x=f();try{if(x?.state.fetchStatus==="fetching"&&await x.promise?.catch(()=>{}),d||x!==f())return;let R=h();if(!R?.pages.length){await m();return}let k=new Set,O=new Set,P=new Set,A=!1;for(let j of v){if(_u(j,n)){A=!0;continue}j.inserted&&(A=!0),j.item_type==="message"&&So(j.path)===n&&!j.inserted&&xo(j)!=="delete"&&P.add(j.path),j.item_id&&k.add(j.item_id),j.parent_id&&k.add(j.parent_id);for(let he of[j.path,j.old_path])he&&ie(he,n)&&(O.add(he),O.add(So(he)))}let M=new Map,I=1/0,F=0;(k.size||O.size)&&R.pages.forEach((j,he)=>{let ve=Jp(j,k,O);ve.length&&M.set(he,ve);for(let je of ve)P.delete(je.path),I=Math.min(I,je.seq),F=Math.max(F,je.seq)});for(let j of R.pages[0].activityMessages??[])P.delete(j.path);if(P.size){await m();return}if(M.size&&(!Number.isSafeInteger(I)||I<1||!Number.isSafeInteger(F+1))){await m();return}let Q=R.pages.find(j=>j.messages.length)?.messages.at(-1)?.seq??0,[K,B]=await Promise.all([M.size?_(I-1,F+1):void 0,A||!M.size?_(Q):void 0]);if(d||x!==f())return;let Qe=h();if(x?.state.fetchStatus==="fetching"||R.pages.some((j,he)=>Qe?.pages[he]!==j)||K&&K.messages.length>=r&&(K.messages.at(-1)?.seq??0)<F||B&&B.messages.length>=r){await m();return}e.setQueryData(t,j=>j&&Yp(j,M,K,B))}catch{!d&&x===f()&&await m()}finally{u=!1,g()}},y=X("vfs_change",v=>{let x=v.item_id??v.path,R=l.get(x);l.set(x,R&&(R.inserted||_u(R,n))&&xo(v)==="update"&&R.path===v.path?{...v,inserted:!0}:v),g()},v=>ir(v,n,void 0,[])||!!v.old_path&&ir({...v,path:v.old_path},n,void 0,[])||v.item_type==="message"&&!!v.parent_id&&ie(v.path,n)&&!!h()?.pages.some(x=>x.messages.some(R=>R.id===v.parent_id)));o={users:0,stop:()=>{d=!0,y(),c&&clearTimeout(c),l.clear()}},s.set(i,o)}o.users++;let a=!1;return()=>{a||(a=!0,--o.users===0&&(o.stop(),s.delete(i)))}}var vu=new WeakMap;function wu(e,t,n){let r=vu.get(e);r||(r=new Map,vu.set(e,r));let s=JSON.stringify(t),i=r.get(s);if(!i){let a=!1,c,u=!1,d=!1,l=new Set,h=new Set,f=()=>e.getQueryData(t)??[],m=()=>{a||u||c||(c=setTimeout(()=>{c=void 0,_()},250))},_=async()=>{if(a)return;u=!0;let x=d;d=!1;let R=[...l],k=new Set(h);h.clear(),l.clear();try{if(x)await ce(e,t,{exact:!0});else{let P=(await Promise.allSettled(R.map(async A=>{let M=e.getQueryCache().find({queryKey:t,exact:!0});if(!M)return;let I=await C("read",{id:A});if(I.success===!1)throw new Error("Channel refresh failed");if(a||!M||e.getQueryCache().find({queryKey:t,exact:!0})!==M)return;let F=He(I.item??I);if(F.id!==A||F.item_type!=="channel")return;let Q=f().find(Qe=>Qe.id===A);if(!Q)return;let K=n({...F}),B={...Q,path:K.path,name:K.name,displayName:K.displayName,messageCount:K.messageCount,aiMode:K.aiMode,activeAgentIds:K.activeAgentIds,isPrivate:K.isPrivate,isDm:K.isDm,autoPilot:K.autoPilot,isArchived:K.isArchived,updatedAt:K.updatedAt};k.has(A)&&(Q.name!==B.name||Q.displayName!==B.displayName||Q.path!==B.path)&&(d=!0),e.setQueryData(t,Qe=>Qe?.map(j=>j.id===A?B:j))}))).find(A=>A.status==="rejected");if(P?.status==="rejected")throw P.reason}}catch(O){console.warn("[channels] refresh failed",O)}finally{u=!1,(d||l.size)&&m()}},g=x=>f().some(R=>R.id===x.item_id||R.path===x.path)?!0:ri(x),b=x=>{if(!g(x))return;let R=String(x.action??"").toLowerCase();if(["insert","delete","rename","move"].includes(R))d=!0;else if(R==="update"){let k=f().find(O=>O.id===x.item_id||O.path===x.path);k&&(l.add(k.id),h.add(k.id))}(d||l.size)&&m()},y=x=>{let R=f().find(k=>k.id===x.parent_id);R&&(l.add(R.id),m())},v=["vfs_change","ccm_change"].flatMap(x=>[X(x,b,R=>R.item_type==="channel"),X(x,y,R=>R.item_type==="message")]);i={users:0,stop:()=>{a=!0,c&&clearTimeout(c),v.forEach(x=>x())}},r.set(s,i)}i.users++;let o=!1;return()=>{o||(o=!0,--i.users===0&&(i.stop(),r.delete(s)))}}var Su=new WeakMap;function xu(e,t,n){let r=Su.get(e);r||(r=new Map,Su.set(e,r));let s=JSON.stringify(t),i=r.get(s);if(!i){let a,c=()=>{a||(a=setTimeout(()=>{a=void 0,ce(e,t,{exact:!0})},250))},u=[X("ccm_change",c,d=>d.edge_type==="replies_to"&&(d.target_item_id??d.target_id)===n),X("vfs_change",c,d=>{let l=d.item_id??d.id;return l?l===n?!0:e.getQueryData(t)?.pages.some(f=>f.messages.some(m=>m.id===l))??!1:!1})];i={users:0,stop:()=>{a&&clearTimeout(a),u.forEach(d=>d())}},r.set(s,i)}i.users++;let o=!1;return()=>{o||(o=!0,--i.users===0&&(i.stop(),r.delete(s)))}}var si=J(ue(),1);var Ro=new Set(["view","edit","delete","admin"]),Ru=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Xp(e){let t=e.item??e,n=t.id??t.item_id,r=t.path??t.item_path;if(e.success!==!0||typeof n!="string"||!Ru.test(n))throw new Error("PERMISSION_TARGET_UNAVAILABLE");return{id:n,...typeof r=="string"?{path:r}:{}}}function ii(e,t){(0,si.useSyncExternalStore)(xe,W,W);let n=(0,si.useSyncExternalStore)(Rs,Bn,Bn),r=(0,si.useSyncExternalStore)(jn,Ft,Ft),s=z(),i=nt()?.principal_id,o=e?.trim()??"",a=[...new Set(t??[])].sort(),c=Ru.test(o),u=c||o.startsWith("/root/")||o==="/root",d=a.some(O=>!Ro.has(O))||!!(o&&!u),l=!!(s&&i&&o&&a.length&&!d),h=["vfs",s??"__unscoped__","permissions",i??"__anonymous__",n,r],f=[...new Set([fe()?.id,...Me().map(O=>O.id)].filter(O=>!!O))],m=[...h,"target",o],_=$({queryKey:m,queryFn:async({signal:O})=>{if(!l||!s)throw new Error("PERMISSION_CONTEXT_REQUIRED");return Xp(await C("read",{path:o,_scope_path:s},{signal:O}))},enabled:l&&!c,staleTime:1/0,gcTime:0,retry:!1,refetchOnWindowFocus:!1,refetchOnReconnect:!1,refetchOnMount:!1,meta:{permissionQuery:{scope:s,scopeIds:f,path:o,targetLookup:!0}}}),g=c?{id:o}:_.data,b=c||_.isSuccess&&!_.isFetching&&!_.isStale,y=Vi({queries:a.filter(O=>Ro.has(O)).map(O=>({queryKey:[...h,"check",g?.id??o,O],queryFn:async({signal:P})=>{if(!l||!s||!g)throw new Error("PERMISSION_CONTEXT_REQUIRED");let A=await C("check-item-access",{id:g.id,action:O,_scope_path:s},{signal:P});if(A.success!==!0||typeof A.allowed!="boolean")throw new Error("PERMISSION_RESPONSE_INVALID");return A.allowed},enabled:l&&b&&!!g,staleTime:1/0,gcTime:0,retry:!1,refetchOnWindowFocus:!1,refetchOnReconnect:!1,refetchOnMount:!1,meta:{permissionQuery:{scope:s,scopeIds:f,itemId:g?.id,path:g?.path??(c?void 0:o)}}}))}),v=d?new Error("PERMISSION_INPUT_INVALID"):!c&&_.error||y.find(O=>O.error)?.error||null,x=l&&b&&!v,R=a.filter(O=>Ro.has(O));return{data:Object.fromEntries(a.map(O=>{let P=y[R.indexOf(O)];return[O,!!(x&&P?.isSuccess&&!P.isFetching&&!P.isStale&&P.data===!0)]})),loading:!!(l&&(!c&&_.isFetching||y.some(O=>O.isFetching||O.isPending))&&!v),error:v,refetch:async()=>{if(l){if(!c&&(!_.data||_.isError)){await _.refetch();return}await Promise.all(y.map(O=>O.refetch()))}}}}function Co(e,t){let n=ii(t,e?[e]:[]);return{...n,data:{allowed:!!(e&&n.data[e])}}}function re(){return(0,w.useSyncExternalStore)(xe,W,W)}function Mu(){return re(),Cs()}function ku(e){return re(),$({queryKey:T.item(e),queryFn:()=>Lr(e),enabled:!!e,staleTime:1/0})}function Ou(e){return re(),$({queryKey:T.itemById(e),queryFn:()=>Kr(e),enabled:!!e,staleTime:1/0})}function To(e){return re(),$({queryKey:T.children(e),queryFn:()=>Hr(e),enabled:!!e})}function Fu(e){let t=To(e);return{...t,children:t.data??[]}}function qu(e,t=1){return re(),$({queryKey:T.tree(e,t),queryFn:()=>Vs(e,t),enabled:!!e})}function Qu(e,t){return re(),$({queryKey:T.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(He)},enabled:!!e&&e.length>0})}function Nu(e){re();let t=(0,w.useMemo)(()=>e,[JSON.stringify(e)]);return $({queryKey:["vfs",z()??"__unscoped__","resolve",JSON.stringify(t??{})],queryFn:async()=>await C("resolve",t),enabled:!!t?.query&&t.query.length>0})}function Du(e){re();let t=qt(e),n=(0,w.useMemo)(()=>t,[JSON.stringify(t)]),r=$({queryKey:T.items(n?.type??"",n),queryFn:({signal:s})=>on(n,{signal:s,throwOnError:!0}),enabled:tr(n),...n?.spaceIds!==void 0?{retry:(s,i)=>!Wn(i)&&Al(s,i)}:{},select:s=>s.items});return n?.spaceIds!==void 0&&Wn(r.error)?{...r,data:void 0}:r}function Ao(e,t={}){let n=re(),{realtime:r=!1}=t,s=qt(e),i=s?.limit??20,o=(0,w.useMemo)(()=>s,[JSON.stringify(s)]),a=(0,w.useMemo)(()=>["vfs",z()??"__unscoped__","infinite-items",o?.type??"",JSON.stringify(o??{})],[n,o]),c=Fn({queryKey:a,queryFn:async({pageParam:l=0,signal:h})=>on({...o,limit:i,offset:l},{throwOnError:!0,signal:h,priority:t.priority}),initialPageParam:0,getNextPageParam:(l,h,f)=>{if(!(o?.spaceIds!==void 0&&l.total_hint!==void 0&&f+l.items.length>=l.total_hint)&&!(l.items.length<i))return f+l.items.length},enabled:tr(o),...o?.spaceIds!==void 0?{retry:(l,h)=>!Wn(h)&&Al(l,h)}:{},staleTime:r?1/0:t.staleTime,meta:r&&o?{infiniteItemsRealtime:{filter:o}}:{}}),u=(0,w.useMemo)(()=>{if(o?.spaceIds!==void 0&&Wn(c.error))return[];if(!c.data?.pages)return[];let l=new Set,h=[];for(let f of c.data.pages)for(let m of f.items)m.id&&!l.has(m.id)&&(l.add(m.id),h.push(m));return h},[c.data?.pages,c.error,o]),d=o?.spaceIds!==void 0&&Wn(c.error);return{allItems:u,refetch:c.refetch,fetchNextPage:c.fetchNextPage,isFetchingNextPage:c.isFetchingNextPage,isExhausted:d||!c.hasNextPage,isLoading:c.isLoading,isFetching:c.isFetching,error:c.error,totalHint:d?void 0:c.data?.pages?.[0]?.total_hint}}function Cu(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 tf(e,t){if(e.is_active===!1||e.item_type!==t.type||!ie(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 Uu(e,t={}){let n=Cu(e),r=Ao(e,n?{realtime:!1,staleTime:3e4}:{realtime:!0}),s=U(),i=JSON.stringify([z(),qt(e)]),[o,a]=(0,w.useState)(()=>({identity:i,upserts:{},deleted:new Set})),c=o.identity===i?o:{identity:i,upserts:{},deleted:new Set},u=(0,w.useMemo)(()=>{if(!n)return r.allItems;let f=Object.values(c.upserts),m=new Set(f.map(y=>y.id)),_=[...f,...r.allItems.filter(y=>!m.has(y.id))].filter(y=>!c.deleted.has(y.path)),g=e.sort_by??"updated_at",b=e.sort_dir==="asc"?1:-1;return _.sort((y,v)=>b*String(y[g]??"").localeCompare(String(v[g]??"")))},[n,r.allItems,c,e?.sort_by,e?.sort_dir]),d=(0,w.useRef)(u);d.current=u;let l=(0,w.useRef)(t.shouldReadUpdate);l.current=t.shouldReadUpdate;let h=(0,w.useRef)(r.refetch);return h.current=r.refetch,(0,w.useEffect)(()=>{if(!Cu(e))return;let f=e,m=!1,_=!1,g=!1,b=0,y=new Map,v=()=>{let P=b;h.current().then(A=>{!m&&!A.isError&&b===P&&a({identity:i,upserts:{},deleted:new Set})})},x=P=>{b++,a(M=>{let I=M.identity===i?M:{identity:i,upserts:{},deleted:new Set},F={...I.upserts};return delete F[P],{identity:i,upserts:F,deleted:new Set(I.deleted).add(P)}});let A=y.get("__reconcile__");A&&clearTimeout(A),y.set("__reconcile__",setTimeout(()=>{y.delete("__reconcile__"),v()},250))},R=P=>{let A=y.get(P);A&&clearTimeout(A),y.set(P,setTimeout(()=>{y.delete(P),s.fetchQuery({queryKey:T.item(P),queryFn:()=>Lr(P),staleTime:0}).then(M=>{if(!m){if(!M||!tf(M,f)){let I=d.current.find(F=>F.path===P||F.id===M?.id);I&&x(I.path);return}a(I=>{let F=I.identity===i?I:{identity:i,upserts:{},deleted:new Set},Q=new Set(F.deleted);return Q.delete(P),{identity:i,upserts:{...F.upserts,[P]:M},deleted:Q}})}}).catch(M=>console.warn("[useIncrementalItems] item read failed:",M))},250))},k=X("vfs_change",P=>{if(!P||typeof P.path!="string"&&typeof P.old_path!="string")return;let A=typeof P.path=="string"?P.path:P.old_path,M=d.current.find(F=>F.path===A||F.path===P.old_path||P.item_id&&F.id===P.item_id),I=!!M;if(!(!ie(A,f.scope)&&!ie(P.old_path,f.scope)&&!I)&&!(P.item_type&&P.item_type!==f.type&&!I)&&!(f.parent_id&&P.parent_id&&P.parent_id!==f.parent_id&&!I)){if(M&&(A!==M.path||P.old_path&&P.old_path!==A||P.parent_id&&P.parent_id!==M.parent_id||P.item_type&&P.item_type!==f.type)){x(M.path);return}if(!M&&P.old_path&&P.old_path!==A&&ie(A,f.scope)){b++,R(A);return}if(P.action==="insert")b++,R(A);else if(P.action==="move")b++,R(A);else if(P.action==="update"){if(!l.current?.(P,d.current))return;b++,R(A)}else P.action==="delete"&&x(M?.path??P.old_path??A)}}),O=Ls(P=>{if(P!=="connected"){_&&(g=!0);return}_=!0,g&&(g=!1,v())});return()=>{m=!0,k(),O(),y.forEach(clearTimeout)}},[s,i]),{...r,allItems:u}}function Ku(e){re();let t=20,n=Fn({queryKey:["vfs",z()??"__unscoped__","infinite-children",e??""],queryFn:async({pageParam:s=0})=>js(e,t,s),initialPageParam:0,getNextPageParam:(s,i,o)=>{if(!(s.items.length<t))return o+s.items.length},enabled:!!e});return{allItems:(0,w.useMemo)(()=>{if(!n.data?.pages)return[];let s=new Set,i=[];for(let o of n.data.pages)for(let a of o.items)a.id&&!s.has(a.id)&&(s.add(a.id),i.push(a));return i},[n.data?.pages]),fetchNextPage:n.fetchNextPage,isFetchingNextPage:n.isFetchingNextPage,isExhausted:!n.hasNextPage,isLoading:n.isLoading,isFetching:n.isFetching,error:n.error,totalHint:n.data?.pages?.[0]?.total_hint}}function Lu(e){return re(),$({queryKey:T.edges(e),queryFn:()=>$s(e),enabled:!!e})}function ai(e){return re(),$({queryKey:T.types(e),queryFn:()=>Bs(e)})}function Hu(e,t){let n=ai(t);return{...n,data:n.data?.get(e)??void 0}}function ju(e,t){re();let n=(0,w.useMemo)(()=>t?.arguments,[JSON.stringify(t?.arguments)]),r=t?.mode,s=t?.strategy,i=t?.width;return $({queryKey:[...T.openEnvelope(e,s),i],queryFn:async()=>{let o=await Br(e,{mode:r,strategy:s,arguments:n});if(i&&o.render?.props?.url){let a=o.render.props.url,c=a.includes("?")?"&":"?";o.render.props.url=`${a}${c}w=${i}`}return o},enabled:!!e})}var Pu={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 Bu(e){let t=ai(e),n=t.data??new Map;return(0,w.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(Pu).map(([f,m])=>({key:f,label:m})),getEdgeTypeLabel:f=>Pu[f]??f.replace(/_/g," "),allTypes:n,loading:t.isLoading}),[n,t.isLoading])}function $u(e,t,n){return re(),$({queryKey:T.memberFocus(e),queryFn:()=>zs(e,t,n),enabled:!!e})}function Vu(e,t={}){let{limit:n=50,offset:r=0,include_snapshots:s=!1}=t;return $({queryKey:T.itemVersions(e,String(n),String(r),String(s)),queryFn:()=>jr(e,{limit:n,offset:r,include_snapshots:s}),enabled:!!e})}function Wu(e,t=50,n=0){return $({queryKey:T.itemHistory(e,String(t),String(n)),queryFn:()=>Gs(e,t,n),enabled:!!e})}function Gu(e,t=50,n=0){return re(),$({queryKey:T.recentActivity(e,String(t),String(n)),queryFn:()=>Ws(e,t,n),enabled:!!e})}function zu(){let[e,t]=(0,w.useState)(null),[n,r]=(0,w.useState)(!0),[s,i]=(0,w.useState)(null);return(0,w.useEffect)(()=>{let o=!1;return gt().then(a=>{if(!o){let c=typeof window<"u"&&window.__FSAOS_CONFIG__||{};t({path:a.scope_path,scope_id:a.scope_id,fractal_id:a.fractal_id,instance_name:a.instance_name,display_name:a.display_name,componentPath:c.componentPath||"",isEmbed:!!c.embedToken}),r(!1)}}).catch(a=>{o||(i(a instanceof Error?a:new Error(String(a))),r(!1))}),()=>{o=!0}},[]),{data:e,loading:n,error:s}}var nf=[];function Eu(){if(typeof window>"u")return!1;let e=window.__FSAOS_CONFIG__?.embedToken;return typeof e=="function"||typeof e=="string"&&e.length>0}function rf(e){return e.filter(t=>t.placement==="switcher_entry").map(t=>({account:t,mountables:e.filter(n=>n.placement!=="switcher_entry"&&n.subordinateTo===t.accountId)}))}function Ju(){let{user:e}=ci(),t=(0,w.useSyncExternalStore)(Rs,Bn,Bn),n=nt()?.principal_id??null,r=(0,w.useRef)(null),[s,i]=(0,w.useState)(null),[o,a]=(0,w.useState)(null);(0,w.useEffect)(()=>{if(n){a(null);return}if(!e?.id&&!Eu()){a(null);return}let y=!1;return gt().then(v=>{y||v.principal_id||a(new Error("Memberships require an authenticated principal"))}).catch(v=>{y||a(v instanceof Error?v:new Error(String(v)))}),()=>{y=!0}},[n,e?.id,t]);let c=$({queryKey:T.memberships(n??"anonymous"),queryFn:Xs,enabled:!!n,staleTime:1e3*60*2}),u=c.data??nf,d=(0,w.useMemo)(()=>u.filter(y=>y.isAccount!==!1&&!y.isSpace),[u]),l=(0,w.useMemo)(()=>{let y=new Set(d.map(x=>x.accountId)),v=x=>!x.subordinateTo||!y.has(x.subordinateTo);return[...d].sort((x,R)=>Number(v(R))-Number(v(x)))},[d]),h=(0,w.useSyncExternalStore)(xe,W,W),f=(0,w.useMemo)(()=>{let y=fe();return y?u.find(v=>v.accountId===y.id)??null:null},[h,u]),m=(0,w.useMemo)(()=>rf(d),[d]);(0,w.useEffect)(()=>{if(!n){r.current=null;return}if(r.current!==n)if(i(null),l.length===1){let y=l[0];Se()||Zt(st(y)),cn(y.accountId),y.personalSpacePath&&un(y.personalSpacePath,v=>{let x=u.find(R=>R.accountId===v);return x?st(x):null}).catch(i),r.current=n}else l.length>1&&(r.current=n)},[n,l,u]);let _=(0,w.useCallback)(async y=>{let v=u.find(k=>k.path===y);if(!v)throw new Error("Account membership is unavailable");let x=st(v);Se()||Zt(x);let R=u.find(k=>k.accountId===Se()?.id);if(!R?.personalSpacePath)throw new Error("The home membership has no mount declaration location");await un(R.personalSpacePath,k=>{let O=u.find(P=>P.accountId===k);return O?st(O):null}),await zr(x),i(null),cn(v.accountId)},[u]),g=(0,w.useCallback)(async y=>{let v=u.find(x=>x.path===y);if(!v)throw new Error("Scope membership is unavailable");await vo(st(v))},[u]),b=(!!e?.id||Eu())&&!n&&!o;return{accounts:l,switcherAccounts:m,allMemberships:u,currentAccount:f,mountedScope:null,switchAccount:_,mountScope:g,loading:b||c.isLoading,error:o??c.error??s}}function Yu(){re();let e=(0,w.useSyncExternalStore)(jn,Ft,Ft),t=(0,w.useMemo)(()=>Me(),[e]),n=fe(),r=(0,w.useMemo)(()=>t.filter(i=>i.kind==="space"&&(n?.kind==="account"||i.id===n?.id)),[t,n]),s=(0,w.useMemo)(()=>r.map(i=>i.id).sort(),[r]);return{mounts:t,selectedSpaces:r,readSpaceIds:s,homeAnchor:Se(),anchor:n,setAnchor:zr,replaceMounts:ni,mount:vo,unmount:gu}}function ci(){let[e,t]=(0,w.useState)(null),[n,r]=(0,w.useState)(null),[s,i]=(0,w.useState)(!0),o=(0,w.useRef)(null);(0,w.useEffect)(()=>{G.auth.getSession().then(({data:f,error:m})=>{if(m){console.warn("[useAuth] getSession error, clearing stale session:",m.message),G.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),G.auth.signOut().catch(()=>{}),r(null),t(null),i(!1)});let{data:{subscription:h}}=G.auth.onAuthStateChange((f,m)=>{if(f==="TOKEN_REFRESHED"&&!m){console.warn("[useAuth] TOKEN_REFRESHED with null session \u2014 signing out"),G.auth.signOut().catch(()=>{}),r(null),t(null),i(!1);return}r(m),t(m?.user??null),i(!1)});return o.current=h,()=>{h?.unsubscribe()}},[]);let a=(0,w.useCallback)(async h=>h.provider?G.auth.signInWithOAuth({provider:h.provider,options:h.redirectTo?{redirectTo:h.redirectTo}:{redirectTo:window.location.href}}):G.auth.signInWithPassword({email:h.email,password:h.password}),[]),c=(0,w.useCallback)(async h=>G.auth.signUp({email:h.email,password:h.password,options:{data:h.metadata||{}}}),[]),u=(0,w.useCallback)(async()=>{await G.auth.signOut(),$n(),N().clear()},[]),d=(0,w.useCallback)(async h=>{let{error:f}=await G.auth.resetPasswordForEmail(h);if(f)throw f},[]),l=(0,w.useCallback)(async(h,f)=>{let{error:m}=await G.auth.signInWithOtp({email:h,options:f?{emailRedirectTo:f}:{emailRedirectTo:window.location.href}});if(m)throw m},[]);return{user:e,session:n,loading:s,signIn:a,signUp:c,signOut:u,resetPassword:d,signInWithMagicLink:l}}function Xu(e){let[t,n]=(0,w.useState)(null),[r,s]=(0,w.useState)(!1),[i,o]=(0,w.useState)(null);return(0,w.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(c=>{c.success&&c.public_url?n({url:c.public_url,id:c.asset_id,name:c.name,mimeType:c.mime_type,width:c.width,height:c.height,sizeBytes:c.size_bytes}):o(new Error(c.error||"Asset not found")),s(!1)}).catch(c=>{o(c instanceof Error?c:new Error(String(c))),s(!1)});else{let u=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"";n({url:u+e}),s(!1)}},[e]),{data:t,loading:r,error:i}}var oi={};ae(()=>{for(let e of Object.keys(oi))delete oi[e]});var Zu=null;function el(e){Zu=e,typeof window<"u"&&!window.__FSAOS_GATEWAY__&&(window.__FSAOS_GATEWAY__=e)}function sf(e){switch(e){case"react":return typeof window<"u"&&window.React||w.default;case"react-dom":case"react-dom/client":return typeof window<"u"&&window.ReactDOM||Zp;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}:ef;case"@fsaos/gateway":case"@fsaos/react":case"@ai4b-team/fsaos-gateway-sdk":return typeof window<"u"&&window.__FSAOS_GATEWAY__||Zu||{};case"@fsaos/ui":case"@ai4b-team/fsaos-gateway-sdk/ui":return typeof window<"u"&&window.__FSAOS_UI__||wo;case"@fsaos/theme":return{};default:return console.warn(`[useComponent] Unknown module requested: ${e}`),{}}}var Xr={};async function of(e){try{let t=await fetch(e);if(!t.ok)return null;let n=await t.text();return!n.trim()||n.includes("No CSS bundle for this component")?null:n}catch{return null}}async function Mo(e,t=()=>of(e)){let n=Xr[e];n||(n=Xr[e]={users:0,text:t(),style:null}),n.users+=1;let r=await n.text;if(Xr[e]!==n||n.users===0||n.style||!r||typeof document>"u")return;let s=document.createElement("style");s.setAttribute("data-fsaos-component-css",e),s.textContent=r,document.head.appendChild(s),n.style=s}function Ce(e){let t=Xr[e];t&&(t.users-=1,!(t.users>0)&&(t.style?.remove(),delete Xr[e]))}function ko(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)(sf),o=t??i;return o?o.default||o:null}finally{n!==void 0?window.__FSAOS_REGISTER__=n:delete window.__FSAOS_REGISTER__}}function Oo(e,t){let[n,r]=(0,w.useState)(null),[s,i]=(0,w.useState)(!0),[o,a]=(0,w.useState)(null),c=(0,w.useRef)(null),u=Number.isSafeInteger(t?.version)&&t.version>0?t.version:null;return(0,w.useEffect)(()=>{if(!e)return;let d=!1;a(null),c.current?.path!==e&&(c.current?.cssUrl&&Ce(c.current.cssUrl),c.current=null,r(null),i(!0));let h=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"";return(async()=>{let f=null;try{let m=1,_=e+"@v1",g=h+e+"/__bundle.js";if(u!==null)m=u,_=e+"@v"+m,g=h+e+"/__bundle.v"+m+".js";else try{let R=await fetch(h+e+"/__meta",{cache:"no-store"});R.ok&&(m=(await R.json()).version||1,_=e+"@v"+m,g=h+e+"/__bundle.v"+m+".js")}catch{g=h+e+"/__bundle.js?v="+Date.now()}if(d)return;let b=g.replace(/__bundle(\.v\d+)?\.js(\?.*)?$/,"__bundle$1.css");f=b;let y=Mo(b),v=oi[_];if(!v){let R=await fetch(g);if(!R.ok)throw new Error(`Failed to fetch bundle: ${R.status} ${R.statusText} (${g})`);let k=await R.text();if(v=ko(k),!v)throw new Error("Bundle did not export a component. Expected window.__FSAOS_COMPONENT__ (FSAOS build) or a __FSAOS_REGISTER__(Component) call.");if(typeof v!="function")throw new Error(`Bundle export is not a React component (got ${typeof v})`);oi[_]=v}if(await y,d){Ce(b);return}let x=c.current?.cssUrl??null;c.current={path:e,cssUrl:b},f=null,r(()=>v),i(!1),x&&Ce(x)}catch(m){f&&Ce(f),d||(a(m instanceof Error?m:new Error(String(m))),i(!1))}})(),()=>{d=!0}},[e,u]),(0,w.useEffect)(()=>()=>{c.current?.cssUrl&&Ce(c.current.cssUrl),c.current=null},[]),{Component:n,loading:s,error:o}}var af=/^embed\/bundle-[A-Za-z0-9_-]+\.js$/,cf=/^embed\/bundle-[A-Za-z0-9_-]+\.css$/;function Iu(e,t,n){let r=Object.keys(e).filter(o=>t.test(o));if(r.length>1)throw new Error(`The published release has more than one in-app ${n}.`);let s=r[0];if(!s)return null;let i=We(e[s]).sha256;return typeof i=="string"&&i?{path:s,sha256:i}:null}var Jr=new Map,Po=new Map;ae(()=>{Jr.clear(),Po.clear()});function We(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function tl(e){let t=We(We(e.type_data).published),n=t.published_release_item_id,r=t.published_version;return typeof n!="string"||!n||typeof r!="number"||!Number.isSafeInteger(r)||r<1?null:{releaseItemId:n,version:r}}async function Tu(e,t,n){let r=await Br(e.path,{mode:"render"}),s=We(We(r.render).props).url;if(typeof s!="string"||!s)throw new Error(`The published ${n} could not be opened.`);let i=await fetch(s);if(!i.ok)throw new Error(`Failed to read the published ${n}: ${i.status} ${i.statusText}`.trim());let o=await i.arrayBuffer();if(Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256",o))).map(c=>c.toString(16).padStart(2,"0")).join("")!==t)throw new Error(`The published ${n} does not match the bytes its release sealed.`);return new TextDecoder().decode(o)}async function uf(e,t,n){let r=await Kr(t);if(!r)throw new Error("The published release could not be read.");let s=We(r.type_data);if(r.item_type!=="revdev_release"||s.component_item_id!==e||s.status!=="committed"||Number(s.version)!==n)throw new Error("This component's live version does not match its release record.");let i=We(s.artifacts),o=Iu(i,af,"script");if(!o)return{status:"no_in_app_version",releaseItemId:t,version:n};let a=Iu(i,cf,"stylesheet"),c=a?[o.path,a.path]:[o.path],u=s.build_item_id;if(typeof u!="string"||!u)throw new Error("The published release names no build.");let{items:d}=await on({type:"file",parent_id:u,field_in:{package_path:c},limit:c.length},{throwOnError:!0}),l=g=>d.find(b=>We(b.type_data).package_path===g),h=l(o.path),f=a?l(a.path):void 0;if(!h||a&&!f)throw new Error("The published release's in-app files could not be found in its build.");let[m,_]=await Promise.all([Tu(h,o.sha256,"script"),f&&a?Tu(f,a.sha256,"stylesheet"):Promise.resolve(null)]);return{status:"ready",releaseItemId:t,version:n,script:m,stylesheet:_?.trim()?_:null}}function nl(e,t,n){let r=Jr.get(t);return r||(r=uf(e,t,n),Jr.set(t,r),r.catch(()=>{Jr.get(t)===r&&Jr.delete(t)})),r}function rl(e){let t=tl(e);return!e.id||!t?Promise.resolve({status:"unpublished"}):nl(e.id,t.releaseItemId,t.version)}function sl(e){let[t,n]=(0,w.useState)(null),[r,s]=(0,w.useState)("loading"),[i,o]=(0,w.useState)(null),a=(0,w.useRef)(null),c=e!=null,u=e?.id||null,d=e?tl(e):null,l=d?.releaseItemId??null,h=d?.version??null;return(0,w.useEffect)(()=>{if(!c)return;let f=()=>{a.current?.cssKey&&Ce(a.current.cssKey),a.current=null,n(null)};if(!u||!l||h===null){f(),o(null),s("unpublished");return}let m=!1;return o(null),a.current&&a.current.componentId!==u&&f(),a.current||s("loading"),(async()=>{let _=null;try{let g=await nl(u,l,h);if(m)return;if(g.status!=="ready"){f(),s(g.status);return}let b=Po.get(l);if(!b){if(b=ko(g.script),!b)throw new Error("The published script did not hand over a component. Expected a __FSAOS_REGISTER__(Component) call or window.__FSAOS_COMPONENT__.");if(typeof b!="function")throw new Error(`The published script handed over something that is not a React component (${typeof b}).`);Po.set(l,b)}let y=g.stylesheet?`release:${l}`:null;if(y&&(_=y,await Mo(y,async()=>g.stylesheet)),m){_&&Ce(_);return}let v=a.current?.cssKey??null;a.current={componentId:u,releaseItemId:l,cssKey:y},_=null,n({Component:b,version:h}),s("ready"),v&&Ce(v)}catch(g){if(_&&Ce(_),m)return;o(g instanceof Error?g:new Error(String(g))),a.current||s("error")}})(),()=>{m=!0}},[c,u,l,h]),(0,w.useEffect)(()=>()=>{a.current?.cssKey&&Ce(a.current.cssKey),a.current=null},[]),{Component:t?.Component??null,status:r,error:i,version:t?.version??null}}var lf=512*1024,Yr=new Map,Eo=new Map;ae(()=>{Yr.clear(),Eo.clear()});var il=(e,t)=>`${e}:${t.toLowerCase()}`;async function df(e){let t=await C("open",{id:e.fileId,mode:"render",...e.scopePath?{_scope_path:e.scopePath}:{}}),n=We(We(t.render).props).url;if(t.item_id!==e.fileId||t.item_type!=="file"||typeof n!="string"||!n)throw new Error("The compiled build could not be opened.");let r=await fetch(n,{credentials:"omit",referrerPolicy:"no-referrer"});if(!r.ok)throw new Error(`Failed to read the compiled build: ${r.status} ${r.statusText}`.trim());let s=await r.arrayBuffer();if(s.byteLength>lf)throw new Error("The compiled build is too large to run.");if(Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256",s))).map(d=>d.toString(16).padStart(2,"0")).join("")!==e.sha256.toLowerCase())throw new Error("The compiled build does not match the bytes it was shown with.");let o;try{o=JSON.parse(new TextDecoder().decode(s))}catch{throw new Error("The compiled build is not a build file.")}let{js:a,css:c,scope:u}=We(o);if(typeof a!="string"||!a||c!=null&&typeof c!="string"||u!=null&&(typeof u!="string"||!/^[A-Za-z0-9_-]{1,64}$/.test(u)))throw new Error("The compiled build is not a build file.");return{script:a,stylesheet:typeof c=="string"&&c.trim()?c:null,scopeClass:typeof u=="string"?`fsaos-c-${u}`:null}}function Fo(e){if(!e.fileId||!/^[0-9a-f]{64}$/i.test(e.sha256||""))return Promise.reject(new Error("A compiled build is named by its file and the SHA-256 of its bytes."));let t=il(e.fileId,e.sha256),n=Yr.get(t);return n||(n=df(e),Yr.set(t,n),n.catch(()=>{Yr.get(t)===n&&Yr.delete(t)})),n}function ol(e){let[t,n]=(0,w.useState)(null),[r,s]=(0,w.useState)("loading"),[i,o]=(0,w.useState)(null),a=(0,w.useRef)(null),c=e?.fileId||null,u=e?.sha256||null,d=e?.scopePath;return(0,w.useEffect)(()=>{if(!c||!u){a.current?.cssKey&&Ce(a.current.cssKey),a.current=null,n(null),o(null),s("loading");return}let l=il(c,u);if(a.current?.key===l)return;let h=!1;return o(null),a.current||s("loading"),(async()=>{let f=null;try{let m=await Fo({fileId:c,sha256:u,scopePath:d});if(h)return;let _=Eo.get(l);if(!_){if(_=ko(m.script),!_)throw new Error("The compiled build did not hand over a component. Expected window.__FSAOS_COMPONENT__ (what the compile emits) or a __FSAOS_REGISTER__(Component) call.");if(typeof _!="function")throw new Error(`The compiled build handed over something that is not a React component (${typeof _}).`);Eo.set(l,_)}let g=m.stylesheet?`compiled:${l}`:null;if(g&&(f=g,await Mo(g,async()=>m.stylesheet)),h){f&&Ce(f);return}let b=a.current?.cssKey??null;a.current={key:l,cssKey:g},f=null,n({Component:_,key:l,scopeClass:m.scopeClass}),s("ready"),b&&Ce(b)}catch(m){if(f&&Ce(f),h)return;o(m instanceof Error?m:new Error(String(m))),a.current||s("error")}})(),()=>{h=!0}},[c,u,d]),(0,w.useEffect)(()=>()=>{a.current?.cssKey&&Ce(a.current.cssKey),a.current=null},[]),{Component:t?.Component??null,scopeClass:t?.scopeClass??null,status:r,error:i}}var pf=["--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 al(){return{data:(0,w.useMemo)(()=>{if(typeof document>"u")return{tokens:{}};let t={},n=getComputedStyle(document.documentElement);return pf.forEach(r=>{t[r]=n.getPropertyValue(r).trim()}),{tokens:t}},[]),loading:!1,error:null}}var be=null,or=null,Io=new Set;function ff(){Io.forEach(e=>e())}ae(()=>{be=null,or=null});async function cl(e){let t={principalId:null,displayName:null,createdAt:null,metadata:null,vfsPath:null},n=nt()?.principal_id??null;if(n){if(be&&be.principalId===n){let{principalId:s,displayName:i,createdAt:o,metadata:a,vfsPath:c}=be;return{principalId:s,displayName:i,createdAt:o,metadata:a,vfsPath:c}}return{...t,principalId:n}}let r=e;if(!r){let{data:s}=await G.auth.getSession();r=s?.session?.user?.id}if(!r)return t;if(be&&be.authUserId===r){let{principalId:s,displayName:i,createdAt:o,metadata:a,vfsPath:c}=be;return{principalId:s,displayName:i,createdAt:o,metadata:a,vfsPath:c}}return or||(or=(async()=>{try{let{data:s,error:i}=await G.from("os_principals").select("id, display_name, created_at, metadata").eq("auth_user_id",r).eq("principal_type","user").maybeSingle();if(i)return console.warn("[SDK] Could not resolve principal:",i.message),t;let o=s?.id??null,a=null;if(o){let{data:u}=await G.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(l=>l.path);a=d.find(l=>l.split("/").length===4)??d[0]??null}let c={principalId:o,displayName:s?.display_name??null,createdAt:s?.created_at??null,metadata:s?.metadata??null,vfsPath:a};return be={authUserId:r,...c},c}finally{or=null}})(),or)}async function ul(e){return(await cl(e)).principalId}function ll(){let e=ci(),t=e.user,n=be?.authUserId===t?.id?be:null,[r,s]=(0,w.useState)(n),i=(0,w.useRef)(null);return(0,w.useEffect)(()=>{let o=()=>{let a=be;a&&a.authUserId===t?.id&&s({principalId:a.principalId,displayName:a.displayName,createdAt:a.createdAt,metadata:a.metadata,vfsPath:a.vfsPath})};return Io.add(o),()=>{Io.delete(o)}},[t?.id]),(0,w.useEffect)(()=>{if(!t?.id){s(null),i.current=null;return}i.current===t.id&&r?.principalId!=null||(i.current=t.id,cl(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 dl(e){let{path:t,...n}=e,r=Oo(t),s=r.Component,{loading:i,error:o}=r;return i?(0,w.createElement)("div",{className:"fsaos-loading"},""):o?(0,w.createElement)("div",{className:"fsaos-error"},"Failed to load component"):s?(0,w.createElement)(s,n):null}function pl(e){return e.children}function fl(e){let t=re(),{channelPath:n,parentMessageId:r,realtime:s=!0,enabled:i}=e,o=i!==void 0?i&&!!n:!!n,a=(0,w.useMemo)(()=>T.channelMessages(n??"",r),[n,r,t]),c=U(),u=(0,w.useRef)(null),d=$({queryKey:a,queryFn:()=>Ys(n,r),enabled:o});(0,w.useEffect)(()=>{if(!s||!o)return;let _=X("vfs_change",()=>{u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{ce(c,a,{exact:!0})},500)},g=>{let b=c.getQueryData(a);return ir(g,n,r,[...b?.messages??[],...b?.activityMessages??[]])});return()=>{_(),u.current&&clearTimeout(u.current)}},[s,o,n,r,a,c]);let l=d.data,h=l?.messages??[],f=l?.messageCards??new Map,m=l?.siblingCards??[];return{messages:h,activityMessages:l?.activityMessages??[],messageCards:f,siblingCards:m,threads:(0,w.useMemo)(()=>h.filter(_=>_.reply_count>0),[h]),breakouts:(0,w.useMemo)(()=>h.filter(_=>_.member_count>0),[h]),isLoading:d.isLoading,isFetching:d.isFetching,error:d.error,refetch:d.refetch}}function ml(e){let t=re(),{channelPath:n,messageId:r,conversationRootId:s,enabled:i=!0,realtime:o=!0,limit:a=25}=e,c=i&&!!n&&!!r,u=(0,w.useMemo)(()=>T.messageReplies(n??"",r,s,a),[n,r,s,a,t]),d=U(),l=Fn({queryKey:u,queryFn:({pageParam:f})=>Js(r,{limit:a,conversationRootId:s,cursor:f}),initialPageParam:void 0,getNextPageParam:f=>f.next_cursor??void 0,enabled:c,staleTime:1/0,refetchOnMount:"always",refetchOnWindowFocus:!1,retry:!1});(0,w.useEffect)(()=>c&&o?xu(d,u,r):void 0,[c,o,d,u,r]);let h=(0,w.useMemo)(()=>{if(!c||l.isError)return[];let f=new Set;return(l.data?.pages??[]).flatMap(m=>m.messages).filter(m=>f.has(m.id)?!1:(f.add(m.id),!0))},[c,l.data,l.isError]);return{...l,messages:h}}function gl(e){let t=re(),{channelPath:n,parentMessageId:r,limit:s=50,realtime:i=!0,enabled:o=!0,conversationsOnly:a=!1,transcriptOnly:c=!1}=e,u=!!r,d=o&&!!n,l=Fn({queryKey:[...T.channelMessages(n||"",r),"infinite",s,"latest-first",...a?["conversations"]:[],...c?["transcript"]:[]],queryFn:async({pageParam:y})=>{let v=await an(n,{parentMessageId:r,limit:s,conversationsOnly:a,transcriptOnly:c,before_seq:y?.before_seq,after_seq:y?.after_seq});return c&&v.messages.length>=s?{...v,olderBefore:v.messages[0]?.seq}:v},initialPageParam:void 0,getPreviousPageParam:y=>{if(!u||y.messages.length<s)return;let v=y.messages[y.messages.length-1]?.seq;return v==null?void 0:{after_seq:v}},getNextPageParam:y=>{if(c)return y.olderBefore==null?void 0:{before_seq:y.olderBefore};if(y.messages.length<s)return;let v=y.messages[0]?.seq;return v==null?void 0:{before_seq:v}},enabled:d}),h=(0,w.useMemo)(()=>{if(!l.data?.pages)return[];let y=new Set,v=[];for(let x of l.data.pages)for(let R of x.messages)y.has(R.id)||(y.add(R.id),v.push(R));return v.sort((x,R)=>x.seq-R.seq)},[l.data?.pages]),{messageCards:f,siblingCards:m}=(0,w.useMemo)(()=>{let y=new Map,v=[];if(!l.data?.pages)return{messageCards:y,siblingCards:v};let x=new Set;for(let[R,k]of l.data.pages.entries()){let O=c&&R>0?new Set(k.messages.map(P=>P.path)):null;for(let[P,A]of k.messageCards)if(!(O&&!O.has(P)))for(let M of A){if(x.has(M.id))continue;x.add(M.id);let I=y.get(P)||[];I.push(M),y.set(P,I)}if(!(c&&R>0))for(let P of k.siblingCards)x.has(P.id)||(x.add(P.id),v.push(P))}return{messageCards:y,siblingCards:v}},[l.data?.pages,c]),_=U(),g=(0,w.useRef)(null),b=(0,w.useMemo)(()=>[...T.channelMessages(n||"",r),"infinite",s,"latest-first",...a?["conversations"]:[],...c?["transcript"]:[]],[n,r,s,a,c,t]);return(0,w.useEffect)(()=>{if(!i||!n||!d)return;if(c)return bu(_,b,n,s);let y=()=>void ce(_,b,{exact:!0}),v=!1,x=!1,R=!1,k=async()=>{if(a){y();return}let A=_.getQueryData(b);if(!A?.pages?.length){y();return}let M=0;for(let I of A.pages)for(let F of I.messages)F.seq>M&&(M=F.seq);if(M===0){y();return}try{let I=await an(n,{parentMessageId:r,limit:s,after_seq:M});if(I.messages.length===0&&I.siblingCards.length===0){y();return}if(I.messages.length>0){let F=Math.min(...I.messages.map(Q=>Q.seq));if(F>M+1){console.warn(`[useInfiniteChannelMessages] sequence gap detected: maxSeq=${M}, minNewSeq=${F}. Triggering full refetch.`),y();return}}_.setQueryData(b,F=>{if(!F)return F;let Q=[...F.pages],K=0,B=Q[K],Qe=new Set(B.messages.map(ye=>ye.id)),j=I.messages.filter(ye=>!Qe.has(ye.id)),he=[...B.messages,...j].sort((ye,hi)=>ye.seq-hi.seq),ve=new Map(B.messageCards);for(let[ye,hi]of I.messageCards){let Zo=ve.get(ye)||[],Od=new Set(Zo.map(yi=>yi.id)),Fd=hi.filter(yi=>!Od.has(yi.id));ve.set(ye,[...Zo,...Fd])}let je=new Set(B.siblingCards.map(ye=>ye.id)),de=I.siblingCards.filter(ye=>!je.has(ye.id)),me=[...B.siblingCards,...de];return Q[K]={...B,activityMessages:I.activityMessages??[],messages:he,messageCards:ve,siblingCards:me},{...F,pages:Q}})}catch(I){console.warn("[useInfiniteChannelMessages] live tail fetch failed, falling back to full invalidation:",I),y()}},O=async()=>{if(v){x=!0;return}v=!0;try{do x=!1,await k();while(x&&!R)}finally{v=!1}},P=X("vfs_change",()=>{g.current&&clearTimeout(g.current),g.current=setTimeout(()=>{O()},500)},A=>a&&A?.item_type==="message"&&(_.getQueryData(b)?.pages??[]).some(M=>M.messages.some(I=>I.id===A.parent_id))||ir(A,n,r,_.getQueryData(b)?.pages.flatMap(M=>M.messages)??[]));return()=>{R=!0,P(),g.current&&clearTimeout(g.current)}},[i,n,d,b,_,r,s,a,c]),{messages:h,activityMessages:l.data?.pages[0]?.activityMessages??[],messageCards:f,siblingCards:m,threads:h.filter(y=>y.reply_count>0),breakouts:h.filter(y=>y.member_count>0),isLoading:l.isLoading,isFetching:l.isFetching,error:l.error,refetch:l.refetch,hasPreviousPage:l.hasNextPage??!1,fetchPreviousPage:l.fetchNextPage,isFetchingPreviousPage:l.isFetchingNextPage??!1,hasNextPage:l.hasPreviousPage??!1,fetchNextPage:l.fetchPreviousPage,isFetchingNextPage:l.isFetchingPreviousPage??!1}}var hl=["open","active","strict","hand_raise"];function mf(e){return e==="open"||e==="active"||e==="strict"||e==="hand_raise"?e:e==="on"||e==="auto"?"active":"strict"}function gf(e){if(Array.isArray(e))return e.filter(t=>typeof t=="string")}function Au(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:mf(t.ai_mode),activeAgentIds:gf(t.active_agent_ids),isPrivate:t.is_private||!1,isDm:t.is_dm||!1,messageCount:t.message_count||0,createdAt:e.created_at||"",updatedAt:e.updated_at||"",chatScopePath:r.context_path||"",contextId:e.scope_item_id||"",contextPath:r.context_path||"",contextType:r.context_type||"",contextName:r.context_name||"",contextDisplayName:r.context_name||"",contextPrincipalId:void 0,accountId:e.account_item_id||"",accountPath:"",accountDisplayName:"",memberRole:n.member_role||"member",memberPath:"",modePath:"",autoPilot:t.auto_pilot||!1,isArchived:t.is_archived===!0}}function ui(e={}){let t=re(),{realtime:n=!0,enabled:r=!0,includeArchived:s=!1}=e,i=U(),o=(0,w.useMemo)(()=>T.channels("all"),[t]),a=$({queryKey:o,queryFn:async()=>((await C("query",{item_type:"channel",include_reader:!0,limit:500})).items||[]).map(Au),enabled:r});return(0,w.useEffect)(()=>{if(!(!n||!r))return wu(i,o,Au)},[n,r,o,i]),{channels:(0,w.useMemo)(()=>(a.data??[]).filter(u=>s||!u.isArchived),[a.data,s]),isLoading:a.isLoading,isFetching:a.isFetching,error:a.error,refetch:a.refetch}}function yl(e={}){let t=ui(e),n=(0,w.useMemo)(()=>t.channels.filter(r=>!r.isDm),[t.channels]);return{...t,channels:n}}function _l(e={}){let t=ui(e),n=(0,w.useMemo)(()=>t.channels.filter(r=>r.isDm),[t.channels]);return{...t,channels:n}}function qo(e={}){let t=re(),{filter:n="all",limit:r=200,realtime:s=!0,enabled:i=!0}=e,o=U(),a=(0,w.useRef)(null),c=(0,w.useMemo)(()=>T.notifications(n,r),[n,r,t]),u=$({queryKey:c,queryFn:async()=>{let l={limit:r};return n==="unread"&&(l.filter="unread"),(await C("get-notifications",l)).notifications||[]},enabled:i});return(0,w.useEffect)(()=>{if(!s||!i)return;let l=["vfs_change","ccm_change"].map(h=>X(h,()=>{a.current&&clearTimeout(a.current),a.current=setTimeout(()=>{o.invalidateQueries({queryKey:c})},2e3)},f=>f.item_type==="notification"&&ri(f)));return()=>{l.forEach(h=>h()),a.current&&clearTimeout(a.current)}},[s,i,c,o]),{notifications:u.data??[],isLoading:u.isLoading,isFetching:u.isFetching,error:u.error,refetch:u.refetch}}function bl(e={}){let{channels:t,realtime:n=!0,enabled:r=!0}=e,{notifications:s,isLoading:i,isFetching:o,error:a,refetch:c}=qo({filter:"unread",limit:200,realtime:n,enabled:r}),u=(0,w.useMemo)(()=>{let f=new Map;for(let m of s)m.is_unread&&m.channel_id&&f.set(m.channel_id,(f.get(m.channel_id)||0)+1);return f},[s]),d=(0,w.useMemo)(()=>{let f=0;return u.forEach(m=>{f+=m}),f},[u]),{dmUnread:l,channelUnread:h}=(0,w.useMemo)(()=>{if(!t)return{dmUnread:0,channelUnread:0};let f=new Set(t.filter(g=>g.isDm).map(g=>g.id)),m=0,_=0;return u.forEach((g,b)=>{f.has(b)?m+=g:_+=g}),{dmUnread:m,channelUnread:_}},[t,u]);return{unreadByChannel:u,totalUnread:d,dmUnread:l,channelUnread:h,isLoading:i,isFetching:o,error:a,refetch:c}}function vl(){let e=U();return oe({mutationFn:t=>C("create",t),onSuccess:(t,n)=>{let r=n.parent_path;r&&e.invalidateQueries({queryKey:T.children(r)})}})}function wl(){let e=U();return oe({mutationFn:t=>C("update",t),onSuccess:(t,n)=>{let r=n.path;if(r){e.invalidateQueries({queryKey:T.item(r)});let s=r.split("/");s.pop();let i=s.join("/");i&&e.invalidateQueries({queryKey:T.children(i)})}}})}function Sl(){return oe({mutationFn:e=>C("update-principal",e),onSuccess:(e,t)=>{if(!be)return;let n=e&&typeof e=="object"&&e.metadata?e.metadata:{...be.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}:{}};be={...be,displayName:typeof t.display_name=="string"?t.display_name:be.displayName,metadata:n},ff()}})}function xl(){let e=U();return oe({mutationFn:t=>C("delete",t),onSuccess:(t,n)=>{let r=n.path;if(r){e.removeQueries({queryKey:T.item(r)});let s=r.split("/");s.pop();let i=s.join("/");i&&e.invalidateQueries({queryKey:T.children(i)})}}})}function Rl(){let e=U();return oe({mutationFn:t=>C("move",t),onSuccess:(t,n)=>{let r=n.path,s=n.new_parent_path;if(r){e.invalidateQueries({queryKey:T.item(r)});let i=r.split("/");i.pop();let o=i.join("/");o&&e.invalidateQueries({queryKey:T.children(o)})}s&&e.invalidateQueries({queryKey:T.children(s)})}})}function Cl(){let e=U();return oe({mutationFn:t=>C("link",t),onSuccess:(t,n)=>{let r=n.source_id,s=n.target_id;r&&e.invalidateQueries({queryKey:T.edges(r)}),s&&e.invalidateQueries({queryKey:T.edges(s)})}})}function Pl(e,t){let n=U(),{optimistic:r,...s}=t??{};return oe({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,a=>r.update(a,i)),{previous:o}}:void 0,onError:(i,o,a)=>{r&&a?.previous!==void 0&&n.setQueryData(r.queryKey,a.previous),s.onError?.(i)},onSuccess:s.onSuccess,onSettled:r?()=>{n.invalidateQueries({queryKey:r.queryKey})}:void 0})}function El(e,t,n){let r,s,i,o=!0;if(typeof e=="string")r=e,s=t,i=n;else{s=e;let u=t;r=u.eventType,i=u.filter,o=u.enabled??!0}let a=(0,w.useRef)(s),c=(0,w.useRef)(i);(0,w.useEffect)(()=>{a.current=s,c.current=i},[s,i]),(0,w.useEffect)(()=>o?X(r,d=>a.current(d),c.current?d=>c.current(d):void 0):void 0,[r,o])}function Il(e){let{queryKey:t,queryFn:n,eventType:r,filter:s,enabled:i=!0,debounceMs:o=500}=e,a=U(),c=(0,w.useRef)(s);c.current=s;let u=(0,w.useRef)(null),d=$({queryKey:t,queryFn:n,enabled:i});return(0,w.useEffect)(()=>{if(!i)return;let l=X(r,()=>{u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{ce(a,t,{exact:!0})},o)},h=>c.current?.(h)??!0);return()=>{l(),u.current&&clearTimeout(u.current)}},[r,i,o,a,JSON.stringify(t)]),d}function ar(e){re();let t=z(),n=(0,w.useMemo)(()=>e?typeof e=="string"?{path:e}:e:null,[typeof e=="string"?e:JSON.stringify(e)]),r=n?._scope_path??t,s=!!t&&!!r&&!!n&&!!(n.key||n.path||n.item_id),i=n?.key??n?.path??n?.item_id??"",o=["vfs",r??"__unscoped__","arrangement",i,n?.scope_id??""],a=$({queryKey:o,staleTime:1/0,retry:!1,meta:{arrangementRealtime:!0},queryFn:async()=>{if(!n)return null;let f=await C("resolve-arrangement",{...n,_scope_path:r});if(f?.success===!1)throw new Error(f?.error||"Arrangement could not be loaded");return f??null},enabled:s}),c=a.data??null,u=(0,w.useMemo)(()=>c?.resolved_children??[],[c]),d=c?.resolution_level??null,l=(0,w.useMemo)(()=>{let m=(c?.type_data??null)?.order;return Array.isArray(m)?m:null},[c]),h=(0,w.useCallback)(f=>{if(!l||!f?.length)return f??[];let m=y=>y.id??y.name??"",_=new Map(l.map((y,v)=>[y,v])),g=[],b=[];for(let y of f)(_.has(m(y))?g:b).push(y);return g.sort((y,v)=>_.get(m(y))-_.get(m(v))),[...g,...b]},[l]);return{...a,arrangement:c,resolvedChildren:u,resolutionLevel:d,order:l,sourceScopeId:c?.scope_item_id??null,arrangementQueryKey:o,applyTo:h}}function Tl(e){let{origin:t,originField:n,fallbackUrl:r,mintError:s,scopeId:i,scopePath:o}=e,a=re(),c=nt(),u=i??c?.scope_id??null,d=(0,w.useMemo)(()=>{if(!t)return null;let R="/accounts/",k=t.indexOf(R);if(k===-1)return null;let O=t.indexOf("/",k+R.length);return O===-1?t:t.slice(0,O)},[t]),l=o??d??c?.scope_path??null,h=n?.trim()||null,f=`${a}
|
|
4
|
-
|
|
1
|
+
/* @fsaos/gateway v2.0.0 — Unified FSAOS Edge Runtime — 2026-11-23T22:33:50.339Z */
|
|
2
|
+
"use strict";var __FSAOS_GATEWAY__=(()=>{var np=Object.create;var dr=Object.defineProperty;var rp=Object.getOwnPropertyDescriptor;var sp=Object.getOwnPropertyNames;var ip=Object.getPrototypeOf,op=Object.prototype.hasOwnProperty;var aa=e=>{throw TypeError(e)};var ap=(e,t,n)=>t in e?dr(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var pr=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),ca=(e,t)=>{for(var n in t)dr(e,n,{get:t[n],enumerable:!0})},ua=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of sp(t))!op.call(e,s)&&s!==n&&dr(e,s,{get:()=>t[s],enumerable:!(r=rp(t,s))||r.enumerable});return e};var J=(e,t,n)=>(n=e!=null?np(ip(e)):{},ua(t||!e||!e.__esModule?dr(n,"default",{value:e,enumerable:!0}):n,e)),cp=e=>ua(dr({},"__esModule",{value:!0}),e);var te=(e,t,n)=>ap(e,typeof t!="symbol"?t+"":t,n),Si=(e,t,n)=>t.has(e)||aa("Cannot "+n);var f=(e,t,n)=>(Si(e,t,"read from private field"),n?n.call(e):t.get(e)),T=(e,t,n)=>t.has(e)?aa("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),R=(e,t,n,r)=>(Si(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n),q=(e,t,n)=>(Si(e,t,"access private method"),n);var fr=(e,t,n,r)=>({set _(s){R(e,t,s,n)},get _(){return f(e,t,r)}});var ue=pr((dm,la)=>{la.exports=React});var fs=pr((gg,Va)=>{Va.exports={jsx:React.createElement,jsxs:React.createElement,Fragment:React.Fragment}});var Xa=pr((ty,Ya)=>{Ya.exports={createClient:window.supabase.createClient}});var Ec=pr((by,Pc)=>{Pc.exports=ReactDOM});var md=pr((Lb,fd)=>{fd.exports=ReactDOM});var ia={};ca(ia,{CHANNEL_AI_MODES:()=>kl,ComponentRenderer:()=>El,EnforcementDeniedError:()=>De,FormSubmissionError:()=>cr,GatewayRequestError:()=>ve,HostSessionUnavailableError:()=>Zt,InteractionTrackingError:()=>or,KernelProvider:()=>Il,QueryClientProvider:()=>Tr,acceptInvitation:()=>Wf,acceptInvite:()=>Vo,answerInput:()=>zo,assignPersonalSection:()=>zd,auth:()=>Rd,awaitAnchorReady:()=>qr,awaitScopeReady:()=>uc,callTool:()=>wd,cancelInvitation:()=>zf,cancelQueuedTurn:()=>ad,cancelTurn:()=>id,clearCachedToken:()=>to,clearSession:()=>co,configureGatewayReads:()=>wc,connectHostSession:()=>dc,createAgent:()=>Go,createFileUpload:()=>ea,createInvitation:()=>$f,createItem:()=>_d,disconnectSSE:()=>wo,disposeVfsRealtimeWs:()=>Ro,electHomeAnchor:()=>Yt,emitEvent:()=>Xc,fetchChannelMessages:()=>du,fetchChannelMessagesPage:()=>sn,fetchChannelMessagesWithCards:()=>Ys,fetchEdgesForItem:()=>$s,fetchItemHistory:()=>Gs,fetchItemVersions:()=>Hr,fetchItems:()=>rn,fetchMemberFocus:()=>zs,fetchMessageReplies:()=>Js,fetchMessageReplyContexts:()=>uu,fetchOpenEnvelope:()=>$r,fetchRecentActivity:()=>Ws,fetchResolvedItems:()=>ta,fetchTimelineHistory:()=>na,fetchTurnQueueEntries:()=>iu,fetchTypeDefinitions:()=>Hs,fetchVfsChildren:()=>jr,fetchVfsChildrenPage:()=>js,fetchVfsItem:()=>Br,fetchVfsItemById:()=>Lr,fetchVfsTree:()=>Vs,filePurchaseNextUrl:()=>pd,funnelCheckoutLink:()=>dd,gatewayCall:()=>P,getAccessToken:()=>dt,getAnchor:()=>Ie,getAnchorRef:()=>pe,getAnchorVersion:()=>so,getAssetUrl:()=>xd,getDefaultSort:()=>Od,getFilePurchase:()=>ld,getHomeAnchor:()=>_e,getInvitation:()=>Vf,getMountVersion:()=>At,getMounts:()=>Ce,getPathSubscriptionState:()=>eu,getQueryClient:()=>N,getRequiredFormFields:()=>Fd,getScope:()=>z,getScopeVersion:()=>W,getServerClockOffsetMs:()=>gc,getServerClockSyncedAt:()=>yc,getSessionEntry:()=>Ze,hasServerClock:()=>hc,initSession:()=>pt,initVfsRealtimeWs:()=>on,initializeFsaos:()=>rd,initializeWorkspace:()=>hi,interpretSchema:()=>Jo,invalidateAllVfs:()=>mu,invalidateChannelMessages:()=>gu,invalidateChildren:()=>Bs,invalidateItem:()=>So,invalidateOpenEnvelope:()=>yu,invalidatePathAndParent:()=>pu,invalidateSubtree:()=>fu,invalidateTypes:()=>hu,inviteMember:()=>$o,isAnchorReady:()=>oo,isChannelPath:()=>se,isListableItemsFilter:()=>Zn,isScopeReady:()=>Cs,itemsFilterFromQueryFilter:()=>ou,listChildren:()=>yd,listInvitations:()=>Yf,loadCompiledBundle:()=>Do,loadMounts:()=>an,loadPublishedBundle:()=>gl,mount:()=>Cd,mountRealtimeScope:()=>tr,normalizeItem:()=>Ne,onConnectionStateChange:()=>Ls,pathSubscriptionMatches:()=>_o,personalSectionsKey:()=>rs,ping:()=>Zc,pushChanges:()=>vd,queryClient:()=>Dc,readItem:()=>gd,refreshQuery:()=>ce,registerCleanup:()=>oe,rejectInvitation:()=>Gf,replaceMounts:()=>ii,resendInvitation:()=>Jf,resetAllSdkState:()=>jn,resolvePrincipalId:()=>Cl,resubscribePath:()=>nu,seatMember:()=>Wo,selectMount:()=>Jr,sendMessage:()=>cu,serveHostSession:()=>sd,serverDeadlinePassed:()=>_c,serverMsUntil:()=>bc,serverNow:()=>Is,setAnchor:()=>Kn,setCachedToken:()=>tc,setQueryClient:()=>Qc,setScope:()=>cc,setupRequireShim:()=>Pd,signal:()=>Sd,startFileCheckout:()=>ud,startTracking:()=>mi,steerTurn:()=>od,submitForm:()=>cd,subscribeAnchor:()=>io,subscribeArtifactStream:()=>yi,subscribeMounts:()=>Ln,subscribeScope:()=>be,subscribeToEvents:()=>X,subscribeToPath:()=>Ks,subscribeToScope:()=>Yn,trackAction:()=>ed,trackEvent:()=>un,trackPageView:()=>Zl,unmountRealtimeScope:()=>ri,updateItem:()=>bd,uploadFile:()=>Ld,useAcceptInvite:()=>Id,useAccounts:()=>il,useAgentTimeline:()=>Vd,useAllChannels:()=>pi,useAnswerInput:()=>Md,useArrangement:()=>ir,useArtifactStream:()=>$d,useAsset:()=>al,useAuth:()=>di,useChannelMessages:()=>Tl,useChannels:()=>Ol,useChildren:()=>ju,useCompiledComponent:()=>Sl,useComponent:()=>Qo,useCreate:()=>Nl,useCreateAgent:()=>Ad,useDelete:()=>Ul,useDmChannels:()=>Fl,useEdges:()=>Ju,useEventStream:()=>jl,useFileUpload:()=>Bd,useIncrementalItems:()=>Gu,useInfiniteChannelMessages:()=>Ml,useInfiniteChildren:()=>zu,useInfiniteItems:()=>Oo,useInviteMember:()=>Ed,useItem:()=>Lu,useItemById:()=>Bu,useItemHistory:()=>nl,useItemVersions:()=>tl,useItems:()=>Wu,useLink:()=>Ll,useList:()=>ko,useMemberFocus:()=>el,useMessageReplies:()=>Al,useMintedAsset:()=>$l,useMounts:()=>ol,useMove:()=>Kl,useMutation:()=>Bl,useNotifications:()=>Uo,useOpen:()=>Xu,usePermission:()=>Ao,usePermissions:()=>ci,usePersonalItemOrder:()=>Wl,usePersonalSections:()=>Yd,usePinnedItems:()=>Gd,usePrincipal:()=>Pl,usePublishedComponent:()=>_l,useRealtimeQuery:()=>Hl,useRecentActivity:()=>rl,useResolve:()=>Vu,useResolvedItems:()=>Hd,useScope:()=>sl,useScopeReady:()=>Ku,useSearch:()=>$u,useSeatMember:()=>Td,useTheme:()=>xl,useTimelineHistory:()=>Wd,useTree:()=>Hu,useType:()=>Yu,useTypeHelpers:()=>Zu,useTypes:()=>li,useUnreadCounts:()=>ql,useUpdate:()=>Ql,useUpdatePrincipal:()=>Dl,vfsKeys:()=>k,waitForPathReady:()=>tu});var De=class e extends Error{constructor(n){let r=n.message||e.fallbackMessage(n);super(r);te(this,"name","EnforcementDeniedError");te(this,"deniedBy");te(this,"ruleKey");te(this,"displayName");te(this,"payload");this.payload=n,this.deniedBy=n.denied_by||n.error_type||n.error||"unknown";let s=n.enforcement;this.ruleKey=s?.rule_key??void 0,this.displayName=s?.display_name??void 0}static fallbackMessage(n){let r=n.error||"",s=n.denied_by||"";return s==="rule"||r==="RULE_DENIED"?"This feature is not enabled for this workspace.":s==="entitlement"||r==="ENTITLEMENT_REQUIRED"?"This feature requires a plan upgrade.":s==="access"||r==="ACCESS_DENIED"||r==="PERMISSION_DENIED"?"You don't have permission to do this.":"This action is not allowed."}get isRuleDenial(){return this.deniedBy==="rule"||this.deniedBy==="RULE_DENIED"}get isAccessDenial(){return this.deniedBy==="access"||this.deniedBy==="ACCESS_DENIED"}get isEntitlementDenial(){return this.deniedBy==="entitlement"||this.deniedBy==="ENTITLEMENT_REQUIRED"}};var qt=J(ue(),1);var we=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 Ut,yt,dn,da,up=(da=class extends we{constructor(){super();T(this,Ut);T(this,yt);T(this,dn);R(this,dn,t=>{if(typeof window<"u"&&window.addEventListener){let n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){f(this,yt)||this.setEventListener(f(this,dn))}onUnsubscribe(){var t;this.hasListeners()||((t=f(this,yt))==null||t.call(this),R(this,yt,void 0))}setEventListener(t){var n;R(this,dn,t),(n=f(this,yt))==null||n.call(this),R(this,yt,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){f(this,Ut)!==t&&(R(this,Ut,t),this.onFocus())}onFocus(){let t=this.isFocused();this.listeners.forEach(n=>{n(t)})}isFocused(){return typeof f(this,Ut)=="boolean"?f(this,Ut):globalThis.document?.visibilityState!=="hidden"}},Ut=new WeakMap,yt=new WeakMap,dn=new WeakMap,da),pn=new up;var lp={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},_t,xi,pa,dp=(pa=class{constructor(){T(this,_t,lp);T(this,xi,!1)}setTimeoutProvider(e){R(this,_t,e)}setTimeout(e,t){return f(this,_t).setTimeout(e,t)}clearTimeout(e){f(this,_t).clearTimeout(e)}setInterval(e,t){return f(this,_t).setInterval(e,t)}clearInterval(e){f(this,_t).clearInterval(e)}},_t=new WeakMap,xi=new WeakMap,pa),Ve=new dp;function fa(e){setTimeout(e,0)}var Ci=typeof window>"u"||"Deno"in globalThis;function Y(){}function ga(e,t){return typeof e=="function"?e(t):e}function mr(e){return typeof e=="number"&&e>=0&&e!==1/0}function ss(e,t){return Math.max(e+(t||0)-Date.now(),0)}function Ue(e,t){return typeof e=="function"?e(t):e}function Se(e,t){return typeof e=="function"?e(t):e}function is(e,t){let{type:n="all",exact:r,fetchStatus:s,predicate:i,queryKey:o,stale:a}=e;if(o){if(r){if(t.queryHash!==hr(o,t.options))return!1}else if(!Kt(t.queryKey,o))return!1}if(n!=="all"){let c=t.isActive();if(n==="active"&&!c||n==="inactive"&&c)return!1}return!(typeof a=="boolean"&&t.isStale()!==a||s&&s!==t.state.fetchStatus||i&&!i(t))}function os(e,t){let{exact:n,status:r,predicate:s,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(We(t.options.mutationKey)!==We(i))return!1}else if(!Kt(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||s&&!s(t))}function hr(e,t){return(t?.queryKeyHashFn||We)(e)}function We(e){return JSON.stringify(e,(t,n)=>Ri(n)?Object.keys(n).sort().reduce((r,s)=>(r[s]=n[s],r),{}):n)}function Kt(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>Kt(e[n],t[n])):!1}var pp=Object.prototype.hasOwnProperty;function gr(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=ma(e)&&ma(t);if(!r&&!(Ri(e)&&Ri(t)))return t;let i=(r?e:Object.keys(e)).length,o=r?t:Object.keys(t),a=o.length,c=r?new Array(a):{},l=0;for(let d=0;d<a;d++){let u=r?d:o[d],m=e[u],p=t[u];if(m===p){c[u]=m,(r?d<i:pp.call(e,u))&&l++;continue}if(m===null||p===null||typeof m!="object"||typeof p!="object"){c[u]=p;continue}let h=gr(m,p,n+1);c[u]=h,h===m&&l++}return i===a&&l===i?e:c}function bt(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 ma(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Ri(e){if(!ha(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!ha(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function ha(e){return Object.prototype.toString.call(e)==="[object Object]"}function ya(e){return new Promise(t=>{Ve.setTimeout(t,e)})}function yr(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?gr(e,t):t}function _a(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function ba(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var fn=Symbol();function as(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===fn?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function mn(e,t){return typeof e=="function"?e(...t):!!e}function va(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 Ge=(()=>{let e=()=>Ci;return{isServer(){return e()},setIsServer(t){e=t}}})();function _r(){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 wa=fa;function fp(){let e=[],t=0,n=a=>{a()},r=a=>{a()},s=wa,i=a=>{t?e.push(a):s(()=>{n(a)})},o=()=>{let a=e;e=[],a.length&&s(()=>{r(()=>{a.forEach(c=>{n(c)})})})};return{batch:a=>{let c;t++;try{c=a()}finally{t--,t||o()}return c},batchCalls:a=>(...c)=>{i(()=>{a(...c)})},schedule:i,setNotifyFunction:a=>{n=a},setBatchNotifyFunction:a=>{r=a},setScheduler:a=>{s=a}}}var L=fp();var hn,vt,gn,Sa,mp=(Sa=class extends we{constructor(){super();T(this,hn,!0);T(this,vt);T(this,gn);R(this,gn,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(){f(this,vt)||this.setEventListener(f(this,gn))}onUnsubscribe(){var t;this.hasListeners()||((t=f(this,vt))==null||t.call(this),R(this,vt,void 0))}setEventListener(t){var n;R(this,gn,t),(n=f(this,vt))==null||n.call(this),R(this,vt,t(this.setOnline.bind(this)))}setOnline(t){f(this,hn)!==t&&(R(this,hn,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return f(this,hn)}},hn=new WeakMap,vt=new WeakMap,gn=new WeakMap,Sa),yn=new mp;function hp(e){return Math.min(1e3*2**e,3e4)}function Pi(e){return(e??"online")==="online"?yn.isOnline():!0}var cs=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function us(e){let t=!1,n=0,r,s=_r(),i=()=>s.status!=="pending",o=g=>{if(!i()){let y=new cs(g);m(y),e.onCancel?.(y)}},a=()=>{t=!0},c=()=>{t=!1},l=()=>pn.isFocused()&&(e.networkMode==="always"||yn.isOnline())&&e.canRun(),d=()=>Pi(e.networkMode)&&e.canRun(),u=g=>{i()||(r?.(),s.resolve(g))},m=g=>{i()||(r?.(),s.reject(g))},p=()=>new Promise(g=>{r=y=>{(i()||l())&&g(y)},e.onPause?.()}).then(()=>{r=void 0,i()||e.onContinue?.()}),h=()=>{if(i())return;let g,y=n===0?e.initialPromise:void 0;try{g=y??e.fn()}catch(S){g=Promise.reject(S)}Promise.resolve(g).then(u).catch(S=>{if(i())return;let _=e.retry??(Ge.isServer()?0:3),w=e.retryDelay??hp,x=typeof w=="function"?w(n,S):w,b=_===!0||typeof _=="number"&&n<_||typeof _=="function"&&_(n,S);if(t||!b){m(S);return}n++,e.onFail?.(n,S),ya(x).then(()=>l()?void 0:p()).then(()=>{t?m(S):h()})})};return{promise:s,status:()=>s.status,cancel:o,continue:()=>(r?.(),s),cancelRetry:a,continueRetry:c,canStart:d,start:()=>(d()?h():p().then(h),s)}}var Lt,xa,ls=(xa=class{constructor(){T(this,Lt)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),mr(this.gcTime)&&R(this,Lt,Ve.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Ge.isServer()?1/0:5*60*1e3))}clearGcTimeout(){f(this,Lt)!==void 0&&(Ve.clearTimeout(f(this,Lt)),R(this,Lt,void 0))}},Lt=new WeakMap,xa);var Bt,_n,Me,jt,de,br,Ht,Pe,Ia,nt,Pa,Ea=(Pa=class extends ls{constructor(t){super();T(this,Pe);T(this,Bt);T(this,_n);T(this,Me);T(this,jt);T(this,de);T(this,br);T(this,Ht);R(this,Ht,!1),R(this,br,t.defaultOptions),this.setOptions(t.options),this.observers=[],R(this,jt,t.client),R(this,Me,f(this,jt).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,R(this,Bt,Ca(this.options)),this.state=t.state??f(this,Bt),this.scheduleGc()}get meta(){return this.options.meta}get promise(){return f(this,de)?.promise}setOptions(t){if(this.options={...f(this,br),...t},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let n=Ca(this.options);n.data!==void 0&&(this.setState(Ra(n.data,n.dataUpdatedAt)),R(this,Bt,n))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&f(this,Me).remove(this)}setData(t,n){let r=yr(this.state.data,t,this.options);return q(this,Pe,nt).call(this,{data:r,type:"success",dataUpdatedAt:n?.updatedAt,manual:n?.manual}),r}setState(t,n){q(this,Pe,nt).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){let n=f(this,de)?.promise;return f(this,de)?.cancel(t),n?n.then(Y).catch(Y):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return f(this,Bt)}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(t=>Se(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===fn||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>Ue(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:!ss(this.state.dataUpdatedAt,t)}onFocus(){this.observers.find(n=>n.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),f(this,de)?.continue()}onOnline(){this.observers.find(n=>n.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),f(this,de)?.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),f(this,Me).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(n=>n!==t),this.observers.length||(f(this,de)&&(f(this,Ht)||q(this,Pe,Ia).call(this)?f(this,de).cancel({revert:!0}):f(this,de).cancelRetry()),this.scheduleGc()),f(this,Me).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||q(this,Pe,nt).call(this,{type:"invalidate"})}async fetch(t,n){if(this.state.fetchStatus!=="idle"&&f(this,de)?.status()!=="rejected"){if(this.state.data!==void 0&&n?.cancelRefetch)this.cancel({silent:!0});else if(f(this,de))return f(this,de).continueRetry(),f(this,de).promise}if(t&&this.setOptions(t),!this.options.queryFn){let c=this.observers.find(l=>l.options.queryFn);c&&this.setOptions(c.options)}let r=new AbortController,s=c=>{Object.defineProperty(c,"signal",{enumerable:!0,get:()=>(R(this,Ht,!0),r.signal)})},i=()=>{let c=as(this.options,n),d=(()=>{let u={client:f(this,jt),queryKey:this.queryKey,meta:this.meta};return s(u),u})();return R(this,Ht,!1),this.options.persister?this.options.persister(c,d,this):c(d)},a=(()=>{let c={fetchOptions:n,options:this.options,queryKey:this.queryKey,client:f(this,jt),state:this.state,fetchFn:i};return s(c),c})();this.options.behavior?.onFetch(a,this),R(this,_n,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==a.fetchOptions?.meta)&&q(this,Pe,nt).call(this,{type:"fetch",meta:a.fetchOptions?.meta}),R(this,de,us({initialPromise:n?.initialPromise,fn:a.fetchFn,onCancel:c=>{c instanceof cs&&c.revert&&this.setState({...f(this,_n),fetchStatus:"idle"}),r.abort()},onFail:(c,l)=>{q(this,Pe,nt).call(this,{type:"failed",failureCount:c,error:l})},onPause:()=>{q(this,Pe,nt).call(this,{type:"pause"})},onContinue:()=>{q(this,Pe,nt).call(this,{type:"continue"})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0}));try{let c=await f(this,de).start();if(c===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(c),f(this,Me).config.onSuccess?.(c,this),f(this,Me).config.onSettled?.(c,this.state.error,this),c}catch(c){if(c instanceof cs){if(c.silent)return f(this,de).promise;if(c.revert){if(this.state.data===void 0)throw c;return this.state.data}}throw q(this,Pe,nt).call(this,{type:"error",error:c}),f(this,Me).config.onError?.(c,this),f(this,Me).config.onSettled?.(this.state.data,c,this),c}finally{this.scheduleGc()}}},Bt=new WeakMap,_n=new WeakMap,Me=new WeakMap,jt=new WeakMap,de=new WeakMap,br=new WeakMap,Ht=new WeakMap,Pe=new WeakSet,Ia=function(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"},nt=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,...Ei(r.data,this.options),fetchMeta:t.meta??null};case"success":let s={...r,...Ra(t.data,t.dataUpdatedAt),dataUpdateCount:r.dataUpdateCount+1,...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return R(this,_n,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()}),f(this,Me).notify({query:this,type:"updated",action:t})})},Pa);function Ei(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Pi(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function Ra(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function Ca(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 xe,K,wr,ye,$t,bn,rt,wt,Sr,vn,wn,Vt,Wt,St,Sn,$,vr,Ii,Ti,Ai,Mi,ki,Oi,Fi,ka,Ma,st=(Ma=class extends we{constructor(t,n){super();T(this,$);T(this,xe);T(this,K);T(this,wr);T(this,ye);T(this,$t);T(this,bn);T(this,rt);T(this,wt);T(this,Sr);T(this,vn);T(this,wn);T(this,Vt);T(this,Wt);T(this,St);T(this,Sn,new Set);this.options=n,R(this,xe,t),R(this,wt,null),R(this,rt,_r()),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(f(this,K).addObserver(this),Ta(f(this,K),this.options)?q(this,$,vr).call(this):this.updateResult(),q(this,$,Mi).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return qi(f(this,K),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return qi(f(this,K),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,q(this,$,ki).call(this),q(this,$,Oi).call(this),f(this,K).removeObserver(this)}setOptions(t){let n=this.options,r=f(this,K);if(this.options=f(this,xe).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof Se(this.options.enabled,f(this,K))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");q(this,$,Fi).call(this),f(this,K).setOptions(this.options),n._defaulted&&!bt(this.options,n)&&f(this,xe).getQueryCache().notify({type:"observerOptionsUpdated",query:f(this,K),observer:this});let s=this.hasListeners();s&&Aa(f(this,K),r,this.options,n)&&q(this,$,vr).call(this),this.updateResult(),s&&(f(this,K)!==r||Se(this.options.enabled,f(this,K))!==Se(n.enabled,f(this,K))||Ue(this.options.staleTime,f(this,K))!==Ue(n.staleTime,f(this,K)))&&q(this,$,Ii).call(this);let i=q(this,$,Ti).call(this);s&&(f(this,K)!==r||Se(this.options.enabled,f(this,K))!==Se(n.enabled,f(this,K))||i!==f(this,St))&&q(this,$,Ai).call(this,i)}getOptimisticResult(t){let n=f(this,xe).getQueryCache().build(f(this,xe),t),r=this.createResult(n,t);return yp(this,r)&&(R(this,ye,r),R(this,bn,this.options),R(this,$t,f(this,K).state)),r}getCurrentResult(){return f(this,ye)}trackResult(t,n){return new Proxy(t,{get:(r,s)=>(this.trackProp(s),n?.(s),s==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&f(this,rt).status==="pending"&&f(this,rt).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(r,s))})}trackProp(t){f(this,Sn).add(t)}getCurrentQuery(){return f(this,K)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){let n=f(this,xe).defaultQueryOptions(t),r=f(this,xe).getQueryCache().build(f(this,xe),n);return r.fetch().then(()=>this.createResult(r,n))}fetch(t){return q(this,$,vr).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),f(this,ye)))}createResult(t,n){let r=f(this,K),s=this.options,i=f(this,ye),o=f(this,$t),a=f(this,bn),l=t!==r?t.state:f(this,wr),{state:d}=t,u={...d},m=!1,p;if(n._optimisticResults){let A=this.hasListeners(),O=!A&&Ta(t,n),M=A&&Aa(t,r,n,s);(O||M)&&(u={...u,...Ei(d.data,t.options)}),n._optimisticResults==="isRestoring"&&(u.fetchStatus="idle")}let{error:h,errorUpdatedAt:g,status:y}=u;p=u.data;let S=!1;if(n.placeholderData!==void 0&&p===void 0&&y==="pending"){let A;i?.isPlaceholderData&&n.placeholderData===a?.placeholderData?(A=i.data,S=!0):A=typeof n.placeholderData=="function"?n.placeholderData(f(this,wn)?.state.data,f(this,wn)):n.placeholderData,A!==void 0&&(y="success",p=yr(i?.data,A,n),m=!0)}if(n.select&&p!==void 0&&!S)if(i&&p===o?.data&&n.select===f(this,Sr))p=f(this,vn);else try{R(this,Sr,n.select),p=n.select(p),p=yr(i?.data,p,n),R(this,vn,p),R(this,wt,null)}catch(A){R(this,wt,A)}f(this,wt)&&(h=f(this,wt),p=f(this,vn),g=Date.now(),y="error");let _=u.fetchStatus==="fetching",w=y==="pending",x=y==="error",b=w&&_,E=p!==void 0,C={status:y,fetchStatus:u.fetchStatus,isPending:w,isSuccess:y==="success",isError:x,isInitialLoading:b,isLoading:b,data:p,dataUpdatedAt:u.dataUpdatedAt,error:h,errorUpdatedAt:g,failureCount:u.fetchFailureCount,failureReason:u.fetchFailureReason,errorUpdateCount:u.errorUpdateCount,isFetched:t.isFetched(),isFetchedAfterMount:u.dataUpdateCount>l.dataUpdateCount||u.errorUpdateCount>l.errorUpdateCount,isFetching:_,isRefetching:_&&!w,isLoadingError:x&&!E,isPaused:u.fetchStatus==="paused",isPlaceholderData:m,isRefetchError:x&&E,isStale:Ni(t,n),refetch:this.refetch,promise:f(this,rt),isEnabled:Se(n.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){let A=C.data!==void 0,O=C.status==="error"&&!A,M=B=>{O?B.reject(C.error):A&&B.resolve(C.data)},F=()=>{let B=R(this,rt,C.promise=_r());M(B)},Q=f(this,rt);switch(Q.status){case"pending":t.queryHash===r.queryHash&&M(Q);break;case"fulfilled":(O||C.data!==Q.value)&&F();break;case"rejected":(!O||C.error!==Q.reason)&&F();break}}return C}updateResult(){let t=f(this,ye),n=this.createResult(f(this,K),this.options);if(R(this,$t,f(this,K).state),R(this,bn,this.options),f(this,$t).data!==void 0&&R(this,wn,f(this,K)),bt(n,t))return;R(this,ye,n);let r=()=>{if(!t)return!0;let{notifyOnChangeProps:s}=this.options,i=typeof s=="function"?s():s;if(i==="all"||!i&&!f(this,Sn).size)return!0;let o=new Set(i??f(this,Sn));return this.options.throwOnError&&o.add("error"),Object.keys(f(this,ye)).some(a=>{let c=a;return f(this,ye)[c]!==t[c]&&o.has(c)})};q(this,$,ka).call(this,{listeners:r()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&q(this,$,Mi).call(this)}},xe=new WeakMap,K=new WeakMap,wr=new WeakMap,ye=new WeakMap,$t=new WeakMap,bn=new WeakMap,rt=new WeakMap,wt=new WeakMap,Sr=new WeakMap,vn=new WeakMap,wn=new WeakMap,Vt=new WeakMap,Wt=new WeakMap,St=new WeakMap,Sn=new WeakMap,$=new WeakSet,vr=function(t){q(this,$,Fi).call(this);let n=f(this,K).fetch(this.options,t);return t?.throwOnError||(n=n.catch(Y)),n},Ii=function(){q(this,$,ki).call(this);let t=Ue(this.options.staleTime,f(this,K));if(Ge.isServer()||f(this,ye).isStale||!mr(t))return;let r=ss(f(this,ye).dataUpdatedAt,t)+1;R(this,Vt,Ve.setTimeout(()=>{f(this,ye).isStale||this.updateResult()},r))},Ti=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(f(this,K)):this.options.refetchInterval)??!1},Ai=function(t){q(this,$,Oi).call(this),R(this,St,t),!(Ge.isServer()||Se(this.options.enabled,f(this,K))===!1||!mr(f(this,St))||f(this,St)===0)&&R(this,Wt,Ve.setInterval(()=>{(this.options.refetchIntervalInBackground||pn.isFocused())&&q(this,$,vr).call(this)},f(this,St)))},Mi=function(){q(this,$,Ii).call(this),q(this,$,Ai).call(this,q(this,$,Ti).call(this))},ki=function(){f(this,Vt)!==void 0&&(Ve.clearTimeout(f(this,Vt)),R(this,Vt,void 0))},Oi=function(){f(this,Wt)!==void 0&&(Ve.clearInterval(f(this,Wt)),R(this,Wt,void 0))},Fi=function(){let t=f(this,xe).getQueryCache().build(f(this,xe),this.options);if(t===f(this,K))return;let n=f(this,K);R(this,K,t),R(this,wr,t.state),this.hasListeners()&&(n?.removeObserver(this),t.addObserver(this))},ka=function(t){L.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(f(this,ye))}),f(this,xe).getQueryCache().notify({query:f(this,K),type:"observerResultsUpdated"})})},Ma);function gp(e,t){return Se(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function Ta(e,t){return gp(e,t)||e.state.data!==void 0&&qi(e,t,t.refetchOnMount)}function qi(e,t,n){if(Se(t.enabled,e)!==!1&&Ue(t.staleTime,e)!=="static"){let r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&Ni(e,t)}return!1}function Aa(e,t,n,r){return(e!==t||Se(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&Ni(e,n)}function Ni(e,t){return Se(t.enabled,e)!==!1&&e.isStaleByTime(Ue(t.staleTime,e))}function yp(e,t){return!bt(e.getCurrentResult(),t)}function xn(e){return{onFetch:(t,n)=>{let r=t.options,s=t.fetchOptions?.meta?.fetchMore?.direction,i=t.state.data?.pages||[],o=t.state.data?.pageParams||[],a={pages:[],pageParams:[]},c=0,l=async()=>{let d=!1,u=h=>{va(h,()=>t.signal,()=>d=!0)},m=as(t.options,t.fetchOptions),p=async(h,g,y)=>{if(d)return Promise.reject();if(g==null&&h.pages.length)return Promise.resolve(h);let _=(()=>{let E={client:t.client,queryKey:t.queryKey,pageParam:g,direction:y?"backward":"forward",meta:t.options.meta};return u(E),E})(),w=await m(_),{maxPages:x}=t.options,b=y?ba:_a;return{pages:b(h.pages,w,x),pageParams:b(h.pageParams,g,x)}};if(s&&i.length){let h=s==="backward",g=h?Oa:Qi,y={pages:i,pageParams:o},S=g(r,y);a=await p(y,S,h)}else{let h=e??i.length;do{let g=c===0?o[0]??r.initialPageParam:Qi(r,a);if(c>0&&g==null)break;a=await p(a,g),c++}while(c<h)}return a};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 Qi(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 Oa(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function Fa(e,t){return t?Qi(e,t)!=null:!1}function qa(e,t){return!t||!e.getPreviousPageParam?!1:Oa(e,t)!=null}var Di=class extends st{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:xn()})}getOptimisticResult(e){return e.behavior=xn(),super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"forward"}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:"backward"}}})}createResult(e,t){let{state:n}=e,r=super.createResult(e,t),{isFetching:s,isRefetching:i,isError:o,isRefetchError:a}=r,c=n.fetchMeta?.fetchMore?.direction,l=o&&c==="forward",d=s&&c==="forward",u=o&&c==="backward",m=s&&c==="backward";return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:Fa(t,n.data),hasPreviousPage:qa(t,n.data),isFetchNextPageError:l,isFetchingNextPage:d,isFetchPreviousPageError:u,isFetchingPreviousPage:m,isRefetchError:a&&!l&&!u,isRefetching:i&&!d&&!m}}};var xr,ze,me,Gt,Je,xt,Na,Qa=(Na=class extends ls{constructor(t){super();T(this,Je);T(this,xr);T(this,ze);T(this,me);T(this,Gt);R(this,xr,t.client),this.mutationId=t.mutationId,R(this,me,t.mutationCache),R(this,ze,[]),this.state=t.state||Ui(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){f(this,ze).includes(t)||(f(this,ze).push(t),this.clearGcTimeout(),f(this,me).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){R(this,ze,f(this,ze).filter(n=>n!==t)),this.scheduleGc(),f(this,me).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){f(this,ze).length||(this.state.status==="pending"?this.scheduleGc():f(this,me).remove(this))}continue(){return f(this,Gt)?.continue()??this.execute(this.state.variables)}async execute(t){let n=()=>{q(this,Je,xt).call(this,{type:"continue"})},r={client:f(this,xr),meta:this.options.meta,mutationKey:this.options.mutationKey};R(this,Gt,us({fn:()=>this.options.mutationFn?this.options.mutationFn(t,r):Promise.reject(new Error("No mutationFn found")),onFail:(o,a)=>{q(this,Je,xt).call(this,{type:"failed",failureCount:o,error:a})},onPause:()=>{q(this,Je,xt).call(this,{type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>f(this,me).canRun(this)}));let s=this.state.status==="pending",i=!f(this,Gt).canStart();try{if(s)n();else{q(this,Je,xt).call(this,{type:"pending",variables:t,isPaused:i}),f(this,me).config.onMutate&&await f(this,me).config.onMutate(t,this,r);let a=await this.options.onMutate?.(t,r);a!==this.state.context&&q(this,Je,xt).call(this,{type:"pending",context:a,variables:t,isPaused:i})}let o=await f(this,Gt).start();return await f(this,me).config.onSuccess?.(o,t,this.state.context,this,r),await this.options.onSuccess?.(o,t,this.state.context,r),await f(this,me).config.onSettled?.(o,null,this.state.variables,this.state.context,this,r),await this.options.onSettled?.(o,null,t,this.state.context,r),q(this,Je,xt).call(this,{type:"success",data:o}),o}catch(o){try{await f(this,me).config.onError?.(o,t,this.state.context,this,r)}catch(a){Promise.reject(a)}try{await this.options.onError?.(o,t,this.state.context,r)}catch(a){Promise.reject(a)}try{await f(this,me).config.onSettled?.(void 0,o,this.state.variables,this.state.context,this,r)}catch(a){Promise.reject(a)}try{await this.options.onSettled?.(void 0,o,t,this.state.context,r)}catch(a){Promise.reject(a)}throw q(this,Je,xt).call(this,{type:"error",error:o}),o}finally{f(this,me).runNext(this)}}},xr=new WeakMap,ze=new WeakMap,me=new WeakMap,Gt=new WeakMap,Je=new WeakSet,xt=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(()=>{f(this,ze).forEach(r=>{r.onMutationUpdate(t)}),f(this,me).notify({mutation:this,type:"updated",action:t})})},Na);function Ui(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var it,Ke,Rr,Da,Ua=(Da=class extends we{constructor(t={}){super();T(this,it);T(this,Ke);T(this,Rr);this.config=t,R(this,it,new Set),R(this,Ke,new Map),R(this,Rr,0)}build(t,n,r){let s=new Qa({client:t,mutationCache:this,mutationId:++fr(this,Rr)._,options:t.defaultMutationOptions(n),state:r});return this.add(s),s}add(t){f(this,it).add(t);let n=ds(t);if(typeof n=="string"){let r=f(this,Ke).get(n);r?r.push(t):f(this,Ke).set(n,[t])}this.notify({type:"added",mutation:t})}remove(t){if(f(this,it).delete(t)){let n=ds(t);if(typeof n=="string"){let r=f(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&&f(this,Ke).delete(n)}}this.notify({type:"removed",mutation:t})}canRun(t){let n=ds(t);if(typeof n=="string"){let s=f(this,Ke).get(n)?.find(i=>i.state.status==="pending");return!s||s===t}else return!0}runNext(t){let n=ds(t);return typeof n=="string"?f(this,Ke).get(n)?.find(s=>s!==t&&s.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){L.batch(()=>{f(this,it).forEach(t=>{this.notify({type:"removed",mutation:t})}),f(this,it).clear(),f(this,Ke).clear()})}getAll(){return Array.from(f(this,it))}find(t){let n={exact:!0,...t};return this.getAll().find(r=>os(n,r))}findAll(t={}){return this.getAll().filter(n=>os(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(Y))))}},it=new WeakMap,Ke=new WeakMap,Rr=new WeakMap,Da);function ds(e){return e.options.scope?.id}var ot,Rt,Re,at,ct,ps,Ki,Ka,Li=(Ka=class extends we{constructor(t,n){super();T(this,ct);T(this,ot);T(this,Rt);T(this,Re);T(this,at);R(this,ot,t),this.setOptions(n),this.bindMethods(),q(this,ct,ps).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(t){let n=this.options;this.options=f(this,ot).defaultMutationOptions(t),bt(this.options,n)||f(this,ot).getMutationCache().notify({type:"observerOptionsUpdated",mutation:f(this,Re),observer:this}),n?.mutationKey&&this.options.mutationKey&&We(n.mutationKey)!==We(this.options.mutationKey)?this.reset():f(this,Re)?.state.status==="pending"&&f(this,Re).setOptions(this.options)}onUnsubscribe(){this.hasListeners()||f(this,Re)?.removeObserver(this)}onMutationUpdate(t){q(this,ct,ps).call(this),q(this,ct,Ki).call(this,t)}getCurrentResult(){return f(this,Rt)}reset(){f(this,Re)?.removeObserver(this),R(this,Re,void 0),q(this,ct,ps).call(this),q(this,ct,Ki).call(this)}mutate(t,n){return R(this,at,n),f(this,Re)?.removeObserver(this),R(this,Re,f(this,ot).getMutationCache().build(f(this,ot),this.options)),f(this,Re).addObserver(this),f(this,Re).execute(t)}},ot=new WeakMap,Rt=new WeakMap,Re=new WeakMap,at=new WeakMap,ct=new WeakSet,ps=function(){let t=f(this,Re)?.state??Ui();R(this,Rt,{...t,isPending:t.status==="pending",isSuccess:t.status==="success",isError:t.status==="error",isIdle:t.status==="idle",mutate:this.mutate,reset:this.reset})},Ki=function(t){L.batch(()=>{if(f(this,at)&&this.hasListeners()){let n=f(this,Rt).variables,r=f(this,Rt).context,s={client:f(this,ot),meta:this.options.meta,mutationKey:this.options.mutationKey};if(t?.type==="success"){try{f(this,at).onSuccess?.(t.data,n,r,s)}catch(i){Promise.reject(i)}try{f(this,at).onSettled?.(t.data,null,n,r,s)}catch(i){Promise.reject(i)}}else if(t?.type==="error"){try{f(this,at).onError?.(t.error,n,r,s)}catch(i){Promise.reject(i)}try{f(this,at).onSettled?.(void 0,t.error,n,r,s)}catch(i){Promise.reject(i)}}}this.listeners.forEach(n=>{n(f(this,Rt))})})},Ka);function La(e,t){let n=new Set(t);return e.filter(r=>!n.has(r))}function _p(e,t,n){let r=e.slice(0);return r[t]=n,r}var Rn,Ee,Cn,Pn,ke,Ct,Cr,Pr,Er,Ir,fe,Bi,ji,Hi,$i,Vi,Ba,Wi=(Ba=class extends we{constructor(t,n,r){super();T(this,fe);T(this,Rn);T(this,Ee);T(this,Cn);T(this,Pn);T(this,ke);T(this,Ct);T(this,Cr);T(this,Pr);T(this,Er);T(this,Ir,[]);R(this,Rn,t),R(this,Pn,r),R(this,Cn,[]),R(this,ke,[]),R(this,Ee,[]),this.setQueries(n)}onSubscribe(){this.listeners.size===1&&f(this,ke).forEach(t=>{t.subscribe(n=>{q(this,fe,$i).call(this,t,n)})})}onUnsubscribe(){this.listeners.size||this.destroy()}destroy(){this.listeners=new Set,f(this,ke).forEach(t=>{t.destroy()})}setQueries(t,n){R(this,Cn,t),R(this,Pn,n),L.batch(()=>{let r=f(this,ke),s=q(this,fe,Hi).call(this,f(this,Cn));s.forEach(u=>u.observer.setOptions(u.defaultedQueryOptions));let i=s.map(u=>u.observer),o=i.map(u=>u.getCurrentResult()),a=r.length!==i.length,c=i.some((u,m)=>u!==r[m]),l=a||c,d=l?!0:o.some((u,m)=>{let p=f(this,Ee)[m];return!p||!bt(u,p)});!l&&!d||(l&&(R(this,Ir,s),R(this,ke,i)),R(this,Ee,o),this.hasListeners()&&(l&&(La(r,i).forEach(u=>{u.destroy()}),La(i,r).forEach(u=>{u.subscribe(m=>{q(this,fe,$i).call(this,u,m)})})),q(this,fe,Vi).call(this)))})}getCurrentResult(){return f(this,Ee)}getQueries(){return f(this,ke).map(t=>t.getCurrentQuery())}getObservers(){return f(this,ke)}getOptimisticResult(t,n){let r=q(this,fe,Hi).call(this,t),s=r.map(o=>o.observer.getOptimisticResult(o.defaultedQueryOptions)),i=r.map(o=>o.defaultedQueryOptions.queryHash);return[s,o=>q(this,fe,ji).call(this,o??s,n,i),()=>q(this,fe,Bi).call(this,s,r)]}},Rn=new WeakMap,Ee=new WeakMap,Cn=new WeakMap,Pn=new WeakMap,ke=new WeakMap,Ct=new WeakMap,Cr=new WeakMap,Pr=new WeakMap,Er=new WeakMap,Ir=new WeakMap,fe=new WeakSet,Bi=function(t,n){return n.map((r,s)=>{let i=t[s];return r.defaultedQueryOptions.notifyOnChangeProps?i:r.observer.trackResult(i,o=>{n.forEach(a=>{a.observer.trackProp(o)})})})},ji=function(t,n,r){if(n){let s=f(this,Er),i=r!==void 0&&s!==void 0&&(s.length!==r.length||r.some((o,a)=>o!==s[a]));return(!f(this,Ct)||f(this,Ee)!==f(this,Pr)||i||n!==f(this,Cr))&&(R(this,Cr,n),R(this,Pr,f(this,Ee)),r!==void 0&&R(this,Er,r),R(this,Ct,gr(f(this,Ct),n(t)))),f(this,Ct)}return t},Hi=function(t){let n=new Map;f(this,ke).forEach(s=>{let i=s.options.queryHash;if(!i)return;let o=n.get(i);o?o.push(s):n.set(i,[s])});let r=[];return t.forEach(s=>{let i=f(this,Rn).defaultQueryOptions(s),a=n.get(i.queryHash)?.shift()??new st(f(this,Rn),i);r.push({defaultedQueryOptions:i,observer:a})}),r},$i=function(t,n){let r=f(this,ke).indexOf(t);r!==-1&&(R(this,Ee,_p(f(this,Ee),r,n)),q(this,fe,Vi).call(this))},Vi=function(){if(this.hasListeners()){let t=f(this,Ct),n=q(this,fe,Bi).call(this,f(this,Ee),f(this,Ir)),r=q(this,fe,ji).call(this,n,f(this,Pn)?.combine);t!==r&&L.batch(()=>{this.listeners.forEach(s=>{s(f(this,Ee))})})}},Ba);var Ye,ja,Ha=(ja=class extends we{constructor(t={}){super();T(this,Ye);this.config=t,R(this,Ye,new Map)}build(t,n,r){let s=n.queryKey,i=n.queryHash??hr(s,n),o=this.get(i);return o||(o=new Ea({client:t,queryKey:s,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(s)}),this.add(o)),o}add(t){f(this,Ye).has(t.queryHash)||(f(this,Ye).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){let n=f(this,Ye).get(t.queryHash);n&&(t.destroy(),n===t&&f(this,Ye).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){L.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return f(this,Ye).get(t)}getAll(){return[...f(this,Ye).values()]}find(t){let n={exact:!0,...t};return this.getAll().find(r=>is(n,r))}findAll(t={}){let n=this.getAll();return Object.keys(t).length>0?n.filter(r=>is(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()})})}},Ye=new WeakMap,ja);var re,Pt,Et,En,In,It,Tn,An,$a,Gi=($a=class{constructor(e={}){T(this,re);T(this,Pt);T(this,Et);T(this,En);T(this,In);T(this,It);T(this,Tn);T(this,An);R(this,re,e.queryCache||new Ha),R(this,Pt,e.mutationCache||new Ua),R(this,Et,e.defaultOptions||{}),R(this,En,new Map),R(this,In,new Map),R(this,It,0)}mount(){fr(this,It)._++,f(this,It)===1&&(R(this,Tn,pn.subscribe(async e=>{e&&(await this.resumePausedMutations(),f(this,re).onFocus())})),R(this,An,yn.subscribe(async e=>{e&&(await this.resumePausedMutations(),f(this,re).onOnline())})))}unmount(){var e,t;fr(this,It)._--,f(this,It)===0&&((e=f(this,Tn))==null||e.call(this),R(this,Tn,void 0),(t=f(this,An))==null||t.call(this),R(this,An,void 0))}isFetching(e){return f(this,re).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return f(this,Pt).findAll({...e,status:"pending"}).length}getQueryData(e){let t=this.defaultQueryOptions({queryKey:e});return f(this,re).get(t.queryHash)?.state.data}ensureQueryData(e){let t=this.defaultQueryOptions(e),n=f(this,re).build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(Ue(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return f(this,re).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=f(this,re).get(r.queryHash)?.state.data,o=ga(t,i);if(o!==void 0)return f(this,re).build(this,r).setData(o,{...n,manual:!0})}setQueriesData(e,t,n){return L.batch(()=>f(this,re).findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){let t=this.defaultQueryOptions({queryKey:e});return f(this,re).get(t.queryHash)?.state}removeQueries(e){let t=f(this,re);L.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){let n=f(this,re);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(()=>f(this,re).findAll(e).map(s=>s.cancel(n)));return Promise.all(r).then(Y).catch(Y)}invalidateQueries(e,t={}){return L.batch(()=>(f(this,re).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(()=>f(this,re).findAll(e).filter(s=>!s.isDisabled()&&!s.isStatic()).map(s=>{let i=s.fetch(void 0,n);return n.throwOnError||(i=i.catch(Y)),s.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(Y)}fetchQuery(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=f(this,re).build(this,t);return n.isStaleByTime(Ue(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Y).catch(Y)}fetchInfiniteQuery(e){return e.behavior=xn(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Y).catch(Y)}ensureInfiniteQueryData(e){return e.behavior=xn(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return yn.isOnline()?f(this,Pt).resumePausedMutations():Promise.resolve()}getQueryCache(){return f(this,re)}getMutationCache(){return f(this,Pt)}getDefaultOptions(){return f(this,Et)}setDefaultOptions(e){R(this,Et,e)}setQueryDefaults(e,t){f(this,En).set(We(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){let t=[...f(this,En).values()],n={};return t.forEach(r=>{Kt(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){f(this,In).set(We(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){let t=[...f(this,In).values()],n={};return t.forEach(r=>{Kt(e,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;let t={...f(this,Et).queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=hr(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===fn&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...f(this,Et).mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){f(this,re).clear(),f(this,Pt).clear()}},re=new WeakMap,Pt=new WeakMap,Et=new WeakMap,En=new WeakMap,In=new WeakMap,It=new WeakMap,Tn=new WeakMap,An=new WeakMap,$a);var Xe=J(ue(),1);var Mn=J(ue(),1),Wa=J(fs(),1),zi=Mn.createContext(void 0),U=e=>{let t=Mn.useContext(zi);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},Tr=({client:e,children:t})=>(Mn.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,Wa.jsx)(zi.Provider,{value:e,children:t}));var ms=J(ue(),1),Ga=ms.createContext(!1),hs=()=>ms.useContext(Ga),_g=Ga.Provider;var Ar=J(ue(),1),bp=J(fs(),1);function vp(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var wp=Ar.createContext(vp()),gs=()=>Ar.useContext(wp);var za=J(ue(),1);var ys=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError=="function"?mn(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},_s=e=>{za.useEffect(()=>{e.clearReset()},[e])},bs=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:s})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(s&&e.data===void 0||mn(n,[e.error,r]));var vs=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))}},Ja=(e,t)=>e.isLoading&&e.isFetching&&!t,Mr=(e,t)=>e?.suspense&&t.isPending,kr=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function Ji({queries:e,...t},n){let r=U(n),s=hs(),i=gs(),o=Xe.useMemo(()=>e.map(g=>{let y=r.defaultQueryOptions(g);return y._optimisticResults=s?"isRestoring":"optimistic",y}),[e,r,s]);o.forEach(g=>{vs(g);let y=r.getQueryCache().get(g.queryHash);ys(g,i,y)}),_s(i);let[a]=Xe.useState(()=>new Wi(r,o,t)),[c,l,d]=a.getOptimisticResult(o,t.combine),u=!s&&t.subscribed!==!1;Xe.useSyncExternalStore(Xe.useCallback(g=>u?a.subscribe(L.batchCalls(g)):Y,[a,u]),()=>a.getCurrentResult(),()=>a.getCurrentResult()),Xe.useEffect(()=>{a.setQueries(o,t)},[o,t,a]);let p=c.some((g,y)=>Mr(o[y],g))?c.flatMap((g,y)=>{let S=o[y];if(S&&Mr(S,g)){let _=new st(r,S);return kr(S,_,i)}return[]}):[];if(p.length>0)throw Promise.all(p);let h=c.find((g,y)=>{let S=o[y];return S&&bs({result:g,errorResetBoundary:i,throwOnError:S.throwOnError,query:r.getQueryCache().get(S.queryHash),suspense:S.suspense})});if(h?.error)throw h.error;return l(d())}var Tt=J(ue(),1);function ws(e,t,n){let r=hs(),s=gs(),i=U(n),o=i.defaultQueryOptions(e);i.getDefaultOptions().queries?._experimental_beforeQuery?.(o);let a=i.getQueryCache().get(o.queryHash);o._optimisticResults=r?"isRestoring":"optimistic",vs(o),ys(o,s,a),_s(s);let c=!i.getQueryCache().get(o.queryHash),[l]=Tt.useState(()=>new t(i,o)),d=l.getOptimisticResult(o),u=!r&&e.subscribed!==!1;if(Tt.useSyncExternalStore(Tt.useCallback(m=>{let p=u?l.subscribe(L.batchCalls(m)):Y;return l.updateResult(),p},[l,u]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),Tt.useEffect(()=>{l.setOptions(o)},[o,l]),Mr(o,d))throw kr(o,l,s);if(bs({result:d,errorResetBoundary:s,throwOnError:o.throwOnError,query:a,suspense:o.suspense}))throw d.error;return i.getDefaultOptions().queries?._experimental_afterQuery?.(o,d),o.experimental_prefetchInRender&&!Ge.isServer()&&Ja(d,r)&&(c?kr(o,l,s):a?.promise)?.catch(Y).finally(()=>{l.updateResult()}),o.notifyOnChangeProps?d:l.trackResult(d)}function H(e,t){return ws(e,st,t)}var ut=J(ue(),1);function ie(e,t){let n=U(t),[r]=ut.useState(()=>new Li(n,e));ut.useEffect(()=>{r.setOptions(e)},[r,e]);let s=ut.useSyncExternalStore(ut.useCallback(o=>r.subscribe(L.batchCalls(o)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),i=ut.useCallback((o,a)=>{r.mutate(o,a).catch(Y)},[r]);if(s.error&&mn(r.options.throwOnError,[s.error]))throw s.error;return{...s,mutate:i,mutateAsync:s.mutate}}function kn(e,t){return ws(e,Di,t)}var Za=J(Xa(),1),On=typeof window<"u"&&window.__FSAOS_CONFIG__||{},zt=Array.isArray(On.sources)?On.sources:[],lt=On.hostSession===!0,Sp=On.supabaseUrl||"https://vahbmsslxuustnlvsrkg.supabase.co",xp=On.supabaseAnonKey||"sb_publishable_ZjosozAjfpZ4InMNElTr6Q_hHB-f5nc",Oe=On.gatewayUrl||"https://fsaos-mcp-gw-rust.fly.dev",G=(0,Za.createClient)(Sp,xp,{auth:{persistSession:!0,autoRefreshToken:!0,detectSessionInUrl:!1}});var Or=null,Ss=0,ec,eo,xs=!1;ec=new Promise(e=>{eo=e});G.auth.onAuthStateChange((e,t)=>{t?.access_token?(Or=t.access_token,Ss=t.expires_at??Math.floor(Date.now()/1e3)+3600):(Or=null,Ss=0),xs||(xs=!0,eo())});setTimeout(()=>{xs||(xs=!0,eo())},5e3);function tc(e,t){Or=e,Ss=t??Math.floor(Date.now()/1e3)+3600}function to(){Or=null,Ss=0}async function dt(){let e=typeof window<"u"&&window.__FSAOS_CONFIG__||{};if(lt)return null;if(e.embedToken){if(typeof e.embedToken=="function")try{return await e.embedToken()??null}catch{return null}return e.embedToken}return await ec,Or}var Qn=null,Dn=null,nc=0,Yi=new Set,no,Fr,Un=!1;no=new Promise(e=>{Fr=e});function ro(){nc++,Yi.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Anchor listener error:",t)}})}function Kn(e){let t=typeof e=="string"?e:e.path,n=Qn!==t||Dn?.id!==(typeof e=="string"?void 0:e.id);Qn=t,Dn=typeof e=="string"?null:e,typeof e!="string"&&!Jt.some(r=>r.id===e.id)&&(Jt=[...Jt,e],ao()),Un||(Un=!0,Fr()),n&&ro()}function Ie(){return Qn}function pe(){return Dn}function so(){return nc}function io(e){return Yi.add(e),()=>{Yi.delete(e)}}function qr(){return no}function oo(){return Un}var Rs=null;function Yt(e,t={}){if(Rs){console.warn("[SDK] electHomeAnchor called twice; ignoring (logout to re-elect).");return}Rs=e,t.activate!==!1&&Kn(e)}function _e(){return Rs}var Jt=[],Xi=new Set,rc=0;function ao(){rc++,Xi.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Mount listener error:",t)}})}function Ce(){return Jt}function At(){return rc}function Ln(e){return Xi.add(e),()=>{Xi.delete(e)}}function sc(e,t){let n=JSON.stringify(Jt)!==JSON.stringify(e),r=Qn!==t.path||Dn?.id!==t.id;Jt=e,Qn=t.path,Dn=t,Un||(Un=!0,Fr()),n&&ao(),r&&ro()}var qn=null,Fn=null,Nn=0,Zi=new Set,ic=0;function oc(){ic++,Zi.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Session listener error:",t)}})}function V(){return Nn}function Bn(){return ic}function Nr(e){return Zi.add(e),()=>{Zi.delete(e)}}async function pt(){if(qn)return qn;if(Fn)return Fn;let e=Nn;return Fn=(async()=>{let t=Xt(),n=await dt();if(e!==Nn)throw new Error("Session changed during initialization");let r={};n&&(r.Authorization=`Bearer ${n}`);let s=await fetch(`${Oe}/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!==Nn)throw new Error("Session changed during initialization");let o=i.entry||i;return qn={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},oc(),qn})().catch(t=>{throw e===Nn&&(Fn=null),t}),Fn}function Ze(){return qn}function co(){Nn++,qn=null,Fn=null,Qn=null,Dn=null,Rs=null,Jt=[],oc()}var ac=[];function oe(e){ac.push(e)}function jn(){co(),to(),Fr(),Un=!1,no=new Promise(e=>{Fr=e}),ro(),ao();for(let e of ac)try{e()}catch(t){console.warn("[SDK] Cleanup function failed:",t)}}function Xt(){if(typeof window<"u"){let e=window.__FSAOS_CONFIG__;return e?.hostname?e.hostname:window.location.hostname}return"localhost"}var cc=Kn,z=Ie,W=so,be=io,uc=qr,Cs=oo;var en="host-session",Rp=5e3;function uo(e){return typeof e=="object"&&e!==null&&e.fsaos===en&&typeof e.kind=="string"}var Zt=class extends Error{constructor(){super(...arguments);te(this,"name","HostSessionUnavailableError")}},Ps=null,Cp=0,Es=new Map;function lc(){return Ps||(Ps=new Promise((e,t)=>{if(!lt){t(new Zt("This page was not started with hostSession."));return}if(typeof window>"u"||!window.parent||window.parent===window){t(new Zt("This page is signed in only inside the app that frames it. Open it from there."));return}let n=window.parent,r=null,s=setTimeout(()=>{r===null&&(window.removeEventListener("message",i),t(new Zt("The window around this page did not sign it in. Open it from the app that owns it.")))},Rp);function i(o){if(o.source!==n||!uo(o.data))return;let a=o.data;if(r===null){if(a.kind!=="welcome")return;r=o.origin,clearTimeout(s),a.anchor&&Kn(a.anchor),e({host:n,origin:r,item:a.item??null});return}if(o.origin!==r||a.kind!=="result")return;let c=Es.get(a.id);c&&(Es.delete(a.id),c.resolve(a.ok?{ok:!0,response:a.response}:{ok:!1,error:a.error}))}window.addEventListener("message",i),n.postMessage({fsaos:en,kind:"hello"},"*")}),Ps)}async function dc(){let{item:e}=await lc();return{item:e}}async function pc(e,t,n){if(n?.aborted)throw new DOMException("Read cancelled","AbortError");let{host:r,origin:s}=await lc();if(n?.aborted)throw new DOMException("Read cancelled","AbortError");let i=JSON.parse(JSON.stringify(t??{}));return new Promise((o,a)=>{let c=`${Date.now().toString(36)}-${(++Cp).toString(36)}`,l=()=>{Es.delete(c),a(new DOMException("Read cancelled","AbortError"))};Es.set(c,{resolve:d=>{n?.removeEventListener("abort",l),o(d)}}),n?.addEventListener("abort",l,{once:!0}),r.postMessage({fsaos:en,kind:"call",id:c,method:e,params:i},s)})}var lo=0,fc=!1,mc=0;function po(e){if(typeof e!="string")return;let t=Date.parse(e);Number.isNaN(t)||(lo=t-Date.now(),fc=!0,mc=Date.now())}function Is(){return Date.now()+lo}function hc(){return fc}function gc(){return lo}function yc(){return mc}function _c(e){if(typeof e!="string")return null;let t=Date.parse(e);return Number.isNaN(t)?null:Is()>=t}function bc(e){if(typeof e!="string")return null;let t=Date.parse(e);return Number.isNaN(t)?null:Math.max(0,t-Is())}var Hn,Fe=new Map,tn=[],fo=0,mo={foreground:0,normal:1,background:2},Ts=()=>performance.now(),ho=()=>new DOMException("Read cancelled","AbortError");function wc(e={}){Hn={concurrency:Math.max(1,Math.min(16,Math.floor(e.concurrency??6))),timeoutMs:Math.max(1e3,e.timeoutMs??15e3),onTiming:e.onTiming},Ms()}function Sc(){for(let e of Fe.values()){e.controller.abort();for(let t of e.consumers)t.detach(),t.reject(ho());e.consumers.clear(),e.timer&&clearTimeout(e.timer)}Fe.clear(),tn.length=0}function xc(e,t){return e==="query"?!("materialize"in t):["read","list","search","resolve","resolve-items","get-channel-messages","list-memberships","message-replies","check-item-access"].includes(e)}function As(e){return Array.isArray(e)?`[${e.map(As).join(",")}]`:e&&typeof e=="object"?`{${Object.entries(e).filter(([,t])=>t!==void 0).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>`${JSON.stringify(t)}:${As(n)}`).join(",")}}`:JSON.stringify(e)}function Rc(e,t,n,r){if(n.signal?.aborted)return Promise.reject(ho());if(!Hn)return r(n.signal);let s=Fe.get(e);if(s)mo[n.priority??"normal"]<mo[s.priority]&&(s.priority=n.priority??"normal");else{s={key:e,method:t,priority:n.priority??"normal",queuedAt:Ts(),controller:new AbortController,consumers:new Set,run:r},Fe.set(e,s),tn.push(s);let a=s;s.timer=setTimeout(()=>{a.controller.abort();let c=new Error("The read timed out. Please retry.");c.name="TimeoutError";for(let l of a.consumers)l.detach(),l.reject(c);a.consumers.clear(),Fe.get(a.key)===a&&Fe.delete(a.key),vc(a)},Hn.timeoutMs)}let i=s,o=new Promise((a,c)=>{let l=()=>{d.detach(),i.consumers.delete(d),c(ho()),i.consumers.size||(i.controller.abort(),Fe.get(i.key)===i&&Fe.delete(i.key),vc(i))},d={resolve:u=>a(structuredClone(u)),reject:c,detach:()=>n.signal?.removeEventListener("abort",l)};i.consumers.add(d),n.signal?.addEventListener("abort",l,{once:!0})});return Ms(),o}function vc(e){let t=tn.indexOf(e);t>=0&&(tn.splice(t,1),Fe.get(e.key)===e&&Fe.delete(e.key),e.timer&&clearTimeout(e.timer)),Ms()}function Ms(){if(Hn)for(;fo<Hn.concurrency&&tn.length;){let e=r=>mo[r.priority]-Math.floor((Ts()-r.queuedAt)/2e3);tn.sort((r,s)=>e(r)-e(s)||r.queuedAt-s.queuedAt);let t=tn.shift();if(!t.consumers.size)continue;fo++,t.startedAt=Ts();let n="success";Promise.resolve().then(()=>t.run(t.controller.signal)).then(r=>{for(let s of t.consumers)s.detach(),s.resolve(r)},r=>{n=t.controller.signal.aborted?"aborted":"error";for(let s of t.consumers)s.detach(),s.reject(r)}).finally(()=>{t.timer&&clearTimeout(t.timer),t.consumers.clear(),Fe.get(t.key)===t&&Fe.delete(t.key),fo--;try{Hn?.onTiming?.({method:t.method,priority:t.priority,queueMs:Math.round(t.startedAt-t.queuedAt),requestMs:Math.round(Ts()-t.startedAt),outcome:n})}catch{}Ms()})}}oe(Sc);var Pp=new Set(["list-memberships","init"]),ve=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);te(this,"name","GatewayRequestError");te(this,"method");te(this,"status");te(this,"statusText");te(this,"payload");te(this,"responseBody");this.method=n.method,this.status=n.status,this.statusText=n.statusText,this.payload=n.payload,this.responseBody=n.responseBody}};async function P(e,t={},n={}){if(lt)return Ep(e,t,n);let r=V(),s=Ie(),i=Xt(),o=`${Oe}/d/${i}`,a={"Content-Type":"application/json"},c=await Cc(dt(),n.signal);if(r!==V())throw new Error("Session changed before gateway request");if(c&&(a.Authorization=`Bearer ${c}`),!Pp.has(e)&&!t._scope_path&&await Cc(qr(),n.signal),r!==V())throw new Error("Session changed before gateway request");let l={...t},d=Ze();!l.domain_scope_id&&d?.scope_id&&(l.domain_scope_id=d.scope_id);let u=s??Ie();!l._scope_path&&u&&(l._scope_path=u);let m=async p=>{if(r!==V())throw new Error("Session changed before queued gateway request");let h=await fetch(o,{method:"POST",signal:p,headers:a,body:JSON.stringify({method:e,params:l})}),g=await h.text();if(r!==V())throw new Error("Session changed during gateway request");let y=null;if(g)try{y=JSON.parse(g)}catch{}if(!h.ok||!y)throw new ve({method:e,status:h.status,statusText:h.statusText,payload:y,responseBody:g});if(y.success===!1){let S=y.error||"",_=y.denied_by||y.error_type||"";throw _==="rule"||_==="access"||_==="entitlement"||S==="RULE_DENIED"||S==="ACCESS_DENIED"||S==="PERMISSION_DENIED"||S==="ENTITLEMENT_REQUIRED"?new De(y):new ve({method:e,status:h.status,statusText:h.statusText,payload:y,responseBody:g})}return y&&y.server_now!==void 0&&po(y.server_now),y};return xc(e,l)?Rc(As([r,i,c,e,l]),e,n,m):m(n.signal)}async function Ep(e,t,n){let r=await pc(e,t,n.signal);if(r.ok){let o=r.response?.server_now;return o!==void 0&&po(o),r.response}let s=r.error;if(s.kind==="denied")throw new De(s.payload);if(s.kind==="gateway")throw new ve({method:s.method,status:s.status,statusText:s.statusText,payload:s.payload,responseBody:s.responseBody});let i=new Error(s.message);throw i.name=s.name,i}function Cc(e,t){return t?t.aborted?Promise.reject(new DOMException("Read cancelled","AbortError")):new Promise((n,r)=>{let s=()=>r(new DOMException("Read cancelled","AbortError"));t.addEventListener("abort",s,{once:!0}),e.then(n,r).finally(()=>t.removeEventListener("abort",s))}):e}var v=J(ue(),1),Sf=J(Ec(),1),xf=J(fs(),1);var Ic=new WeakMap;function ce(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(u=>u.promise?[u.promise]:[]);if(i.length===0)return s();let o=`${r?"=":"^"}${JSON.stringify(t)}`,a=Ic.get(e);a||(a=new Map,Ic.set(e,a));let c=a.get(o);if(c)return c;let l=a,d=Promise.allSettled(i).then(()=>(l.delete(o),s()));return l.set(o,d),d}function se(e,t){return typeof e=="string"&&(e===t||e.startsWith(`${t}/`))}var ks=new WeakMap,Tc=e=>e.meta?.arrangementRealtime===!0;function ft(e,t){let n=e.getQueryCache().find({queryKey:t,exact:!0});if(!n)return;let r=ks.get(e);r||(r=new Map,ks.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&&ce(e,t,{exact:!0})},250))}function Ac(e,t){if(!(!t||typeof t!="object"))for(let n of e.getQueryCache().getAll()){if(!Tc(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")&&ft(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)))&&ft(e,n.queryKey)}}function Mc(e){for(let t of e.getQueryCache().getAll())Tc(t)&&t.state.data!==void 0&&ft(e,t.queryKey)}function kc(e){ks.get(e)?.forEach(clearTimeout),ks.delete(e)}var Os=new WeakMap,Ip=new Set(["shared_with","has_member","member_of","owned_by"]);function Oc(e,t){let n=Os.get(e);n||(n=new Map,Os.set(e,n)),!n.has(t)&&(e.cancelQueries({queryKey:t.queryKey,exact:!0}),e.invalidateQueries({queryKey:t.queryKey,exact:!0,refetchType:"none"}),t.isActive()&&n.set(t,setTimeout(()=>{n.delete(t),!(e.getQueryCache().get(t.queryHash)!==t||!t.isActive())&&ce(e,t.queryKey,{exact:!0})},250)))}function Fc(e,t,n){let r=n==="ccm_change";if(r&&!Ip.has(t.edge_type))return;let s=[t.path,t.old_path,t.source_path].filter(o=>typeof o=="string"),i=[t.item_id,t.source_item_id,t.source_id,t.target_item_id,t.target_id].filter(Boolean);if(!(!s.length&&!i.length))for(let o of e.getQueryCache().findAll({queryKey:["vfs"]})){let a=o.meta?.permissionQuery;if(!a?.scope)continue;let c=!!(a.itemId&&i.includes(a.itemId)),l=!!(a.path&&s.some(p=>se(a.path,p))),d=a.scope,m=(s.some(p=>se(p,d)||se(d,p))||[t.scope_item_id,t.account_item_id,t.space_item_id].some(p=>p&&a.scopeIds.includes(p)))&&(t.item_type==="member"||t.item_type==="principal"||r);(c||l||!a.targetLookup&&m)&&Oc(e,o)}}function qc(e){for(let t of e.getQueryCache().findAll({queryKey:["vfs"]}))t.meta?.permissionQuery&&Oc(e,t)}function Nc(e){Os.get(e)?.forEach(t=>clearTimeout(t)),Os.delete(e)}var mt=null;oe(()=>{mt&&(mt.cancelQueries({queryKey:["vfs"]}),mt.removeQueries({queryKey:["vfs"]}))});function Qc(e){if(mt&&mt!==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.");mt=e}function N(){return mt||(mt=new Gi({defaultOptions:{queries:{staleTime:1e3*60*2,gcTime:1e3*60*10,refetchOnWindowFocus:!1,retry:1}}})),mt}var Dc=new Proxy({},{get(e,t,n){let r=N(),s=r[t];return typeof s=="function"?s.bind(r):s}});var Fs=new WeakMap;function go(e){return e.meta?.infiniteItemsRealtime?.filter}function Tp(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 Ap(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 Mp(e,t,n){if(Tp(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&&!se(n.path,r)&&!se(n.old_path,r))return!1;if(n.item_type==="symlink"&&s&&i)return!0;let o=Ap(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 Uc(e,t){let n=Fs.get(e);n||(n=new Map,Fs.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||!go(t))&&ce(e,t.queryKey,{exact:!0})},500))}function Kc(e,t){if(!(!t||typeof t!="object"))for(let n of e.getQueryCache().getAll()){let r=go(n);r&&Mp(n,r,t)&&Uc(e,n)}}function Lc(e){for(let t of e.getQueryCache().getAll())go(t)&&t.state.data!==void 0&&Uc(e,t)}function Bc(e){Fs.get(e)?.forEach(clearTimeout),Fs.delete(e)}var qs=class extends Error{constructor(){super("The server did not confirm the selected-Space listing contract")}};function jc(e,t){if(!Array.isArray(t)||t.some(n=>typeof n!="string")||JSON.stringify([...new Set(t)].sort())!==JSON.stringify(e))throw new qs}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 $n(e){return e instanceof qs||e instanceof De||e instanceof ve&&(e.payload?.error==="SPACE_SELECTION_UNAVAILABLE"||e.payload?.error==="QUERY_PARAMS_INVALID"||e.status===401||e.status===403)}function le(){return z()??"__unscoped__"}var k={all:()=>["vfs",le()],item:e=>["vfs",le(),"item",e],itemById:e=>["vfs","item-by-id",e],children:e=>["vfs",le(),"children",e],allChildren:()=>["vfs",le(),"children"],types:e=>["vfs","types",e??"default"],edges:e=>["vfs","edges",e],search:(e,t)=>["vfs",le(),"search",e,...t??[]],items:(e,t)=>["vfs",le(),"items",e,JSON.stringify(Mt(t??{}))],allItems:()=>["vfs",le(),"items"],tree:(e,t)=>["vfs",le(),"tree",e,t??1],openEnvelope:(e,t)=>["vfs",le(),"open",e,t??"__default__"],allOpenEnvelopes:()=>["vfs",le(),"open"],memberFocus:e=>["vfs","member-focus",e],fractalInstances:()=>["vfs","fractal-instances"],recentActivity:(e,t,n)=>["vfs",le(),"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",le(),"channel-messages",e,t??"__top__"],allChannelMessages:()=>["vfs",le(),"channel-messages"],channels:e=>["vfs",le(),"channels",e??"all"],messageReplies:(e,t,n,r=25)=>["vfs",le(),"channel-messages",e,n??"__top__","contextual-replies",t,r],allChannels:()=>["vfs",le(),"channels"],notifications:(e,t)=>["vfs",le(),"notifications",e??"all",t??200],allNotifications:()=>["vfs",le(),"notifications"],unreadCounts:()=>["vfs",le(),"unread-counts"],memberships:e=>["memberships",e]};var kp=typeof window<"u"&&(window.location?.hostname==="localhost"||window.location?.hostname==="127.0.0.1"||window.__FSAOS_WS_DEBUG__);function ne(...e){kp&&console.log("[WS]",...e)}var D=null,Vn=null,Gn=null,Qr=0,Op=3e4,Hc=1e4,Jn=!1,$c=!1,Jc=3e4,Fp=Jc*2+5e3,Ns=0,Qs=null,Vc=!1;function qp(){Ur(),Ns=Date.now(),Qs=setInterval(()=>{if(D&&D.readyState===WebSocket.OPEN&&Date.now()-Ns>Fp){ne("ping: no inbound traffic for",Date.now()-Ns,"ms \u2014 closing half-open socket");try{D.close(4e3,"liveness timeout")}catch{}return}gt({type:"ping"})},Jc)}function Ur(){Qs&&(clearInterval(Qs),Qs=null)}function Np(){typeof document>"u"||(document.hidden?Ur():Dr()&&(ne("Tab visible, reconnecting..."),nn()))}function Qp(){Vc||typeof document>"u"||(document.addEventListener("visibilitychange",Np),Vc=!0)}var Te={};function _o(e,t){let n=e.replace(/\/+$/,""),r=t.replace(/\/+$/,"");return!n||!r?n===r:r===n||r.startsWith(`${n}/`)}var zn=[],ht=new Map,Wn=new Map,qe=new Map;function Dp(e){let t=Wn.get(e);return t?Array.from(new Set(Array.from(t.values()).flatMap(n=>n.event_types))).sort():[]}function Wc(e,t){return e?e.length===t.length&&e.every((n,r)=>n===t[r]):!1}function Gc(e){let t=Dp(e);if(t.length===0)return ht.delete(e),null;let n={scope_id:e,event_types:t};return ht.set(e,n),n}var et=new Map,kt=new Map,yo="disconnected",Ds=[];function Us(e){if(yo!==e){yo=e;for(let t of[...Ds])try{t(e)}catch{}}}function Up(e){et.set(e,"ready");let t=kt.get(e);if(t){kt.delete(e);for(let n of t)n()}}function Kp(){for(let e of et.keys())et.set(e,"disconnected")}function bo(e,t){et.set(e,"pending"),gt({type:"subscribe_path",path:e,event_types:t})}function Lp(){return Object.keys(Te).some(t=>Te[t]&&Te[t].length>0)||zn.length>0}function Dr(){return ht.size>0||qe.size>0}async function nn(){if(lt){ne("ensureConnection: the host holds the session, no realtime connection");return}if(!Dr()){ne("ensureConnection: no active subscriptions, skipping");return}if(D&&D.readyState===WebSocket.OPEN){ne("ensureConnection: already open");return}if(Vn)return ne("ensureConnection: connection already in flight, waiting..."),Vn;if(D){ne("ensureConnection: killing stale WS in state",D.readyState);try{D.close()}catch{}D=null}return Jn=!1,Vn=(async()=>{try{let e=typeof window<"u"&&window.__FSAOS_CONFIG__||{},t=Oe,n=await dt();if(!n){ne("ensureConnection: no token available, will retry"),zc();return}let r=t.startsWith("https")?"wss":"ws",s=t.replace(/^https?:\/\//,""),i=`${r}://${s}/ws`;i+=`?token=${encodeURIComponent(n)}`,ne("ensureConnection: opening WS to",i.substring(0,50)+"..."),Us("connecting"),D=new WebSocket(i);let o=D;await new Promise((a,c)=>{if(!D)return c(new Error("WebSocket not created"));let l=setTimeout(()=>{if(D===o){if(ne("ensureConnection: TIMEOUT after",Hc,"ms"),D&&D.readyState!==WebSocket.OPEN){try{D.close()}catch{}D=null}c(new Error("WebSocket connection timeout"))}},Hc);o.onopen=()=>{if(D!==o)return;clearTimeout(l),ne("ensureConnection: CONNECTED");let d=$c;$c=!0,Qr=0,Us("connected"),Bp(d),(typeof document>"u"||!document.hidden)&&qp(),Qp(),a()},o.onmessage=d=>{D===o&&jp(d.data)},o.onerror=()=>{ne("ensureConnection: WS error event")},o.onclose=d=>{clearTimeout(l),D===o&&(ne("ensureConnection: WS closed, code:",d.code,"reason:",d.reason),D=null,Ur(),Kp(),Us("disconnected"),!Jn&&Dr()&&zc(),c(new Error(`WebSocket closed: ${d.code}`)))}})}catch(e){ne("ensureConnection: failed -",e?.message||e)}finally{Vn=null}})(),Vn}function zc(){if(Gn||typeof document<"u"&&document.hidden)return;let e=Math.min(1e3*Math.pow(2,Qr)+Math.random()*1e3,Op);Qr++,ne("scheduleReconnect: attempt",Qr,"in",Math.round(e),"ms"),Gn=setTimeout(()=>{Gn=null,Dr()&&nn()},e)}function Bp(e=!1){for(let t of ht.values())ne("resubscribeAll: scope",t.scope_id),gt({type:"subscribe",scope_id:t.scope_id,event_types:t.event_types});for(let t of qe.values())ne("resubscribeAll: path",t.path),bo(t.path,t.event_types);e&&Yc("reconnect")}function Yc(e){try{let t=N();Lc(t),Mc(t),qc(t);for(let n of qe.values())t.invalidateQueries({queryKey:k.item(n.path)}),t.invalidateQueries({queryKey:k.children(n.path)});t.invalidateQueries({queryKey:k.allChannelMessages()}),ne("catchUpAfterGap:",e,"- invalidated",qe.size,"paths and the transcripts on screen")}catch(t){ne("catchUpAfterGap: cache invalidation skipped",t)}}function gt(e){D&&D.readyState===WebSocket.OPEN&&D.send(JSON.stringify(e))}function jp(e){Ns=Date.now();try{let t=JSON.parse(e);if(t.type==="subscribed_path"){typeof t.path=="string"&&Up(t.path);return}if(t.type==="subscribed"||t.type==="unsubscribed"||t.type==="unsubscribed_path"||t.type==="pong")return;if(t.type==="error"){console.warn("[WS] Server error:",t.message);return}if(t.type==="resync"){Yc(typeof t.reason=="string"?t.reason:"resync");return}if(t.type==="event"||t.event_type){let n=t.event_type||"message",r=t.data||t;if((n==="vfs_change"||n==="ccm_change")&&Fc(N(),r,n),n==="vfs_change"&&(Kc(N(),r),Ac(N(),r)),typeof r.path=="string")for(let[s,i]of Object.entries(Te))s!=="*"&&_o(s,r.path)&&i.forEach(o=>o(r));Te["*"]&&Te["*"].forEach(s=>s(r));for(let s of zn)s.eventType!=="*"&&s.eventType!==n||s.filter&&!s.filter(r)||s.callback(r)}}catch{}}function vo(){!Lp()&&ht.size===0&&qe.size===0&&D&&(Jn=!0,Ur(),D.close(),D=null,Jn=!1)}function Ks(e,t){return Te[e]||(Te[e]=[]),Te[e].push(t),qe.has(e)||(qe.set(e,{path:e,event_types:["token_stream"]}),D&&D.readyState===WebSocket.OPEN?bo(e,["token_stream"]):et.set(e,"pending")),nn(),()=>{let n=Te[e];if(n){let r=n.indexOf(t);r!==-1&&n.splice(r,1),n.length===0&&(delete Te[e],qe.delete(e),et.delete(e),kt.delete(e),gt({type:"unsubscribe_path",path:e}))}vo()}}function X(e,t,n){let s=(Array.isArray(e)?e:[e]).map(i=>({eventType:i,callback:t,filter:n}));return zn.push(...s),Dr()&&nn(),()=>{for(let i of s){let o=zn.indexOf(i);o!==-1&&zn.splice(o,1)}vo()}}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=Wn.get(e)??new Map,i=ht.get(e)?.event_types;s.set(n,{event_types:r}),Wn.set(e,s);let o=Gc(e);if(!o)return()=>{};ne("subscribeToScope:",e,o.event_types),D&&D.readyState===WebSocket.OPEN&&!Wc(i,o.event_types)&>({type:"subscribe",scope_id:e,event_types:o.event_types}),nn();let a=!0;return()=>{if(!a)return;a=!1;let c=Wn.get(e);if(!c?.delete(n))return;let l=ht.get(e)?.event_types;if(c.size===0)Wn.delete(e),ht.delete(e),gt({type:"unsubscribe",scope_id:e});else{let d=Gc(e);d&&D&&D.readyState===WebSocket.OPEN&&!Wc(l,d.event_types)&>({type:"subscribe",scope_id:e,event_types:d.event_types})}vo()}}function Xc(e,t,n={}){gt({type:"emit",scope_id:e,event_type:t,payload:n})}function wo(){ne("disconnectSSE: tearing down"),Bc(N()),kc(N()),Nc(N()),Jn=!0,Ur(),D&&(D.close(),D=null),Gn&&(clearTimeout(Gn),Gn=null),Vn=null,Jn=!1,Qr=0;for(let e of Object.keys(Te))delete Te[e];zn.length=0,ht.clear(),Wn.clear(),qe.clear(),et.clear(),kt.clear(),Us("disconnected")}function Zc(){gt({type:"ping"})}function eu(e){return qe.has(e)?et.get(e)??"pending":"unsubscribed"}function tu(e,t=5e3){return!qe.has(e)||lt?Promise.resolve(!1):et.get(e)==="ready"&&D&&D.readyState===WebSocket.OPEN?Promise.resolve(!0):(nn(),new Promise(n=>{let r=!1,s=kt.get(e)??[],i=()=>{r||(r=!0,clearTimeout(o),n(!0))};s.push(i),kt.set(e,s);let o=setTimeout(()=>{if(r)return;r=!0;let a=kt.get(e);if(a){let c=a.indexOf(i);c!==-1&&a.splice(c,1),a.length===0&&kt.delete(e)}n(!1)},t)}))}function nu(e){let t=qe.get(e);if(!t){ne("resubscribePath: no active subscription for",e);return}D&&D.readyState===WebSocket.OPEN?(ne("resubscribePath: re-sending frame for",e),bo(t.path,t.event_types)):(et.set(e,"pending"),nn())}function Ls(e){Ds.push(e);try{e(yo)}catch{}return()=>{let t=Ds.indexOf(e);t!==-1&&Ds.splice(t,1)}}oe(wo);function ru(){return new Date().toISOString()}function su(){return crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function Ne(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||ru(),updated_at:e.updated_at||ru(),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 Kr(e){return(e.content?.items||e.items||[]).map(Ne)}async function Lr(e){try{let t=await P("read",{id:e});if(t.item_name||t.item_path){let r=Ne(t);return r.path&&N().setQueryData(k.item(r.path),r),r}let n=t.item;if(n){let r=Ne(n);return r.path&&N().setQueryData(k.item(r.path),r),r}return null}catch{return null}}async function Br(e){try{let t=await P("read",{path:e});if(t.item_name||t.item_path)return Ne(t);let n=t.item;return n?Ne(n):null}catch{return null}}async function jr(e){try{let t=await P("list",{path:e,limit:200}),n=Kr(t);for(let r of n)N().setQueryData(k.item(r.path),r);return n}catch(t){return console.error(`[gateway] Failed to fetch children of ${e}:`,t),[]}}async function iu(e,t){let{items:n}=await rn({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 js(e,t,n){try{let r=await P("list",{path:e,limit:t,offset:n}),s=Kr(r);for(let i of s)N().setQueryData(k.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 Hs(e){let n=await P("types-list",e?{scope_id:e}:{}),r=n.content?.items||n.items||[],s=new Map;for(let i of r){let o=i.name,a=i.type_data;!o||!a||s.set(o,{type_key:o,display_name:a.display_name||o,display_name_plural:a.display_name_plural||o+"s",icon:a.icon||"File",color:a.color||"gray",description:a.description||"",input_schema:a.input_schema||{},system_schema:a.system_schema||{},json_schema:a.input_schema||a.json_schema||{},default_data:a.default_data||{},field_defaults:a.field_defaults||{},renderer_config:a.renderer_config||{},is_system:a.is_system??!1,is_active:a.is_active??!0,is_container:a.is_container??!1,is_scope:a.is_scope??!1,render_mode:a.render_mode||"none",placement_mode:a.placement_mode,direct_parent_types:a.direct_parent_types,allowed_parent_types:a.allowed_parent_types,governed_create:a.governed_create,create_method:a.create_method,dedup:a.dedup,edges:a.edges,events:a.events})}return s}async function $s(e){try{let t=await P("edges",{item_id:e}),n=t.outgoing||[],r=t.incoming||[],s=[];for(let i of n)s.push({id:i.edge_id||su(),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||su(),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 Vs(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 P("tree",s),o=Kr(i);for(let a of o)N().setQueryData(k.item(a.path),a);return o}catch(s){return console.error(`[gateway] Failed to fetch tree at ${e}:`,s),[]}}async function Ws(e,t=50,n=0){try{let r=await P("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 Hr(e,t={}){let{limit:n=50,offset:r=0,include_snapshots:s=!1}=t;try{let i=await P("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 Gs(e,t=50,n=0){return Hr(e,{limit:t,offset:n})}async function zs(e,t,n){try{let r={scope_id:e};t?.length&&(r.item_types=t),n&&(r.limit=n);let s=await P("member-focus",r),i=Kr(s);for(let o of i)N().setQueryData(k.item(o.path),o);return i}catch(r){return console.error(`[gateway] Failed to fetch member focus for scope ${e}:`,r),[]}}async function $r(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 P("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 Zn(e){return!!e&&(!!e.type||Array.isArray(e.any_of)&&e.any_of.length>0)}function Hp(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 $p=["catalog","parent_only","internal"];function ou(e,t={}){if(!e||typeof e!="object")return null;let n=o=>typeof o=="string"||typeof o=="number"||typeof o=="boolean",r=o=>{let a={},c={};for(let[l,d]of Object.entries(o))l.startsWith("field.")&&l.length>6&&n(d)?a[l.slice(6)]=d:l.startsWith("field_in.")&&l.length>9&&Array.isArray(d)&&(c[l.slice(9)]=d.filter(n));return{fields:a,field_in:c}},s={};typeof e.type=="string"&&e.type&&(s.type=e.type),typeof e.sort_by=="string"&&(s.sort_by=e.sort_by),(e.sort_dir==="asc"||e.sort_dir==="desc")&&(s.sort_dir=e.sort_dir),typeof e.name=="string"&&e.name&&(s.name=e.name),typeof e.tag=="string"&&e.tag&&(s.tag=e.tag),typeof e.discovery=="string"&&$p.includes(e.discovery)&&(s.discovery=e.discovery);let i=r(e);if(Object.keys(i.fields).length&&(s.fields=i.fields),Object.keys(i.field_in).length&&(s.field_in=i.field_in),Array.isArray(e.any_of)){let o=[];for(let a of e.any_of){if(!a||typeof a!="object"||Array.isArray(a))continue;let c=a,l={};typeof c.item_type=="string"&&c.item_type&&(l.item_type=c.item_type);let d=r(c);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 Zn(s)?{...s,...t}:null}async function rn(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(Hp)),Object.keys(r).length>0&&(n.filters=r),e.limit!=null&&(n.limit=e.limit);try{let s=await P("query",n,t);e.spaceIds!==void 0&&jc(e.spaceIds,s.selected_space_ids??s.content?.selected_space_ids);let i=Kr(s);for(let o of i)N().setQueryData(k.item(o.path),o);return{items:i,total_hint:s.total??s.content?.total??i.length}}catch(s){if(t.signal?.aborted||s instanceof Error&&s.name==="AbortError"||(console.error(`[gateway] Failed to fetch items of type ${e.type??"(any_of)"}:`,s),t.throwOnError||e.spaceIds!==void 0))throw s;return{items:[],total_hint:0}}}function au(e){if(!e||typeof e!="object")return;let t=e;if(t.state==="unavailable")return{state:"unavailable"};if(!(t.state!=="available"||typeof t.message_id!="string"||typeof t.path!="string"||typeof t.excerpt!="string"))return{state:"available",message_id:t.message_id,path:t.path,role:typeof t.role=="string"?t.role:void 0,sender_principal_id:typeof t.sender_principal_id=="string"?t.sender_principal_id:void 0,sender_display_name:typeof t.sender_display_name=="string"?t.sender_display_name:void 0,excerpt:t.excerpt,truncated:t.truncated===!0}}async function cu(e){if(!e.channel_id&&!e.channel_path)throw new Error("A message requires a channel.");let t=e.reply_to_message_id!==void 0;if(t&&(typeof e.reply_to_message_id!="string"||!e.reply_to_message_id.trim()))throw new Error("A contextual reply requires a target message ID.");if(t&&(e.conversation_mode==="new_thread"||e.hand_off_to))throw new Error("A contextual reply stays in the current conversation.");return await P(t?"reply-message":"send-message",e)}async function uu(e,t){let n=new Set(e),r=[...n];if(!r.length)return{};if(r.length>200)throw new Error("Reply context supports at most 200 messages per batch.");let i=(await P("message-replies",{operation:"context",message_ids:r},t)).replies;if(!i||typeof i!="object"||Array.isArray(i))throw new Error("Invalid reply-context response.");return Object.fromEntries(Object.entries(i).flatMap(([o,a])=>{let c=au(a);return c&&n.has(o)?[[o,c]]:[]}))}async function Js(e,t={},n){let r=t.limit??25;if(!Number.isInteger(r)||r<1||r>100)throw new Error("Reply page size must be between 1 and 100.");let s=await P("message-replies",{operation:"list",message_id:e,limit:r,...t.cursor?{cursor:t.cursor}:{},...t.conversationRootId?{conversation_root_id:t.conversationRootId}:{}},n);if(!Array.isArray(s.messages))throw new Error("Invalid reply-list response.");let i=s.next_cursor;if(i&&(typeof i.updated_at!="string"||typeof i.edge_id!="string"))throw new Error("Invalid reply-list cursor.");let o=new Map(Xn(s.messages).map(a=>[a.id,a]));return{messages:s.messages.flatMap(a=>{let c=o.get(a.id);return c?[c]:[]}),next_cursor:i??null}}function Vp(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 lu(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:Vp(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 Xn(e){return e.filter(t=>t.item_type==="message").map(t=>{let n=t.type_data||{},r="user";n.role==="assistant"?r="assistant":n.role==="system"&&(r="system");let s=n.metadata||{};return{id:t.id||"",path:t.path||"",content:n.message||n.content||"",created_at:t.created_at||"",role:r,status:typeof n.status=="string"?n.status:void 0,delivery_state:typeof n.delivery_state=="string"?n.delivery_state:void 0,cognition_event_id:typeof n.cognition_event_id=="string"?n.cognition_event_id:void 0,seq:n.seq||0,principal_id:n.principal_id,member_id:typeof n.member_id=="string"?n.member_id:void 0,sender_display_name:typeof n.sender_display_name=="string"?n.sender_display_name:void 0,sender_is_ai:typeof n.sender_is_ai=="boolean"?n.sender_is_ai:void 0,sender_role_display_name:typeof n.sender_role_display_name=="string"?n.sender_role_display_name:void 0,reply_count:n.reply_count||0,member_count:n.member_count||0,parent_message_id:n.parent_message_id,reply_to:au(t.reply_to),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 du(e,t){try{let n={channel_path:e};t&&(n.parent_message_id=t);let s=await P("get-channel-messages",n),i=s.messages||s.content?.items||s.items||[];return Xn(i)}catch(n){throw console.error(`[gateway] Failed to fetch channel messages for ${e}:`,n),n}}async function Ys(e,t){try{let n={channel_path:e};t&&(n.parent_message_id=t);let s=await P("get-channel-messages",n),i=s.messages||[],o=Xn(i),a=lu(i),c=new Map,l=[];for(let d of a)if(d.parentMessagePath){let u=c.get(d.parentMessagePath)||[];u.push(d),c.set(d.parentMessagePath,u)}else l.push(d);return{messages:o,activityMessages:Xn(s.activity_messages||[]),messageCards:c,siblingCards:l,mode:s.mode||"top_level"}}catch(n){throw console.error(`[gateway] Failed to fetch channel messages with cards for ${e}:`,n),n}}async function sn(e,t){try{let n={channel_path:e};t?.parentMessageId&&(n.parent_message_id=t.parentMessageId),t?.conversationsOnly&&(n.conversations_only=!0),t?.transcriptOnly&&(n.transcript_only=!0),t?.limit&&(n.limit=t.limit),t?.before_seq!=null&&(n.before_seq=t.before_seq),t?.after_seq!=null&&(n.after_seq=t.after_seq);let s=await P("get-channel-messages",n);if(t?.conversationsOnly&&s.conversations_only!==!0)throw new Error("This server does not support conversation history lists yet. Update the message reader.");if(t?.transcriptOnly&&s.transcript_only!==!0)throw new Error("This server does not support channel transcript pages yet. Update the message reader.");let i=s.messages||[],o=lu(i),a=new Map,c=[];for(let l of o)if(l.parentMessagePath){let d=a.get(l.parentMessagePath)||[];d.push(l),a.set(l.parentMessagePath,d)}else c.push(l);return{messages:Xn(i),activityMessages:Xn(s.activity_messages||[]),messageCards:a,siblingCards:c,mode:s.mode||"top_level"}}catch(n){throw console.error(`[gateway] Failed to fetch channel messages page for ${e}:`,n),n}}function Bs(e){N().invalidateQueries({queryKey:k.children(e)})}function So(e){N().invalidateQueries({queryKey:k.item(e)})}function pu(e,t){So(e),Bs(e);let n=e.split("/");n.pop();let r=n.join("/")||t;r&&Bs(r)}function fu(e){let t=e+"/";N().invalidateQueries({predicate:n=>{let r=n.queryKey;return r[0]!=="vfs"?!1:r.some(s=>typeof s=="string"&&(s===e||s.startsWith(t)))}})}function mu(){N().invalidateQueries({queryKey:k.all()})}function hu(e){N().invalidateQueries({queryKey:k.types(e)})}function gu(e,t){e?N().invalidateQueries({queryKey:k.channelMessages(e,t)}):N().invalidateQueries({queryKey:k.allChannelMessages()})}function yu(e,t){e&&t?N().invalidateQueries({queryKey:k.openEnvelope(e,t)}):e?N().invalidateQueries({predicate:n=>{let r=n.queryKey;return r[0]==="vfs"&&r[2]==="open"&&r[3]===e}}):N().invalidateQueries({queryKey:k.allOpenEnvelopes()})}var Xs=new WeakMap;function xo(e,t){let n,r=window.__FSAOS_REGISTER__,s=window.__FSAOS_COMPONENT__;window.__FSAOS_REGISTER__=i=>{n=i},delete window.__FSAOS_COMPONENT__;try{e(t);let i=n??window.__FSAOS_COMPONENT__;return i?.default||i}finally{r===void 0?delete window.__FSAOS_REGISTER__:window.__FSAOS_REGISTER__=r,s===void 0?delete window.__FSAOS_COMPONENT__:window.__FSAOS_COMPONENT__=s}}async function Zs(e){let t=new Uint8Array(await crypto.subtle.digest("SHA-256",e));return Array.from(t,n=>n.toString(16).padStart(2,"0")).join("")}function Wp(e){return`window.__FSAOS_COMPONENT_SCRIPT__?.(document.currentScript, function(require) {
|
|
3
|
+
`+e+`
|
|
4
|
+
});
|
|
5
|
+
`}function ei(){return typeof window>"u"?void 0:window.__FSAOS_CONFIG__?.componentScriptPath}async function _u(e,t,n,r){let s=V(),i=Ie(),o=()=>s===V()&&i===Ie(),a=new URL(e,window.location.origin);if(a.origin!==window.location.origin||a.search||a.hash)throw new Error("The component script endpoint must be on the host page\u2019s origin.");let[c,l]=await Promise.all([fetch(a,{method:"POST",credentials:"same-origin",redirect:"error",cache:"no-store",headers:{"Content-Type":"application/json"},referrerPolicy:"strict-origin",signal:AbortSignal.timeout(3e4),body:JSON.stringify(n)}),crypto.subtle.digest("SHA-256",new TextEncoder().encode(Wp(t)))]);if(!c.ok)throw new Error(`The component script could not be prepared (HTTP ${c.status}).`);let{path:d}=await c.json();if(typeof d!="string"||!d.startsWith(a.pathname+"/")||!/^\/[a-f0-9-]{36}\.js$/.test(d.slice(a.pathname.length)))throw new Error("The component script did not have a valid host URL.");if(!o())throw new Error("The account or Space changed while loading the component.");return new Promise((u,m)=>{let p=document.createElement("script");p.src=new URL(d,a).href,p.integrity="sha256-"+btoa(String.fromCharCode(...new Uint8Array(l))),p.referrerPolicy="no-referrer",p.async=!0;let h=()=>{clearTimeout(y),Xs.delete(p),p.remove()},g=S=>{h(),m(new Error(S))},y=setTimeout(()=>g("The component script did not finish loading."),3e4);Xs.set(p,S=>{if(h(),!o()){m(new Error("The account or Space changed while loading the component."));return}try{u(xo(S,r))}catch(_){m(_)}}),window.__FSAOS_COMPONENT_SCRIPT__=(S,_)=>{S&&Xs.get(S)?.(_)},p.onerror=()=>g("The component script failed to load or did not match its verified bytes."),p.onload=()=>{Xs.has(p)&&g("The component script did not register.")},document.head.appendChild(p)})}function tt(e){return{id:e.accountId,path:e.path,kind:e.isSpace?"space":"account",name:e.name,grantedUnderAccountId:e.grantedUnderAccountId??void 0}}async function ti(){return((await P("list-memberships",{})).memberships||[]).map(n=>({accountId:n.account_id,path:n.account_path,name:n.account_name,role:n.role||"member",typeData:n.account_type_data||{},joinedAt:n.joined_at,via:n.via,placement:n.placement,subordinateTo:n.subordinate_to??null,cascadeAnchorId:n.cascade_anchor_id??null,isAccount:n.is_account??void 0,isSpace:n.is_space??void 0,isOwner:n.is_owner??void 0,billingResponsible:n.billing_responsible??void 0,grantedVia:n.granted_via??null,invitationAccepted:n.invitation_accepted===!0,grantedUnderAccountId:n.granted_under_account_id??null,membershipPath:n.membership_path??null,personalSpaceId:n.personal_space_id??null,personalSpacePath:n.personal_space_path??null}))}var er=new Map,Wr=null,ni=null,Ot=new Map,bu=250,Vr=new Map;function on(e){if(Wr){tr(e);return}tr(e),Wr=X("vfs_change",t=>Gp(t)),ni=X("ccm_change",t=>zp(t))}function tr(e){if(er.has(e))return;let t=Yn(e,["vfs_change","ccm_change"]);er.set(e,t)}function ri(e){let t=er.get(e);t&&(t(),er.delete(e))}function Ro(){for(let[,e]of er)e();er.clear(),Wr&&(Wr(),Wr=null),ni&&(ni(),ni=null),Ot.forEach(e=>clearTimeout(e)),Ot.clear(),Vr.clear()}oe(Ro);function Gp(e){let t=e.path,n=e.action;if(!t)return;let r=t.split("/");r.pop();let s=r.join("/")||"/root",i=Vr.get(s);i||(i=new Map,Vr.set(s,i)),i.set(t,{action:n,itemId:typeof e.item_id=="string"?e.item_id:void 0});let o=Ot.get(s);o&&clearTimeout(o);let a=setTimeout(()=>{Ot.delete(s);let c=Vr.get(s);Vr.delete(s),c&&Jp(s,c)},bu);Ot.set(s,a)}function zp(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=Ot.get(s);i&&clearTimeout(i);let o=setTimeout(()=>{Ot.delete(s),t&&N().invalidateQueries({queryKey:k.edges(t)}),n&&N().invalidateQueries({queryKey:k.edges(n)})},bu);Ot.set(s,o)}function Jp(e,t){let n=N();for(let[s,i]of t)(i.action||"").toUpperCase()==="DELETE"?(n.removeQueries({queryKey:k.item(s)}),n.removeQueries({queryKey:k.children(s)}),n.removeQueries({queryKey:k.tree(s)})):ce(n,k.item(s),{exact:!0}),i.itemId&&n.invalidateQueries({queryKey:k.itemById(i.itemId)});n.invalidateQueries({queryKey:k.children(e)});let r=[...t.keys()];n.invalidateQueries({predicate:s=>{let i=s.queryKey;if(i[0]!=="vfs"||i[1]!=="tree")return!1;let o=i[2];return r.some(a=>a.startsWith(o+"/")||a===o)}})}var nr=null;oe(()=>{nr=null});function Ft(e){if(e!==nr||e.generation!==V())throw new Error("Workspace session changed")}function Yp(e){return e instanceof ve&&e.payload?.error==="item_not_found"}function Gr(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 zr(e){let t=_e();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 vu(e,t){return JSON.stringify({mounts:e.map(n=>n.id),last_anchor:t.id})}async function wu(e,t,n){Ft(e);let r=vu(t,n);if(e.saved===r)return;let s=JSON.parse(r);await P(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}),Ft(e),e.exists=!0,e.saved=r}function Su(e,t){let n=Ce();on(_e().id);for(let r of n)e.some(s=>s.id===r.id)||ri(r.id);for(let r of e)tr(r.id);sc(e,t)}async function an(e,t,n={}){let r=_e();if(!r)throw new Error("Elect a home account before loading mounts");let s=`${e}/settings/mounts`;if(nr&&nr.path!==s)throw new Error("Reset the session before changing the mount declaration owner");let i=nr??(nr={generation:V(),path:s,scope:r.path,resolve:t,exists:!1,ready:!1,saved:null,queue:Promise.resolve()});return Ft(i),i.resolve=t,i.loading?i.loading:i.ready?Ce():(i.loading=(async()=>{let o=null;try{let d=await P("read",{path:s,_scope_path:i.scope});if(Ft(i),o=d.type_data??d.item?.type_data,!o||!Array.isArray(o.mounts)||!o.mounts.every(u=>typeof u=="string"))throw new Error("Invalid saved mount declaration");i.exists=!0}catch(d){if(Ft(i),!Yp(d))throw d;i.exists=!1}let a=n.initialAnchor?Gr(i,n.initialAnchor):r,c=zr(o?o.mounts.map(d=>i.resolve(d)).filter(d=>d!==null):[a]),l=o?c.find(d=>d.id===o.last_anchor)??c.find(d=>d.kind==="space")??r:a;return o?i.saved=vu(c,l):n.initialAnchor&&await wu(i,c,l),Ft(i),i.ready=!0,Su(c,l),c})().finally(()=>{i.loading=void 0}),i.loading)}function si(e){let t=nr;if(!t?.ready)return Promise.reject(new Error("Workspace mounts are not loaded"));let n=t.queue.then(async()=>{Ft(t);let{refs:r,anchor:s}=e(t);await wu(t,r,s),Ft(t),Su(r,s)});return t.queue=n.catch(()=>{}),n}function Co(e){return si(t=>({refs:zr([...Ce(),Gr(t,e)]),anchor:pe()}))}function xu(e){return si(()=>{if(e===_e().id)throw new Error("The home account cannot be unmounted");let t=zr(Ce().filter(r=>r.id!==e)),n=t.find(r=>r.id===pe()?.id)??t.find(r=>r.kind==="space")??_e();return{refs:t,anchor:n}})}function Jr(e){return si(t=>{let n=Gr(t,e);return{refs:zr([...Ce(),n]),anchor:n}})}function ii(e,t){return si(n=>{let r=zr(e.map(i=>Gr(n,i))),s=Gr(n,t);if(!r.some(i=>i.id===s.id))throw new Error("Selected mount must be in the working set");return{refs:r,anchor:s}})}var Po={};ca(Po,{Badge:()=>rf,Breadcrumbs:()=>hf,Button:()=>of,Card:()=>nf,DataView:()=>cf,Detail:()=>df,Empty:()=>af,FilePreview:()=>_f,Form:()=>lf,Grid:()=>ef,Image:()=>gf,Link:()=>ff,Page:()=>Xp,Router:()=>pf,Sidebar:()=>tf,Spinner:()=>sf,Stack:()=>Zp,Table:()=>uf,Tabs:()=>mf,Video:()=>yf});var Z=J(ue(),1);function Ru(){return(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||""}function Xp(e){return(0,Z.createElement)("div",{style:{minHeight:"100vh",display:"flex",flexDirection:"column"},className:e.className||""},e.children)}function Zp(e){let t=e.direction||"vertical";return(0,Z.createElement)("div",{style:{display:"flex",flexDirection:t==="horizontal"?"row":"column",gap:e.gap||"0.5rem",padding:e.padding||"0",alignItems:e.align||"stretch",justifyContent:e.justify||"flex-start",flex:e.flex||"initial"},className:e.className||""},e.children)}function ef(e){return(0,Z.createElement)("div",{style:{display:"grid",gridTemplateColumns:"repeat("+(e.columns||3)+", 1fr)",gap:e.gap||"1rem",padding:e.padding||"0"},className:e.className||""},e.children)}function tf(e){return(0,Z.createElement)("div",{style:{display:"flex",flexDirection:"row",minHeight:"100vh"},className:e.className||""},e.children)}function nf(e){return(0,Z.createElement)("div",{style:{border:"1px solid var(--color-border, #e5e7eb)",borderRadius:"var(--border-radius, 0.5rem)",padding:e.padding||"1rem",background:"var(--color-surface, #fff)"},className:e.className||"",onClick:e.onClick},e.children)}function rf(e){return(0,Z.createElement)("span",{style:{display:"inline-flex",alignItems:"center",padding:"0.125rem 0.5rem",fontSize:"0.75rem",fontWeight:"500",borderRadius:"9999px",background:e.color||"#e5e7eb",color:e.textColor||"#374151"},className:e.className||""},e.children||e.label)}function sf(e){let t=e.size||"1.5rem";return(0,Z.createElement)("div",{style:{width:t,height:t,border:"2px solid #e5e7eb",borderTopColor:"var(--color-primary, #3b82f6)",borderRadius:"50%",animation:"fsaos-spin 0.6s linear infinite"}})}function of(e){return(0,Z.createElement)("button",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",padding:"0.5rem 1rem",fontSize:"0.875rem",fontWeight:"500",borderRadius:"var(--border-radius, 0.375rem)",border:e.variant==="outline"?"1px solid var(--color-border, #d1d5db)":"none",background:e.variant==="outline"||e.variant==="ghost"?"transparent":"var(--color-primary, #3b82f6)",color:e.variant==="outline"||e.variant==="ghost"?"var(--color-text, #1a1a1a)":"#fff",cursor:e.disabled?"not-allowed":"pointer",opacity:e.disabled?"0.5":"1",gap:"0.5rem"},className:e.className||"",onClick:e.onClick,disabled:e.disabled},e.children||e.label)}function af(e){return(0,Z.createElement)("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:"3rem",color:"var(--color-text-secondary, #6b7280)",textAlign:"center"}},e.icon?(0,Z.createElement)("div",{style:{fontSize:"2rem",marginBottom:"0.5rem"}},e.icon):null,(0,Z.createElement)("div",{style:{fontWeight:500,marginBottom:"0.25rem"}},e.title||e.message||e.children||"No items"),e.description?(0,Z.createElement)("div",{style:{fontSize:"0.875rem",opacity:.7}},e.description):null)}function cf(e){return(0,Z.createElement)("div",{className:e.className||""},e.children)}function uf(e){return(0,Z.createElement)("table",{className:e.className||""},e.children)}function lf(e){return(0,Z.createElement)("form",{className:e.className||"",onSubmit:e.onSubmit},e.children)}function df(e){return(0,Z.createElement)("div",{className:e.className||""},e.children)}function pf(e){return(0,Z.createElement)("div",null,e.children)}function ff(e){return(0,Z.createElement)("a",{href:e.href||e.to,className:e.className||"",onClick:e.onClick},e.children)}function mf(e){return(0,Z.createElement)("div",{className:e.className||""},e.children)}function hf(e){return(0,Z.createElement)("nav",{className:e.className||""},e.children)}function gf(e){return(0,Z.createElement)("img",{src:e.src||(e.path?Ru()+e.path:""),alt:e.alt||"",className:e.className||"",style:e.style})}function yf(e){return(0,Z.createElement)("video",{src:e.src||(e.path?Ru()+e.path:""),controls:!0,className:e.className||""})}function _f(e){return(0,Z.createElement)("div",{className:e.className||""},e.children||"File preview")}function oi(e){if(typeof e.path!="string")return!1;let t=[...Ce().map(n=>n.path),pe()?.path].filter(n=>!!n);return!t.length&&z()&&t.push(z()),t.some(n=>se(e.path,n))}function rr(e,t,n,r){if(!["message","card"].includes(e?.item_type)||!se(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&&se(e.path,i)})}var Cu=new WeakMap,Eo=e=>e.slice(0,e.lastIndexOf("/")),Io=e=>e.action?.toLowerCase();function Pu(e,t){return e.item_type==="message"&&Io(e)==="insert"&&Eo(e.path)===t&&!e.old_path}function bf(e,t,n){return e.messages.filter(r=>t.has(r.id)||n.has(r.path))}function vf(e,t,n,r){let s=e.pages.slice(),i=new Map(n?.messages.map(l=>[l.id,l]));for(let[l,d]of t){let u=s[l],m=new Set(d.map(h=>h.id)),p=new Map(u.messageCards);for(let h of d){p.delete(h.path);let g=i.get(h.id),y=g&&n?.messageCards.get(g.path);g&&y?.length&&p.set(g.path,y)}s[l]={...u,messages:u.messages.flatMap(h=>{if(!m.has(h.id))return[h];let g=i.get(h.id);return g?[g]:[]}),messageCards:p}}let o=r??n,a=s[0],c=new Map(a.messageCards);for(let l of a.activityMessages??[])c.delete(l.path);for(let l of[...o.activityMessages??[],...r?.messages??[]]){let d=o.messageCards.get(l.path);d?.length&&c.set(l.path,d)}return s[0]={...a,messages:r?[...a.messages,...r.messages]:a.messages,activityMessages:o.activityMessages,siblingCards:o.siblingCards,messageCards:c},{...e,pages:s}}function Eu(e,t,n,r){let s=Cu.get(e);s||(s=new Map,Cu.set(e,s));let i=JSON.stringify(t),o=s.get(i);if(!o){let c,l=!1,d=!1,u=new Map,m=()=>e.getQueryData(t),p=()=>e.getQueryCache().find({queryKey:t,exact:!0}),h=()=>ce(e,t,{exact:!0}),g=(w,x)=>sn(n,{transcriptOnly:!0,limit:r,after_seq:w,before_seq:x}),y=()=>{d||l||c||!u.size||(c=setTimeout(()=>{c=void 0,S()},500))},S=async()=>{l=!0;let w=[...u.values()];u.clear();let x=p();try{if(x?.state.fetchStatus==="fetching"&&await x.promise?.catch(()=>{}),d||x!==p())return;let b=m();if(!b?.pages.length){await h();return}let E=new Set,I=new Set,C=new Set,A=!1;for(let j of w){if(Pu(j,n)){A=!0;continue}j.inserted&&(A=!0),j.item_type==="message"&&Eo(j.path)===n&&!j.inserted&&Io(j)!=="delete"&&C.add(j.path),j.item_id&&E.add(j.item_id),j.parent_id&&E.add(j.parent_id);for(let $e of[j.path,j.old_path])$e&&se($e,n)&&(I.add($e),I.add(Eo($e)))}let O=new Map,M=1/0,F=0;(E.size||I.size)&&b.pages.forEach((j,$e)=>{let Dt=bf(j,E,I);Dt.length&&O.set($e,Dt);for(let lr of Dt)C.delete(lr.path),M=Math.min(M,lr.seq),F=Math.max(F,lr.seq)});for(let j of b.pages[0].activityMessages??[])C.delete(j.path);if(C.size){await h();return}if(O.size&&(!Number.isSafeInteger(M)||M<1||!Number.isSafeInteger(F+1))){await h();return}let Q=b.pages.find(j=>j.messages.length)?.messages.at(-1)?.seq??0,[B,ae]=await Promise.all([O.size?g(M-1,F+1):void 0,A||!O.size?g(Q):void 0]);if(d||x!==p())return;let He=m();if(x?.state.fetchStatus==="fetching"||b.pages.some((j,$e)=>He?.pages[$e]!==j)||B&&B.messages.length>=r&&(B.messages.at(-1)?.seq??0)<F||ae&&ae.messages.length>=r){await h();return}e.setQueryData(t,j=>j&&vf(j,O,B,ae))}catch{!d&&x===p()&&await h()}finally{l=!1,y()}},_=X("vfs_change",w=>{let x=w.item_id??w.path,b=u.get(x);u.set(x,b&&(b.inserted||Pu(b,n))&&Io(w)==="update"&&b.path===w.path?{...w,inserted:!0}:w),y()},w=>rr(w,n,void 0,[])||!!w.old_path&&rr({...w,path:w.old_path},n,void 0,[])||w.item_type==="message"&&!!w.parent_id&&se(w.path,n)&&!!m()?.pages.some(x=>x.messages.some(b=>b.id===w.parent_id)));o={users:0,stop:()=>{d=!0,_(),c&&clearTimeout(c),u.clear()}},s.set(i,o)}o.users++;let a=!1;return()=>{a||(a=!0,--o.users===0&&(o.stop(),s.delete(i)))}}var Iu=new WeakMap;function Tu(e,t,n){let r=Iu.get(e);r||(r=new Map,Iu.set(e,r));let s=JSON.stringify(t),i=r.get(s);if(!i){let a=!1,c,l=!1,d=!1,u=new Set,m=new Set,p=()=>e.getQueryData(t)??[],h=()=>{a||l||c||(c=setTimeout(()=>{c=void 0,g()},250))},g=async()=>{if(a)return;l=!0;let x=d;d=!1;let b=[...u],E=new Set(m);m.clear(),u.clear();try{if(x)await ce(e,t,{exact:!0});else{let C=(await Promise.allSettled(b.map(async A=>{let O=e.getQueryCache().find({queryKey:t,exact:!0});if(!O)return;let M=await P("read",{id:A});if(M.success===!1)throw new Error("Channel refresh failed");if(a||!O||e.getQueryCache().find({queryKey:t,exact:!0})!==O)return;let F=Ne(M.item??M);if(F.id!==A||F.item_type!=="channel")return;let Q=p().find(He=>He.id===A);if(!Q)return;let B=n({...F}),ae={...Q,path:B.path,name:B.name,displayName:B.displayName,messageCount:B.messageCount,aiMode:B.aiMode,activeAgentIds:B.activeAgentIds,isPrivate:B.isPrivate,isDm:B.isDm,autoPilot:B.autoPilot,isArchived:B.isArchived,updatedAt:B.updatedAt};E.has(A)&&(Q.name!==ae.name||Q.displayName!==ae.displayName||Q.path!==ae.path)&&(d=!0),e.setQueryData(t,He=>He?.map(j=>j.id===A?ae:j))}))).find(A=>A.status==="rejected");if(C?.status==="rejected")throw C.reason}}catch(I){console.warn("[channels] refresh failed",I)}finally{l=!1,(d||u.size)&&h()}},y=x=>p().some(b=>b.id===x.item_id||b.path===x.path)?!0:oi(x),S=x=>{if(!y(x))return;let b=String(x.action??"").toLowerCase();if(["insert","delete","rename","move"].includes(b))d=!0;else if(b==="update"){let E=p().find(I=>I.id===x.item_id||I.path===x.path);E&&(u.add(E.id),m.add(E.id))}(d||u.size)&&h()},_=x=>{let b=p().find(E=>E.id===x.parent_id);b&&(u.add(b.id),h())},w=["vfs_change","ccm_change"].flatMap(x=>[X(x,S,b=>b.item_type==="channel"),X(x,_,b=>b.item_type==="message")]);i={users:0,stop:()=>{a=!0,c&&clearTimeout(c),w.forEach(x=>x())}},r.set(s,i)}i.users++;let o=!1;return()=>{o||(o=!0,--i.users===0&&(i.stop(),r.delete(s)))}}var Au=new WeakMap;function Mu(e,t,n){let r=Au.get(e);r||(r=new Map,Au.set(e,r));let s=JSON.stringify(t),i=r.get(s);if(!i){let a,c=()=>{a||(a=setTimeout(()=>{a=void 0,ce(e,t,{exact:!0})},250))},l=[X("ccm_change",c,d=>d.edge_type==="replies_to"&&(d.target_item_id??d.target_id)===n),X("vfs_change",c,d=>{let u=d.item_id??d.id;return u?u===n?!0:e.getQueryData(t)?.pages.some(p=>p.messages.some(h=>h.id===u))??!1:!1})];i={users:0,stop:()=>{a&&clearTimeout(a),l.forEach(d=>d())}},r.set(s,i)}i.users++;let o=!1;return()=>{o||(o=!0,--i.users===0&&(i.stop(),r.delete(s)))}}var ai=J(ue(),1);var To=new Set(["view","edit","delete","admin"]),ku=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function wf(e){let t=e.item??e,n=t.id??t.item_id,r=t.path??t.item_path;if(e.success!==!0||typeof n!="string"||!ku.test(n))throw new Error("PERMISSION_TARGET_UNAVAILABLE");return{id:n,...typeof r=="string"?{path:r}:{}}}function ci(e,t){(0,ai.useSyncExternalStore)(be,W,W);let n=(0,ai.useSyncExternalStore)(Nr,Bn,Bn),r=(0,ai.useSyncExternalStore)(Ln,At,At),s=z(),i=Ze()?.principal_id,o=e?.trim()??"",a=[...new Set(t??[])].sort(),c=ku.test(o),l=c||o.startsWith("/root/")||o==="/root",d=a.some(I=>!To.has(I))||!!(o&&!l),u=!!(s&&i&&o&&a.length&&!d),m=["vfs",s??"__unscoped__","permissions",i??"__anonymous__",n,r],p=[...new Set([pe()?.id,...Ce().map(I=>I.id)].filter(I=>!!I))],h=[...m,"target",o],g=H({queryKey:h,queryFn:async({signal:I})=>{if(!u||!s)throw new Error("PERMISSION_CONTEXT_REQUIRED");return wf(await P("read",{path:o,_scope_path:s},{signal:I}))},enabled:u&&!c,staleTime:1/0,gcTime:0,retry:!1,refetchOnWindowFocus:!1,refetchOnReconnect:!1,refetchOnMount:!1,meta:{permissionQuery:{scope:s,scopeIds:p,path:o,targetLookup:!0}}}),y=c?{id:o}:g.data,S=c||g.isSuccess&&!g.isFetching&&!g.isStale,_=Ji({queries:a.filter(I=>To.has(I)).map(I=>({queryKey:[...m,"check",y?.id??o,I],queryFn:async({signal:C})=>{if(!u||!s||!y)throw new Error("PERMISSION_CONTEXT_REQUIRED");let A=await P("check-item-access",{id:y.id,action:I,_scope_path:s},{signal:C});if(A.success!==!0||typeof A.allowed!="boolean")throw new Error("PERMISSION_RESPONSE_INVALID");return A.allowed},enabled:u&&S&&!!y,staleTime:1/0,gcTime:0,retry:!1,refetchOnWindowFocus:!1,refetchOnReconnect:!1,refetchOnMount:!1,meta:{permissionQuery:{scope:s,scopeIds:p,itemId:y?.id,path:y?.path??(c?void 0:o)}}}))}),w=d?new Error("PERMISSION_INPUT_INVALID"):!c&&g.error||_.find(I=>I.error)?.error||null,x=u&&S&&!w,b=a.filter(I=>To.has(I));return{data:Object.fromEntries(a.map(I=>{let C=_[b.indexOf(I)];return[I,!!(x&&C?.isSuccess&&!C.isFetching&&!C.isStale&&C.data===!0)]})),loading:!!(u&&(!c&&g.isFetching||_.some(I=>I.isFetching||I.isPending))&&!w),error:w,refetch:async()=>{if(u){if(!c&&(!g.data||g.isError)){await g.refetch();return}await Promise.all(_.map(I=>I.refetch()))}}}}function Ao(e,t){let n=ci(t,e?[e]:[]);return{...n,data:{allowed:!!(e&&n.data[e])}}}function ee(){return(0,v.useSyncExternalStore)(be,W,W)}function Ku(){return ee(),Cs()}function Lu(e){return ee(),H({queryKey:k.item(e),queryFn:()=>Br(e),enabled:!!e,staleTime:1/0})}function Bu(e){return ee(),H({queryKey:k.itemById(e),queryFn:()=>Lr(e),enabled:!!e,staleTime:1/0})}function ko(e){return ee(),H({queryKey:k.children(e),queryFn:()=>jr(e),enabled:!!e})}function ju(e){let t=ko(e);return{...t,children:t.data??[]}}function Hu(e,t=1){return ee(),H({queryKey:k.tree(e,t),queryFn:()=>Vs(e,t),enabled:!!e})}function $u(e,t){return ee(),H({queryKey:k.search(e,t),queryFn:async()=>{let n={query:e};t?.length&&(n.item_types=t);let r=await P("search",n);return(r.content?.items||r.items||r.results||[]).map(Ne)},enabled:!!e&&e.length>0})}function Vu(e){ee();let t=(0,v.useMemo)(()=>e,[JSON.stringify(e)]);return H({queryKey:["vfs",z()??"__unscoped__","resolve",JSON.stringify(t??{})],queryFn:async()=>await P("resolve",t),enabled:!!t?.query&&t.query.length>0})}function Wu(e){ee();let t=Mt(e),n=(0,v.useMemo)(()=>t,[JSON.stringify(t)]),r=H({queryKey:k.items(n?.type??"",n),queryFn:({signal:s})=>rn(n,{signal:s,throwOnError:!0}),enabled:Zn(n),...n?.spaceIds!==void 0?{retry:(s,i)=>!$n(i)&&Vl(s,i)}:{},select:s=>s.items});return n?.spaceIds!==void 0&&$n(r.error)?{...r,data:void 0}:r}function Oo(e,t={}){let n=ee(),{realtime:r=!1}=t,s=Mt(e),i=s?.limit??20,o=(0,v.useMemo)(()=>s,[JSON.stringify(s)]),a=(0,v.useMemo)(()=>["vfs",z()??"__unscoped__","infinite-items",o?.type??"",JSON.stringify(o??{})],[n,o]),c=kn({queryKey:a,queryFn:async({pageParam:u=0,signal:m})=>rn({...o,limit:i,offset:u},{throwOnError:!0,signal:m,priority:t.priority}),initialPageParam:0,getNextPageParam:(u,m,p)=>{if(!(o?.spaceIds!==void 0&&u.total_hint!==void 0&&p+u.items.length>=u.total_hint)&&!(u.items.length<i))return p+u.items.length},enabled:Zn(o),...o?.spaceIds!==void 0?{retry:(u,m)=>!$n(m)&&Vl(u,m)}:{},staleTime:r?1/0:t.staleTime,meta:r&&o?{infiniteItemsRealtime:{filter:o}}:{}}),l=(0,v.useMemo)(()=>{if(o?.spaceIds!==void 0&&$n(c.error))return[];if(!c.data?.pages)return[];let u=new Set,m=[];for(let p of c.data.pages)for(let h of p.items)h.id&&!u.has(h.id)&&(u.add(h.id),m.push(h));return m},[c.data?.pages,c.error,o]),d=o?.spaceIds!==void 0&&$n(c.error);return{allItems:l,refetch:c.refetch,fetchNextPage:c.fetchNextPage,isFetchingNextPage:c.isFetchingNextPage,isExhausted:d||!c.hasNextPage,isLoading:c.isLoading,isFetching:c.isFetching,error:c.error,totalHint:d?void 0:c.data?.pages?.[0]?.total_hint}}function Ou(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 Rf(e,t){if(e.is_active===!1||e.item_type!==t.type||!se(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 Gu(e,t={}){let n=Ou(e),r=Oo(e,n?{realtime:!1,staleTime:3e4}:{realtime:!0}),s=U(),i=JSON.stringify([z(),Mt(e)]),[o,a]=(0,v.useState)(()=>({identity:i,upserts:{},deleted:new Set})),c=o.identity===i?o:{identity:i,upserts:{},deleted:new Set},l=(0,v.useMemo)(()=>{if(!n)return r.allItems;let p=Object.values(c.upserts),h=new Set(p.map(_=>_.id)),g=[...p,...r.allItems.filter(_=>!h.has(_.id))].filter(_=>!c.deleted.has(_.path)),y=e.sort_by??"updated_at",S=e.sort_dir==="asc"?1:-1;return g.sort((_,w)=>S*String(_[y]??"").localeCompare(String(w[y]??"")))},[n,r.allItems,c,e?.sort_by,e?.sort_dir]),d=(0,v.useRef)(l);d.current=l;let u=(0,v.useRef)(t.shouldReadUpdate);u.current=t.shouldReadUpdate;let m=(0,v.useRef)(r.refetch);return m.current=r.refetch,(0,v.useEffect)(()=>{if(!Ou(e))return;let p=e,h=!1,g=!1,y=!1,S=0,_=new Map,w=()=>{let C=S;m.current().then(A=>{!h&&!A.isError&&S===C&&a({identity:i,upserts:{},deleted:new Set})})},x=C=>{S++,a(O=>{let M=O.identity===i?O:{identity:i,upserts:{},deleted:new Set},F={...M.upserts};return delete F[C],{identity:i,upserts:F,deleted:new Set(M.deleted).add(C)}});let A=_.get("__reconcile__");A&&clearTimeout(A),_.set("__reconcile__",setTimeout(()=>{_.delete("__reconcile__"),w()},250))},b=C=>{let A=_.get(C);A&&clearTimeout(A),_.set(C,setTimeout(()=>{_.delete(C),s.fetchQuery({queryKey:k.item(C),queryFn:()=>Br(C),staleTime:0}).then(O=>{if(!h){if(!O||!Rf(O,p)){let M=d.current.find(F=>F.path===C||F.id===O?.id);M&&x(M.path);return}a(M=>{let F=M.identity===i?M:{identity:i,upserts:{},deleted:new Set},Q=new Set(F.deleted);return Q.delete(C),{identity:i,upserts:{...F.upserts,[C]:O},deleted:Q}})}}).catch(O=>console.warn("[useIncrementalItems] item read failed:",O))},250))},E=X("vfs_change",C=>{if(!C||typeof C.path!="string"&&typeof C.old_path!="string")return;let A=typeof C.path=="string"?C.path:C.old_path,O=d.current.find(F=>F.path===A||F.path===C.old_path||C.item_id&&F.id===C.item_id),M=!!O;if(!(!se(A,p.scope)&&!se(C.old_path,p.scope)&&!M)&&!(C.item_type&&C.item_type!==p.type&&!M)&&!(p.parent_id&&C.parent_id&&C.parent_id!==p.parent_id&&!M)){if(O&&(A!==O.path||C.old_path&&C.old_path!==A||C.parent_id&&C.parent_id!==O.parent_id||C.item_type&&C.item_type!==p.type)){x(O.path);return}if(!O&&C.old_path&&C.old_path!==A&&se(A,p.scope)){S++,b(A);return}if(C.action==="insert")S++,b(A);else if(C.action==="move")S++,b(A);else if(C.action==="update"){if(!u.current?.(C,d.current))return;S++,b(A)}else C.action==="delete"&&x(O?.path??C.old_path??A)}}),I=Ls(C=>{if(C!=="connected"){g&&(y=!0);return}g=!0,y&&(y=!1,w())});return()=>{h=!0,E(),I(),_.forEach(clearTimeout)}},[s,i]),{...r,allItems:l}}function zu(e){ee();let t=20,n=kn({queryKey:["vfs",z()??"__unscoped__","infinite-children",e??""],queryFn:async({pageParam:s=0})=>js(e,t,s),initialPageParam:0,getNextPageParam:(s,i,o)=>{if(!(s.items.length<t))return o+s.items.length},enabled:!!e});return{allItems:(0,v.useMemo)(()=>{if(!n.data?.pages)return[];let s=new Set,i=[];for(let o of n.data.pages)for(let a of o.items)a.id&&!s.has(a.id)&&(s.add(a.id),i.push(a));return i},[n.data?.pages]),fetchNextPage:n.fetchNextPage,isFetchingNextPage:n.isFetchingNextPage,isExhausted:!n.hasNextPage,isLoading:n.isLoading,isFetching:n.isFetching,error:n.error,totalHint:n.data?.pages?.[0]?.total_hint}}function Ju(e){return ee(),H({queryKey:k.edges(e),queryFn:()=>$s(e),enabled:!!e})}function li(e){return ee(),H({queryKey:k.types(e),queryFn:()=>Hs(e)})}function Yu(e,t){let n=li(t);return{...n,data:n.data?.get(e)??void 0}}function Xu(e,t){ee();let n=(0,v.useMemo)(()=>t?.arguments,[JSON.stringify(t?.arguments)]),r=t?.mode,s=t?.strategy,i=t?.width;return H({queryKey:[...k.openEnvelope(e,s),i],queryFn:async()=>{let o=await $r(e,{mode:r,strategy:s,arguments:n});if(i&&o.render?.props?.url){let a=o.render.props.url,c=a.includes("?")?"&":"?";o.render.props.url=`${a}${c}w=${i}`}return o},enabled:!!e})}var Fu={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 Zu(e){let t=li(e),n=t.data??new Map;return(0,v.useMemo)(()=>({canHaveChildren:p=>n.get(p.item_type)?.is_container??!1,isScope:p=>n.get(p.item_type)?.is_scope??!1,isScopeType:p=>n.get(p)?.is_scope??!1,isContainerType:p=>n.get(p)?.is_container??!1,getTypeDefinition:p=>n.get(p),getTypeColor:p=>n.get(p)?.color??"gray",getTypeIcon:p=>n.get(p)?.icon??"File",getTypeDisplayName:p=>n.get(p)?.display_name??p,getKnownEdgeTypes:()=>Object.entries(Fu).map(([p,h])=>({key:p,label:h})),getEdgeTypeLabel:p=>Fu[p]??p.replace(/_/g," "),allTypes:n,loading:t.isLoading}),[n,t.isLoading])}function el(e,t,n){return ee(),H({queryKey:k.memberFocus(e),queryFn:()=>zs(e,t,n),enabled:!!e})}function tl(e,t={}){let{limit:n=50,offset:r=0,include_snapshots:s=!1}=t;return H({queryKey:k.itemVersions(e,String(n),String(r),String(s)),queryFn:()=>Hr(e,{limit:n,offset:r,include_snapshots:s}),enabled:!!e})}function nl(e,t=50,n=0){return H({queryKey:k.itemHistory(e,String(t),String(n)),queryFn:()=>Gs(e,t,n),enabled:!!e})}function rl(e,t=50,n=0){return ee(),H({queryKey:k.recentActivity(e,String(t),String(n)),queryFn:()=>Ws(e,t,n),enabled:!!e})}function sl(){let[e,t]=(0,v.useState)(null),[n,r]=(0,v.useState)(!0),[s,i]=(0,v.useState)(null);return(0,v.useEffect)(()=>{let o=!1;return pt().then(a=>{if(!o){let c=typeof window<"u"&&window.__FSAOS_CONFIG__||{};t({path:a.scope_path,scope_id:a.scope_id,fractal_id:a.fractal_id,instance_name:a.instance_name,display_name:a.display_name,componentPath:c.componentPath||"",isEmbed:!!c.embedToken}),r(!1)}}).catch(a=>{o||(i(a instanceof Error?a:new Error(String(a))),r(!1))}),()=>{o=!0}},[]),{data:e,loading:n,error:s}}var Cf=[];function qu(){if(typeof window>"u")return!1;let e=window.__FSAOS_CONFIG__?.embedToken;return typeof e=="function"||typeof e=="string"&&e.length>0}function Pf(e){return e.filter(t=>t.placement==="switcher_entry").map(t=>({account:t,mountables:e.filter(n=>n.placement!=="switcher_entry"&&n.subordinateTo===t.accountId)}))}function il(){let{user:e}=di(),t=(0,v.useSyncExternalStore)(Nr,Bn,Bn),n=Ze()?.principal_id??null,r=(0,v.useRef)(null),[s,i]=(0,v.useState)(null),[o,a]=(0,v.useState)(null);(0,v.useEffect)(()=>{if(n){a(null);return}if(!e?.id&&!qu()){a(null);return}let _=!1;return pt().then(w=>{_||w.principal_id||a(new Error("Memberships require an authenticated principal"))}).catch(w=>{_||a(w instanceof Error?w:new Error(String(w)))}),()=>{_=!0}},[n,e?.id,t]);let c=H({queryKey:k.memberships(n??"anonymous"),queryFn:ti,enabled:!!n,staleTime:1e3*60*2}),l=c.data??Cf,d=(0,v.useMemo)(()=>l.filter(_=>_.isAccount!==!1&&!_.isSpace),[l]),u=(0,v.useMemo)(()=>{let _=new Set(d.map(x=>x.accountId)),w=x=>!x.subordinateTo||!_.has(x.subordinateTo);return[...d].sort((x,b)=>Number(w(b))-Number(w(x)))},[d]),m=(0,v.useSyncExternalStore)(be,W,W),p=(0,v.useMemo)(()=>{let _=pe();return _?l.find(w=>w.accountId===_.id)??null:null},[m,l]),h=(0,v.useMemo)(()=>Pf(d),[d]);(0,v.useEffect)(()=>{if(!n){r.current=null;return}if(r.current!==n)if(i(null),u.length===1){let _=u[0];_e()||Yt(tt(_)),on(_.accountId),_.personalSpacePath&&an(_.personalSpacePath,w=>{let x=l.find(b=>b.accountId===w);return x?tt(x):null}).catch(i),r.current=n}else u.length>1&&(r.current=n)},[n,u,l]);let g=(0,v.useCallback)(async _=>{let w=l.find(E=>E.path===_);if(!w)throw new Error("Account membership is unavailable");let x=tt(w);_e()||Yt(x);let b=l.find(E=>E.accountId===_e()?.id);if(!b?.personalSpacePath)throw new Error("The home membership has no mount declaration location");await an(b.personalSpacePath,E=>{let I=l.find(C=>C.accountId===E);return I?tt(I):null}),await Jr(x),i(null),on(w.accountId)},[l]),y=(0,v.useCallback)(async _=>{let w=l.find(x=>x.path===_);if(!w)throw new Error("Scope membership is unavailable");await Co(tt(w))},[l]),S=(!!e?.id||qu())&&!n&&!o;return{accounts:u,switcherAccounts:h,allMemberships:l,currentAccount:p,mountedScope:null,switchAccount:g,mountScope:y,loading:S||c.isLoading,error:o??c.error??s}}function ol(){ee();let e=(0,v.useSyncExternalStore)(Ln,At,At),t=(0,v.useMemo)(()=>Ce(),[e]),n=pe(),r=(0,v.useMemo)(()=>t.filter(i=>i.kind==="space"&&(n?.kind==="account"||i.id===n?.id)),[t,n]),s=(0,v.useMemo)(()=>r.map(i=>i.id).sort(),[r]);return{mounts:t,selectedSpaces:r,readSpaceIds:s,homeAnchor:_e(),anchor:n,setAnchor:Jr,replaceMounts:ii,mount:Co,unmount:xu}}function di(){let[e,t]=(0,v.useState)(null),[n,r]=(0,v.useState)(null),[s,i]=(0,v.useState)(!0),o=(0,v.useRef)(null);(0,v.useEffect)(()=>{G.auth.getSession().then(({data:p,error:h})=>{if(h){console.warn("[useAuth] getSession error, clearing stale session:",h.message),G.auth.signOut().catch(()=>{}),r(null),t(null),i(!1);return}r(p?.session??null),t(p?.session?.user??null),i(!1)}).catch(p=>{console.warn("[useAuth] getSession threw, clearing stale session:",p?.message),G.auth.signOut().catch(()=>{}),r(null),t(null),i(!1)});let{data:{subscription:m}}=G.auth.onAuthStateChange((p,h)=>{if(p==="TOKEN_REFRESHED"&&!h){console.warn("[useAuth] TOKEN_REFRESHED with null session \u2014 signing out"),G.auth.signOut().catch(()=>{}),r(null),t(null),i(!1);return}r(h),t(h?.user??null),i(!1)});return o.current=m,()=>{m?.unsubscribe()}},[]);let a=(0,v.useCallback)(async m=>m.provider?G.auth.signInWithOAuth({provider:m.provider,options:m.redirectTo?{redirectTo:m.redirectTo}:{redirectTo:window.location.href}}):G.auth.signInWithPassword({email:m.email,password:m.password}),[]),c=(0,v.useCallback)(async m=>G.auth.signUp({email:m.email,password:m.password,options:{data:m.metadata||{}}}),[]),l=(0,v.useCallback)(async()=>{await G.auth.signOut(),jn(),N().clear()},[]),d=(0,v.useCallback)(async m=>{let{error:p}=await G.auth.resetPasswordForEmail(m);if(p)throw p},[]),u=(0,v.useCallback)(async(m,p)=>{let{error:h}=await G.auth.signInWithOtp({email:m,options:p?{emailRedirectTo:p}:{emailRedirectTo:window.location.href}});if(h)throw h},[]);return{user:e,session:n,loading:s,signIn:a,signUp:c,signOut:l,resetPassword:d,signInWithMagicLink:u}}function al(e){let[t,n]=(0,v.useState)(null),[r,s]=(0,v.useState)(!1),[i,o]=(0,v.useState)(null);return(0,v.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),P("resolve-asset",{asset_id:e}).then(c=>{c.success&&c.public_url?n({url:c.public_url,id:c.asset_id,name:c.name,mimeType:c.mime_type,width:c.width,height:c.height,sizeBytes:c.size_bytes}):o(new Error(c.error||"Asset not found")),s(!1)}).catch(c=>{o(c instanceof Error?c:new Error(String(c))),s(!1)});else{let l=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"";n({url:l+e}),s(!1)}},[e]),{data:t,loading:r,error:i}}var cl=new Map;oe(()=>cl.clear());var ul=null;function ll(e){ul=e,typeof window<"u"&&!window.__FSAOS_GATEWAY__&&(window.__FSAOS_GATEWAY__=e)}function Nu(e){switch(e){case"react":return typeof window<"u"&&window.React||v.default;case"react-dom":case"react-dom/client":return typeof window<"u"&&window.ReactDOM||Sf;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}:xf;case"@fsaos/gateway":case"@fsaos/react":case"@ai4b-team/fsaos-gateway-sdk":return typeof window<"u"&&window.__FSAOS_GATEWAY__||ul||{};case"@fsaos/ui":case"@ai4b-team/fsaos-gateway-sdk/ui":return typeof window<"u"&&window.__FSAOS_UI__||Po;case"@fsaos/theme":return{};default:return console.warn(`[useComponent] Unknown module requested: ${e}`),{}}}var Zr={};async function Ef(e){try{let t=await fetch(e);if(!t.ok)return null;let n=await t.text();return!n.trim()||n.includes("No CSS bundle for this component")?null:n}catch{return null}}async function Fo(e,t=()=>Ef(e)){let n=Zr[e];n||(n=Zr[e]={users:0,text:t(),style:null}),n.users+=1;let r=await n.text;if(Zr[e]!==n||n.users===0||n.style||!r||typeof document>"u")return;let s=document.createElement("style");s.setAttribute("data-fsaos-component-css",e),s.textContent=r,document.head.appendChild(s),n.style=s}function ge(e){let t=Zr[e];t&&(t.users-=1,!(t.users>0)&&(t.style?.remove(),delete Zr[e]))}function Be(...e){return JSON.stringify([V(),Ie(),...e])}function qo(e){return ee(),(0,v.useSyncExternalStore)(Nr,V,V),Be(e??null)}function No(e,t,n,r){let s=e.get(t);if(!s){let i=Be();s=n().then(o=>{if(i!==Be())throw new Error("The account or Space changed while loading the component.");if(!o)throw new Error(`${r} did not hand over a component. Expected __FSAOS_REGISTER__(Component) or window.__FSAOS_COMPONENT__.`);if(typeof o!="function")throw new Error(`${r} did not export a React component.`);return o}),e.set(t,s),s.catch(()=>{e.get(t)===s&&e.delete(t)})}return s}function dl(e,t,n){if(n!==Be())throw new Error("The account or Space changed while loading the component.");let r=ei();return r?_u(r,e,t,Nu):xo(new Function(`var require = arguments[0];
|
|
6
|
+
`+e),Nu)}function Qo(e,t){let[n,r]=(0,v.useState)(null),[s,i]=(0,v.useState)(!0),[o,a]=(0,v.useState)(null),c=(0,v.useRef)(null),l=qo(),d=Number.isSafeInteger(t?.version)&&t.version>0?t.version:null;return(0,v.useEffect)(()=>{if(!e)return;let u=!1;a(null),(c.current?.path!==e||c.current?.scopeKey!==l)&&(c.current?.cssUrl&&ge(c.current.cssUrl),c.current=null,r(null),i(!0));let p=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"";return(async()=>{let h=null;try{let g=1,y=e+"@v1",S=p+e+"/__bundle.js";if(d!==null)g=d,y=e+"@v"+g,S=p+e+"/__bundle.v"+g+".js";else try{let I=await fetch(p+e+"/__meta",{cache:"no-store"});I.ok&&(g=(await I.json()).version||1,y=e+"@v"+g,S=p+e+"/__bundle.v"+g+".js")}catch{S=p+e+"/__bundle.js?v="+Date.now()}if(u)return;let _=S.replace(/__bundle(\.v\d+)?\.js(\?.*)?$/,"__bundle$1.css");h=_;let w=Fo(_),x=Be(),b=await No(cl,Be(y),async()=>{let I=await fetch(S);if(!I.ok)throw new Error(`Failed to fetch bundle: ${I.status} ${I.statusText} (${S})`);let C=await I.arrayBuffer(),A=new TextDecoder().decode(C);return dl(A,{kind:"legacy",url:new URL(S,window.location.origin||"https://"+window.location.hostname).href,sha256:ei()?await Zs(C):""},x)},"The component bundle");if(await w,u){ge(_);return}let E=c.current?.cssUrl??null;c.current={path:e,cssUrl:_,scopeKey:l},h=null,r({Component:b,scopeKey:l}),i(!1),E&&ge(E)}catch(g){h&&ge(h),u||(a(g instanceof Error?g:new Error(String(g))),i(!1))}})(),()=>{u=!0}},[e,d,l]),(0,v.useEffect)(()=>()=>{c.current?.cssUrl&&ge(c.current.cssUrl),c.current=null},[]),{Component:n?.scopeKey===l?n.Component:null,loading:s,error:o}}var If=/^embed\/bundle-[A-Za-z0-9_-]+\.js$/,Tf=/^embed\/bundle-[A-Za-z0-9_-]+\.css$/;function Qu(e,t,n){let r=Object.keys(e).filter(o=>t.test(o));if(r.length>1)throw new Error(`The published release has more than one in-app ${n}.`);let s=r[0];if(!s)return null;let i=Le(e[s]).sha256;return typeof i=="string"&&i?{path:s,sha256:i}:null}var Yr=new Map,pl=new Map,ui=new WeakMap;oe(()=>{Yr.clear(),pl.clear()});function Le(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function fl(e){let t=Le(Le(e.type_data).published),n=t.published_release_item_id,r=t.published_version;return typeof n!="string"||!n||typeof r!="number"||!Number.isSafeInteger(r)||r<1?null:{releaseItemId:n,version:r}}async function Du(e,t,n){let r=await $r(e.path,{mode:"render"}),s=Le(Le(r.render).props).url;if(typeof s!="string"||!s)throw new Error(`The published ${n} could not be opened.`);let i=await fetch(s,{credentials:"omit",referrerPolicy:"no-referrer"});if(!i.ok)throw new Error(`Failed to read the published ${n}: ${i.status} ${i.statusText}`.trim());let o=await i.arrayBuffer();if(await Zs(o)!==t)throw new Error(`The published ${n} does not match the bytes its release sealed.`);return{text:new TextDecoder().decode(o),url:s}}async function ml(e,t,n){let r=await Lr(t);if(!r)throw new Error("The published release could not be read.");let s=Le(r.type_data);if(r.item_type!=="revdev_release"||s.component_item_id!==e||s.status!=="committed"||Number(s.version)!==n)throw new Error("This component's live version does not match its release record.");let i=Le(s.artifacts),o=Qu(i,If,"script");if(!o)return{status:"no_in_app_version",releaseItemId:t,version:n};let a=Qu(i,Tf,"stylesheet"),c=a?[o.path,a.path]:[o.path],l=s.build_item_id;if(typeof l!="string"||!l)throw new Error("The published release names no build.");let{items:d}=await rn({type:"file",parent_id:l,field_in:{package_path:c},limit:c.length},{throwOnError:!0}),u=S=>d.find(_=>Le(_.type_data).package_path===S),m=u(o.path),p=a?u(a.path):void 0;if(!m||a&&!p)throw new Error("The published release's in-app files could not be found in its build.");let[h,g]=await Promise.all([Du(m,o.sha256,"script"),p&&a?Du(p,a.sha256,"stylesheet"):Promise.resolve(null)]),y={status:"ready",releaseItemId:t,version:n,script:h.text,stylesheet:g?.text.trim()?g.text:null};return ui.set(y,{source:{kind:"published",url:h.url,sha256:o.sha256},readAt:Date.now()}),y}function hl(e,t,n){let r=Be(e,t,String(n)),s=Yr.get(r);return s||(s=ml(e,t,n),Yr.set(r,s),s.catch(()=>{Yr.get(r)===s&&Yr.delete(r)})),s}function gl(e){let t=fl(e);return!e.id||!t?Promise.resolve({status:"unpublished"}):hl(e.id,t.releaseItemId,t.version)}async function yl(e,t,n){let r=ui.get(e);if(!r)throw new Error("The component has no authorized script source.");ei()&&Date.now()-r.readAt>5*6e4&&(e=await t());let s=ui.get(e)?.source;if(!s)throw new Error("The component has no authorized script source.");return dl(e.script,s,n)}function _l(e){let[t,n]=(0,v.useState)(null),[r,s]=(0,v.useState)("loading"),[i,o]=(0,v.useState)(null),a=(0,v.useRef)(null),c=qo(),l=e!=null,d=e?.id||null,u=e?fl(e):null,m=u?.releaseItemId??null,p=u?.version??null;return(0,v.useEffect)(()=>{if(!l)return;let h=()=>{a.current?.cssKey&&ge(a.current.cssKey),a.current=null,n(null)};if(!d||!m||p===null){h(),o(null),s("unpublished");return}let g=!1;return o(null),a.current&&(a.current.componentId!==d||a.current.scopeKey!==c)&&h(),a.current||s("loading"),(async()=>{let y=null;try{let S=Be(),_=await hl(d,m,p);if(g)return;if(_.status!=="ready"){h(),s(_.status);return}let w=Be(d,m,String(p)),x=await No(pl,w,()=>yl(_,async()=>{let I=await ml(d,m,p);if(I.status!=="ready")throw new Error("The published component is unavailable.");return I},S),"The published script"),b=_.stylesheet?`release:${m}`:null;if(b&&(y=b,await Fo(b,async()=>_.stylesheet)),g){y&&ge(y);return}let E=a.current?.cssKey??null;a.current={componentId:d,releaseItemId:m,cssKey:b,scopeKey:c},y=null,n({Component:x,version:p,scopeKey:c}),s("ready"),E&&ge(E)}catch(S){if(y&&ge(y),g)return;o(S instanceof Error?S:new Error(String(S))),a.current||s("error")}})(),()=>{g=!0}},[l,d,m,p,c]),(0,v.useEffect)(()=>()=>{a.current?.cssKey&&ge(a.current.cssKey),a.current=null},[]),{Component:t?.scopeKey===c?t.Component:null,status:r,error:i,version:t?.scopeKey===c?t.version:null}}var Af=512*1024,Xr=new Map,bl=new Map;oe(()=>{Xr.clear(),bl.clear()});var vl=(e,t,n)=>Be(e,t.toLowerCase(),n??null);async function wl(e){let t=await P("open",{id:e.fileId,mode:"render",...e.scopePath?{_scope_path:e.scopePath}:{}}),n=Le(Le(t.render).props).url;if(t.item_id!==e.fileId||t.item_type!=="file"||typeof n!="string"||!n)throw new Error("The compiled build could not be opened.");let r=await fetch(n,{credentials:"omit",referrerPolicy:"no-referrer"});if(!r.ok)throw new Error(`Failed to read the compiled build: ${r.status} ${r.statusText}`.trim());let s=await r.arrayBuffer();if(s.byteLength>Af)throw new Error("The compiled build is too large to run.");let i=await Zs(s);if(i!==e.sha256.toLowerCase())throw new Error("The compiled build does not match the bytes it was shown with.");let o;try{o=JSON.parse(new TextDecoder().decode(s))}catch{throw new Error("The compiled build is not a build file.")}let{js:a,css:c,scope:l}=Le(o);if(typeof a!="string"||!a||c!=null&&typeof c!="string"||l!=null&&(typeof l!="string"||!/^[A-Za-z0-9_-]{1,64}$/.test(l)))throw new Error("The compiled build is not a build file.");let d={script:a,stylesheet:typeof c=="string"&&c.trim()?c:null,scopeClass:typeof l=="string"?`fsaos-c-${l}`:null};return ui.set(d,{source:{kind:"compiled",url:n,sha256:i},readAt:Date.now()}),d}function Do(e){if(!e.fileId||!/^[0-9a-f]{64}$/i.test(e.sha256||""))return Promise.reject(new Error("A compiled build is named by its file and the SHA-256 of its bytes."));let t=vl(e.fileId,e.sha256,e.scopePath),n=Xr.get(t);return n||(n=wl(e),Xr.set(t,n),n.catch(()=>{Xr.get(t)===n&&Xr.delete(t)})),n}function Sl(e){let[t,n]=(0,v.useState)(null),[r,s]=(0,v.useState)("loading"),[i,o]=(0,v.useState)(null),a=(0,v.useRef)(null),c=e?.fileId||null,l=e?.sha256||null,d=e?.scopePath,u=qo(d);return(0,v.useEffect)(()=>{if(!c||!l){a.current?.cssKey&&ge(a.current.cssKey),a.current=null,n(null),o(null),s("loading");return}let m=vl(c,l,d);if(a.current?.key===m)return;a.current&&a.current.scopeKey!==u&&(a.current.cssKey&&ge(a.current.cssKey),a.current=null,n(null));let p=!1;return o(null),a.current||s("loading"),(async()=>{let h=null;try{let g=Be(),y={fileId:c,sha256:l,scopePath:d},S=await Do(y);if(p)return;let _=await No(bl,m,()=>yl(S,()=>wl(y),g),"The compiled build"),w=S.stylesheet?`compiled:${m}`:null;if(w&&(h=w,await Fo(w,async()=>S.stylesheet)),p){h&&ge(h);return}let x=a.current?.cssKey??null;a.current={key:m,cssKey:w,scopeKey:u},h=null,n({Component:_,scopeKey:u,scopeClass:S.scopeClass}),s("ready"),x&&ge(x)}catch(g){if(h&&ge(h),p)return;o(g instanceof Error?g:new Error(String(g))),a.current||s("error")}})(),()=>{p=!0}},[c,l,d,u]),(0,v.useEffect)(()=>()=>{a.current?.cssKey&&ge(a.current.cssKey),a.current=null},[]),{Component:t?.scopeKey===u?t.Component:null,scopeClass:t?.scopeKey===u?t.scopeClass:null,status:r,error:i}}var Mf=["--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 xl(){return{data:(0,v.useMemo)(()=>{if(typeof document>"u")return{tokens:{}};let t={},n=getComputedStyle(document.documentElement);return Mf.forEach(r=>{t[r]=n.getPropertyValue(r).trim()}),{tokens:t}},[]),loading:!1,error:null}}var he=null,sr=null,Mo=new Set;function kf(){Mo.forEach(e=>e())}oe(()=>{he=null,sr=null});async function Rl(e){let t={principalId:null,displayName:null,createdAt:null,metadata:null,vfsPath:null},n=Ze()?.principal_id??null;if(n){if(he&&he.principalId===n){let{principalId:s,displayName:i,createdAt:o,metadata:a,vfsPath:c}=he;return{principalId:s,displayName:i,createdAt:o,metadata:a,vfsPath:c}}return{...t,principalId:n}}let r=e;if(!r){let{data:s}=await G.auth.getSession();r=s?.session?.user?.id}if(!r)return t;if(he&&he.authUserId===r){let{principalId:s,displayName:i,createdAt:o,metadata:a,vfsPath:c}=he;return{principalId:s,displayName:i,createdAt:o,metadata:a,vfsPath:c}}return sr||(sr=(async()=>{try{let{data:s,error:i}=await G.from("os_principals").select("id, display_name, created_at, metadata").eq("auth_user_id",r).eq("principal_type","user").maybeSingle();if(i)return console.warn("[SDK] Could not resolve principal:",i.message),t;let o=s?.id??null,a=null;if(o){let{data:l}=await G.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(u=>u.path);a=d.find(u=>u.split("/").length===4)??d[0]??null}let c={principalId:o,displayName:s?.display_name??null,createdAt:s?.created_at??null,metadata:s?.metadata??null,vfsPath:a};return he={authUserId:r,...c},c}finally{sr=null}})(),sr)}async function Cl(e){return(await Rl(e)).principalId}function Pl(){let e=di(),t=e.user,n=he?.authUserId===t?.id?he:null,[r,s]=(0,v.useState)(n),i=(0,v.useRef)(null);return(0,v.useEffect)(()=>{let o=()=>{let a=he;a&&a.authUserId===t?.id&&s({principalId:a.principalId,displayName:a.displayName,createdAt:a.createdAt,metadata:a.metadata,vfsPath:a.vfsPath})};return Mo.add(o),()=>{Mo.delete(o)}},[t?.id]),(0,v.useEffect)(()=>{if(!t?.id){s(null),i.current=null;return}i.current===t.id&&r?.principalId!=null||(i.current=t.id,Rl(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 El(e){let{path:t,...n}=e,r=Qo(t),s=r.Component,{loading:i,error:o}=r;return i?(0,v.createElement)("div",{className:"fsaos-loading"},""):o?(0,v.createElement)("div",{className:"fsaos-error"},"Failed to load component"):s?(0,v.createElement)(s,n):null}function Il(e){return e.children}function Tl(e){let t=ee(),{channelPath:n,parentMessageId:r,realtime:s=!0,enabled:i}=e,o=i!==void 0?i&&!!n:!!n,a=(0,v.useMemo)(()=>k.channelMessages(n??"",r),[n,r,t]),c=U(),l=(0,v.useRef)(null),d=H({queryKey:a,queryFn:()=>Ys(n,r),enabled:o});(0,v.useEffect)(()=>{if(!s||!o)return;let g=X("vfs_change",()=>{l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{ce(c,a,{exact:!0})},500)},y=>{let S=c.getQueryData(a);return rr(y,n,r,[...S?.messages??[],...S?.activityMessages??[]])});return()=>{g(),l.current&&clearTimeout(l.current)}},[s,o,n,r,a,c]);let u=d.data,m=u?.messages??[],p=u?.messageCards??new Map,h=u?.siblingCards??[];return{messages:m,activityMessages:u?.activityMessages??[],messageCards:p,siblingCards:h,threads:(0,v.useMemo)(()=>m.filter(g=>g.reply_count>0),[m]),breakouts:(0,v.useMemo)(()=>m.filter(g=>g.member_count>0),[m]),isLoading:d.isLoading,isFetching:d.isFetching,error:d.error,refetch:d.refetch}}function Al(e){let t=ee(),{channelPath:n,messageId:r,conversationRootId:s,enabled:i=!0,realtime:o=!0,limit:a=25}=e,c=i&&!!n&&!!r,l=(0,v.useMemo)(()=>k.messageReplies(n??"",r,s,a),[n,r,s,a,t]),d=U(),u=kn({queryKey:l,queryFn:({pageParam:p})=>Js(r,{limit:a,conversationRootId:s,cursor:p}),initialPageParam:void 0,getNextPageParam:p=>p.next_cursor??void 0,enabled:c,staleTime:1/0,refetchOnMount:"always",refetchOnWindowFocus:!1,retry:!1});(0,v.useEffect)(()=>c&&o?Mu(d,l,r):void 0,[c,o,d,l,r]);let m=(0,v.useMemo)(()=>{if(!c||u.isError)return[];let p=new Set;return(u.data?.pages??[]).flatMap(h=>h.messages).filter(h=>p.has(h.id)?!1:(p.add(h.id),!0))},[c,u.data,u.isError]);return{...u,messages:m}}function Ml(e){let t=ee(),{channelPath:n,parentMessageId:r,limit:s=50,realtime:i=!0,enabled:o=!0,conversationsOnly:a=!1,transcriptOnly:c=!1}=e,l=!!r,d=o&&!!n,u=kn({queryKey:[...k.channelMessages(n||"",r),"infinite",s,"latest-first",...a?["conversations"]:[],...c?["transcript"]:[]],queryFn:async({pageParam:_})=>{let w=await sn(n,{parentMessageId:r,limit:s,conversationsOnly:a,transcriptOnly:c,before_seq:_?.before_seq,after_seq:_?.after_seq});return c&&w.messages.length>=s?{...w,olderBefore:w.messages[0]?.seq}:w},initialPageParam:void 0,getPreviousPageParam:_=>{if(!l||_.messages.length<s)return;let w=_.messages[_.messages.length-1]?.seq;return w==null?void 0:{after_seq:w}},getNextPageParam:_=>{if(c)return _.olderBefore==null?void 0:{before_seq:_.olderBefore};if(_.messages.length<s)return;let w=_.messages[0]?.seq;return w==null?void 0:{before_seq:w}},enabled:d}),m=(0,v.useMemo)(()=>{if(!u.data?.pages)return[];let _=new Set,w=[];for(let x of u.data.pages)for(let b of x.messages)_.has(b.id)||(_.add(b.id),w.push(b));return w.sort((x,b)=>x.seq-b.seq)},[u.data?.pages]),{messageCards:p,siblingCards:h}=(0,v.useMemo)(()=>{let _=new Map,w=[];if(!u.data?.pages)return{messageCards:_,siblingCards:w};let x=new Set;for(let[b,E]of u.data.pages.entries()){let I=c&&b>0?new Set(E.messages.map(C=>C.path)):null;for(let[C,A]of E.messageCards)if(!(I&&!I.has(C)))for(let O of A){if(x.has(O.id))continue;x.add(O.id);let M=_.get(C)||[];M.push(O),_.set(C,M)}if(!(c&&b>0))for(let C of E.siblingCards)x.has(C.id)||(x.add(C.id),w.push(C))}return{messageCards:_,siblingCards:w}},[u.data?.pages,c]),g=U(),y=(0,v.useRef)(null),S=(0,v.useMemo)(()=>[...k.channelMessages(n||"",r),"infinite",s,"latest-first",...a?["conversations"]:[],...c?["transcript"]:[]],[n,r,s,a,c,t]);return(0,v.useEffect)(()=>{if(!i||!n||!d)return;if(c)return Eu(g,S,n,s);let _=()=>void ce(g,S,{exact:!0}),w=!1,x=!1,b=!1,E=async()=>{if(a){_();return}let A=g.getQueryData(S);if(!A?.pages?.length){_();return}let O=0;for(let M of A.pages)for(let F of M.messages)F.seq>O&&(O=F.seq);if(O===0){_();return}try{let M=await sn(n,{parentMessageId:r,limit:s,after_seq:O});if(M.messages.length===0&&M.siblingCards.length===0){_();return}if(M.messages.length>0){let F=Math.min(...M.messages.map(Q=>Q.seq));if(F>O+1){console.warn(`[useInfiniteChannelMessages] sequence gap detected: maxSeq=${O}, minNewSeq=${F}. Triggering full refetch.`),_();return}}g.setQueryData(S,F=>{if(!F)return F;let Q=[...F.pages],B=0,ae=Q[B],He=new Set(ae.messages.map(Ae=>Ae.id)),j=M.messages.filter(Ae=>!He.has(Ae.id)),$e=[...ae.messages,...j].sort((Ae,vi)=>Ae.seq-vi.seq),Dt=new Map(ae.messageCards);for(let[Ae,vi]of M.messageCards){let oa=Dt.get(Ae)||[],ep=new Set(oa.map(wi=>wi.id)),tp=vi.filter(wi=>!ep.has(wi.id));Dt.set(Ae,[...oa,...tp])}let lr=new Set(ae.siblingCards.map(Ae=>Ae.id)),Xd=M.siblingCards.filter(Ae=>!lr.has(Ae.id)),Zd=[...ae.siblingCards,...Xd];return Q[B]={...ae,activityMessages:M.activityMessages??[],messages:$e,messageCards:Dt,siblingCards:Zd},{...F,pages:Q}})}catch(M){console.warn("[useInfiniteChannelMessages] live tail fetch failed, falling back to full invalidation:",M),_()}},I=async()=>{if(w){x=!0;return}w=!0;try{do x=!1,await E();while(x&&!b)}finally{w=!1}},C=X("vfs_change",()=>{y.current&&clearTimeout(y.current),y.current=setTimeout(()=>{I()},500)},A=>a&&A?.item_type==="message"&&(g.getQueryData(S)?.pages??[]).some(O=>O.messages.some(M=>M.id===A.parent_id))||rr(A,n,r,g.getQueryData(S)?.pages.flatMap(O=>O.messages)??[]));return()=>{b=!0,C(),y.current&&clearTimeout(y.current)}},[i,n,d,S,g,r,s,a,c]),{messages:m,activityMessages:u.data?.pages[0]?.activityMessages??[],messageCards:p,siblingCards:h,threads:m.filter(_=>_.reply_count>0),breakouts:m.filter(_=>_.member_count>0),isLoading:u.isLoading,isFetching:u.isFetching,error:u.error,refetch:u.refetch,hasPreviousPage:u.hasNextPage??!1,fetchPreviousPage:u.fetchNextPage,isFetchingPreviousPage:u.isFetchingNextPage??!1,hasNextPage:u.hasPreviousPage??!1,fetchNextPage:u.fetchPreviousPage,isFetchingNextPage:u.isFetchingPreviousPage??!1}}var kl=["open","active","strict","hand_raise"];function Of(e){return e==="open"||e==="active"||e==="strict"||e==="hand_raise"?e:e==="on"||e==="auto"?"active":"strict"}function Ff(e){if(Array.isArray(e))return e.filter(t=>typeof t=="string")}function Uu(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:Of(t.ai_mode),activeAgentIds:Ff(t.active_agent_ids),isPrivate:t.is_private||!1,isDm:t.is_dm||!1,messageCount:t.message_count||0,createdAt:e.created_at||"",updatedAt:e.updated_at||"",chatScopePath:r.context_path||"",contextId:e.scope_item_id||"",contextPath:r.context_path||"",contextType:r.context_type||"",contextName:r.context_name||"",contextDisplayName:r.context_name||"",contextPrincipalId:void 0,accountId:e.account_item_id||"",accountPath:"",accountDisplayName:"",memberRole:n.member_role||"member",memberPath:"",modePath:"",autoPilot:t.auto_pilot||!1,isArchived:t.is_archived===!0}}function pi(e={}){let t=ee(),{realtime:n=!0,enabled:r=!0,includeArchived:s=!1}=e,i=U(),o=(0,v.useMemo)(()=>k.channels("all"),[t]),a=H({queryKey:o,queryFn:async()=>((await P("query",{item_type:"channel",include_reader:!0,limit:500})).items||[]).map(Uu),enabled:r});return(0,v.useEffect)(()=>{if(!(!n||!r))return Tu(i,o,Uu)},[n,r,o,i]),{channels:(0,v.useMemo)(()=>(a.data??[]).filter(l=>s||!l.isArchived),[a.data,s]),isLoading:a.isLoading,isFetching:a.isFetching,error:a.error,refetch:a.refetch}}function Ol(e={}){let t=pi(e),n=(0,v.useMemo)(()=>t.channels.filter(r=>!r.isDm),[t.channels]);return{...t,channels:n}}function Fl(e={}){let t=pi(e),n=(0,v.useMemo)(()=>t.channels.filter(r=>r.isDm),[t.channels]);return{...t,channels:n}}function Uo(e={}){let t=ee(),{filter:n="all",limit:r=200,realtime:s=!0,enabled:i=!0}=e,o=U(),a=(0,v.useRef)(null),c=(0,v.useMemo)(()=>k.notifications(n,r),[n,r,t]),l=H({queryKey:c,queryFn:async()=>{let u={limit:r};return n==="unread"&&(u.filter="unread"),(await P("get-notifications",u)).notifications||[]},enabled:i});return(0,v.useEffect)(()=>{if(!s||!i)return;let u=["vfs_change","ccm_change"].map(m=>X(m,()=>{a.current&&clearTimeout(a.current),a.current=setTimeout(()=>{o.invalidateQueries({queryKey:c})},2e3)},p=>p.item_type==="notification"&&oi(p)));return()=>{u.forEach(m=>m()),a.current&&clearTimeout(a.current)}},[s,i,c,o]),{notifications:l.data??[],isLoading:l.isLoading,isFetching:l.isFetching,error:l.error,refetch:l.refetch}}function ql(e={}){let{channels:t,realtime:n=!0,enabled:r=!0}=e,{notifications:s,isLoading:i,isFetching:o,error:a,refetch:c}=Uo({filter:"unread",limit:200,realtime:n,enabled:r}),l=(0,v.useMemo)(()=>{let p=new Map;for(let h of s)h.is_unread&&h.channel_id&&p.set(h.channel_id,(p.get(h.channel_id)||0)+1);return p},[s]),d=(0,v.useMemo)(()=>{let p=0;return l.forEach(h=>{p+=h}),p},[l]),{dmUnread:u,channelUnread:m}=(0,v.useMemo)(()=>{if(!t)return{dmUnread:0,channelUnread:0};let p=new Set(t.filter(y=>y.isDm).map(y=>y.id)),h=0,g=0;return l.forEach((y,S)=>{p.has(S)?h+=y:g+=y}),{dmUnread:h,channelUnread:g}},[t,l]);return{unreadByChannel:l,totalUnread:d,dmUnread:u,channelUnread:m,isLoading:i,isFetching:o,error:a,refetch:c}}function Nl(){let e=U();return ie({mutationFn:t=>P("create",t),onSuccess:(t,n)=>{let r=n.parent_path;r&&e.invalidateQueries({queryKey:k.children(r)})}})}function Ql(){let e=U();return ie({mutationFn:t=>P("update",t),onSuccess:(t,n)=>{let r=n.path;if(r){e.invalidateQueries({queryKey:k.item(r)});let s=r.split("/");s.pop();let i=s.join("/");i&&e.invalidateQueries({queryKey:k.children(i)})}}})}function Dl(){return ie({mutationFn:e=>P("update-principal",e),onSuccess:(e,t)=>{if(!he)return;let n=e&&typeof e=="object"&&e.metadata?e.metadata:{...he.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}:{}};he={...he,displayName:typeof t.display_name=="string"?t.display_name:he.displayName,metadata:n},kf()}})}function Ul(){let e=U();return ie({mutationFn:t=>P("delete",t),onSuccess:(t,n)=>{let r=n.path;if(r){e.removeQueries({queryKey:k.item(r)});let s=r.split("/");s.pop();let i=s.join("/");i&&e.invalidateQueries({queryKey:k.children(i)})}}})}function Kl(){let e=U();return ie({mutationFn:t=>P("move",t),onSuccess:(t,n)=>{let r=n.path,s=n.new_parent_path;if(r){e.invalidateQueries({queryKey:k.item(r)});let i=r.split("/");i.pop();let o=i.join("/");o&&e.invalidateQueries({queryKey:k.children(o)})}s&&e.invalidateQueries({queryKey:k.children(s)})}})}function Ll(){let e=U();return ie({mutationFn:t=>P("link",t),onSuccess:(t,n)=>{let r=n.source_id,s=n.target_id;r&&e.invalidateQueries({queryKey:k.edges(r)}),s&&e.invalidateQueries({queryKey:k.edges(s)})}})}function Bl(e,t){let n=U(),{optimistic:r,...s}=t??{};return ie({mutationFn:i=>P(e,i),onMutate:r?async i=>{await n.cancelQueries({queryKey:r.queryKey});let o=n.getQueryData(r.queryKey);return n.setQueryData(r.queryKey,a=>r.update(a,i)),{previous:o}}:void 0,onError:(i,o,a)=>{r&&a?.previous!==void 0&&n.setQueryData(r.queryKey,a.previous),s.onError?.(i)},onSuccess:s.onSuccess,onSettled:r?()=>{n.invalidateQueries({queryKey:r.queryKey})}:void 0})}function jl(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 a=(0,v.useRef)(s),c=(0,v.useRef)(i);(0,v.useEffect)(()=>{a.current=s,c.current=i},[s,i]),(0,v.useEffect)(()=>o?X(r,d=>a.current(d),c.current?d=>c.current(d):void 0):void 0,[r,o])}function Hl(e){let{queryKey:t,queryFn:n,eventType:r,filter:s,enabled:i=!0,debounceMs:o=500}=e,a=U(),c=(0,v.useRef)(s);c.current=s;let l=(0,v.useRef)(null),d=H({queryKey:t,queryFn:n,enabled:i});return(0,v.useEffect)(()=>{if(!i)return;let u=X(r,()=>{l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{ce(a,t,{exact:!0})},o)},m=>c.current?.(m)??!0);return()=>{u(),l.current&&clearTimeout(l.current)}},[r,i,o,a,JSON.stringify(t)]),d}function ir(e){ee();let t=z(),n=(0,v.useMemo)(()=>e?typeof e=="string"?{path:e}:e:null,[typeof e=="string"?e:JSON.stringify(e)]),r=n?._scope_path??t,s=!!t&&!!r&&!!n&&!!(n.key||n.path||n.item_id),i=n?.key??n?.path??n?.item_id??"",o=["vfs",r??"__unscoped__","arrangement",i,n?.scope_id??""],a=H({queryKey:o,staleTime:1/0,retry:!1,meta:{arrangementRealtime:!0},queryFn:async()=>{if(!n)return null;let p=await P("resolve-arrangement",{...n,_scope_path:r});if(p?.success===!1)throw new Error(p?.error||"Arrangement could not be loaded");return p??null},enabled:s}),c=a.data??null,l=(0,v.useMemo)(()=>c?.resolved_children??[],[c]),d=c?.resolution_level??null,u=(0,v.useMemo)(()=>{let h=(c?.type_data??null)?.order;return Array.isArray(h)?h:null},[c]),m=(0,v.useCallback)(p=>{if(!u||!p?.length)return p??[];let h=_=>_.id??_.name??"",g=new Map(u.map((_,w)=>[_,w])),y=[],S=[];for(let _ of p)(g.has(h(_))?y:S).push(_);return y.sort((_,w)=>g.get(h(_))-g.get(h(w))),[...y,...S]},[u]);return{...a,arrangement:c,resolvedChildren:l,resolutionLevel:d,order:u,sourceScopeId:c?.scope_item_id??null,arrangementQueryKey:o,applyTo:m}}function $l(e){let{origin:t,originField:n,fallbackUrl:r,mintError:s,scopeId:i,scopePath:o}=e,a=ee(),c=Ze(),l=i??c?.scope_id??null,d=(0,v.useMemo)(()=>{if(!t)return null;let b="/accounts/",E=t.indexOf(b);if(E===-1)return null;let I=t.indexOf("/",E+b.length);return I===-1?t:t.slice(0,I)},[t]),u=o??d??c?.scope_path??null,m=n?.trim()||null,p=`${a}
|
|
5
7
|
${l??""}
|
|
6
|
-
${
|
|
7
|
-
${t??""}`,[m,_]=(0,w.useState)(null),g=(0,w.useRef)({key:f,found:null,earlyContentPaths:new Set}),b=m?.key===f?m:null;(0,w.useLayoutEffect)(()=>{g.current={key:f,found:b,earlyContentPaths:new Set}},[f]);let y=$({queryKey:["vfs",l??"__unscoped__","minted-asset",h??"",t??""],queryFn:async()=>{let R=await C("query",{scope_path:l,filters:{[`field.${h}`]:t},limit:1}),k=R.content?.items??R.items??[],O=k[0]?He(k[0]):null;if(!O)return null;let A=(await Hr(O.path)).some(M=>M.item_type==="file"&&!!M.type_data?.file_ref);return{asset:O,hasBytes:A}},enabled:!!(t&&l&&h&&!s),refetchInterval:R=>g.current.key===f&&g.current.found?.hasBytes||R.state.data?.hasBytes?!1:1500});(0,w.useEffect)(()=>{let R=y.data;if(!R||g.current.key!==f)return;let k=g.current.found,O={key:f,itemId:R.asset.id,itemPath:R.asset.path,displayName:typeof R.asset.type_data?.display_name=="string"?R.asset.type_data.display_name:R.asset.name,hasBytes:R.hasBytes||!!(k?.itemId===R.asset.id&&k.hasBytes)};g.current.found=O,_(O)},[y.data,f]);let v=!!(t&&u)&&!s&&!b?.hasBytes;return(0,w.useEffect)(()=>{if(!(!v||!u))return Zn(u,["asset.materialized","content.written"])},[v,u]),(0,w.useEffect)(()=>{if(!v||!t||!u)return;let R=f,k=I=>I?.payload??I,O=I=>{let Q=k(I)?.scope_id??I?.scope_id;return typeof Q=="string"?Q:void 0},P=I=>{let Q=k(I)?.item_path??I?.item_path;return typeof Q=="string"&&Q?Q:void 0},A=(I,F)=>{let Q=F.replace(/\/+$/,"");return I===Q||I.startsWith(`${Q}/`)},M=[X("asset.materialized",I=>{if(g.current.key!==R)return;let F=k(I);if(typeof F?.item_id!="string"||!F.item_id)return;let Q=g.current.found,K=typeof F.item_path=="string"?F.item_path:void 0,B=!!F.has_bytes||!!(K&&Array.from(g.current.earlyContentPaths).some(j=>A(j,K)))||!!(Q&&Q.itemId===F.item_id&&Q.hasBytes),Qe={key:R,itemId:F.item_id,itemPath:K,displayName:typeof F.display_name=="string"?F.display_name:void 0,hasBytes:B};g.current.found=Qe,_(Qe)},I=>{let F=O(I);return(!F||F===u)&&k(I)?.origin===t}),X("content.written",I=>{if(g.current.key!==R)return;let F=P(I);if(!F)return;let Q=g.current.found;if(!Q?.itemPath||!A(F,Q.itemPath)){if(g.current.earlyContentPaths.add(F),g.current.earlyContentPaths.size>128){let B=g.current.earlyContentPaths.values().next().value;B&&g.current.earlyContentPaths.delete(B)}return}if(Q.hasBytes)return;let K={...Q,hasBytes:!0};g.current.found=K,_(K)},I=>{let F=O(I);return(!F||F===u)&&!!P(I)})];return()=>M.forEach(I=>I())},[v,t,u,f]),{state:s?"failed":t?b?b.hasBytes?"ready":"materializing":"pending":"idle",itemId:b?.itemId,itemPath:b?.itemPath,displayName:b?.displayName,fallbackUrl:r??void 0,error:s??void 0}}function Al(e,t){let n=N().getDefaultOptions().queries?.retry??1;return typeof n=="function"?n(e,t):n===!0||typeof n=="number"&&e<n}function Ml(e,t,n){let r=(0,Ut.useSyncExternalStore)(xe,W,W),s=fe(),i=z(),o=n?.path??i,a=n?.id??s?.id,c=!!(n?.id&&n.path)||s?.kind==="space",u=(0,Ut.useMemo)(()=>({}),[r,i,o,a]),d=(0,Ut.useRef)(u);d.current=u;let l=ar(c&&o?{key:e,scope_id:a,_scope_path:o}:null),h=(0,Ut.useMemo)(()=>{let y=l.applyTo([...t]);if(e!=="channel-order")return y;let v=new Set(l.order??[]),x=y.filter(k=>!v.has(k.id)),R=k=>Date.parse(k.createdAt??"")||0;return x.sort((k,O)=>R(O)-R(k)),[...x,...y.filter(k=>v.has(k.id))]},[e,t,l.applyTo,l.order]),f=U(),m=(0,Ut.useRef)(!1),_=!!(c&&!l.error&&l.arrangement?.item_id&&l.resolutionLevel==="member"&&l.arrangement.write_target_id===l.arrangement.item_id),g=oe({mutationFn:async y=>{let v=await C("update",{_scope_path:y.scopePath,id:y.arrangementId,type_data:{order:y.ids}});if(v?.success===!1)throw new Error(v.error||"Order could not be saved");return v},onSettled:(y,v,x)=>ht(f,x.queryKey)});async function b(y){if(!_||!o||u!==d.current||r!==W()||z()!==i)throw new Error("Personal order is not available in this Space");if(m.current)throw new Error("An order change is already being saved");let v=t.map(M=>M.id);if(y.length!==v.length||new Set(y).size!==v.length||v.some(M=>!y.includes(M)))throw new Error("Order must include each displayed item exactly once");let x=f.getQueryData(l.arrangementQueryKey);if(x?.item_id!==l.arrangement.item_id||JSON.stringify(x?.type_data?.order??[])!==JSON.stringify(l.order??[]))throw new Error("The saved order changed. Try dragging again");let R=h.map(M=>M.id);if(y.every((M,I)=>R[I]===M))return;let k=new Set(v),O=0,A=[...(l.order??[]).map(M=>k.has(M)?y[O++]:M),...y.slice(O)];m.current=!0;try{return await g.mutateAsync({ids:A,scopePath:o,arrangementId:l.arrangement.item_id,queryKey:l.arrangementQueryKey})}finally{m.current=!1}}return{items:h,ready:_,supported:c,contextKey:`${r}:${o}:${e}`,isLoading:c&&l.isLoading,error:l.error,refetch:l.refetch,isSaving:g.isPending,saveError:g.error,reorder:b}}var Qo=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,hf=/^[A-Za-z_:][A-Za-z0-9_:.-]{0,127}$/,kl=new Map,Ol=new Map,cr=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 ln(e){let t=e?Yt.find(n=>n.id===e):Yt.find(n=>n.default===!0)??(Yt.length===1?Yt[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 li(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 yf(e){return e.length>0&&e.length<=128&&!/[\u0000-\u001f\u007f]/.test(e)}function _f(e,t){if(!yf(t)||!e.observations?.includes(t))throw new TypeError("The observation is not declared by this release source")}function No(e){if(!(typeof window>"u"||e.storage==="memory"))try{return e.storage==="session"?window.sessionStorage:window.localStorage}catch{return}}function bf(e){try{let t=No(e)?.getItem(e.key)??void 0;return t&&Qo.test(t)?t:void 0}catch{return}}function Fl(e,t){try{No(e)?.setItem(e.key,t)}catch{}}function ql(e){let t=e.identity?.visitor;if(!t?.key)throw new TypeError("The source visitor identity policy is invalid");let n=bf(t)??kl.get(e.id);if(n)return n;let r=crypto.randomUUID();return kl.set(e.id,r),Fl(t,r),r}function Ql(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=No(n)?.getItem(n.key);r=u?JSON.parse(u):void 0}catch{r=void 0}let s=Ol.get(e.id),i=r&&typeof r.id=="string"&&Qo.test(r.id)&&typeof r.lastSeenAt=="number"?{id:r.id,lastSeenAt:r.lastSeenAt}:s,o=n.idle_seconds*1e3,c=i&&t-i.lastSeenAt>=0&&t-i.lastSeenAt<o?{id:i.id,lastSeenAt:t}:{id:crypto.randomUUID(),lastSeenAt:t};return Ol.set(e.id,c),Fl(n,JSON.stringify(c)),c.id}function vf(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(a=>{if(typeof a!="string"||a.length===0||a.length>128)return[];let c=r.searchParams.get(a);return c?[[a,c.slice(0,i)]]:[]}));return Object.keys(o).length>0?o:void 0}async function dn(e,t={},n={}){let r=ln(n.source);if(_f(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??ql(r),o=n.sessionId??Ql(r);if(![s,i,o].every(g=>Qo.test(g)))throw new TypeError("event, visitor, and session IDs must be UUIDs");let a=n.pageUrl??(typeof window<"u"?window.location.href:void 0);if(!a)throw new TypeError("pageUrl is required outside a browser");let c=n.occurredAt??new Date().toISOString();if(Number.isNaN(Date.parse(c)))throw new TypeError("occurredAt is invalid");let u=n.referrer??(typeof document<"u"&&document.referrer||void 0),d=vf(r,a),l=d?{...t,source_keys:d}:t,h=en(),f=`${Ue.replace(/\/+$/,"")}/d/${encodeURIComponent(h)}/interactions`,m;try{m=await fetch(f,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({source:r.id,page_url:a,visitor_id:i,session_id:o,referrer:u,events:[{id:s,event_type:e,occurred_at:c,properties:l}]}),signal:n.signal,credentials:"omit",keepalive:n.keepalive??!1})}catch(g){throw new cr(g instanceof Error?g.message:"Observation transport network error","OBSERVATION_NETWORK_ERROR",0,s)}let _=null;try{_=await m.json()}catch{}if(!m.ok||_?.success!==!0){let g=_;throw new cr(g?.message||g?.error||`Observation transport failed (${m.status})`,g?.error||"OBSERVATION_TRANSPORT_FAILED",m.status,s)}return _}function Nl(e={},t={}){let n=ln(t.source),r=li("page_view",n),s=typeof document>"u"||!r.title_property?{}:{[r.title_property]:document.title.slice(0,512)};return dn(r.observation,{...s,...e},{...t,source:n.id})}function Dl(e,t={},n={}){if(!e||e.length>128)throw new TypeError("actionId is invalid");let r=ln(n.source),s=li("declared_action",r),i=s.id_property?{[s.id_property]:e}:{};return dn(s.observation,{...t,...i},{...n,source:r.id})}function Ul(){try{let e=ln();return li("form_receipt",e),{visitor_id:ql(e),session_id:Ql(e),source:e.id}}catch{return}}function wf(e,t={}){let n=ln(t.source),r=li("form_receipt",n);return dn(r.observation,e,{...t,source:n.id})}async function Sf(e,t){let r=new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`${e}\0${t}`))).slice(0,16);r[6]=r[6]&15|80,r[8]=r[8]&63|128;let s=Array.from(r,i=>i.toString(16).padStart(2,"0")).join("");return`${s.slice(0,8)}-${s.slice(8,12)}-${s.slice(12,16)}-${s.slice(16,20)}-${s.slice(20)}`}async function Kl(e,t,n,r,s){let i=Yt.filter(o=>o.adapters?.some(a=>a.type==="form_receipt"));await Promise.allSettled(i.map(async o=>{let a=o.id===r?.source;return wf(e,{source:o.id,eventId:a?t:await Sf(t,o.id),pageUrl:n,signal:s,keepalive:!0,...a?{visitorId:r.visitor_id,sessionId:r.session_id}:{}})}))}var Zr;function di(e={}){if(typeof window>"u"||typeof document>"u")return()=>{};if(Zr)return Zr;if(window.__FSAOS_CONFIG__?.tracking?.enabled===!1)return()=>{};let t;try{t=e.source?[ln(e.source)]:Yt.map(h=>ln(h.id))}catch{return()=>{}}if(t.length===0)return()=>{};let n=e.pageViews===!1?[]:t.flatMap(h=>h.adapters.filter(f=>f.type==="page_view").map(f=>({source:h,adapter:f}))),r=e.declaredActions===!1?[]:t.flatMap(h=>h.adapters.filter(f=>f.type==="declared_action").map(f=>({source:h,adapter:f}))),s="",i=()=>{if(window.location.href!==s){s=window.location.href;for(let{source:h,adapter:f}of n){let m=f.title_property?{[f.title_property]:document.title.slice(0,512)}:{};dn(f.observation,m,{source:h.id,keepalive:!0}).catch(()=>{})}}},o=h=>{if(h.target instanceof Element)for(let{source:f,adapter:m}of r){let _=m.attribute;if(!_||!hf.test(_))continue;let g=h.target.closest(`[${_}]`);if(!g)continue;let b=g.getAttribute(_)?.trim();if(!b||b.length>128)continue;let y={};m.id_property&&(y[m.id_property]=b),m.element_property&&(y[m.element_property]=g.tagName.toLowerCase()),dn(m.observation,y,{source:f.id,keepalive:!0}).catch(()=>{})}},a=window.history.pushState,c=window.history.replaceState,u=()=>queueMicrotask(i),d=n.some(({adapter:h})=>h.history===!0),l=n.some(({adapter:h})=>h.pageshow===!0);return d&&(window.history.pushState=function(...f){a.apply(this,f),u()},window.history.replaceState=function(...f){c.apply(this,f),u()},window.addEventListener("popstate",i)),l&&window.addEventListener("pageshow",i),r.length>0&&document.addEventListener("click",o,{capture:!0}),n.length>0&&queueMicrotask(i),Zr=()=>{window.removeEventListener("popstate",i),window.removeEventListener("pageshow",i),document.removeEventListener("click",o,{capture:!0}),d&&(window.history.pushState=a,window.history.replaceState=c),Zr=void 0},Zr}var ur;ae(()=>{ur=void 0});function pi(e){if(ur)return ur.accountPath!==e.accountPath?Promise.reject(new Error("Reset the session before changing accounts")):ur.promise;let t=te(),n=()=>{if(t!==te())throw new Error("Workspace session changed")},r=(async()=>{let s=await gt();if(n(),!s.principal_id)throw new Error("Workspace initialization requires an authenticated principal");let i=await N().fetchQuery({queryKey:T.memberships(s.principal_id),queryFn:Xs,staleTime:12e4,retry:!1});n();let o=i.find(l=>l.path===e.accountPath&&l.isAccount&&!l.isSpace);if(!o)throw new Error("Authenticated account membership is unavailable");let a=i.find(l=>l.isSpace&&l.accountId===o.personalSpaceId&&l.path===o.personalSpacePath);if(!a||!o.personalSpacePath)throw new Error("A provisioned default Space membership is required");let c=st(o),u=st(a),d=Se();if(d&&d.id!==c.id)throw new Error("Reset the session before changing accounts");return d||Zt(c,{activate:!1}),await un(o.personalSpacePath,l=>{let h=i.find(f=>f.accountId===l&&(f.isAccount||f.isSpace));return h?st(h):null},{initialAnchor:u}),n(),{home:c,defaultSpace:u,memberships:i}})().catch(s=>{throw t===te()&&(ur=void 0),s});return ur={accountPath:e.accountPath,promise:r},r}var pn,ts,es;ae(()=>{ts?.(),ts=void 0,pn=void 0,es=void 0});function Ll(e={}){if(pn)return e.workspace&&e.workspace.accountPath!==es?Promise.reject(new Error("Initialize workspace through initializeWorkspace, or dispose the existing runtime first")):pn;es=e.workspace?.accountPath;let t=te();return pn=(async()=>{let n=e.tracking??!0,r=n===!1?()=>{}:di(typeof n=="object"?n:{});ts=r;try{let s=e.session===!1?null:await gt(),i=e.workspace?await pi(e.workspace):void 0;if(t!==te())throw new Error("Session changed during initialization");let o=!1;return{session:s,workspace:i,dispose(){o||(o=!0,r(),t===te()&&(pn=void 0,es=void 0,ts=void 0))}}}catch(s){throw r(),t===te()&&(pn=void 0,es=void 0,ts=void 0),s}})(),pn}function xf(e){return e instanceof Be?{kind:"denied",payload:e.payload}:e instanceof Re?{kind:"gateway",method:e.method,status:e.status,statusText:e.statusText,payload:e.payload,responseBody:e.responseBody}:e instanceof Error?{kind:"other",name:e.name,message:e.message}:{kind:"other",name:"Error",message:String(e)}}function Hl(e){let t=(s,i)=>{s.postMessage(i,e.origin)},n=!0,r=s=>{if(s.origin!==e.origin)return;let i=e.frame();if(!i||s.source!==i||!io(s.data))return;let o=s.data;if(o.kind==="hello"){t(i,{fsaos:nn,kind:"welcome",anchor:fe()??Ot(),item:e.item?.()??null});return}if(o.kind!=="call"||typeof o.id!="string"||typeof o.method!="string")return;let{id:a,method:c,params:u}=o;C(c,u&&typeof u=="object"?u:{}).then(d=>{n&&t(i,{fsaos:nn,kind:"result",id:a,ok:!0,response:d})},d=>{n&&t(i,{fsaos:nn,kind:"result",id:a,ok:!1,error:xf(d)})})};return window.addEventListener("message",r),()=>{n=!1,window.removeEventListener("message",r)}}async function Do(e){try{return await C("execution-control-transition",e)}catch(t){if(!(t instanceof Re)||t.status<500)throw t;return await new Promise(n=>setTimeout(n,250)),C("execution-control-transition",e)}}function Uo(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 jl(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 Do({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 Uo(i?{...s,state:i}:s)}async function Bl(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 Do({op:"request",command:"steer",delivery:"immediate",request_message_id:r,selected_queue_entry_id:s,idempotency_key:i,...n.scopePath?{_scope_path:n.scopePath}:{}}),a=o.outcome??o.state??o.status;return Uo(a?{...o,state:a}:o)}async function $l(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 Do({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 Uo(i?{...s,outcome:i}:s)}var Rf=/^[a-z][a-z0-9_-]{0,63}$/,Cf=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,lr=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 Vl(e,t,n={}){if(!Rf.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(!Cf.test(r))throw new TypeError("fillId must be a UUID");let s=en(),i=n.pageUrl??(typeof window<"u"?window.location.href:void 0);if(!i)throw new TypeError("pageUrl is required outside a browser");let o=`${Ue.replace(/\/+$/,"")}/d/${encodeURIComponent(s)}/actions/${encodeURIComponent(e)}`,a=Ul(),c=a?{visitor_id:a.visitor_id,session_id:a.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,...c?{attribution:c}:{}}),signal:n.signal,credentials:"omit"})}catch(l){throw new lr(l instanceof Error?l.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 l=d;throw new lr(l?.message||l?.error||`Form submission failed (${u.status})`,l?.error||"FORM_SUBMISSION_FAILED",u.status,r)}return await Kl({fill_id:r,action_id:e,release_id:d.release_id},r,i,a,n.signal),d}async function Wl(e){return C("commerce-file-sale",{action:"checkout",product_id:e.productId,expected_product_revision_id:e.productRevisionId,destination_id:e.destinationId,request_key:e.requestKey,_scope_path:e.scopePath,...e.journey?{journey:e.journey}:{}})}async function Gl(e,t){return C("commerce-file-sale",{action:"get",license_id:e,_scope_path:t})}function zl(e){let t=new URL(e.hostOrigin);if(t.protocol!=="https:"&&!(t.protocol==="http:"&&t.hostname==="127.0.0.1")||t.username||t.password||t.search||t.hash||t.pathname!=="/")throw new TypeError("hostOrigin must be an HTTPS origin or the local 127.0.0.1 app");let n=new URL(e.pageUrl??window.location.href);if(n.protocol!=="https:"||n.username||n.password||n.hash||n.port)throw new TypeError("The funnel must be a published HTTPS page");let r=new URL("/v2/revven",t);return r.search=new URLSearchParams({surface:"library",offer:e.productId,sale_page:n.href,sale_action:e.capabilityId}).toString(),r.href}function Jl(e){if(e.success!==!0||e.state!=="ready"||!e.item_id||!e.file_id||!e.journey?.next_url)return null;let t=new URL(e.journey.next_url),n=new URL(e.journey.return_url);if(t.protocol!=="https:"||n.protocol!=="https:"||t.origin!==n.origin||t.username||t.password||t.hash||t.searchParams.getAll("funnel_id").length!==1||t.searchParams.get("funnel_id")!==e.journey.funnel_id)throw new Error("The purchase destination could not be verified");return t.href}var Ko=J(ue(),1),Zl=J(Xl(),1);function ed(e){return C("read",{path:e})}function td(e,t){return C("list",{path:e,...t})}function nd(e){return C("create",e)}function rd(e){return C("update",e)}function sd(e){return C("create",e)}function id(e,t){let r=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).scopePath||"";return C("tools/call",{name:e,instance_path:r,...t||{}})}function od(e,t,n){return C("signal",{target_id:e,event_name:t,payload:n||{}})}function ad(e){return((typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"")+e}var cd={signIn:e=>e.provider?G.auth.signInWithOAuth({provider:e.provider,options:{redirectTo:e.redirectTo||window.location.href}}):G.auth.signInWithPassword({email:e.email,password:e.password}),signUp:e=>G.auth.signUp({email:e.email,password:e.password,options:{data:e.metadata||{}}}),signOut:async()=>{await G.auth.signOut(),$n(),N().clear()},getSession:()=>G.auth.getSession().then(e=>e.data.session),getUser:()=>G.auth.getUser().then(e=>e.data.user),onAuthStateChange:e=>{let{data:{subscription:t}}=G.auth.onAuthStateChange((n,r)=>{e({event:n,session:r,user:r?.user??null})});return()=>t?.unsubscribe()},resetPassword:e=>G.auth.resetPasswordForEmail(e),signInWithMagicLink:(e,t)=>G.auth.signInWithOtp({email:e,options:{emailRedirectTo:t||window.location.href}})};function ud(){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,Zl.createRoot)(e).render((0,Ko.createElement)(Tr,{client:N()},(0,Ko.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 ld(){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}var Pf=e=>C("create-invitation",{...e}),Ef=e=>C("get-invitation",{invitation_id:e}),If=e=>C("accept-invite",{invitation_id:e}),Tf=e=>C("reject-invite",{invitation_id:e}),Af=e=>C("cancel-invite",{invitation_id:e}),Mf=(e,t)=>C("resend-invite",{invitation_id:e,request_id:t}),kf=(e,t)=>C("list-invitations",{account_id:e,...t?{after:t}:{}});function Lo(e){return C("invite-member",e)}function Ho(e){return C("accept-invite",e)}function jo(e){let t={};return e.role&&(t.role=e.role),C("link",{source_id:e.chat_id,target_id:e.member_id,edge_type:"has_member",context:t})}function Bo(e){return C("create-agent",e)}function $o(e){return!e.input_request_id&&!e.input_request?Promise.reject(new Error("answerInput needs input_request_id or the input_request object read from the step.")):C("todo-control",{action:"answer_input",...e})}function dd(){return oe({mutationFn:Lo})}function pd(){let e=U();return oe({mutationFn:Ho,onSuccess:()=>{e.invalidateQueries({queryKey:["memberships"]})}})}function fd(){let e=U();return oe({mutationFn:jo,onSuccess:(t,n)=>{e.invalidateQueries({queryKey:T.edges(n.chat_id)}),e.invalidateQueries({queryKey:T.edges(n.member_id)})}})}function md(){let e=U();return oe({mutationFn:Bo,onSuccess:()=>{e.invalidateQueries({queryKey:["memberships"]})}})}function gd(){let e=U();return oe({mutationFn:$o,onSuccess:(t,n)=>{e.invalidateQueries({queryKey:T.itemById(n.step_id)})}})}function Of(e){return e.split("_").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function Ff(e,t){return t&&t.length>0?"select":e==="boolean"?"toggle":e==="integer"||e==="number"?"range":e==="string"?"text":"none"}function qf(e,t){return!(e==="object"||e==="array")}function Qf(e){return["string","number","integer","boolean"].includes(e)}function Nf(e){return e!=="object"&&e!=="array"}function hd(e,t,n,r){let s=e?.properties;if(!s||typeof s!="object")return[];let i=[];for(let[o,a]of Object.entries(s)){let c=a.type||"string",u=a.enum,d=qf(c,u),l=Qf(c),h=Ff(c,u);i.push({key:o,label:a.title||Of(o),type:c,description:a.description,enum_values:u,default_value:n[o]??r[o]??a.default,editable:t,filterable:d,sortable:l,filter_widget:h})}return i}function Vo(e){let t=e.default_data||{},n=e.field_defaults||{},r=hd(e.input_schema,!0,t,n),s=hd(e.system_schema,!1,t,n),i=[...r,...s],o=i.filter(u=>Nf(u.type)),a=i.filter(u=>u.filterable),c=i.filter(u=>u.sortable);return{fields:i,columns:o,filterable:a,sortable:c,form_fields:r,system_fields:s}}function yd(e){return{field:"updated_at",direction:"desc"}}function _d(e){let t=Vo(e),n=new Set(e.input_schema?.required||[]);return t.form_fields.filter(r=>n.has(r.key)||r.default_value===void 0)}var Pe=J(ue(),1);var bd=Promise.resolve();function qe(e){if(e?.aborted)throw new Error("Upload cancelled")}async function Wo(e,t){if(qe(t),e.size>16777216||!globalThis.crypto?.subtle)return{};let n=bd.then(async()=>{qe(t);let r=await e.arrayBuffer();qe(t);let s=await globalThis.crypto.subtle.digest("SHA-256",r);return qe(t),{expected_sha256:Array.from(new Uint8Array(s),i=>i.toString(16).padStart(2,"0")).join(""),expected_size_bytes:e.size}});return bd=n.catch(()=>{}),n}function vd(){if(globalThis.crypto?.randomUUID)return globalThis.crypto.randomUUID();let e=new Uint8Array(16);if(globalThis.crypto?.getRandomValues){globalThis.crypto.getRandomValues(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=Array.from(e,n=>n.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{let n=Math.floor(Math.random()*16);return(t==="x"?n:n&3|8).toString(16)})}async function wd(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",a=t.collisionPolicy||"keep_both",c=a==="keep_both"?vd():void 0,u=W(),d=te(),l=await Wo(e,r);if(qe(r),u!==W()||d!==te())throw new Error("The account or Space changed while preparing the upload. Start it again.");let h={parent_path:t.parentPath,item_type:o,name:s,type_data:{...t.typeData||{},file_source:{type:"upload",content_type:i,collision_policy:a,...c?{upload_id:c}:{},...l}}};t.cardParentPath&&(h.card_parent_path=t.cardParentPath);let f=await C("create",h);qe(r);let m=f;if(!m.id)throw new Error(m.error||m.message||"Failed to create file item");let _=m.id,g=m.path;if(m.storage_completed&&m.file_ref)return{itemId:_,itemPath:g,fileRef:m.file_ref};let b=m.storage_key,y=m.upload_token,v=m.storage_worker_url||"https://fsaos-storage.radns.workers.dev";if(!b)throw new Error("Gateway returned no storage_key \u2014 file_source may not be supported for this item type");await Df(v,b,y,e,i,n,r),qe(r);let x=await Sd(_,b,i,y,l.expected_sha256,e.size);return{itemId:_,itemPath:g,fileRef:x}}function Df(e,t,n,r,s,i,o){return new Promise((a,c)=>{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?a():c(new Error(`Storage upload failed: HTTP ${u.status} \u2014 ${u.responseText?.slice(0,300)}`))},u.onerror=()=>c(new Error("Storage upload network error")),u.ontimeout=()=>c(new Error("Storage upload timed out")),u.onabort=()=>c(new Error("Upload cancelled")),o){if(o.aborted){c(new Error("Upload cancelled"));return}o.addEventListener("abort",()=>{u.abort(),c(new Error("Upload cancelled"))})}u.send(r)})}async function Sd(e,t,n,r,s,i){let o=await mt(),a=await fetch(`${Ue}/storage/upload-complete`,{method:"POST",headers:{"Content-Type":"application/json",...o?{Authorization:`Bearer ${o}`}:{}},body:JSON.stringify({item_id:e,storage_key:t,content_type:n,...r?{upload_token:r}:{},...s?{hash:s}:{}})});if(!a.ok){let u=await a.text().catch(()=>"");throw new Error(`Upload confirmation failed: HTTP ${a.status} \u2014 ${u.slice(0,300)}`)}let c=await a.json();if(!c.success)throw new Error(c.error||c.message||"Upload confirmation rejected");if(s&&(c.file_ref?.content_sha256!==s||c.file_ref?.size_bytes!==i||c.file_ref?.content_type!==n))throw new Error("Stored file did not confirm the expected checksum, size and type");return c.file_ref}function xd(){let[e,t]=(0,Pe.useState)([]),n=U(),r=(0,Pe.useRef)(e);r.current=e;let s=(0,Pe.useRef)(new Map),i=(0,Pe.useCallback)((g,b)=>{t(y=>y.map(v=>v.id===g?{...v,...b}:v))},[]),o=(0,Pe.useCallback)(g=>{t(b=>[...b,g])},[]),a=(0,Pe.useCallback)(async(g,b,y,v,x)=>{let R=y.name||b.name,k=b.type||"application/octet-stream",O=y.itemType||"file",P=y.collisionPolicy||"keep_both",A=x?.itemId||null,M=x?.itemPath||null,I=x?.storageKey||null,F=x?.uploadToken||null,Q=x?.storageWorkerUrl||null,K=x?.contentSha256||void 0,B=new AbortController,Qe=W(),j=te();s.current.get(g)?.abort(),s.current.set(g,B);try{if(!v||v==="create"){i(g,{status:"creating",error:null,_failedAt:null});let ve=await Wo(b,B.signal);if(qe(B.signal),Qe!==W()||j!==te())throw new Error("The account or Space changed while preparing the upload. Start it again.");K=ve.expected_sha256;let je=await C("create",{parent_path:y.parentPath,item_type:O,name:R,type_data:{...y.typeData||{},file_source:{type:"upload",content_type:k,collision_policy:P,...P==="keep_both"?{upload_id:g}:{},...ve}}});qe(B.signal);let de=je;if(!de.id)throw Object.assign(new Error(de.error||de.message||"Failed to create file item"),{_step:"create"});if(A=de.id,M=de.path,i(g,{itemId:A,itemPath:M}),de.storage_completed&&de.file_ref){i(g,{status:"complete",progress:100,fileRef:de.file_ref}),n.invalidateQueries({queryKey:T.children(y.parentPath)});return}if(I=de.storage_key,F=de.upload_token||"",Q=de.storage_worker_url||"https://fsaos-storage.radns.workers.dev",i(g,{_storageKey:I,_uploadToken:F,_storageWorkerUrl:Q,_contentSha256:K||null}),!I)throw Object.assign(new Error("Gateway returned no storage_key"),{_step:"create"})}(!v||v==="create"||v==="upload")&&(i(g,{status:"uploading",progress:0,error:null,_failedAt:null}),await new Promise((je,de)=>{let me=new XMLHttpRequest;i(g,{_xhr:me}),me.open("PUT",`${Q}/upload`),me.setRequestHeader("X-Storage-Key",I),me.setRequestHeader("Content-Type",k),F&&me.setRequestHeader("X-Upload-Token",F),me.upload.onprogress=ye=>{ye.lengthComputable&&i(g,{progress:Math.round(ye.loaded/ye.total*100)})},me.onload=()=>{me.status>=200&&me.status<300?je():de(Object.assign(new Error(`Storage upload failed: HTTP ${me.status}`),{_step:"upload"}))},me.onerror=()=>de(Object.assign(new Error("Storage upload network error"),{_step:"upload"})),me.ontimeout=()=>de(Object.assign(new Error("Storage upload timed out"),{_step:"upload"})),me.onabort=()=>de(Object.assign(new Error("Upload cancelled"),{_step:"upload"})),B.signal.addEventListener("abort",()=>me.abort(),{once:!0}),qe(B.signal),me.send(b)}),qe(B.signal),i(g,{progress:100,_xhr:null})),i(g,{status:"confirming",error:null,_failedAt:null});let he=await Sd(A,I,k,F||"",K,b.size).catch(ve=>{throw Object.assign(ve,{_step:"confirm"})});qe(B.signal),i(g,{status:"complete",fileRef:he}),n.invalidateQueries({queryKey:T.children(y.parentPath)})}catch(he){if(s.current.get(g)!==B)return;let ve=he?.message||String(he),je=he?._step||"create";i(g,{status:"error",error:ve,_failedAt:je,_xhr:null})}finally{s.current.get(g)===B&&s.current.delete(g)}},[i,n]),c=(0,Pe.useCallback)((g,b)=>{let y=vd();o({id:y,file:g,status:"creating",progress:0,error:null,itemId:null,itemPath:null,fileRef:null,options:b,_storageKey:null,_uploadToken:null,_storageWorkerUrl:null,_contentSha256:null,_xhr:null,_failedAt:null}),a(y,g,b)},[o,a]),u=(0,Pe.useCallback)((g,b)=>{for(let y of g)c(y,b)},[c]),d=(0,Pe.useCallback)(g=>{let b=r.current.find(x=>x.id===g);if(!b||b.status!=="error")return;let y=b._failedAt||"create",v=b._storageKey&&b.itemId?{storageKey:b._storageKey,uploadToken:b._uploadToken||"",storageWorkerUrl:b._storageWorkerUrl||"https://fsaos-storage.radns.workers.dev",itemId:b.itemId,itemPath:b.itemPath||"",contentSha256:b._contentSha256}:void 0;a(g,b.file,b.options,y,v)},[a]),l=(0,Pe.useCallback)(g=>{s.current.get(g)?.abort();let b=r.current.find(y=>y.id===g);b&&(b._xhr&&b._xhr.abort(),i(g,{status:"error",error:"Cancelled",_xhr:null,_failedAt:null}))},[i]),h=(0,Pe.useCallback)(g=>{s.current.get(g)?.abort(),s.current.delete(g),t(b=>b.filter(y=>y.id!==g))},[]),f=(0,Pe.useCallback)(()=>{t(g=>g.filter(b=>b.status!=="complete"))},[]),m=e.some(g=>g.status==="creating"||g.status==="uploading"||g.status==="confirming"),_=e.map(({_storageKey:g,_uploadToken:b,_storageWorkerUrl:y,_contentSha256:v,_xhr:x,_failedAt:R,...k})=>k);return{upload:c,uploadMultiple:u,uploads:_,retryUpload:d,cancelUpload:l,removeUpload:h,clearCompleted:f,isUploading:m}}var Rd=J(ue(),1);async function Go(e,t){return await C("resolve-items",{context_id:e,item_type:t})}function Cd(e,t){return(0,Rd.useSyncExternalStore)(xe,W,W),$({queryKey:["vfs",z()??"__unscoped__","resolved-items",e??"",t],queryFn:()=>Go(e,t),enabled:!!(e&&t)})}var Ge=J(ue(),1);function fi(e,t){let n={artifacts:new Map,timeline:[]},r=new Map;function s(o){if(!o.action?.startsWith("artifact_"))return;let c,u=o.name;if(typeof u=="string"&&u.startsWith("{"))try{c=JSON.parse(u)}catch{return}else if(o.artifact_id)c=o;else return;switch(c.type){case"artifact_opened":{let d=Date.now();if(n.artifacts.set(c.artifact_id,{artifact_id:c.artifact_id,surface_type:c.surface_type,tool_id:c.tool_id,tool_name:c.tool_name,target_uri:c.target_uri,status:"streaming",content:"",total_chars:0,delta_count:0,artifact_item_uri:null,evidence_uri:null,meta:c.meta,started_at:d,completed_at:null}),r.has(c.tool_id)){let l=r.get(c.tool_id);n.timeline[l].artifact_ids.push(c.artifact_id)}else{let l=n.timeline.length;n.timeline.push({tool_id:c.tool_id,tool_name:c.tool_name,status:"started",target_uri:c.target_uri,started_at:d,completed_at:null,artifact_ids:[c.artifact_id]}),r.set(c.tool_id,l)}break}case"artifact_delta":{let d=n.artifacts.get(c.artifact_id);d&&(d.content+=c.content_delta,d.total_chars+=c.content_delta.length,d.delta_count+=1,c.target_uri&&!d.target_uri&&(d.target_uri=c.target_uri));break}case"artifact_done":{let d=n.artifacts.get(c.artifact_id);d&&(d.status=c.status,d.total_chars=c.total_chars,d.artifact_item_uri=c.artifact_item_uri,d.evidence_uri=c.evidence_uri,c.target_uri&&(d.target_uri=c.target_uri),(c.status==="completed"||c.status==="failed")&&(d.completed_at=Date.now()));let l=r.get(c.tool_id);if(l!==void 0){let h=n.timeline[l];c.status==="executing"?h.status="executing":c.status==="completed"?(h.status="completed",h.completed_at=Date.now()):c.status==="failed"&&(h.status="failed",h.completed_at=Date.now()),c.target_uri&&!h.target_uri&&(h.target_uri=c.target_uri)}break}}t(n)}return Ks(e,s)}function Pd(e,t=!0){let[n,r]=(0,Ge.useState)(new Map),[s,i]=(0,Ge.useState)([]),o=(0,Ge.useRef)({artifacts:new Map,timeline:[]});(0,Ge.useEffect)(()=>!e||!t?void 0:fi(e,l=>{o.current=l,r(new Map(l.artifacts)),i([...l.timeline])}),[e,t]);let a=(0,Ge.useCallback)(()=>{r(new Map),i([]),o.current={artifacts:new Map,timeline:[]}},[]),c=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:c,activeActivities:u,reset:a}}function Ed(e,t=!0){let[n,r]=(0,Ge.useState)([]);(0,Ge.useEffect)(()=>!e||!t?void 0:fi(e,o=>{r([...o.timeline])}),[e,t]);let s=n.length>0?n[n.length-1]:null;return{timeline:n,latestActivity:s}}var mi=J(ue(),1);function Uf(e,t,n,r){return["vfs","timeline-history",e,t??"__all__",n??500,r??0]}async function zo(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 a=(await C("open",{path:n,mode:"extract",strategy:"rows",arguments:i}))?.content;return a?(a.rows??a.items??a.data??[]).map(Kf).sort((u,d)=>u.seq-d.seq):[]}catch(o){if(o?.status===404||o?.message?.includes("not found"))return[];throw o}}function Id(e,t){let{turnId:n,limit:r=500,offset:s=0,enabled:i=!0,debounceMs:o=300}=t??{},a=e?`${e}/datasets/agent-events`:null,c=U(),u=(0,mi.useRef)(null),d=a?Uf(a,n,r,s):["vfs","timeline-history","__disabled__"],l=$({queryKey:d,queryFn:()=>zo(e,{turnId:n,limit:r,offset:s}),enabled:!!e&&i});return(0,mi.useEffect)(()=>{if(!a||!i)return;let h=X("vfs_change",()=>{u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{c.invalidateQueries({queryKey:d})},o)},f=>{let m=f?.path;return m?m===a&&f.item_type==="dataset":!1});return()=>{h(),u.current&&clearTimeout(u.current)}},[a,i,o,c,JSON.stringify(d)]),{events:l.data??[],isLoading:l.isLoading,error:l.error,isFetching:l.isFetching,refetch:()=>{l.refetch()}}}function Kf(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 Kt=J(ue(),1);function Td(e){let t=(0,Kt.useSyncExternalStore)(xe,W,W),n=z(),r=e?.path??n,s=fe(),i=e?.id??s?.id,o=(0,Kt.useMemo)(()=>({}),[t,n,r,i]),a=(0,Kt.useRef)(o);a.current=o;let c=ar(r?{key:"pinned",scope_id:i,_scope_path:r}:null),u=U(),d=c.resolvedChildren,l=!!(!c.error&&c.arrangement?.item_id&&c.resolutionLevel==="member"&&c.arrangement.write_target_id===c.arrangement.item_id),h=oe({mutationFn:async m=>{let _,g={_scope_path:m.scopePath};if(m.operation==="pin"?_=await C("create",{...g,parent_id:m.arrangementId,name:`pin-${m.target.id}`,item_type:"symlink",type_data:{target_item_id:m.target.id,target_type:m.target.item_type}}):m.operation==="unpin"?_=await C("delete",{...g,id:m.entry.id}):_=await C("update",{...g,id:m.arrangementId,type_data:{order:m.ids}}),_?.success===!1)throw new Error(_.error||"Pins could not be saved");return _},onSettled:(m,_,g)=>ht(u,g.queryKey)}),f=(0,Kt.useCallback)(m=>!l||!r||a.current!==o||t!==W()||z()!==n?Promise.reject(new Error("Personal pins are not available in this context")):m.operation==="unpin"&&!d.some(_=>_.id===m.entry.id)?Promise.reject(new Error("Pin is outside this arrangement")):m.operation==="reorder"&&(new Set(m.ids).size!==d.length||m.ids.length!==d.length||d.some(_=>!m.ids.includes(_.id)))?Promise.reject(new Error("Order must include each pin exactly once")):m.operation==="pin"&&d.some(_=>_.symlink_type_data?.target_item_id===m.target.id)?Promise.resolve(null):h.mutateAsync({...m,scopePath:r,arrangementId:c.arrangement.item_id,arrangementPath:c.arrangement.item_path,queryKey:c.arrangementQueryKey}),[l,t,n,r,o,d,c.arrangement,c.arrangementQueryKey,h.mutateAsync]);return{entries:d,isLoading:c.isLoading,error:c.error,refetch:c.refetch,ready:l,isSaving:h.isPending,saveError:h.error,isPinned:m=>d.some(_=>_.symlink_type_data?.target_item_id===m),pin:m=>f({operation:"pin",target:m}),unpin:m=>{let _=d.find(g=>g.symlink_type_data?.target_item_id===m||g.id===m);return _?f({operation:"unpin",entry:_}):Promise.resolve(null)},reorder:m=>f({operation:"reorder",ids:m})}}var gi=J(ue(),1);var ns=(e,t,n)=>["vfs",e,"personal-sections",t,n];function Jo(e,t){return e&&e.item_id===t.item_id&&e.version>t.version?e:t}async function Yo(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 Ad(e,t){let n=await Yo(e.scopePath,e.contextId,e.collection,{operation:"assign",section_id:e.sectionId,target_id:t}),r=N();return r.setQueryData(ns(e.scopePath,e.contextId,e.collection),s=>Jo(s,n)),Md(r,e.scopePath),n}function Md(e,t){for(let n of e.getQueryCache().getAll())n.queryKey[0]==="vfs"&&n.queryKey[1]===t&&n.queryKey[2]==="personal-sections"&&ht(e,n.queryKey)}function kd(e,t){let n=(0,gi.useSyncExternalStore)(xe,W,W),r=z(),s=U(),i=ns(r,e,t),o=$({queryKey:i,enabled:!!r&&!!e,queryFn:()=>Yo(r,e,t,{operation:"list"}),staleTime:1/0,retry:!1,meta:{arrangementRealtime:!0,personalSections:!0},structuralSharing:(l,h)=>Jo(l,h)}),a=(0,gi.useRef)(!1),c=oe({mutationFn:async l=>{let h=await Yo(l.scope,l.context,l.collection,{...l.change,...l.change.operation.startsWith("reorder")?{expected_version:l.version}:{}});return s.setQueryData(ns(l.scope,l.context,l.collection),f=>Jo(f,h)),h},onSettled:(l,h,f)=>Md(s,f.scope)});async function u(l){if(!r||!e||n!==W()||z()!==r||!o.data||o.error)throw new Error("Select the Space again before changing sections");if(a.current)throw new Error("A section change is still being saved");a.current=!0;try{return await c.mutateAsync({change:l,scope:r,context:e,collection:t,version:o.data.version})}finally{a.current=!1}}function d(l){if(!r||!e||!o.data?.sections.some(h=>h.id===l))throw new Error("Section is unavailable");return{scopePath:r,contextId:e,collection:t,sectionId:l}}return{sections:o.data?.sections??[],ready:!!o.data&&!o.error,isLoading:o.isLoading,error:o.error,refetch:o.refetch,isSaving:c.isPending,change:u,destination:d,contextKey:`${n}:${r}:${e}:${t}`}}el(Xo);return Ld(Xo);})();
|
|
8
|
+
${u??""}
|
|
9
|
+
${m??""}
|
|
10
|
+
${t??""}`,[h,g]=(0,v.useState)(null),y=(0,v.useRef)({key:p,found:null,earlyContentPaths:new Set}),S=h?.key===p?h:null;(0,v.useLayoutEffect)(()=>{y.current={key:p,found:S,earlyContentPaths:new Set}},[p]);let _=H({queryKey:["vfs",u??"__unscoped__","minted-asset",m??"",t??""],queryFn:async()=>{let b=await P("query",{scope_path:u,filters:{[`field.${m}`]:t},limit:1}),E=b.content?.items??b.items??[],I=E[0]?Ne(E[0]):null;if(!I)return null;let A=(await jr(I.path)).some(O=>O.item_type==="file"&&!!O.type_data?.file_ref);return{asset:I,hasBytes:A}},enabled:!!(t&&u&&m&&!s),refetchInterval:b=>y.current.key===p&&y.current.found?.hasBytes||b.state.data?.hasBytes?!1:1500});(0,v.useEffect)(()=>{let b=_.data;if(!b||y.current.key!==p)return;let E=y.current.found,I={key:p,itemId:b.asset.id,itemPath:b.asset.path,displayName:typeof b.asset.type_data?.display_name=="string"?b.asset.type_data.display_name:b.asset.name,hasBytes:b.hasBytes||!!(E?.itemId===b.asset.id&&E.hasBytes)};y.current.found=I,g(I)},[_.data,p]);let w=!!(t&&l)&&!s&&!S?.hasBytes;return(0,v.useEffect)(()=>{if(!(!w||!l))return Yn(l,["asset.materialized","content.written"])},[w,l]),(0,v.useEffect)(()=>{if(!w||!t||!l)return;let b=p,E=M=>M?.payload??M,I=M=>{let Q=E(M)?.scope_id??M?.scope_id;return typeof Q=="string"?Q:void 0},C=M=>{let Q=E(M)?.item_path??M?.item_path;return typeof Q=="string"&&Q?Q:void 0},A=(M,F)=>{let Q=F.replace(/\/+$/,"");return M===Q||M.startsWith(`${Q}/`)},O=[X("asset.materialized",M=>{if(y.current.key!==b)return;let F=E(M);if(typeof F?.item_id!="string"||!F.item_id)return;let Q=y.current.found,B=typeof F.item_path=="string"?F.item_path:void 0,ae=!!F.has_bytes||!!(B&&Array.from(y.current.earlyContentPaths).some(j=>A(j,B)))||!!(Q&&Q.itemId===F.item_id&&Q.hasBytes),He={key:b,itemId:F.item_id,itemPath:B,displayName:typeof F.display_name=="string"?F.display_name:void 0,hasBytes:ae};y.current.found=He,g(He)},M=>{let F=I(M);return(!F||F===l)&&E(M)?.origin===t}),X("content.written",M=>{if(y.current.key!==b)return;let F=C(M);if(!F)return;let Q=y.current.found;if(!Q?.itemPath||!A(F,Q.itemPath)){if(y.current.earlyContentPaths.add(F),y.current.earlyContentPaths.size>128){let ae=y.current.earlyContentPaths.values().next().value;ae&&y.current.earlyContentPaths.delete(ae)}return}if(Q.hasBytes)return;let B={...Q,hasBytes:!0};y.current.found=B,g(B)},M=>{let F=I(M);return(!F||F===l)&&!!C(M)})];return()=>O.forEach(M=>M())},[w,t,l,p]),{state:s?"failed":t?S?S.hasBytes?"ready":"materializing":"pending":"idle",itemId:S?.itemId,itemPath:S?.itemPath,displayName:S?.displayName,fallbackUrl:r??void 0,error:s??void 0}}function Vl(e,t){let n=N().getDefaultOptions().queries?.retry??1;return typeof n=="function"?n(e,t):n===!0||typeof n=="number"&&e<n}function Wl(e,t,n){let r=(0,qt.useSyncExternalStore)(be,W,W),s=pe(),i=z(),o=n?.path??i,a=n?.id??s?.id,c=!!(n?.id&&n.path)||s?.kind==="space",l=(0,qt.useMemo)(()=>({}),[r,i,o,a]),d=(0,qt.useRef)(l);d.current=l;let u=ir(c&&o?{key:e,scope_id:a,_scope_path:o}:null),m=(0,qt.useMemo)(()=>{let _=u.applyTo([...t]);if(e!=="channel-order")return _;let w=new Set(u.order??[]),x=_.filter(E=>!w.has(E.id)),b=E=>Date.parse(E.createdAt??"")||0;return x.sort((E,I)=>b(I)-b(E)),[...x,..._.filter(E=>w.has(E.id))]},[e,t,u.applyTo,u.order]),p=U(),h=(0,qt.useRef)(!1),g=!!(c&&!u.error&&u.arrangement?.item_id&&u.resolutionLevel==="member"&&u.arrangement.write_target_id===u.arrangement.item_id),y=ie({mutationFn:async _=>{let w=await P("update",{_scope_path:_.scopePath,id:_.arrangementId,type_data:{order:_.ids}});if(w?.success===!1)throw new Error(w.error||"Order could not be saved");return w},onSettled:(_,w,x)=>ft(p,x.queryKey)});async function S(_){if(!g||!o||l!==d.current||r!==W()||z()!==i)throw new Error("Personal order is not available in this Space");if(h.current)throw new Error("An order change is already being saved");let w=t.map(O=>O.id);if(_.length!==w.length||new Set(_).size!==w.length||w.some(O=>!_.includes(O)))throw new Error("Order must include each displayed item exactly once");let x=p.getQueryData(u.arrangementQueryKey);if(x?.item_id!==u.arrangement.item_id||JSON.stringify(x?.type_data?.order??[])!==JSON.stringify(u.order??[]))throw new Error("The saved order changed. Try dragging again");let b=m.map(O=>O.id);if(_.every((O,M)=>b[M]===O))return;let E=new Set(w),I=0,A=[...(u.order??[]).map(O=>E.has(O)?_[I++]:O),..._.slice(I)];h.current=!0;try{return await y.mutateAsync({ids:A,scopePath:o,arrangementId:u.arrangement.item_id,queryKey:u.arrangementQueryKey})}finally{h.current=!1}}return{items:m,ready:g,supported:c,contextKey:`${r}:${o}:${e}`,isLoading:c&&u.isLoading,error:u.error,refetch:u.refetch,isSaving:y.isPending,saveError:y.error,reorder:S}}var Ko=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,qf=/^[A-Za-z_:][A-Za-z0-9_:.-]{0,127}$/,Gl=new Map,zl=new Map,or=class extends Error{constructor(n,r,s,i){super(n);te(this,"code");te(this,"status");te(this,"eventId");this.name="InteractionTrackingError",this.code=r,this.status=s,this.eventId=i}};function cn(e){let t=e?zt.find(n=>n.id===e):zt.find(n=>n.default===!0)??(zt.length===1?zt[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 fi(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 Nf(e){return e.length>0&&e.length<=128&&!/[\u0000-\u001f\u007f]/.test(e)}function Qf(e,t){if(!Nf(t)||!e.observations?.includes(t))throw new TypeError("The observation is not declared by this release source")}function Lo(e){if(!(typeof window>"u"||e.storage==="memory"))try{return e.storage==="session"?window.sessionStorage:window.localStorage}catch{return}}function Df(e){try{let t=Lo(e)?.getItem(e.key)??void 0;return t&&Ko.test(t)?t:void 0}catch{return}}function Jl(e,t){try{Lo(e)?.setItem(e.key,t)}catch{}}function Yl(e){let t=e.identity?.visitor;if(!t?.key)throw new TypeError("The source visitor identity policy is invalid");let n=Df(t)??Gl.get(e.id);if(n)return n;let r=crypto.randomUUID();return Gl.set(e.id,r),Jl(t,r),r}function Xl(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=Lo(n)?.getItem(n.key);r=l?JSON.parse(l):void 0}catch{r=void 0}let s=zl.get(e.id),i=r&&typeof r.id=="string"&&Ko.test(r.id)&&typeof r.lastSeenAt=="number"?{id:r.id,lastSeenAt:r.lastSeenAt}:s,o=n.idle_seconds*1e3,c=i&&t-i.lastSeenAt>=0&&t-i.lastSeenAt<o?{id:i.id,lastSeenAt:t}:{id:crypto.randomUUID(),lastSeenAt:t};return zl.set(e.id,c),Jl(n,JSON.stringify(c)),c.id}function Uf(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(a=>{if(typeof a!="string"||a.length===0||a.length>128)return[];let c=r.searchParams.get(a);return c?[[a,c.slice(0,i)]]:[]}));return Object.keys(o).length>0?o:void 0}async function un(e,t={},n={}){let r=cn(n.source);if(Qf(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??Yl(r),o=n.sessionId??Xl(r);if(![s,i,o].every(y=>Ko.test(y)))throw new TypeError("event, visitor, and session IDs must be UUIDs");let a=n.pageUrl??(typeof window<"u"?window.location.href:void 0);if(!a)throw new TypeError("pageUrl is required outside a browser");let c=n.occurredAt??new Date().toISOString();if(Number.isNaN(Date.parse(c)))throw new TypeError("occurredAt is invalid");let l=n.referrer??(typeof document<"u"&&document.referrer||void 0),d=Uf(r,a),u=d?{...t,source_keys:d}:t,m=Xt(),p=`${Oe.replace(/\/+$/,"")}/d/${encodeURIComponent(m)}/interactions`,h;try{h=await fetch(p,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({source:r.id,page_url:a,visitor_id:i,session_id:o,referrer:l,events:[{id:s,event_type:e,occurred_at:c,properties:u}]}),signal:n.signal,credentials:"omit",keepalive:n.keepalive??!1})}catch(y){throw new or(y instanceof Error?y.message:"Observation transport network error","OBSERVATION_NETWORK_ERROR",0,s)}let g=null;try{g=await h.json()}catch{}if(!h.ok||g?.success!==!0){let y=g;throw new or(y?.message||y?.error||`Observation transport failed (${h.status})`,y?.error||"OBSERVATION_TRANSPORT_FAILED",h.status,s)}return g}function Zl(e={},t={}){let n=cn(t.source),r=fi("page_view",n),s=typeof document>"u"||!r.title_property?{}:{[r.title_property]:document.title.slice(0,512)};return un(r.observation,{...s,...e},{...t,source:n.id})}function ed(e,t={},n={}){if(!e||e.length>128)throw new TypeError("actionId is invalid");let r=cn(n.source),s=fi("declared_action",r),i=s.id_property?{[s.id_property]:e}:{};return un(s.observation,{...t,...i},{...n,source:r.id})}function td(){try{let e=cn();return fi("form_receipt",e),{visitor_id:Yl(e),session_id:Xl(e),source:e.id}}catch{return}}function Kf(e,t={}){let n=cn(t.source),r=fi("form_receipt",n);return un(r.observation,e,{...t,source:n.id})}async function Lf(e,t){let r=new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`${e}\0${t}`))).slice(0,16);r[6]=r[6]&15|80,r[8]=r[8]&63|128;let s=Array.from(r,i=>i.toString(16).padStart(2,"0")).join("");return`${s.slice(0,8)}-${s.slice(8,12)}-${s.slice(12,16)}-${s.slice(16,20)}-${s.slice(20)}`}async function nd(e,t,n,r,s){let i=zt.filter(o=>o.adapters?.some(a=>a.type==="form_receipt"));await Promise.allSettled(i.map(async o=>{let a=o.id===r?.source;return Kf(e,{source:o.id,eventId:a?t:await Lf(t,o.id),pageUrl:n,signal:s,keepalive:!0,...a?{visitorId:r.visitor_id,sessionId:r.session_id}:{}})}))}var es;function mi(e={}){if(typeof window>"u"||typeof document>"u")return()=>{};if(es)return es;if(window.__FSAOS_CONFIG__?.tracking?.enabled===!1)return()=>{};let t;try{t=e.source?[cn(e.source)]:zt.map(m=>cn(m.id))}catch{return()=>{}}if(t.length===0)return()=>{};let n=e.pageViews===!1?[]:t.flatMap(m=>m.adapters.filter(p=>p.type==="page_view").map(p=>({source:m,adapter:p}))),r=e.declaredActions===!1?[]:t.flatMap(m=>m.adapters.filter(p=>p.type==="declared_action").map(p=>({source:m,adapter:p}))),s="",i=()=>{if(window.location.href!==s){s=window.location.href;for(let{source:m,adapter:p}of n){let h=p.title_property?{[p.title_property]:document.title.slice(0,512)}:{};un(p.observation,h,{source:m.id,keepalive:!0}).catch(()=>{})}}},o=m=>{if(m.target instanceof Element)for(let{source:p,adapter:h}of r){let g=h.attribute;if(!g||!qf.test(g))continue;let y=m.target.closest(`[${g}]`);if(!y)continue;let S=y.getAttribute(g)?.trim();if(!S||S.length>128)continue;let _={};h.id_property&&(_[h.id_property]=S),h.element_property&&(_[h.element_property]=y.tagName.toLowerCase()),un(h.observation,_,{source:p.id,keepalive:!0}).catch(()=>{})}},a=window.history.pushState,c=window.history.replaceState,l=()=>queueMicrotask(i),d=n.some(({adapter:m})=>m.history===!0),u=n.some(({adapter:m})=>m.pageshow===!0);return d&&(window.history.pushState=function(...p){a.apply(this,p),l()},window.history.replaceState=function(...p){c.apply(this,p),l()},window.addEventListener("popstate",i)),u&&window.addEventListener("pageshow",i),r.length>0&&document.addEventListener("click",o,{capture:!0}),n.length>0&&queueMicrotask(i),es=()=>{window.removeEventListener("popstate",i),window.removeEventListener("pageshow",i),document.removeEventListener("click",o,{capture:!0}),d&&(window.history.pushState=a,window.history.replaceState=c),es=void 0},es}var ar;oe(()=>{ar=void 0});function hi(e){if(ar)return ar.accountPath!==e.accountPath?Promise.reject(new Error("Reset the session before changing accounts")):ar.promise;let t=V(),n=()=>{if(t!==V())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 N().fetchQuery({queryKey:k.memberships(s.principal_id),queryFn:ti,staleTime:12e4,retry:!1});n();let o=i.find(u=>u.path===e.accountPath&&u.isAccount&&!u.isSpace);if(!o)throw new Error("Authenticated account membership is unavailable");let a=i.find(u=>u.isSpace&&u.accountId===o.personalSpaceId&&u.path===o.personalSpacePath);if(!a||!o.personalSpacePath)throw new Error("A provisioned default Space membership is required");let c=tt(o),l=tt(a),d=_e();if(d&&d.id!==c.id)throw new Error("Reset the session before changing accounts");return d||Yt(c,{activate:!1}),await an(o.personalSpacePath,u=>{let m=i.find(p=>p.accountId===u&&(p.isAccount||p.isSpace));return m?tt(m):null},{initialAnchor:l}),n(),{home:c,defaultSpace:l,memberships:i}})().catch(s=>{throw t===V()&&(ar=void 0),s});return ar={accountPath:e.accountPath,promise:r},r}var ln,ns,ts;oe(()=>{ns?.(),ns=void 0,ln=void 0,ts=void 0});function rd(e={}){if(ln)return e.workspace&&e.workspace.accountPath!==ts?Promise.reject(new Error("Initialize workspace through initializeWorkspace, or dispose the existing runtime first")):ln;ts=e.workspace?.accountPath;let t=V();return ln=(async()=>{let n=e.tracking??!0,r=n===!1?()=>{}:mi(typeof n=="object"?n:{});ns=r;try{let s=e.session===!1?null:await pt(),i=e.workspace?await hi(e.workspace):void 0;if(t!==V())throw new Error("Session changed during initialization");let o=!1;return{session:s,workspace:i,dispose(){o||(o=!0,r(),t===V()&&(ln=void 0,ts=void 0,ns=void 0))}}}catch(s){throw r(),t===V()&&(ln=void 0,ts=void 0,ns=void 0),s}})(),ln}function Bf(e){return e instanceof De?{kind:"denied",payload:e.payload}:e instanceof ve?{kind:"gateway",method:e.method,status:e.status,statusText:e.statusText,payload:e.payload,responseBody:e.responseBody}:e instanceof Error?{kind:"other",name:e.name,message:e.message}:{kind:"other",name:"Error",message:String(e)}}function sd(e){let t=(s,i)=>{s.postMessage(i,e.origin)},n=!0,r=s=>{if(s.origin!==e.origin)return;let i=e.frame();if(!i||s.source!==i||!uo(s.data))return;let o=s.data;if(o.kind==="hello"){t(i,{fsaos:en,kind:"welcome",anchor:pe()??Ie(),item:e.item?.()??null});return}if(o.kind!=="call"||typeof o.id!="string"||typeof o.method!="string")return;let{id:a,method:c,params:l}=o;P(c,l&&typeof l=="object"?l:{}).then(d=>{n&&t(i,{fsaos:en,kind:"result",id:a,ok:!0,response:d})},d=>{n&&t(i,{fsaos:en,kind:"result",id:a,ok:!1,error:Bf(d)})})};return window.addEventListener("message",r),()=>{n=!1,window.removeEventListener("message",r)}}async function Bo(e){try{return await P("execution-control-transition",e)}catch(t){if(!(t instanceof ve)||t.status<500)throw t;return await new Promise(n=>setTimeout(n,250)),P("execution-control-transition",e)}}function jo(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 id(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 Bo({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 jo(i?{...s,state:i}:s)}async function od(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 Bo({op:"request",command:"steer",delivery:"immediate",request_message_id:r,selected_queue_entry_id:s,idempotency_key:i,...n.scopePath?{_scope_path:n.scopePath}:{}}),a=o.outcome??o.state??o.status;return jo(a?{...o,state:a}:o)}async function ad(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 Bo({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 jo(i?{...s,outcome:i}:s)}var jf=/^[a-z][a-z0-9_-]{0,63}$/,Hf=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,cr=class extends Error{constructor(n,r,s,i){super(n);te(this,"code");te(this,"status");te(this,"fillId");this.name="FormSubmissionError",this.code=r,this.status=s,this.fillId=i}};async function cd(e,t,n={}){if(!jf.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(!Hf.test(r))throw new TypeError("fillId must be a UUID");let s=Xt(),i=n.pageUrl??(typeof window<"u"?window.location.href:void 0);if(!i)throw new TypeError("pageUrl is required outside a browser");let o=`${Oe.replace(/\/+$/,"")}/d/${encodeURIComponent(s)}/actions/${encodeURIComponent(e)}`,a=td(),c=a?{visitor_id:a.visitor_id,session_id:a.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,...c?{attribution:c}:{}}),signal:n.signal,credentials:"omit"})}catch(u){throw new cr(u instanceof Error?u.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 u=d;throw new cr(u?.message||u?.error||`Form submission failed (${l.status})`,u?.error||"FORM_SUBMISSION_FAILED",l.status,r)}return await nd({fill_id:r,action_id:e,release_id:d.release_id},r,i,a,n.signal),d}async function ud(e){return P("commerce-file-sale",{action:"checkout",product_id:e.productId,expected_product_revision_id:e.productRevisionId,destination_id:e.destinationId,request_key:e.requestKey,_scope_path:e.scopePath,...e.journey?{journey:e.journey}:{}})}async function ld(e,t){return P("commerce-file-sale",{action:"get",license_id:e,_scope_path:t})}function dd(e){let t=new URL(e.hostOrigin);if(t.protocol!=="https:"&&!(t.protocol==="http:"&&t.hostname==="127.0.0.1")||t.username||t.password||t.search||t.hash||t.pathname!=="/")throw new TypeError("hostOrigin must be an HTTPS origin or the local 127.0.0.1 app");let n=new URL(e.pageUrl??window.location.href);if(n.protocol!=="https:"||n.username||n.password||n.hash||n.port)throw new TypeError("The funnel must be a published HTTPS page");let r=new URL("/v2/revven",t);return r.search=new URLSearchParams({surface:"library",offer:e.productId,sale_page:n.href,sale_action:e.capabilityId}).toString(),r.href}function pd(e){if(e.success!==!0||e.state!=="ready"||!e.item_id||!e.file_id||!e.journey?.next_url)return null;let t=new URL(e.journey.next_url),n=new URL(e.journey.return_url);if(t.protocol!=="https:"||n.protocol!=="https:"||t.origin!==n.origin||t.username||t.password||t.hash||t.searchParams.getAll("funnel_id").length!==1||t.searchParams.get("funnel_id")!==e.journey.funnel_id)throw new Error("The purchase destination could not be verified");return t.href}var Ho=J(ue(),1),hd=J(md(),1);function gd(e){return P("read",{path:e})}function yd(e,t){return P("list",{path:e,...t})}function _d(e){return P("create",e)}function bd(e){return P("update",e)}function vd(e){return P("create",e)}function wd(e,t){let r=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).scopePath||"";return P("tools/call",{name:e,instance_path:r,...t||{}})}function Sd(e,t,n){return P("signal",{target_id:e,event_name:t,payload:n||{}})}function xd(e){return((typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"")+e}var Rd={signIn:e=>e.provider?G.auth.signInWithOAuth({provider:e.provider,options:{redirectTo:e.redirectTo||window.location.href}}):G.auth.signInWithPassword({email:e.email,password:e.password}),signUp:e=>G.auth.signUp({email:e.email,password:e.password,options:{data:e.metadata||{}}}),signOut:async()=>{await G.auth.signOut(),jn(),N().clear()},getSession:()=>G.auth.getSession().then(e=>e.data.session),getUser:()=>G.auth.getUser().then(e=>e.data.user),onAuthStateChange:e=>{let{data:{subscription:t}}=G.auth.onAuthStateChange((n,r)=>{e({event:n,session:r,user:r?.user??null})});return()=>t?.unsubscribe()},resetPassword:e=>G.auth.resetPasswordForEmail(e),signInWithMagicLink:(e,t)=>G.auth.signInWithOtp({email:e,options:{emailRedirectTo:t||window.location.href}})};function Cd(){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,hd.createRoot)(e).render((0,Ho.createElement)(Tr,{client:N()},(0,Ho.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 Pd(){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}var $f=e=>P("create-invitation",{...e}),Vf=e=>P("get-invitation",{invitation_id:e}),Wf=e=>P("accept-invite",{invitation_id:e}),Gf=e=>P("reject-invite",{invitation_id:e}),zf=e=>P("cancel-invite",{invitation_id:e}),Jf=(e,t)=>P("resend-invite",{invitation_id:e,request_id:t}),Yf=(e,t)=>P("list-invitations",{account_id:e,...t?{after:t}:{}});function $o(e){return P("invite-member",e)}function Vo(e){return P("accept-invite",e)}function Wo(e){let t={};return e.role&&(t.role=e.role),P("link",{source_id:e.chat_id,target_id:e.member_id,edge_type:"has_member",context:t})}function Go(e){return P("create-agent",e)}function zo(e){return!e.input_request_id&&!e.input_request?Promise.reject(new Error("answerInput needs input_request_id or the input_request object read from the step.")):P("todo-control",{action:"answer_input",...e})}function Ed(){return ie({mutationFn:$o})}function Id(){let e=U();return ie({mutationFn:Vo,onSuccess:()=>{e.invalidateQueries({queryKey:["memberships"]})}})}function Td(){let e=U();return ie({mutationFn:Wo,onSuccess:(t,n)=>{e.invalidateQueries({queryKey:k.edges(n.chat_id)}),e.invalidateQueries({queryKey:k.edges(n.member_id)})}})}function Ad(){let e=U();return ie({mutationFn:Go,onSuccess:()=>{e.invalidateQueries({queryKey:["memberships"]})}})}function Md(){let e=U();return ie({mutationFn:zo,onSuccess:(t,n)=>{e.invalidateQueries({queryKey:k.itemById(n.step_id)})}})}function Xf(e){return e.split("_").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function Zf(e,t){return t&&t.length>0?"select":e==="boolean"?"toggle":e==="integer"||e==="number"?"range":e==="string"?"text":"none"}function em(e,t){return!(e==="object"||e==="array")}function tm(e){return["string","number","integer","boolean"].includes(e)}function nm(e){return e!=="object"&&e!=="array"}function kd(e,t,n,r){let s=e?.properties;if(!s||typeof s!="object")return[];let i=[];for(let[o,a]of Object.entries(s)){let c=a.type||"string",l=a.enum,d=em(c,l),u=tm(c),m=Zf(c,l);i.push({key:o,label:a.title||Xf(o),type:c,description:a.description,enum_values:l,default_value:n[o]??r[o]??a.default,editable:t,filterable:d,sortable:u,filter_widget:m})}return i}function Jo(e){let t=e.default_data||{},n=e.field_defaults||{},r=kd(e.input_schema,!0,t,n),s=kd(e.system_schema,!1,t,n),i=[...r,...s],o=i.filter(l=>nm(l.type)),a=i.filter(l=>l.filterable),c=i.filter(l=>l.sortable);return{fields:i,columns:o,filterable:a,sortable:c,form_fields:r,system_fields:s}}function Od(e){return{field:"updated_at",direction:"desc"}}function Fd(e){let t=Jo(e),n=new Set(e.input_schema?.required||[]);return t.form_fields.filter(r=>n.has(r.key)||r.default_value===void 0)}var Qe=J(ue(),1);var qd=Promise.resolve();function ur(e){if(e?.aborted)throw new Error("Upload cancelled")}async function Nd(e,t){if(ur(t),e.size>16777216||!globalThis.crypto?.subtle)return{};let n=qd.then(async()=>{ur(t);let r=await e.arrayBuffer();ur(t);let s=await globalThis.crypto.subtle.digest("SHA-256",r);return ur(t),{expected_sha256:Array.from(new Uint8Array(s),i=>i.toString(16).padStart(2,"0")).join(""),expected_size_bytes:e.size}});return qd=n.catch(()=>{}),n}function Yo(e){let t=Math.max(32,Math.ceil(e/1e4/1048576))*1048576;if(t>104857600)throw new Error("This file exceeds the storage upload part limit.");return t}var Nt=class extends Error{constructor(n,r){super(r);this.status=n}};function Xo(e){if(e?.aborted)throw new Error("Upload cancelled")}function rm(e,t){return new Promise((n,r)=>{Xo(t);let s=()=>{clearTimeout(i),r(new Error("Upload cancelled"))},i=setTimeout(()=>{t?.removeEventListener("abort",s),n()},e);t?.addEventListener("abort",s,{once:!0})})}function Zo(e,t,n,r,s){return new Promise((i,o)=>{Xo(s);let a=new XMLHttpRequest;a.open("PUT",e);for(let[d,u]of Object.entries(t))a.setRequestHeader(d,u);let c=()=>a.abort(),l=()=>s?.removeEventListener("abort",c);a.upload.onprogress=d=>{d.lengthComputable&&r?.(d.loaded)},a.onload=()=>{l(),a.status>=200&&a.status<300?i(a.responseText||""):o(new Nt(a.status,`Storage upload failed: HTTP ${a.status} \u2014 ${a.responseText?.slice(0,300)||""}`))},a.onerror=()=>{l(),o(new Nt(0,"Storage upload network error"))},a.ontimeout=()=>{l(),o(new Nt(408,"Storage upload timed out"))},a.onabort=()=>{l(),o(new Error("Upload cancelled"))},s?.addEventListener("abort",c,{once:!0}),a.send(n)})}async function Qd(e,t,n,r){let s=await fetch(e,{method:"POST",signal:r,headers:{"Content-Type":"application/json","X-Upload-Token":t},body:JSON.stringify(n)});if(!s.ok)throw new Nt(s.status,`Storage upload failed: HTTP ${s.status}`);return await s.json()}async function Dd(e,t,n,r,s,i,o){let a=Yo(e.size);async function c(m){Xo(o);let p=await s();try{return await m(p)}catch(h){if(!(h instanceof Nt)||h.status!==401)throw h;return await m(await s(!0))}}if(!r.id){let m=await c(p=>Qd(`${t}/multipart/create`,p,{storage_key:n,content_type:e.type||"application/octet-stream"},o));if(m.success!==!0||m.storage_key!==n||typeof m.upload_id!="string"||!m.upload_id)throw new Error("Storage did not start the requested multipart upload.");r.id=m.upload_id}let l=-1,d=m=>{let p=Math.min(99,Math.floor(100*m/e.size));p>l&&(l=p,i?.(p))};for(d(Math.min(e.size,r.parts.length*a));r.parts.length*a<e.size;){let m=a*r.parts.length,p=r.parts.length+1,h=e.slice(m,Math.min(m+a,e.size));for(let g=0;;g++)try{let y=await c(_=>Zo(`${t}/multipart/part`,{"X-Storage-Key":n,"X-Upload-Id":r.id,"X-Part-Number":String(p),"X-Upload-Token":_,"Content-Type":"application/octet-stream"},h,w=>d(m+Math.min(w,h.size)),o)),S=JSON.parse(y);if(S.success!==!0||S.part_number!==p||typeof S.etag!="string"||!S.etag)throw new Error("Storage did not acknowledge the requested upload part.");r.parts.push({partNumber:p,etag:S.etag}),d(m+h.size);break}catch(y){if(!(y instanceof Nt&&(y.status===0||y.status===408||y.status===429||y.status>=500))||g>=2)throw y;await rm(300*2**g,o)}}r.completing=!0;let u=await c(m=>Qd(`${t}/multipart/complete`,m,{storage_key:n,upload_id:r.id,parts:r.parts},o));if(u.success!==!0||u.storage_key!==n||u.size_bytes!==e.size||typeof u.etag!="string"||!u.etag)throw r.completing=!1,new Error("Storage did not confirm the assembled file size and identity.");r.etag=u.etag}function Ud(){if(globalThis.crypto?.randomUUID)return globalThis.crypto.randomUUID();let e=new Uint8Array(16);if(globalThis.crypto?.getRandomValues){globalThis.crypto.getRandomValues(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=Array.from(e,n=>n.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{let n=Math.floor(Math.random()*16);return(t==="x"?n:n&3|8).toString(16)})}var gi=class extends Error{constructor(n){super("File already saved");this.saved=n}};function Kd(e,t,n){let r=t.name||(e instanceof File?e.name:`file-${Date.now()}`),s=e.type||"application/octet-stream",i=t.collisionPolicy||"keep_both",o=i==="keep_both"?Ud():void 0,a=W(),c=V(),l=e.size>104857600?{parts:[]}:void 0,d,u,m=!1,p,h;function g(x){if(ur(x),a!==W()||c!==V())throw new Error("The account or Space changed while preparing the upload. Start it again.")}function y(x,b,E){if(!E||!E.storage_key||u&&E.storage_key!==u.key||(l||d?.expected_sha256)&&(E.size_bytes!==e.size||E.content_type!==s)||d?.expected_sha256&&E.content_sha256!==d.expected_sha256||l?.etag&&E.etag!==l.etag)throw new Error("Stored file did not confirm the expected checksum, size, type or identity");return{itemId:x,itemPath:b,fileRef:E}}async function S(x){g(x);let b=await P("create",{parent_path:t.parentPath,item_type:t.itemType||"file",name:r,...t.cardParentPath?{card_parent_path:t.cardParentPath}:{},type_data:{...t.typeData,file_source:{type:"upload",content_type:s,collision_policy:i,...o?{upload_id:o}:{},...d}}});if(g(x),!b.id||b.error||b.success===!1)throw new Error(b.error||b.message||"Failed to create file item");if(u&&b.id!==u.id)throw new Error("Upload renewal returned a different file.");if(b.storage_completed&&b.file_ref){p=y(b.id,b.path,b.file_ref);return}if(!b.storage_key)throw new Error("Gateway returned no storage_key for this upload.");let E=b.storage_worker_url||"https://fsaos-storage.radns.workers.dev";if(u&&(b.storage_key!==u.key||E!==u.worker))throw new Error("Upload renewal returned a different storage destination.");u={id:b.id,path:b.path,key:b.storage_key,worker:E,token:b.upload_token||"",expiresAt:b.upload_expires_at}}async function _(x,b){if(g(b),p||(l&&Yo(e.size),!u&&(n?.("creating"),d??(d=await Nd(e,b)),await S(b),p)))return p;let E=u,I=async(A=!1)=>{if(g(b),A||o&&u?.expiresAt&&Date.now()/1e3>=u.expiresAt-15){if(!o)throw new Error("The upload grant expired for this exact-path file.");if(await S(b),p)throw new gi(p)}return u.token};async function C(){let A=await I();n?.("confirming",E);let O=await im(E.id,E.key,s,A,d?.expected_sha256);return g(b),y(E.id,E.path,O)}if(l?.completing&&!m)try{return p=await C(),p}catch(A){if(!(A instanceof Error)||!A.message.includes("Object not found in storage"))throw A}if(!m){if(n?.("uploading",E),l)await Dd(e,E.worker,E.key,l,I,x,b);else{let A=await I();await Zo(`${E.worker}/upload`,{"X-Storage-Key":E.key,"Content-Type":s,...A?{"X-Upload-Token":A}:{}},e,O=>x?.(Math.min(99,Math.floor(100*O/Math.max(1,e.size)))),b)}m=!0}return p=await C(),p}function w(x,b){if(h)return h.signal?.aborted&&!b?.aborted?h.promise.catch(()=>{}).then(()=>w(x,b)):h.promise;let E=_(x,b).catch(I=>{if(I instanceof gi)return I.saved;throw I}).then(I=>(x?.(100),I)).finally(()=>{h=void 0});return h={promise:E,signal:b},E}return{run:w}}function ea(e,t){return Kd(e,t)}function Ld(e,t,n,r){return ea(e,t).run(n,r)}async function im(e,t,n,r,s){let i=await dt(),o=await fetch(`${Oe}/storage/upload-complete`,{method:"POST",headers:{"Content-Type":"application/json",...i?{Authorization:`Bearer ${i}`}:{}},body:JSON.stringify({item_id:e,storage_key:t,content_type:n,...r?{upload_token:r}:{},...s?{hash:s}:{}})});if(!o.ok){let c=await o.text().catch(()=>"");throw new Error(`Upload confirmation failed: HTTP ${o.status} \u2014 ${c.slice(0,300)}`)}let a=await o.json();if(!a.success)throw new Error(a.error||a.message||"Upload confirmation rejected");return a.file_ref}function Bd(){let[e,t]=(0,Qe.useState)([]),n=(0,Qe.useRef)(new Map),r=U(),s=(0,Qe.useCallback)((u,m)=>{t(p=>p.map(h=>h.id===u?{...h,...m}:h))},[]),i=(0,Qe.useCallback)(u=>{let m=n.current.get(u);if(!m||m.controller&&!m.controller.signal.aborted)return;let p=new AbortController;m.controller=p,m.attempt.run(h=>{p.signal.aborted||s(u,{progress:h})},p.signal).then(h=>{m.controller!==p||p.signal.aborted||(s(u,{status:"complete",progress:100,error:null,fileRef:h.fileRef,itemPath:h.itemPath,itemId:h.itemId}),r.invalidateQueries({queryKey:k.children(m.options.parentPath)}),n.current.delete(u))}).catch(h=>{m.controller===p&&!p.signal.aborted&&s(u,{status:"error",error:h instanceof Error?h.message:String(h)})}).finally(()=>{m.controller===p&&(m.controller=void 0)})},[r,s]),o=(0,Qe.useCallback)((u,m)=>{let p=Ud(),h=Kd(u,m,(g,y)=>s(p,{status:g,error:null,...y?{itemId:y.id,itemPath:y.path}:{}}));n.current.set(p,{attempt:h,options:m}),t(g=>[...g,{id:p,file:u,status:"creating",progress:0,error:null,itemId:null,itemPath:null,fileRef:null,options:m}]),i(p)},[i,s]),a=(0,Qe.useCallback)((u,m)=>{for(let p of u)o(p,m)},[o]),c=(0,Qe.useCallback)(u=>{let m=n.current.get(u);m&&(m.controller?.abort(),s(u,{status:"error",error:"Cancelled"}))},[s]),l=(0,Qe.useCallback)(u=>{n.current.get(u)?.controller?.abort(),n.current.delete(u),t(m=>m.filter(p=>p.id!==u))},[]),d=(0,Qe.useCallback)(()=>t(u=>u.filter(m=>m.status!=="complete")),[]);return{upload:o,uploadMultiple:a,uploads:e,retryUpload:i,cancelUpload:c,removeUpload:l,clearCompleted:d,isUploading:e.some(u=>u.status==="creating"||u.status==="uploading"||u.status==="confirming")}}var jd=J(ue(),1);async function ta(e,t){return await P("resolve-items",{context_id:e,item_type:t})}function Hd(e,t){return(0,jd.useSyncExternalStore)(be,W,W),H({queryKey:["vfs",z()??"__unscoped__","resolved-items",e??"",t],queryFn:()=>ta(e,t),enabled:!!(e&&t)})}var je=J(ue(),1);function yi(e,t){let n={artifacts:new Map,timeline:[]},r=new Map;function s(o){if(!o.action?.startsWith("artifact_"))return;let c,l=o.name;if(typeof l=="string"&&l.startsWith("{"))try{c=JSON.parse(l)}catch{return}else if(o.artifact_id)c=o;else return;switch(c.type){case"artifact_opened":{let d=Date.now();if(n.artifacts.set(c.artifact_id,{artifact_id:c.artifact_id,surface_type:c.surface_type,tool_id:c.tool_id,tool_name:c.tool_name,target_uri:c.target_uri,status:"streaming",content:"",total_chars:0,delta_count:0,artifact_item_uri:null,evidence_uri:null,meta:c.meta,started_at:d,completed_at:null}),r.has(c.tool_id)){let u=r.get(c.tool_id);n.timeline[u].artifact_ids.push(c.artifact_id)}else{let u=n.timeline.length;n.timeline.push({tool_id:c.tool_id,tool_name:c.tool_name,status:"started",target_uri:c.target_uri,started_at:d,completed_at:null,artifact_ids:[c.artifact_id]}),r.set(c.tool_id,u)}break}case"artifact_delta":{let d=n.artifacts.get(c.artifact_id);d&&(d.content+=c.content_delta,d.total_chars+=c.content_delta.length,d.delta_count+=1,c.target_uri&&!d.target_uri&&(d.target_uri=c.target_uri));break}case"artifact_done":{let d=n.artifacts.get(c.artifact_id);d&&(d.status=c.status,d.total_chars=c.total_chars,d.artifact_item_uri=c.artifact_item_uri,d.evidence_uri=c.evidence_uri,c.target_uri&&(d.target_uri=c.target_uri),(c.status==="completed"||c.status==="failed")&&(d.completed_at=Date.now()));let u=r.get(c.tool_id);if(u!==void 0){let m=n.timeline[u];c.status==="executing"?m.status="executing":c.status==="completed"?(m.status="completed",m.completed_at=Date.now()):c.status==="failed"&&(m.status="failed",m.completed_at=Date.now()),c.target_uri&&!m.target_uri&&(m.target_uri=c.target_uri)}break}}t(n)}return Ks(e,s)}function $d(e,t=!0){let[n,r]=(0,je.useState)(new Map),[s,i]=(0,je.useState)([]),o=(0,je.useRef)({artifacts:new Map,timeline:[]});(0,je.useEffect)(()=>!e||!t?void 0:yi(e,u=>{o.current=u,r(new Map(u.artifacts)),i([...u.timeline])}),[e,t]);let a=(0,je.useCallback)(()=>{r(new Map),i([]),o.current={artifacts:new Map,timeline:[]}},[]),c=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:c,activeActivities:l,reset:a}}function Vd(e,t=!0){let[n,r]=(0,je.useState)([]);(0,je.useEffect)(()=>!e||!t?void 0:yi(e,o=>{r([...o.timeline])}),[e,t]);let s=n.length>0?n[n.length-1]:null;return{timeline:n,latestActivity:s}}var _i=J(ue(),1);function om(e,t,n,r){return["vfs","timeline-history",e,t??"__all__",n??500,r??0]}async function na(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 a=(await P("open",{path:n,mode:"extract",strategy:"rows",arguments:i}))?.content;return a?(a.rows??a.items??a.data??[]).map(am).sort((l,d)=>l.seq-d.seq):[]}catch(o){if(o?.status===404||o?.message?.includes("not found"))return[];throw o}}function Wd(e,t){let{turnId:n,limit:r=500,offset:s=0,enabled:i=!0,debounceMs:o=300}=t??{},a=e?`${e}/datasets/agent-events`:null,c=U(),l=(0,_i.useRef)(null),d=a?om(a,n,r,s):["vfs","timeline-history","__disabled__"],u=H({queryKey:d,queryFn:()=>na(e,{turnId:n,limit:r,offset:s}),enabled:!!e&&i});return(0,_i.useEffect)(()=>{if(!a||!i)return;let m=X("vfs_change",()=>{l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{c.invalidateQueries({queryKey:d})},o)},p=>{let h=p?.path;return h?h===a&&p.item_type==="dataset":!1});return()=>{m(),l.current&&clearTimeout(l.current)}},[a,i,o,c,JSON.stringify(d)]),{events:u.data??[],isLoading:u.isLoading,error:u.error,isFetching:u.isFetching,refetch:()=>{u.refetch()}}}function am(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 Qt=J(ue(),1);function Gd(e){let t=(0,Qt.useSyncExternalStore)(be,W,W),n=z(),r=e?.path??n,s=pe(),i=e?.id??s?.id,o=(0,Qt.useMemo)(()=>({}),[t,n,r,i]),a=(0,Qt.useRef)(o);a.current=o;let c=ir(r?{key:"pinned",scope_id:i,_scope_path:r}:null),l=U(),d=c.resolvedChildren,u=!!(!c.error&&c.arrangement?.item_id&&c.resolutionLevel==="member"&&c.arrangement.write_target_id===c.arrangement.item_id),m=ie({mutationFn:async h=>{let g,y={_scope_path:h.scopePath};if(h.operation==="pin"?g=await P("create",{...y,parent_id:h.arrangementId,name:`pin-${h.target.id}`,item_type:"symlink",type_data:{target_item_id:h.target.id,target_type:h.target.item_type}}):h.operation==="unpin"?g=await P("delete",{...y,id:h.entry.id}):g=await P("update",{...y,id:h.arrangementId,type_data:{order:h.ids}}),g?.success===!1)throw new Error(g.error||"Pins could not be saved");return g},onSettled:(h,g,y)=>ft(l,y.queryKey)}),p=(0,Qt.useCallback)(h=>!u||!r||a.current!==o||t!==W()||z()!==n?Promise.reject(new Error("Personal pins are not available in this context")):h.operation==="unpin"&&!d.some(g=>g.id===h.entry.id)?Promise.reject(new Error("Pin is outside this arrangement")):h.operation==="reorder"&&(new Set(h.ids).size!==d.length||h.ids.length!==d.length||d.some(g=>!h.ids.includes(g.id)))?Promise.reject(new Error("Order must include each pin exactly once")):h.operation==="pin"&&d.some(g=>g.symlink_type_data?.target_item_id===h.target.id)?Promise.resolve(null):m.mutateAsync({...h,scopePath:r,arrangementId:c.arrangement.item_id,arrangementPath:c.arrangement.item_path,queryKey:c.arrangementQueryKey}),[u,t,n,r,o,d,c.arrangement,c.arrangementQueryKey,m.mutateAsync]);return{entries:d,isLoading:c.isLoading,error:c.error,refetch:c.refetch,ready:u,isSaving:m.isPending,saveError:m.error,isPinned:h=>d.some(g=>g.symlink_type_data?.target_item_id===h),pin:h=>p({operation:"pin",target:h}),unpin:h=>{let g=d.find(y=>y.symlink_type_data?.target_item_id===h||y.id===h);return g?p({operation:"unpin",entry:g}):Promise.resolve(null)},reorder:h=>p({operation:"reorder",ids:h})}}var bi=J(ue(),1);var rs=(e,t,n)=>["vfs",e,"personal-sections",t,n];function ra(e,t){return e&&e.item_id===t.item_id&&e.version>t.version?e:t}async function sa(e,t,n,r){let s=await P("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 zd(e,t){let n=await sa(e.scopePath,e.contextId,e.collection,{operation:"assign",section_id:e.sectionId,target_id:t}),r=N();return r.setQueryData(rs(e.scopePath,e.contextId,e.collection),s=>ra(s,n)),Jd(r,e.scopePath),n}function Jd(e,t){for(let n of e.getQueryCache().getAll())n.queryKey[0]==="vfs"&&n.queryKey[1]===t&&n.queryKey[2]==="personal-sections"&&ft(e,n.queryKey)}function Yd(e,t){let n=(0,bi.useSyncExternalStore)(be,W,W),r=z(),s=U(),i=rs(r,e,t),o=H({queryKey:i,enabled:!!r&&!!e,queryFn:()=>sa(r,e,t,{operation:"list"}),staleTime:1/0,retry:!1,meta:{arrangementRealtime:!0,personalSections:!0},structuralSharing:(u,m)=>ra(u,m)}),a=(0,bi.useRef)(!1),c=ie({mutationFn:async u=>{let m=await sa(u.scope,u.context,u.collection,{...u.change,...u.change.operation.startsWith("reorder")?{expected_version:u.version}:{}});return s.setQueryData(rs(u.scope,u.context,u.collection),p=>ra(p,m)),m},onSettled:(u,m,p)=>Jd(s,p.scope)});async function l(u){if(!r||!e||n!==W()||z()!==r||!o.data||o.error)throw new Error("Select the Space again before changing sections");if(a.current)throw new Error("A section change is still being saved");a.current=!0;try{return await c.mutateAsync({change:u,scope:r,context:e,collection:t,version:o.data.version})}finally{a.current=!1}}function d(u){if(!r||!e||!o.data?.sections.some(m=>m.id===u))throw new Error("Section is unavailable");return{scopePath:r,contextId:e,collection:t,sectionId:u}}return{sections:o.data?.sections??[],ready:!!o.data&&!o.error,isLoading:o.isLoading,error:o.error,refetch:o.refetch,isSaving:c.isPending,change:l,destination:d,contextKey:`${n}:${r}:${e}:${t}`}}ll(ia);return cp(ia);})();
|
|
8
11
|
|
|
9
12
|
/* ── Auto-setup: require shim + mount + backward compat globals ── */
|
|
10
13
|
(function() {
|