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