@ai4b-team/fsaos-gateway-sdk 3.20.0 → 3.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
- /* @fsaos/gateway v2.0.0 — Unified FSAOS Edge Runtime — 2026-08-27T17:15:03.713Z */
2
- "use strict";var __FSAOS_GATEWAY__=(()=>{var Na=Object.create;var Xt=Object.defineProperty;var Qa=Object.getOwnPropertyDescriptor;var Ka=Object.getOwnPropertyNames;var La=Object.getPrototypeOf,ja=Object.prototype.hasOwnProperty;var Os=e=>{throw TypeError(e)};var Va=(e,t,n)=>t in e?Xt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Zt=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Ha=(e,t)=>{for(var n in t)Xt(e,n,{get:t[n],enumerable:!0})},Ms=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Ka(t))!ja.call(e,s)&&s!==n&&Xt(e,s,{get:()=>t[s],enumerable:!(r=Qa(t,s))||r.enumerable});return e};var j=(e,t,n)=>(n=e!=null?Na(La(e)):{},Ms(t||!e||!e.__esModule?Xt(n,"default",{value:e,enumerable:!0}):n,e)),Wa=e=>Ms(Xt({},"__esModule",{value:!0}),e);var se=(e,t,n)=>Va(e,typeof t!="symbol"?t+"":t,n),Ar=(e,t,n)=>t.has(e)||Os("Cannot "+n);var c=(e,t,n)=>(Ar(e,t,"read from private field"),n?n.call(e):t.get(e)),b=(e,t,n)=>t.has(e)?Os("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),v=(e,t,n,r)=>(Ar(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n),C=(e,t,n)=>(Ar(e,t,"access private method"),n);var en=(e,t,n,r)=>({set _(s){v(e,t,s,n)},get _(){return c(e,t,r)}});var Fs=Zt((Zc,ks)=>{ks.exports={createClient:window.supabase.createClient}});var oe=Zt((hd,Mi)=>{Mi.exports=React});var tr=Zt((gd,ki)=>{ki.exports={jsx:React.createElement,jsxs:React.createElement,Fragment:React.Fragment}});var po=Zt((df,fo)=>{fo.exports=ReactDOM});var xo=Zt((_f,Po)=>{Po.exports=ReactDOM});var As={};Ha(As,{ComponentRenderer:()=>ua,EnforcementDeniedError:()=>mt,FormSubmissionError:()=>Rt,InteractionTrackingError:()=>bt,KernelProvider:()=>la,QueryClientProvider:()=>wn,auth:()=>Ro,awaitAnchorReady:()=>sn,awaitScopeReady:()=>Ws,callTool:()=>bo,clearCachedToken:()=>qr,clearSession:()=>jr,createItem:()=>yo,disconnectSSE:()=>vs,disposeVfsRealtimeWs:()=>Rr,electHomeAnchor:()=>on,emitEvent:()=>ao,fetchChannelMessages:()=>Ji,fetchChannelMessagesPage:()=>xn,fetchChannelMessagesWithCards:()=>gr,fetchEdgesForItem:()=>lr,fetchItemHistory:()=>pr,fetchItemVersions:()=>Cn,fetchItems:()=>Pn,fetchMemberFocus:()=>mr,fetchOpenEnvelope:()=>hr,fetchRecentActivity:()=>fr,fetchResolvedItems:()=>Ts,fetchTimelineHistory:()=>Is,fetchTypeDefinitions:()=>ur,fetchVfsChildren:()=>ar,fetchVfsChildrenPage:()=>cr,fetchVfsItem:()=>or,fetchVfsItemById:()=>ir,fetchVfsTree:()=>dr,gatewayCall:()=>R,getAccessToken:()=>xe,getAnchor:()=>rn,getAnchorRef:()=>Ze,getAnchorVersion:()=>Nr,getAssetUrl:()=>So,getDefaultSort:()=>xa,getHomeAnchor:()=>Qe,getMountVersion:()=>cn,getMounts:()=>yt,getQueryClient:()=>P,getRequiredFormFields:()=>Ta,getScope:()=>fe,getScopeVersion:()=>be,getSessionEntry:()=>Vn,initSession:()=>_t,initVfsRealtimeWs:()=>Mn,initializeFsaos:()=>Ys,interpretSchema:()=>xs,invalidateAllVfs:()=>Zi,invalidateChannelMessages:()=>to,invalidateChildren:()=>sr,invalidateItem:()=>ys,invalidateOpenEnvelope:()=>no,invalidatePathAndParent:()=>Yi,invalidateSubtree:()=>Xi,invalidateTypes:()=>eo,isAnchorReady:()=>Kr,isScopeReady:()=>Hn,listChildren:()=>go,mount:()=>Eo,mountRealtimeScope:()=>kn,normalizeItem:()=>he,ping:()=>co,pushChanges:()=>vo,queryClient:()=>$i,readItem:()=>ho,registerCleanup:()=>Te,resetAllSdkState:()=>vt,resolvePrincipalId:()=>oa,setAnchor:()=>Ne,setCachedToken:()=>Us,setQueryClient:()=>Wi,setScope:()=>Hs,setupRequireShim:()=>Co,signal:()=>wo,startTracking:()=>Wn,submitForm:()=>Xs,subscribeAnchor:()=>Qr,subscribeArtifactStream:()=>xr,subscribeMounts:()=>jn,subscribeScope:()=>tt,subscribeToEvents:()=>J,subscribeToPath:()=>vr,subscribeToScope:()=>br,trackAction:()=>$r,trackEvent:()=>wt,trackPageView:()=>Wr,unmountRealtimeScope:()=>lo,updateItem:()=>_o,uploadFile:()=>Ia,useAccounts:()=>Yo,useAgentTimeline:()=>qa,useAllChannels:()=>Pr,useArrangement:()=>Ca,useArtifactStream:()=>Fa,useAsset:()=>Zo,useAuth:()=>Cr,useChannelMessages:()=>da,useChannels:()=>pa,useChildren:()=>qo,useComponent:()=>Cs,useCreate:()=>ga,useDelete:()=>va,useDmChannels:()=>ma,useEdges:()=>jo,useEventStream:()=>Ra,useFileUpload:()=>Oa,useInfiniteChannelMessages:()=>fa,useInfiniteChildren:()=>Lo,useInfiniteItems:()=>Ko,useItem:()=>ko,useItemById:()=>Fo,useItemHistory:()=>Go,useItemVersions:()=>Bo,useItems:()=>Qo,useLink:()=>wa,useList:()=>Es,useMemberFocus:()=>$o,useMounts:()=>Xo,useMove:()=>ba,useMutation:()=>Sa,useNotifications:()=>Ps,useOpen:()=>Ho,usePermission:()=>ra,usePermissions:()=>sa,usePrincipal:()=>aa,useRealtimeQuery:()=>Ea,useRecentActivity:()=>zo,useResolve:()=>No,useResolvedItems:()=>ka,useScope:()=>Jo,useScopeReady:()=>Mo,useSearch:()=>Uo,useTheme:()=>na,useTimelineHistory:()=>Da,useTool:()=>ca,useTree:()=>Do,useType:()=>Vo,useTypeHelpers:()=>Wo,useTypes:()=>Er,useUnreadCounts:()=>ha,useUpdate:()=>ya,useUpdatePrincipal:()=>_a,vfsKeys:()=>w});var mt=class e extends Error{constructor(n){let r=n.message||e.fallbackMessage(n);super(r);se(this,"name","EnforcementDeniedError");se(this,"deniedBy");se(this,"ruleKey");se(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 qs=j(Fs(),1),Or=typeof window<"u"&&window.__FSAOS_CONFIG__||{},$a=Or.supabaseUrl||"https://vahbmsslxuustnlvsrkg.supabase.co",Ba=Or.supabaseAnonKey||"sb_publishable_ZjosozAjfpZ4InMNElTr6Q_hHB-f5nc",ce=Or.gatewayUrl||"https://fsaos-mcp-gw-rust.fly.dev",k=(0,qs.createClient)($a,Ba,{auth:{persistSession:!0,autoRefreshToken:!0,detectSessionInUrl:!1}});var nn=null,Un=0,Ds,Fr,Nn=!1;Ds=new Promise(e=>{Fr=e});k.auth.onAuthStateChange((e,t)=>{t?.access_token?(nn=t.access_token,Un=t.expires_at??Math.floor(Date.now()/1e3)+3600):(nn=null,Un=0),Nn||(Nn=!0,Fr())});setTimeout(()=>{Nn||(Nn=!0,Fr())},5e3);function Us(e,t){nn=e,Un=t??Math.floor(Date.now()/1e3)+3600}function qr(){nn=null,Un=0}async function xe(){let e=typeof window<"u"&&window.__FSAOS_CONFIG__||{};if(e.embedToken){if(typeof e.embedToken=="function")try{return await e.embedToken()??null}catch{return null}return e.embedToken}return await Ds,nn}var Qn=null,Ln=null,Ns=0,Mr=new Set,Dr,Ur,Kn=!1;Dr=new Promise(e=>{Ur=e});function Qs(){Ns++,Mr.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Anchor listener error:",t)}})}function Ne(e){let t=typeof e=="string"?e:e.path,n=Qn!==t;Qn=t,Ln=typeof e=="string"?null:e,typeof e!="string"&&!ue.some(r=>r.id===e.id)&&(ue=[...ue,e],an()),Kn||(Kn=!0,Ur()),n&&Qs()}function rn(){return Qn}function Ze(){return Ln}function Nr(){return Ns}function Qr(e){return Mr.add(e),()=>{Mr.delete(e)}}function sn(){return Dr}function Kr(){return Kn}var gt=null;function on(e){if(gt){console.warn("[SDK] electHomeAnchor called twice; ignoring (logout to re-elect).");return}gt=e,Ne(e)}function Qe(){return gt}var ue=[],kr=new Set,Ks=0;function an(){Ks++,kr.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Mount listener error:",t)}})}function yt(){return ue}function cn(){return Ks}function jn(e){return kr.add(e),()=>{kr.delete(e)}}function Lr(e){ue=e,an()}function Ls(e){ue.some(t=>t.id===e.id)||(ue=[...ue,e],an())}function js(e){ue.find(n=>n.id===e)&&(ue=ue.filter(n=>n.id!==e),an(),Ln?.id===e&&gt&&Ne(gt))}var ht=null,tn=null;async function _t(){return ht||tn||(tn=(async()=>{let e=et(),t=await xe(),n={};t&&(n.Authorization=`Bearer ${t}`);let r=await fetch(`${ce}/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 ht={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},ht})(),tn)}function Vn(){return ht}function jr(){ht=null,tn=null,Qn=null,Ln=null,gt=null,ue=[]}var Vs=[];function Te(e){Vs.push(e)}function vt(){jr(),qr(),Kn=!1,Dr=new Promise(e=>{Ur=e}),Qs(),an();for(let e of Vs)try{e()}catch(t){console.warn("[SDK] Cleanup function failed:",t)}}function et(){if(typeof window<"u"){let e=window.__FSAOS_CONFIG__;return e?.hostname?e.hostname:window.location.hostname}return"localhost"}var Hs=Ne,fe=rn,be=Nr,tt=Qr,Ws=sn,Hn=Kr;var Vr=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,Ga=/^[a-z_]{1,32}(?:\.[a-z_]{1,32})+$/,$s="fsaos.visitor_id",Bs="fsaos.session",za=30*60*1e3,Gs,zs,bt=class extends Error{constructor(n,r,s,i){super(n);se(this,"code");se(this,"status");se(this,"eventId");this.name="InteractionTrackingError",this.code=r,this.status=s,this.eventId=i}};function Hr(){if(!(typeof window>"u"))try{return window.localStorage}catch{return}}function Ja(e){try{let t=Hr()?.getItem(e)??void 0;return t&&Vr.test(t)?t:void 0}catch{return}}function Js(e,t){try{Hr()?.setItem(e,t)}catch{}}function Ya(){let e=Ja($s)??Gs;if(e)return e;let t=crypto.randomUUID();return Gs=t,Js($s,t),t}function Xa(e=Date.now()){let t;try{let i=Hr()?.getItem(Bs);t=i?JSON.parse(i):void 0}catch{t=void 0}let n=t&&typeof t.id=="string"&&Vr.test(t.id)&&typeof t.lastSeenAt=="number"?{id:t.id,lastSeenAt:t.lastSeenAt}:zs,s=n&&e-n.lastSeenAt>=0&&e-n.lastSeenAt<za?{id:n.id,lastSeenAt:e}:{id:crypto.randomUUID(),lastSeenAt:e};return zs=s,Js(Bs,JSON.stringify(s)),s.id}function Za(e){let t;try{t=new URL(e)}catch{return}let r=Object.fromEntries(["utm_source","utm_medium","utm_campaign","utm_term","utm_content","gclid","gbraid","wbraid","fbclid","msclkid","ttclid"].flatMap(s=>{let i=t.searchParams.get(s);return i?[[s,i.slice(0,512)]]:[]}));return Object.keys(r).length>0?r:void 0}async function wt(e,t={},n={}){if(!Ga.test(e))throw new TypeError("eventType must be a namespaced lowercase identifier");if(!t||typeof t!="object"||Array.isArray(t))throw new TypeError("properties must be an object");let r=n.eventId??crypto.randomUUID(),s=n.visitorId??Ya(),i=n.sessionId??Xa();if(![r,s,i].every(h=>Vr.test(h)))throw new TypeError("event, visitor, and session IDs must be UUIDs");let a=n.pageUrl??(typeof window<"u"?window.location.href:void 0);if(!a)throw new TypeError("pageUrl is required outside a browser");let o=n.occurredAt??new Date().toISOString();if(Number.isNaN(Date.parse(o)))throw new TypeError("occurredAt is invalid");let u=n.referrer??(typeof document<"u"&&document.referrer||void 0),l=Za(a),d=l?{...t,attribution:l}:t,p=et(),f=`${ce.replace(/\/+$/,"")}/d/${encodeURIComponent(p)}/interactions`,m;try{m=await fetch(f,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({page_url:a,visitor_id:s,session_id:i,referrer:u,events:[{id:r,event_type:e,occurred_at:o,properties:d}]}),signal:n.signal,credentials:"omit",keepalive:n.keepalive??!1})}catch(h){throw new bt(h instanceof Error?h.message:"Interaction tracking network error","INTERACTION_NETWORK_ERROR",0,r)}let _=null;try{_=await m.json()}catch{}if(!m.ok||_?.success!==!0){let h=_;throw new bt(h?.message||h?.error||`Interaction tracking failed (${m.status})`,h?.error||"INTERACTION_TRACKING_FAILED",m.status,r)}return _}function Wr(e={},t={}){let n=typeof document>"u"?{}:{title:document.title.slice(0,512)};return wt("page.viewed",{...n,...e},t)}function $r(e,t={},n={}){if(!e||e.length>128)throw new TypeError("actionId is invalid");return wt("action.clicked",{...t,action_id:e},n)}var un;function Wn(e={}){if(typeof window>"u"||typeof document>"u")return()=>{};if(un)return un;if(window.__FSAOS_CONFIG__?.tracking?.enabled===!1)return()=>{};let n=e.pageViews??!0,r=e.declaredActions??!0,s="",i=()=>{!n||window.location.href===s||(s=window.location.href,Wr({},{keepalive:!0}).catch(()=>{}))},a=f=>{if(!r||!(f.target instanceof Element))return;let m=f.target.closest("[data-fsaos-action]");if(!m)return;let _=m.dataset.fsaosAction?.trim();_&&$r(_,{element:m.tagName.toLowerCase()},{keepalive:!0}).catch(()=>{})},o=window.history.pushState,u=window.history.replaceState,l=()=>queueMicrotask(i);window.history.pushState=function(...m){o.apply(this,m),l()},window.history.replaceState=function(...m){u.apply(this,m),l()},window.addEventListener("popstate",i),window.addEventListener("pageshow",i),document.addEventListener("click",a,{capture:!0}),queueMicrotask(i),un=()=>{window.removeEventListener("popstate",i),window.removeEventListener("pageshow",i),document.removeEventListener("click",a,{capture:!0}),window.history.pushState===d&&(window.history.pushState=o),window.history.replaceState===p&&(window.history.replaceState=u),un=void 0};let d=window.history.pushState,p=window.history.replaceState;return un}var St;function Ys(e={}){return St||(St=(async()=>{let t=e.tracking??!0,n=t===!1?()=>{}:Wn(typeof t=="object"?t:{});try{let r=e.session===!1?null:await _t(),s=!1;return{session:r,dispose(){s||(s=!0,n(),St=void 0)}}}catch(r){throw n(),St=void 0,r}})(),St)}var ec=new Set(["list-memberships","init"]);async function R(e,t={}){let n=et(),r=`${ce}/d/${n}`,s={"Content-Type":"application/json"},i=await xe();i&&(s.Authorization=`Bearer ${i}`),!ec.has(e)&&!t._scope_path&&await sn();let a={...t},o=Vn();!a.domain_scope_id&&o?.scope_id&&(a.domain_scope_id=o.scope_id);let u=rn();!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 d=await l.json();if(d.success===!1){let p=d.error||"",f=d.denied_by||d.error_type||"";throw f==="rule"||f==="access"||f==="entitlement"||p==="RULE_DENIED"||p==="ACCESS_DENIED"||p==="PERMISSION_DENIED"||p==="ENTITLEMENT_REQUIRED"?new mt(d):new Error(d.message||d.error||`Gateway call ${e} failed`)}return d}var tc=/^[a-z][a-z0-9_-]{0,63}$/,nc=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,Rt=class extends Error{constructor(n,r,s,i){super(n);se(this,"code");se(this,"status");se(this,"fillId");this.name="FormSubmissionError",this.code=r,this.status=s,this.fillId=i}};async function Xs(e,t,n={}){if(!tc.test(e))throw new TypeError("capabilityId is invalid");if(!t||typeof t!="object"||Array.isArray(t))throw new TypeError("fields must be an object");let r=n.fillId??crypto.randomUUID();if(!nc.test(r))throw new TypeError("fillId must be a UUID");let s=et(),i=n.pageUrl??(typeof window<"u"?window.location.href:void 0);if(!i)throw new TypeError("pageUrl is required outside a browser");let a=`${ce.replace(/\/+$/,"")}/d/${encodeURIComponent(s)}/actions/${encodeURIComponent(e)}`,o;try{o=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({fill_id:r,page_url:i,fields:t}),signal:n.signal,credentials:"omit"})}catch(l){throw new Rt(l instanceof Error?l.message:"Form submission network error","FORM_NETWORK_ERROR",0,r)}let u=null;try{u=await o.json()}catch{}if(!o.ok||u?.success!==!0){let l=u;throw new Rt(l?.message||l?.error||`Form submission failed (${o.status})`,l?.error||"FORM_SUBMISSION_FAILED",o.status,r)}try{await wt("form.submitted",{fill_id:r,action_id:e,release_id:u.release_id},{eventId:r,pageUrl:i,signal:n.signal,keepalive:!0})}catch{}return u}var le=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 nt,Ke,Et,Zs,rc=(Zs=class extends le{constructor(){super();b(this,nt);b(this,Ke);b(this,Et);v(this,Et,t=>{if(typeof window<"u"&&window.addEventListener){let n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){c(this,Ke)||this.setEventListener(c(this,Et))}onUnsubscribe(){var t;this.hasListeners()||((t=c(this,Ke))==null||t.call(this),v(this,Ke,void 0))}setEventListener(t){var n;v(this,Et,t),(n=c(this,Ke))==null||n.call(this),v(this,Ke,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){c(this,nt)!==t&&(v(this,nt,t),this.onFocus())}onFocus(){let t=this.isFocused();this.listeners.forEach(n=>{n(t)})}isFocused(){return typeof c(this,nt)=="boolean"?c(this,nt):globalThis.document?.visibilityState!=="hidden"}},nt=new WeakMap,Ke=new WeakMap,Et=new WeakMap,Zs),Ct=new rc;var sc={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},Le,Br,ei,ic=(ei=class{constructor(){b(this,Le,sc);b(this,Br,!1)}setTimeoutProvider(e){v(this,Le,e)}setTimeout(e,t){return c(this,Le).setTimeout(e,t)}clearTimeout(e){c(this,Le).clearTimeout(e)}setInterval(e,t){return c(this,Le).setInterval(e,t)}clearInterval(e){c(this,Le).clearInterval(e)}},Le=new WeakMap,Br=new WeakMap,ei),we=new ic;function ti(e){setTimeout(e,0)}var zr=typeof window>"u"||"Deno"in globalThis;function q(){}function si(e,t){return typeof e=="function"?e(t):e}function ln(e){return typeof e=="number"&&e>=0&&e!==1/0}function $n(e,t){return Math.max(e+(t||0)-Date.now(),0)}function pe(e,t){return typeof e=="function"?e(t):e}function X(e,t){return typeof e=="function"?e(t):e}function Bn(e,t){let{type:n="all",exact:r,fetchStatus:s,predicate:i,queryKey:a,stale:o}=e;if(a){if(r){if(t.queryHash!==dn(a,t.options))return!1}else if(!rt(t.queryKey,a))return!1}if(n!=="all"){let u=t.isActive();if(n==="active"&&!u||n==="inactive"&&u)return!1}return!(typeof o=="boolean"&&t.isStale()!==o||s&&s!==t.state.fetchStatus||i&&!i(t))}function Gn(e,t){let{exact:n,status:r,predicate:s,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(Se(t.options.mutationKey)!==Se(i))return!1}else if(!rt(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||s&&!s(t))}function dn(e,t){return(t?.queryKeyHashFn||Se)(e)}function Se(e){return JSON.stringify(e,(t,n)=>Gr(n)?Object.keys(n).sort().reduce((r,s)=>(r[s]=n[s],r),{}):n)}function rt(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>rt(e[n],t[n])):!1}var oc=Object.prototype.hasOwnProperty;function Jr(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=ni(e)&&ni(t);if(!r&&!(Gr(e)&&Gr(t)))return t;let i=(r?e:Object.keys(e)).length,a=r?t:Object.keys(t),o=a.length,u=r?new Array(o):{},l=0;for(let d=0;d<o;d++){let p=r?d:a[d],f=e[p],m=t[p];if(f===m){u[p]=f,(r?d<i:oc.call(e,p))&&l++;continue}if(f===null||m===null||typeof f!="object"||typeof m!="object"){u[p]=m;continue}let _=Jr(f,m,n+1);u[p]=_,_===f&&l++}return i===o&&l===i?e:u}function Pt(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 ni(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function Gr(e){if(!ri(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!ri(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function ri(e){return Object.prototype.toString.call(e)==="[object Object]"}function ii(e){return new Promise(t=>{we.setTimeout(t,e)})}function fn(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?Jr(e,t):t}function oi(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function ai(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var xt=Symbol();function zn(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===xt?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function Tt(e,t){return typeof e=="function"?e(...t):!!e}function ci(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 Re=(()=>{let e=()=>zr;return{isServer(){return e()},setIsServer(t){e=t}}})();function pn(){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 ui=ti;function ac(){let e=[],t=0,n=o=>{o()},r=o=>{o()},s=ui,i=o=>{t?e.push(o):s(()=>{n(o)})},a=()=>{let o=e;e=[],o.length&&s(()=>{r(()=>{o.forEach(u=>{n(u)})})})};return{batch:o=>{let u;t++;try{u=o()}finally{t--,t||a()}return u},batchCalls:o=>(...u)=>{i(()=>{o(...u)})},schedule:i,setNotifyFunction:o=>{n=o},setBatchNotifyFunction:o=>{r=o},setScheduler:o=>{s=o}}}var M=ac();var It,je,At,li,cc=(li=class extends le{constructor(){super();b(this,It,!0);b(this,je);b(this,At);v(this,At,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(){c(this,je)||this.setEventListener(c(this,At))}onUnsubscribe(){var t;this.hasListeners()||((t=c(this,je))==null||t.call(this),v(this,je,void 0))}setEventListener(t){var n;v(this,At,t),(n=c(this,je))==null||n.call(this),v(this,je,t(this.setOnline.bind(this)))}setOnline(t){c(this,It)!==t&&(v(this,It,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return c(this,It)}},It=new WeakMap,je=new WeakMap,At=new WeakMap,li),Ot=new cc;function uc(e){return Math.min(1e3*2**e,3e4)}function Yr(e){return(e??"online")==="online"?Ot.isOnline():!0}var Jn=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function Yn(e){let t=!1,n=0,r,s=pn(),i=()=>s.status!=="pending",a=h=>{if(!i()){let g=new Jn(h);f(g),e.onCancel?.(g)}},o=()=>{t=!0},u=()=>{t=!1},l=()=>Ct.isFocused()&&(e.networkMode==="always"||Ot.isOnline())&&e.canRun(),d=()=>Yr(e.networkMode)&&e.canRun(),p=h=>{i()||(r?.(),s.resolve(h))},f=h=>{i()||(r?.(),s.reject(h))},m=()=>new Promise(h=>{r=g=>{(i()||l())&&h(g)},e.onPause?.()}).then(()=>{r=void 0,i()||e.onContinue?.()}),_=()=>{if(i())return;let h,g=n===0?e.initialPromise:void 0;try{h=g??e.fn()}catch(S){h=Promise.reject(S)}Promise.resolve(h).then(p).catch(S=>{if(i())return;let E=e.retry??(Re.isServer()?0:3),x=e.retryDelay??uc,U=typeof x=="function"?x(n,S):x,L=E===!0||typeof E=="number"&&n<E||typeof E=="function"&&E(n,S);if(t||!L){f(S);return}n++,e.onFail?.(n,S),ii(U).then(()=>l()?void 0:m()).then(()=>{t?f(S):_()})})};return{promise:s,status:()=>s.status,cancel:a,continue:()=>(r?.(),s),cancelRetry:o,continueRetry:u,canStart:d,start:()=>(d()?_():m().then(_),s)}}var st,di,Xn=(di=class{constructor(){b(this,st)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),ln(this.gcTime)&&v(this,st,we.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Re.isServer()?1/0:5*60*1e3))}clearGcTimeout(){c(this,st)!==void 0&&(we.clearTimeout(c(this,st)),v(this,st,void 0))}},st=new WeakMap,di);var it,Mt,de,ot,V,mn,at,ie,gi,Ie,mi,hi=(mi=class extends Xn{constructor(t){super();b(this,ie);b(this,it);b(this,Mt);b(this,de);b(this,ot);b(this,V);b(this,mn);b(this,at);v(this,at,!1),v(this,mn,t.defaultOptions),this.setOptions(t.options),this.observers=[],v(this,ot,t.client),v(this,de,c(this,ot).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,v(this,it,pi(this.options)),this.state=t.state??c(this,it),this.scheduleGc()}get meta(){return this.options.meta}get promise(){return c(this,V)?.promise}setOptions(t){if(this.options={...c(this,mn),...t},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let n=pi(this.options);n.data!==void 0&&(this.setState(fi(n.data,n.dataUpdatedAt)),v(this,it,n))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&c(this,de).remove(this)}setData(t,n){let r=fn(this.state.data,t,this.options);return C(this,ie,Ie).call(this,{data:r,type:"success",dataUpdatedAt:n?.updatedAt,manual:n?.manual}),r}setState(t,n){C(this,ie,Ie).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){let n=c(this,V)?.promise;return c(this,V)?.cancel(t),n?n.then(q).catch(q):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return c(this,it)}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(t=>X(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===xt||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>pe(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:!$n(this.state.dataUpdatedAt,t)}onFocus(){this.observers.find(n=>n.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),c(this,V)?.continue()}onOnline(){this.observers.find(n=>n.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),c(this,V)?.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),c(this,de).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(n=>n!==t),this.observers.length||(c(this,V)&&(c(this,at)||C(this,ie,gi).call(this)?c(this,V).cancel({revert:!0}):c(this,V).cancelRetry()),this.scheduleGc()),c(this,de).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||C(this,ie,Ie).call(this,{type:"invalidate"})}async fetch(t,n){if(this.state.fetchStatus!=="idle"&&c(this,V)?.status()!=="rejected"){if(this.state.data!==void 0&&n?.cancelRefetch)this.cancel({silent:!0});else if(c(this,V))return c(this,V).continueRetry(),c(this,V).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:()=>(v(this,at,!0),r.signal)})},i=()=>{let u=zn(this.options,n),d=(()=>{let p={client:c(this,ot),queryKey:this.queryKey,meta:this.meta};return s(p),p})();return v(this,at,!1),this.options.persister?this.options.persister(u,d,this):u(d)},o=(()=>{let u={fetchOptions:n,options:this.options,queryKey:this.queryKey,client:c(this,ot),state:this.state,fetchFn:i};return s(u),u})();this.options.behavior?.onFetch(o,this),v(this,Mt,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==o.fetchOptions?.meta)&&C(this,ie,Ie).call(this,{type:"fetch",meta:o.fetchOptions?.meta}),v(this,V,Yn({initialPromise:n?.initialPromise,fn:o.fetchFn,onCancel:u=>{u instanceof Jn&&u.revert&&this.setState({...c(this,Mt),fetchStatus:"idle"}),r.abort()},onFail:(u,l)=>{C(this,ie,Ie).call(this,{type:"failed",failureCount:u,error:l})},onPause:()=>{C(this,ie,Ie).call(this,{type:"pause"})},onContinue:()=>{C(this,ie,Ie).call(this,{type:"continue"})},retry:o.options.retry,retryDelay:o.options.retryDelay,networkMode:o.options.networkMode,canRun:()=>!0}));try{let u=await c(this,V).start();if(u===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(u),c(this,de).config.onSuccess?.(u,this),c(this,de).config.onSettled?.(u,this.state.error,this),u}catch(u){if(u instanceof Jn){if(u.silent)return c(this,V).promise;if(u.revert){if(this.state.data===void 0)throw u;return this.state.data}}throw C(this,ie,Ie).call(this,{type:"error",error:u}),c(this,de).config.onError?.(u,this),c(this,de).config.onSettled?.(this.state.data,u,this),u}finally{this.scheduleGc()}}},it=new WeakMap,Mt=new WeakMap,de=new WeakMap,ot=new WeakMap,V=new WeakMap,mn=new WeakMap,at=new WeakMap,ie=new WeakSet,gi=function(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"},Ie=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,...Xr(r.data,this.options),fetchMeta:t.meta??null};case"success":let s={...r,...fi(t.data,t.dataUpdatedAt),dataUpdateCount:r.dataUpdateCount+1,...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return v(this,Mt,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),M.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),c(this,de).notify({query:this,type:"updated",action:t})})},mi);function Xr(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Yr(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function fi(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function pi(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 Z,T,gn,z,ct,kt,Ae,Ve,yn,Ft,qt,ut,lt,He,Dt,O,hn,Zr,es,ts,ns,rs,ss,is,bi,vi,_n=(vi=class extends le{constructor(t,n){super();b(this,O);b(this,Z);b(this,T);b(this,gn);b(this,z);b(this,ct);b(this,kt);b(this,Ae);b(this,Ve);b(this,yn);b(this,Ft);b(this,qt);b(this,ut);b(this,lt);b(this,He);b(this,Dt,new Set);this.options=n,v(this,Z,t),v(this,Ve,null),v(this,Ae,pn()),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(c(this,T).addObserver(this),yi(c(this,T),this.options)?C(this,O,hn).call(this):this.updateResult(),C(this,O,ns).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return os(c(this,T),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return os(c(this,T),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,C(this,O,rs).call(this),C(this,O,ss).call(this),c(this,T).removeObserver(this)}setOptions(t){let n=this.options,r=c(this,T);if(this.options=c(this,Z).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof X(this.options.enabled,c(this,T))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");C(this,O,is).call(this),c(this,T).setOptions(this.options),n._defaulted&&!Pt(this.options,n)&&c(this,Z).getQueryCache().notify({type:"observerOptionsUpdated",query:c(this,T),observer:this});let s=this.hasListeners();s&&_i(c(this,T),r,this.options,n)&&C(this,O,hn).call(this),this.updateResult(),s&&(c(this,T)!==r||X(this.options.enabled,c(this,T))!==X(n.enabled,c(this,T))||pe(this.options.staleTime,c(this,T))!==pe(n.staleTime,c(this,T)))&&C(this,O,Zr).call(this);let i=C(this,O,es).call(this);s&&(c(this,T)!==r||X(this.options.enabled,c(this,T))!==X(n.enabled,c(this,T))||i!==c(this,He))&&C(this,O,ts).call(this,i)}getOptimisticResult(t){let n=c(this,Z).getQueryCache().build(c(this,Z),t),r=this.createResult(n,t);return dc(this,r)&&(v(this,z,r),v(this,kt,this.options),v(this,ct,c(this,T).state)),r}getCurrentResult(){return c(this,z)}trackResult(t,n){return new Proxy(t,{get:(r,s)=>(this.trackProp(s),n?.(s),s==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&c(this,Ae).status==="pending"&&c(this,Ae).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(r,s))})}trackProp(t){c(this,Dt).add(t)}getCurrentQuery(){return c(this,T)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){let n=c(this,Z).defaultQueryOptions(t),r=c(this,Z).getQueryCache().build(c(this,Z),n);return r.fetch().then(()=>this.createResult(r,n))}fetch(t){return C(this,O,hn).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),c(this,z)))}createResult(t,n){let r=c(this,T),s=this.options,i=c(this,z),a=c(this,ct),o=c(this,kt),l=t!==r?t.state:c(this,gn),{state:d}=t,p={...d},f=!1,m;if(n._optimisticResults){let Q=this.hasListeners(),Y=!Q&&yi(t,n),ye=Q&&_i(t,r,n,s);(Y||ye)&&(p={...p,...Xr(d.data,t.options)}),n._optimisticResults==="isRestoring"&&(p.fetchStatus="idle")}let{error:_,errorUpdatedAt:h,status:g}=p;m=p.data;let S=!1;if(n.placeholderData!==void 0&&m===void 0&&g==="pending"){let Q;i?.isPlaceholderData&&n.placeholderData===o?.placeholderData?(Q=i.data,S=!0):Q=typeof n.placeholderData=="function"?n.placeholderData(c(this,qt)?.state.data,c(this,qt)):n.placeholderData,Q!==void 0&&(g="success",m=fn(i?.data,Q,n),f=!0)}if(n.select&&m!==void 0&&!S)if(i&&m===a?.data&&n.select===c(this,yn))m=c(this,Ft);else try{v(this,yn,n.select),m=n.select(m),m=fn(i?.data,m,n),v(this,Ft,m),v(this,Ve,null)}catch(Q){v(this,Ve,Q)}c(this,Ve)&&(_=c(this,Ve),m=c(this,Ft),h=Date.now(),g="error");let E=p.fetchStatus==="fetching",x=g==="pending",U=g==="error",L=x&&E,$=m!==void 0,re={status:g,fetchStatus:p.fetchStatus,isPending:x,isSuccess:g==="success",isError:U,isInitialLoading:L,isLoading:L,data:m,dataUpdatedAt:p.dataUpdatedAt,error:_,errorUpdatedAt:h,failureCount:p.fetchFailureCount,failureReason:p.fetchFailureReason,errorUpdateCount:p.errorUpdateCount,isFetched:t.isFetched(),isFetchedAfterMount:p.dataUpdateCount>l.dataUpdateCount||p.errorUpdateCount>l.errorUpdateCount,isFetching:E,isRefetching:E&&!x,isLoadingError:U&&!$,isPaused:p.fetchStatus==="paused",isPlaceholderData:f,isRefetchError:U&&$,isStale:as(t,n),refetch:this.refetch,promise:c(this,Ae),isEnabled:X(n.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){let Q=re.data!==void 0,Y=re.status==="error"&&!Q,ye=I=>{Y?I.reject(re.error):Q&&I.resolve(re.data)},_e=()=>{let I=v(this,Ae,re.promise=pn());ye(I)},ve=c(this,Ae);switch(ve.status){case"pending":t.queryHash===r.queryHash&&ye(ve);break;case"fulfilled":(Y||re.data!==ve.value)&&_e();break;case"rejected":(!Y||re.error!==ve.reason)&&_e();break}}return re}updateResult(){let t=c(this,z),n=this.createResult(c(this,T),this.options);if(v(this,ct,c(this,T).state),v(this,kt,this.options),c(this,ct).data!==void 0&&v(this,qt,c(this,T)),Pt(n,t))return;v(this,z,n);let r=()=>{if(!t)return!0;let{notifyOnChangeProps:s}=this.options,i=typeof s=="function"?s():s;if(i==="all"||!i&&!c(this,Dt).size)return!0;let a=new Set(i??c(this,Dt));return this.options.throwOnError&&a.add("error"),Object.keys(c(this,z)).some(o=>{let u=o;return c(this,z)[u]!==t[u]&&a.has(u)})};C(this,O,bi).call(this,{listeners:r()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&C(this,O,ns).call(this)}},Z=new WeakMap,T=new WeakMap,gn=new WeakMap,z=new WeakMap,ct=new WeakMap,kt=new WeakMap,Ae=new WeakMap,Ve=new WeakMap,yn=new WeakMap,Ft=new WeakMap,qt=new WeakMap,ut=new WeakMap,lt=new WeakMap,He=new WeakMap,Dt=new WeakMap,O=new WeakSet,hn=function(t){C(this,O,is).call(this);let n=c(this,T).fetch(this.options,t);return t?.throwOnError||(n=n.catch(q)),n},Zr=function(){C(this,O,rs).call(this);let t=pe(this.options.staleTime,c(this,T));if(Re.isServer()||c(this,z).isStale||!ln(t))return;let r=$n(c(this,z).dataUpdatedAt,t)+1;v(this,ut,we.setTimeout(()=>{c(this,z).isStale||this.updateResult()},r))},es=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(c(this,T)):this.options.refetchInterval)??!1},ts=function(t){C(this,O,ss).call(this),v(this,He,t),!(Re.isServer()||X(this.options.enabled,c(this,T))===!1||!ln(c(this,He))||c(this,He)===0)&&v(this,lt,we.setInterval(()=>{(this.options.refetchIntervalInBackground||Ct.isFocused())&&C(this,O,hn).call(this)},c(this,He)))},ns=function(){C(this,O,Zr).call(this),C(this,O,ts).call(this,C(this,O,es).call(this))},rs=function(){c(this,ut)!==void 0&&(we.clearTimeout(c(this,ut)),v(this,ut,void 0))},ss=function(){c(this,lt)!==void 0&&(we.clearInterval(c(this,lt)),v(this,lt,void 0))},is=function(){let t=c(this,Z).getQueryCache().build(c(this,Z),this.options);if(t===c(this,T))return;let n=c(this,T);v(this,T,t),v(this,gn,t.state),this.hasListeners()&&(n?.removeObserver(this),t.addObserver(this))},bi=function(t){M.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(c(this,z))}),c(this,Z).getQueryCache().notify({query:c(this,T),type:"observerResultsUpdated"})})},vi);function lc(e,t){return X(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function yi(e,t){return lc(e,t)||e.state.data!==void 0&&os(e,t,t.refetchOnMount)}function os(e,t,n){if(X(t.enabled,e)!==!1&&pe(t.staleTime,e)!=="static"){let r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&as(e,t)}return!1}function _i(e,t,n,r){return(e!==t||X(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&as(e,n)}function as(e,t){return X(t.enabled,e)!==!1&&e.isStaleByTime(pe(t.staleTime,e))}function dc(e,t){return!Pt(e.getCurrentResult(),t)}function Ut(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||[],o={pages:[],pageParams:[]},u=0,l=async()=>{let d=!1,p=_=>{ci(_,()=>t.signal,()=>d=!0)},f=zn(t.options,t.fetchOptions),m=async(_,h,g)=>{if(d)return Promise.reject();if(h==null&&_.pages.length)return Promise.resolve(_);let E=(()=>{let $={client:t.client,queryKey:t.queryKey,pageParam:h,direction:g?"backward":"forward",meta:t.options.meta};return p($),$})(),x=await f(E),{maxPages:U}=t.options,L=g?ai:oi;return{pages:L(_.pages,x,U),pageParams:L(_.pageParams,h,U)}};if(s&&i.length){let _=s==="backward",h=_?wi:cs,g={pages:i,pageParams:a},S=h(r,g);o=await m(g,S,_)}else{let _=e??i.length;do{let h=u===0?a[0]??r.initialPageParam:cs(r,o);if(u>0&&h==null)break;o=await m(o,h),u++}while(u<_)}return o};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 cs(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 wi(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function Si(e,t){return t?cs(e,t)!=null:!1}function Ri(e,t){return!t||!e.getPreviousPageParam?!1:wi(e,t)!=null}var us=class extends _n{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:Ut()})}getOptimisticResult(e){return e.behavior=Ut(),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:o}=r,u=n.fetchMeta?.fetchMore?.direction,l=a&&u==="forward",d=s&&u==="forward",p=a&&u==="backward",f=s&&u==="backward";return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:Si(t,n.data),hasPreviousPage:Ri(t,n.data),isFetchNextPageError:l,isFetchingNextPage:d,isFetchPreviousPageError:p,isFetchingPreviousPage:f,isRefetchError:o&&!l&&!p,isRefetching:i&&!d&&!f}}};var vn,Ee,G,dt,Ce,We,Ei,Ci=(Ei=class extends Xn{constructor(t){super();b(this,Ce);b(this,vn);b(this,Ee);b(this,G);b(this,dt);v(this,vn,t.client),this.mutationId=t.mutationId,v(this,G,t.mutationCache),v(this,Ee,[]),this.state=t.state||ls(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){c(this,Ee).includes(t)||(c(this,Ee).push(t),this.clearGcTimeout(),c(this,G).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){v(this,Ee,c(this,Ee).filter(n=>n!==t)),this.scheduleGc(),c(this,G).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){c(this,Ee).length||(this.state.status==="pending"?this.scheduleGc():c(this,G).remove(this))}continue(){return c(this,dt)?.continue()??this.execute(this.state.variables)}async execute(t){let n=()=>{C(this,Ce,We).call(this,{type:"continue"})},r={client:c(this,vn),meta:this.options.meta,mutationKey:this.options.mutationKey};v(this,dt,Yn({fn:()=>this.options.mutationFn?this.options.mutationFn(t,r):Promise.reject(new Error("No mutationFn found")),onFail:(a,o)=>{C(this,Ce,We).call(this,{type:"failed",failureCount:a,error:o})},onPause:()=>{C(this,Ce,We).call(this,{type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>c(this,G).canRun(this)}));let s=this.state.status==="pending",i=!c(this,dt).canStart();try{if(s)n();else{C(this,Ce,We).call(this,{type:"pending",variables:t,isPaused:i}),c(this,G).config.onMutate&&await c(this,G).config.onMutate(t,this,r);let o=await this.options.onMutate?.(t,r);o!==this.state.context&&C(this,Ce,We).call(this,{type:"pending",context:o,variables:t,isPaused:i})}let a=await c(this,dt).start();return await c(this,G).config.onSuccess?.(a,t,this.state.context,this,r),await this.options.onSuccess?.(a,t,this.state.context,r),await c(this,G).config.onSettled?.(a,null,this.state.variables,this.state.context,this,r),await this.options.onSettled?.(a,null,t,this.state.context,r),C(this,Ce,We).call(this,{type:"success",data:a}),a}catch(a){try{await c(this,G).config.onError?.(a,t,this.state.context,this,r)}catch(o){Promise.reject(o)}try{await this.options.onError?.(a,t,this.state.context,r)}catch(o){Promise.reject(o)}try{await c(this,G).config.onSettled?.(void 0,a,this.state.variables,this.state.context,this,r)}catch(o){Promise.reject(o)}try{await this.options.onSettled?.(void 0,a,t,this.state.context,r)}catch(o){Promise.reject(o)}throw C(this,Ce,We).call(this,{type:"error",error:a}),a}finally{c(this,G).runNext(this)}}},vn=new WeakMap,Ee=new WeakMap,G=new WeakMap,dt=new WeakMap,Ce=new WeakSet,We=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),M.batch(()=>{c(this,Ee).forEach(r=>{r.onMutationUpdate(t)}),c(this,G).notify({mutation:this,type:"updated",action:t})})},Ei);function ls(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Oe,me,bn,Pi,xi=(Pi=class extends le{constructor(t={}){super();b(this,Oe);b(this,me);b(this,bn);this.config=t,v(this,Oe,new Set),v(this,me,new Map),v(this,bn,0)}build(t,n,r){let s=new Ci({client:t,mutationCache:this,mutationId:++en(this,bn)._,options:t.defaultMutationOptions(n),state:r});return this.add(s),s}add(t){c(this,Oe).add(t);let n=Zn(t);if(typeof n=="string"){let r=c(this,me).get(n);r?r.push(t):c(this,me).set(n,[t])}this.notify({type:"added",mutation:t})}remove(t){if(c(this,Oe).delete(t)){let n=Zn(t);if(typeof n=="string"){let r=c(this,me).get(n);if(r)if(r.length>1){let s=r.indexOf(t);s!==-1&&r.splice(s,1)}else r[0]===t&&c(this,me).delete(n)}}this.notify({type:"removed",mutation:t})}canRun(t){let n=Zn(t);if(typeof n=="string"){let s=c(this,me).get(n)?.find(i=>i.state.status==="pending");return!s||s===t}else return!0}runNext(t){let n=Zn(t);return typeof n=="string"?c(this,me).get(n)?.find(s=>s!==t&&s.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){M.batch(()=>{c(this,Oe).forEach(t=>{this.notify({type:"removed",mutation:t})}),c(this,Oe).clear(),c(this,me).clear()})}getAll(){return Array.from(c(this,Oe))}find(t){let n={exact:!0,...t};return this.getAll().find(r=>Gn(n,r))}findAll(t={}){return this.getAll().filter(n=>Gn(t,n))}notify(t){M.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){let t=this.getAll().filter(n=>n.state.isPaused);return M.batch(()=>Promise.all(t.map(n=>n.continue().catch(q))))}},Oe=new WeakMap,me=new WeakMap,bn=new WeakMap,Pi);function Zn(e){return e.options.scope?.id}var Me,$e,ee,ke,Fe,er,ds,Ti,fs=(Ti=class extends le{constructor(t,n){super();b(this,Fe);b(this,Me);b(this,$e);b(this,ee);b(this,ke);v(this,Me,t),this.setOptions(n),this.bindMethods(),C(this,Fe,er).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(t){let n=this.options;this.options=c(this,Me).defaultMutationOptions(t),Pt(this.options,n)||c(this,Me).getMutationCache().notify({type:"observerOptionsUpdated",mutation:c(this,ee),observer:this}),n?.mutationKey&&this.options.mutationKey&&Se(n.mutationKey)!==Se(this.options.mutationKey)?this.reset():c(this,ee)?.state.status==="pending"&&c(this,ee).setOptions(this.options)}onUnsubscribe(){this.hasListeners()||c(this,ee)?.removeObserver(this)}onMutationUpdate(t){C(this,Fe,er).call(this),C(this,Fe,ds).call(this,t)}getCurrentResult(){return c(this,$e)}reset(){c(this,ee)?.removeObserver(this),v(this,ee,void 0),C(this,Fe,er).call(this),C(this,Fe,ds).call(this)}mutate(t,n){return v(this,ke,n),c(this,ee)?.removeObserver(this),v(this,ee,c(this,Me).getMutationCache().build(c(this,Me),this.options)),c(this,ee).addObserver(this),c(this,ee).execute(t)}},Me=new WeakMap,$e=new WeakMap,ee=new WeakMap,ke=new WeakMap,Fe=new WeakSet,er=function(){let t=c(this,ee)?.state??ls();v(this,$e,{...t,isPending:t.status==="pending",isSuccess:t.status==="success",isError:t.status==="error",isIdle:t.status==="idle",mutate:this.mutate,reset:this.reset})},ds=function(t){M.batch(()=>{if(c(this,ke)&&this.hasListeners()){let n=c(this,$e).variables,r=c(this,$e).context,s={client:c(this,Me),meta:this.options.meta,mutationKey:this.options.mutationKey};if(t?.type==="success"){try{c(this,ke).onSuccess?.(t.data,n,r,s)}catch(i){Promise.reject(i)}try{c(this,ke).onSettled?.(t.data,null,n,r,s)}catch(i){Promise.reject(i)}}else if(t?.type==="error"){try{c(this,ke).onError?.(t.error,n,r,s)}catch(i){Promise.reject(i)}try{c(this,ke).onSettled?.(void 0,t.error,n,r,s)}catch(i){Promise.reject(i)}}}this.listeners.forEach(n=>{n(c(this,$e))})})},Ti);var Pe,Ii,Ai=(Ii=class extends le{constructor(t={}){super();b(this,Pe);this.config=t,v(this,Pe,new Map)}build(t,n,r){let s=n.queryKey,i=n.queryHash??dn(s,n),a=this.get(i);return a||(a=new hi({client:t,queryKey:s,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(s)}),this.add(a)),a}add(t){c(this,Pe).has(t.queryHash)||(c(this,Pe).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){let n=c(this,Pe).get(t.queryHash);n&&(t.destroy(),n===t&&c(this,Pe).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){M.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return c(this,Pe).get(t)}getAll(){return[...c(this,Pe).values()]}find(t){let n={exact:!0,...t};return this.getAll().find(r=>Bn(n,r))}findAll(t={}){let n=this.getAll();return Object.keys(t).length>0?n.filter(r=>Bn(t,r)):n}notify(t){M.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){M.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){M.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},Pe=new WeakMap,Ii);var D,Be,Ge,Nt,Qt,ze,Kt,Lt,Oi,ps=(Oi=class{constructor(e={}){b(this,D);b(this,Be);b(this,Ge);b(this,Nt);b(this,Qt);b(this,ze);b(this,Kt);b(this,Lt);v(this,D,e.queryCache||new Ai),v(this,Be,e.mutationCache||new xi),v(this,Ge,e.defaultOptions||{}),v(this,Nt,new Map),v(this,Qt,new Map),v(this,ze,0)}mount(){en(this,ze)._++,c(this,ze)===1&&(v(this,Kt,Ct.subscribe(async e=>{e&&(await this.resumePausedMutations(),c(this,D).onFocus())})),v(this,Lt,Ot.subscribe(async e=>{e&&(await this.resumePausedMutations(),c(this,D).onOnline())})))}unmount(){var e,t;en(this,ze)._--,c(this,ze)===0&&((e=c(this,Kt))==null||e.call(this),v(this,Kt,void 0),(t=c(this,Lt))==null||t.call(this),v(this,Lt,void 0))}isFetching(e){return c(this,D).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return c(this,Be).findAll({...e,status:"pending"}).length}getQueryData(e){let t=this.defaultQueryOptions({queryKey:e});return c(this,D).get(t.queryHash)?.state.data}ensureQueryData(e){let t=this.defaultQueryOptions(e),n=c(this,D).build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(pe(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return c(this,D).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=c(this,D).get(r.queryHash)?.state.data,a=si(t,i);if(a!==void 0)return c(this,D).build(this,r).setData(a,{...n,manual:!0})}setQueriesData(e,t,n){return M.batch(()=>c(this,D).findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){let t=this.defaultQueryOptions({queryKey:e});return c(this,D).get(t.queryHash)?.state}removeQueries(e){let t=c(this,D);M.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){let n=c(this,D);return M.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){let n={revert:!0,...t},r=M.batch(()=>c(this,D).findAll(e).map(s=>s.cancel(n)));return Promise.all(r).then(q).catch(q)}invalidateQueries(e,t={}){return M.batch(()=>(c(this,D).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=M.batch(()=>c(this,D).findAll(e).filter(s=>!s.isDisabled()&&!s.isStatic()).map(s=>{let i=s.fetch(void 0,n);return n.throwOnError||(i=i.catch(q)),s.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(q)}fetchQuery(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=c(this,D).build(this,t);return n.isStaleByTime(pe(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(q).catch(q)}fetchInfiniteQuery(e){return e.behavior=Ut(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(q).catch(q)}ensureInfiniteQueryData(e){return e.behavior=Ut(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return Ot.isOnline()?c(this,Be).resumePausedMutations():Promise.resolve()}getQueryCache(){return c(this,D)}getMutationCache(){return c(this,Be)}getDefaultOptions(){return c(this,Ge)}setDefaultOptions(e){v(this,Ge,e)}setQueryDefaults(e,t){c(this,Nt).set(Se(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){let t=[...c(this,Nt).values()],n={};return t.forEach(r=>{rt(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){c(this,Qt).set(Se(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){let t=[...c(this,Qt).values()],n={};return t.forEach(r=>{rt(e,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;let t={...c(this,Ge).queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=dn(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===xt&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...c(this,Ge).mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){c(this,D).clear(),c(this,Be).clear()}},D=new WeakMap,Be=new WeakMap,Ge=new WeakMap,Nt=new WeakMap,Qt=new WeakMap,ze=new WeakMap,Kt=new WeakMap,Lt=new WeakMap,Oi);var jt=j(oe(),1),Fi=j(tr(),1),ms=jt.createContext(void 0),N=e=>{let t=jt.useContext(ms);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},wn=({client:e,children:t})=>(jt.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,Fi.jsx)(ms.Provider,{value:e,children:t}));var nr=j(oe(),1),qi=nr.createContext(!1),Di=()=>nr.useContext(qi),_d=qi.Provider;var Sn=j(oe(),1),fc=j(tr(),1);function pc(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var mc=Sn.createContext(pc()),Ui=()=>Sn.useContext(mc);var Ni=j(oe(),1);var Qi=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError=="function"?Tt(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},Ki=e=>{Ni.useEffect(()=>{e.clearReset()},[e])},Li=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:s})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(s&&e.data===void 0||Tt(n,[e.error,r]));var ji=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))}},Vi=(e,t)=>e.isLoading&&e.isFetching&&!t,Hi=(e,t)=>e?.suspense&&t.isPending,hs=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});var Je=j(oe(),1);function rr(e,t,n){let r=Di(),s=Ui(),i=N(n),a=i.defaultQueryOptions(e);i.getDefaultOptions().queries?._experimental_beforeQuery?.(a);let o=i.getQueryCache().get(a.queryHash);a._optimisticResults=r?"isRestoring":"optimistic",ji(a),Qi(a,s,o),Ki(s);let u=!i.getQueryCache().get(a.queryHash),[l]=Je.useState(()=>new t(i,a)),d=l.getOptimisticResult(a),p=!r&&e.subscribed!==!1;if(Je.useSyncExternalStore(Je.useCallback(f=>{let m=p?l.subscribe(M.batchCalls(f)):q;return l.updateResult(),m},[l,p]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),Je.useEffect(()=>{l.setOptions(a)},[a,l]),Hi(a,d))throw hs(a,l,s);if(Li({result:d,errorResetBoundary:s,throwOnError:a.throwOnError,query:o,suspense:a.suspense}))throw d.error;return i.getDefaultOptions().queries?._experimental_afterQuery?.(a,d),a.experimental_prefetchInRender&&!Re.isServer()&&Vi(d,r)&&(u?hs(a,l,s):o?.promise)?.catch(q).finally(()=>{l.updateResult()}),a.notifyOnChangeProps?d:l.trackResult(d)}function F(e,t){return rr(e,_n,t)}var qe=j(oe(),1);function De(e,t){let n=N(t),[r]=qe.useState(()=>new fs(n,e));qe.useEffect(()=>{r.setOptions(e)},[r,e]);let s=qe.useSyncExternalStore(qe.useCallback(a=>r.subscribe(M.batchCalls(a)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),i=qe.useCallback((a,o)=>{r.mutate(a,o).catch(q)},[r]);if(s.error&&Tt(r.options.throwOnError,[s.error]))throw s.error;return{...s,mutate:i,mutateAsync:s.mutate}}function Rn(e,t){return rr(e,us,t)}var Vt=null;function Wi(e){if(Vt&&Vt!==e)throw new Error("[fsaos-gateway-sdk] setQueryClient() called after a QueryClient was already in use. Inject the host client before rendering or starting realtime subscriptions.");Vt=e}function P(){return Vt||(Vt=new ps({defaultOptions:{queries:{staleTime:1e3*60*2,gcTime:1e3*60*10,refetchOnWindowFocus:!1,retry:1}}})),Vt}var $i=new Proxy({},{get(e,t,n){let r=P(),s=r[t];return typeof s=="function"?s.bind(r):s}});function H(){return fe()??"__unscoped__"}var w={all:()=>["vfs",H()],item:e=>["vfs",H(),"item",e],itemById:e=>["vfs","item-by-id",e],children:e=>["vfs",H(),"children",e],allChildren:()=>["vfs",H(),"children"],types:e=>["vfs","types",e??"default"],edges:e=>["vfs","edges",e],search:(e,t)=>["vfs",H(),"search",e,...t??[]],items:(e,t)=>["vfs",H(),"items",e,JSON.stringify(t??{})],allItems:()=>["vfs",H(),"items"],tree:(e,t)=>["vfs",H(),"tree",e,t??1],openEnvelope:(e,t)=>["vfs",H(),"open",e,t??"__default__"],allOpenEnvelopes:()=>["vfs",H(),"open"],memberFocus:e=>["vfs","member-focus",e],fractalInstances:()=>["vfs","fractal-instances"],recentActivity:(e,t,n)=>["vfs",H(),"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",H(),"channel-messages",e,t??"__top__"],allChannelMessages:()=>["vfs",H(),"channel-messages"],channels:e=>["vfs",H(),"channels",e??"all"],allChannels:()=>["vfs",H(),"channels"],notifications:(e,t)=>["vfs",H(),"notifications",e??"all",t??200],allNotifications:()=>["vfs",H(),"notifications"],unreadCounts:()=>["vfs",H(),"unread-counts"],memberships:e=>["memberships",e]};function Bi(){return new Date().toISOString()}function Gi(){return crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function he(e){let t=e.path||e.item_path||"",n=t.split("/");n.pop();let r=n.join("/"),s=e.type_data||{};return s.allowed_parent_types&&!s.accepts&&(s.accepts=s.allowed_parent_types),delete s.allowed_parent_types,{id:e.id||e.item_id||"",name:e.name||e.item_name||"",item_type:e.item_type||"unknown",path:t,parent_path:r,is_active:e.is_active!==!1,has_children:e.has_children??!1,created_at:e.created_at||Bi(),updated_at:e.updated_at||Bi(),visibility:e.visibility,type_data:s,scope_item_id:e.scope_item_id,fractal_id:e.fractal_id,parent_instance_id:e.parent_instance_id,owner_principal_id:e.owner_principal_id,created_by_principal_id:e.created_by_principal_id,parent_id:e.parent_id,space_item_id:e.space_item_id,account_item_id:e.account_item_id}}function En(e){return(e.content?.items||e.items||[]).map(he)}async function ir(e){try{let t=await R("read",{id:e});if(t.item_name||t.item_path){let r=he(t);return r.path&&P().setQueryData(w.item(r.path),r),r}let n=t.item;if(n){let r=he(n);return r.path&&P().setQueryData(w.item(r.path),r),r}return null}catch{return null}}async function or(e){try{let t=await R("read",{path:e});if(t.item_name||t.item_path)return he(t);let n=t.item;return n?he(n):null}catch{return null}}async function ar(e){try{let t=await R("list",{path:e,limit:200}),n=En(t);for(let r of n)P().setQueryData(w.item(r.path),r);return n}catch(t){return console.error(`[gateway] Failed to fetch children of ${e}:`,t),[]}}async function cr(e,t,n){try{let r=await R("list",{path:e,limit:t,offset:n}),s=En(r);for(let i of s)P().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 ur(e){let n=await R("types-list",e?{scope_id:e}:{}),r=n.content?.items||n.items||[],s=new Map;for(let i of r){let a=i.name,o=i.type_data;!a||!o||s.set(a,{type_key:a,display_name:o.display_name||a,display_name_plural:o.display_name_plural||a+"s",icon:o.icon||"File",color:o.color||"gray",description:o.description||"",input_schema:o.input_schema||{},system_schema:o.system_schema||{},json_schema:o.input_schema||o.json_schema||{},default_data:o.default_data||{},field_defaults:o.field_defaults||{},renderer_config:o.renderer_config||{},is_system:o.is_system??!1,is_active:o.is_active??!0,is_container:o.is_container??!1,is_scope:o.is_scope??!1,render_mode:o.render_mode||"none",placement_mode:o.placement_mode,direct_parent_types:o.direct_parent_types,allowed_parent_types:o.allowed_parent_types,governed_create:o.governed_create,create_method:o.create_method,dedup:o.dedup,edges:o.edges,events:o.events})}return s}async function lr(e){try{let t=await R("edges",{item_id:e}),n=t.outgoing||[],r=t.incoming||[],s=[];for(let i of n)s.push({id:i.edge_id||Gi(),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||Gi(),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 dr(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 R("tree",s),a=En(i);for(let o of a)P().setQueryData(w.item(o.path),o);return a}catch(s){return console.error(`[gateway] Failed to fetch tree at ${e}:`,s),[]}}async function fr(e,t=50,n=0){try{let r=await R("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 Cn(e,t={}){let{limit:n=50,offset:r=0,include_snapshots:s=!1}=t;try{let i=await R("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 pr(e,t=50,n=0){return Cn(e,{limit:t,offset:n})}async function mr(e,t,n){try{let r={scope_id:e};t?.length&&(r.item_types=t),n&&(r.limit=n);let s=await R("member-focus",r),i=En(s);for(let a of i)P().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 hr(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 R("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 Pn(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 R("query",t),s=En(r);for(let i of s)P().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 hc(e){if(!e||typeof e!="object")return;let t=e;if(t.version!==1||typeof t.work_id!="string"||!t.work_id)return;let n=r=>{let s=t[r];return typeof s=="string"&&s?s:void 0};return{version:1,workId:t.work_id,threadRootId:n("thread_root_id"),requestMessageId:n("request_message_id"),replyMessageId:n("reply_message_id"),replyMessagePath:n("reply_message_path"),todoListId:n("todo_list_id"),todoListPath:n("todo_list_path"),stepId:n("step_id"),stepPath:n("step_path"),runId:n("run_id"),parentRunId:n("parent_run_id"),toolCallId:n("tool_call_id"),traceId:n("trace_id")}}function zi(e){return e.filter(t=>t.item_type==="card").map(t=>{let n=t.type_data||{},r=n.payload||{};return{id:t.id||"",path:t.path||"",name:t.name||(t.path||"").split("/").pop()||"",createdAt:t.created_at||"",action:n.action||"created",targetId:n.target_id||void 0,targetPath:n.target_path||"",targetDisplayName:n.target_display_name||"",targetDescription:n.target_description||"",targetItemType:n.target_item_type||"",toolId:(t.name||"").startsWith("card-")?(t.name||"").substring(5):void 0,parentMessagePath:t.parent_message_path||void 0,visibility:n.visibility||"private",openWith:r.open_with||void 0,hostBundled:r.host_bundled===!0?!0:void 0,bundleExport:r.bundle_export||void 0,launchArguments:r.launch_arguments||void 0,requiresUserAttention:r.requires_user_attention===!0?!0:void 0,origin:hc(n.origin),presentationRole:r.presentation_role==="user-request"?"user-request":r.presentation_role==="output"?"output":void 0}}).sort((t,n)=>t.createdAt.localeCompare(n.createdAt))}function 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,metadata:Object.keys(s).length>0?s:void 0,thread_summary:Array.isArray(n.thread_summary)&&n.thread_summary.length>0?n.thread_summary:void 0}}).sort((t,n)=>t.seq-n.seq)}async function Ji(e,t){try{let n={channel_path:e};t&&(n.parent_message_id=t);let s=await R("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 gr(e,t){try{let n={channel_path:e};t&&(n.parent_message_id=t);let s=await R("get-channel-messages",n),i=s.messages||[],a=gs(i),o=zi(i),u=new Map,l=[];for(let d of o)if(d.parentMessagePath){let p=u.get(d.parentMessagePath)||[];p.push(d),u.set(d.parentMessagePath,p)}else l.push(d);return{messages:a,messageCards:u,siblingCards:l,mode:s.mode||"top_level"}}catch(n){return console.error(`[gateway] Failed to fetch channel messages with cards for ${e}:`,n),{messages:[],messageCards:new Map,siblingCards:[],mode:"top_level"}}}async function xn(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 R("get-channel-messages",n),i=s.messages||[],a=zi(i),o=new Map,u=[];for(let l of a)if(l.parentMessagePath){let d=o.get(l.parentMessagePath)||[];d.push(l),o.set(l.parentMessagePath,d)}else u.push(l);return{messages:gs(i),messageCards:o,siblingCards:u,mode:s.mode||"top_level"}}catch(n){return console.error(`[gateway] Failed to fetch channel messages page for ${e}:`,n),{messages:[],messageCards:new Map,siblingCards:[],mode:"top_level"}}}function sr(e){P().invalidateQueries({queryKey:w.children(e)})}function ys(e){P().invalidateQueries({queryKey:w.item(e)})}function Yi(e,t){ys(e),sr(e);let n=e.split("/");n.pop();let r=n.join("/")||t;r&&sr(r)}function Xi(e){let t=e+"/";P().invalidateQueries({predicate:n=>{let r=n.queryKey;return r[0]!=="vfs"?!1:r.some(s=>typeof s=="string"&&(s===e||s.startsWith(t)))}})}function Zi(){P().invalidateQueries({queryKey:w.all()})}function eo(e){P().invalidateQueries({queryKey:w.types(e)})}function to(e,t){e?P().invalidateQueries({queryKey:w.channelMessages(e,t)}):P().invalidateQueries({queryKey:w.allChannelMessages()})}function no(e,t){e&&t?P().invalidateQueries({queryKey:w.openEnvelope(e,t)}):e?P().invalidateQueries({predicate:n=>{let r=n.queryKey;return r[0]==="vfs"&&r[2]==="open"&&r[3]===e}}):P().invalidateQueries({queryKey:w.allOpenEnvelopes()})}var gc=typeof window<"u"&&(window.location?.hostname==="localhost"||window.location?.hostname==="127.0.0.1"||window.__FSAOS_WS_DEBUG__);function W(...e){gc&&console.log("[WS]",...e)}var A=null,Ht=null,Wt=null,Tn=0,yc=3e4,ro=1e4,Bt=!1,oo=3e4,_c=oo*2+5e3,yr=0,_r=null,so=!1;function vc(){An(),yr=Date.now(),_r=setInterval(()=>{if(A&&A.readyState===WebSocket.OPEN&&Date.now()-yr>_c){W("ping: no inbound traffic for",Date.now()-yr,"ms \u2014 closing half-open socket");try{A.close(4e3,"liveness timeout")}catch{}return}Ue({type:"ping"})},oo)}function An(){_r&&(clearInterval(_r),_r=null)}function bc(){typeof document>"u"||(document.hidden?An():In()&&(W("Tab visible, reconnecting..."),On()))}function wc(){so||typeof document>"u"||(document.addEventListener("visibilitychange",bc),so=!0)}var te={},$t=[],Gt=new Map,ft=new Map;function Sc(){return Object.keys(te).some(t=>te[t]&&te[t].length>0)||$t.length>0}function In(){return Gt.size>0||ft.size>0}async function On(){if(!In()){W("ensureConnection: no active subscriptions, skipping");return}if(A&&A.readyState===WebSocket.OPEN){W("ensureConnection: already open");return}if(Ht)return W("ensureConnection: connection already in flight, waiting..."),Ht;if(A){W("ensureConnection: killing stale WS in state",A.readyState);try{A.close()}catch{}A=null}return Bt=!1,Ht=(async()=>{try{let e=typeof window<"u"&&window.__FSAOS_CONFIG__||{},t=ce,n=await xe();if(!n){W("ensureConnection: no token available, will retry"),io();return}let r=t.startsWith("https")?"wss":"ws",s=t.replace(/^https?:\/\//,""),i=`${r}://${s}/ws`;i+=`?token=${encodeURIComponent(n)}`,W("ensureConnection: opening WS to",i.substring(0,50)+"..."),A=new WebSocket(i),await new Promise((a,o)=>{if(!A)return o(new Error("WebSocket not created"));let u=setTimeout(()=>{if(W("ensureConnection: TIMEOUT after",ro,"ms"),A&&A.readyState!==WebSocket.OPEN){try{A.close()}catch{}A=null}o(new Error("WebSocket connection timeout"))},ro);A.onopen=()=>{clearTimeout(u),W("ensureConnection: CONNECTED"),Tn=0,Rc(),(typeof document>"u"||!document.hidden)&&vc(),wc(),a()},A.onmessage=l=>{Ec(l.data)},A.onerror=()=>{W("ensureConnection: WS error event")},A.onclose=l=>{clearTimeout(u),W("ensureConnection: WS closed, code:",l.code,"reason:",l.reason),A=null,An(),!Bt&&In()&&io(),o(new Error(`WebSocket closed: ${l.code}`))}})}catch(e){W("ensureConnection: failed -",e?.message||e)}finally{Ht=null}})(),Ht}function io(){if(Wt||typeof document<"u"&&document.hidden)return;let e=Math.min(1e3*Math.pow(2,Tn)+Math.random()*1e3,yc);Tn++,W("scheduleReconnect: attempt",Tn,"in",Math.round(e),"ms"),Wt=setTimeout(()=>{Wt=null,In()&&On()},e)}function Rc(){for(let e of Gt.values())W("resubscribeAll: scope",e.scope_id),Ue({type:"subscribe",scope_id:e.scope_id,event_types:e.event_types});for(let e of ft.values())W("resubscribeAll: path",e.path),Ue({type:"subscribe_path",path:e.path,event_types:e.event_types})}function Ue(e){A&&A.readyState===WebSocket.OPEN&&A.send(JSON.stringify(e))}function Ec(e){yr=Date.now();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&&te[r.path]&&te[r.path].forEach(s=>s(r)),te["*"]&&te["*"].forEach(s=>s(r));for(let s of $t)s.eventType!=="*"&&s.eventType!==n||s.filter&&!s.filter(r)||s.callback(r)}}catch{}}function _s(){!Sc()&&Gt.size===0&&ft.size===0&&A&&(Bt=!0,An(),A.close(),A=null,Bt=!1)}function vr(e,t){return te[e]||(te[e]=[]),te[e].push(t),ft.has(e)||(ft.set(e,{path:e,event_types:["token_stream"]}),A&&A.readyState===WebSocket.OPEN&&Ue({type:"subscribe_path",path:e,event_types:["token_stream"]})),On(),()=>{let n=te[e];if(n){let r=n.indexOf(t);r!==-1&&n.splice(r,1),n.length===0&&(delete te[e],ft.delete(e),Ue({type:"unsubscribe_path",path:e}))}_s()}}function J(e,t,n){let s=(Array.isArray(e)?e:[e]).map(i=>({eventType:i,callback:t,filter:n}));return $t.push(...s),In()&&On(),()=>{for(let i of s){let a=$t.indexOf(i);a!==-1&&$t.splice(a,1)}_s()}}function br(e,t=["vfs_change","ccm_change"]){return W("subscribeToScope:",e,t),Gt.set(e,{scope_id:e,event_types:t}),A&&A.readyState===WebSocket.OPEN&&Ue({type:"subscribe",scope_id:e,event_types:t}),On(),()=>{Gt.delete(e),Ue({type:"unsubscribe",scope_id:e}),_s()}}function ao(e,t,n={}){Ue({type:"emit",scope_id:e,event_type:t,payload:n})}function vs(){W("disconnectSSE: tearing down"),Bt=!0,An(),A&&(A.close(),A=null),Wt&&(clearTimeout(Wt),Wt=null),Ht=null,Bt=!1,Tn=0;for(let e of Object.keys(te))delete te[e];$t.length=0,Gt.clear(),ft.clear()}function co(){Ue({type:"ping"})}Te(vs);var zt=new Map,wr=null,Sr=null,Ye=new Map,uo=250;function Mn(e){Rr(),kn(e),wr=J("vfs_change",t=>Cc(t)),Sr=J("ccm_change",t=>Pc(t))}function kn(e){if(zt.has(e))return;let t=br(e,["vfs_change","ccm_change"]);zt.set(e,t)}function lo(e){let t=zt.get(e);t&&(t(),zt.delete(e))}function Rr(){for(let[,e]of zt)e();zt.clear(),wr&&(wr(),wr=null),Sr&&(Sr(),Sr=null),Ye.forEach(e=>clearTimeout(e)),Ye.clear()}Te(Rr);function Cc(e){let t=e.path,n=e.action;if(!t)return;let r=t.split("/");r.pop();let s=r.join("/")||"/root",i=Ye.get(s);i&&clearTimeout(i);let a=setTimeout(()=>{Ye.delete(s),xc(n,t,e,s)},uo);Ye.set(s,a)}function Pc(e){if(!e||typeof e!="object")return;let t=e.source_item_id||e.source_id,n=e.target_item_id||e.target_id;if(!(e.edge_type!=null||t!=null||n!=null))return;let s=`ccm:${t??""}:${n??""}`,i=Ye.get(s);i&&clearTimeout(i);let a=setTimeout(()=>{Ye.delete(s),t&&P().invalidateQueries({queryKey:w.edges(t)}),n&&P().invalidateQueries({queryKey:w.edges(n)}),!t&&!n&&P().invalidateQueries({predicate:o=>o.queryKey[0]==="vfs"&&o.queryKey[1]==="edges"})},uo);Ye.set(s,a)}function xc(e,t,n,r){if((e||"").toUpperCase()==="DELETE")P().removeQueries({queryKey:w.item(t)}),P().removeQueries({queryKey:w.children(t)}),P().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=he(i);a&&a.id&&P().setQueryData(w.item(t),a)}catch{}P().invalidateQueries({queryKey:w.children(r)}),P().invalidateQueries({predicate:i=>{let a=i.queryKey;if(a[0]!=="vfs"||a[1]!=="tree")return!1;let o=a[2];return t.startsWith(o+"/")||t===o}}),n.item_id&&P().invalidateQueries({queryKey:w.itemById(n.item_id)})}var bs=j(oe(),1),mo=j(po(),1);function ho(e){return R("read",{path:e})}function go(e,t){return R("list",{path:e,...t})}function yo(e){return R("create",e)}function _o(e){return R("update",e)}function vo(e){return R("create",e)}function bo(e,t){let r=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).scopePath||"";return R("tools/call",{name:e,instance_path:r,...t||{}})}function wo(e,t,n){return R("signal",{target_id:e,event_name:t,payload:n||{}})}function So(e){return((typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"")+e}var Ro={signIn:e=>e.provider?k.auth.signInWithOAuth({provider:e.provider,options:{redirectTo:e.redirectTo||window.location.href}}):k.auth.signInWithPassword({email:e.email,password:e.password}),signUp:e=>k.auth.signUp({email:e.email,password:e.password,options:{data:e.metadata||{}}}),signOut:async()=>{await k.auth.signOut(),vt(),P().clear()},getSession:()=>k.auth.getSession().then(e=>e.data.session),getUser:()=>k.auth.getUser().then(e=>e.data.user),onAuthStateChange:e=>{let{data:{subscription:t}}=k.auth.onAuthStateChange((n,r)=>{e({event:n,session:r,user:r?.user??null})});return()=>t?.unsubscribe()},resetPassword:e=>k.auth.resetPasswordForEmail(e),signInWithMagicLink:(e,t)=>k.auth.signInWithOtp({email:e,options:{emailRedirectTo:t||window.location.href}})};function Eo(){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,mo.createRoot)(e).render((0,bs.createElement)(wn,{client:P()},(0,bs.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 Co(){let e=window.React,t=window.ReactDOM,n=window.__FSAOS_GATEWAY__,r=window.__FSAOS_UI__;if(!n){console.error("[FSAOS] Cannot set up require shim: __FSAOS_GATEWAY__ not found");return}let s={react:e,"react-dom":t,"react-dom/client":t,"react/jsx-runtime":{jsx:e?.createElement,jsxs:e?.createElement,Fragment:e?.Fragment},"@fsaos/kernel":n,"@fsaos/react":n,"@fsaos/gateway":n,"@fsaos/ui":r||{}};window.require=function(a){if(s[a])return s[a];throw new Error("[FSAOS] Module not found: "+a)},window.__FSAOS_MOUNT__=n.mount}var y=j(oe(),1),Ic=j(xo(),1),Ac=j(tr(),1);function Tc(e){return`${e}/settings/mounts`}var Fn=null;async function ws(e,t){Fn=Tc(e);try{let s=((await R("read",{path:Fn}))?.item?.type_data?.mounts??[]).map(t).filter(a=>a!==null),i=Qe();return i&&!s.some(a=>a.id===i.id)&&s.unshift(i),Lr(s),s}catch{let n=Qe(),r=n?[n]:[];return Lr(r),r}}async function To(){if(!Fn)return;let e=yt().map(n=>n.id),t=Ze()?.id??null;try{await R("update",{path:Fn,type_data:{mounts:e,last_anchor:t}})}catch{try{let r=Fn.split("/").slice(0,-1).join("/");await R("create",{parent_path:r,name:"mounts",item_type:"file",type_data:{mounts:e,last_anchor:t}})}catch(r){console.warn("[SDK] mount declaration persist failed:",r)}}}async function Ss(e){Ls(e),await To()}async function Io(e){js(e),await To()}function K(){return(0,y.useSyncExternalStore)(tt,be,be)}function Mo(){return K(),Hn()}function ko(e){return K(),F({queryKey:w.item(e),queryFn:()=>or(e),enabled:!!e})}function Fo(e){return K(),F({queryKey:w.itemById(e),queryFn:()=>ir(e),enabled:!!e})}function Es(e){return K(),F({queryKey:w.children(e),queryFn:()=>ar(e),enabled:!!e})}function qo(e){let t=Es(e);return{...t,children:t.data??[]}}function Do(e,t=1){return K(),F({queryKey:w.tree(e,t),queryFn:()=>dr(e,t),enabled:!!e})}function Uo(e,t){return K(),F({queryKey:w.search(e,t),queryFn:async()=>{let n={query:e};t?.length&&(n.item_types=t);let r=await R("search",n);return(r.content?.items||r.items||r.results||[]).map(he)},enabled:!!e&&e.length>0})}function No(e){K();let t=(0,y.useMemo)(()=>e,[JSON.stringify(e)]);return F({queryKey:["vfs",fe()??"__unscoped__","resolve",JSON.stringify(t??{})],queryFn:async()=>await R("resolve",t),enabled:!!t?.query&&t.query.length>0})}function Qo(e){K();let t=(0,y.useMemo)(()=>e,[JSON.stringify(e)]);return F({queryKey:w.items(t?.type??"",t),queryFn:()=>Pn(t),enabled:!!t?.type,select:n=>n.items})}function Ko(e){K();let t=e?.limit??20,n=(0,y.useMemo)(()=>e,[JSON.stringify(e)]),r=Rn({queryKey:["vfs",fe()??"__unscoped__","infinite-items",n?.type??"",JSON.stringify(n??{})],queryFn:async({pageParam:i=0})=>Pn({...n,limit:t,offset:i}),initialPageParam:0,getNextPageParam:(i,a,o)=>{if(!(i.items.length<t))return o+i.items.length},enabled:!!n?.type});return{allItems:(0,y.useMemo)(()=>{if(!r.data?.pages)return[];let i=new Set,a=[];for(let o of r.data.pages)for(let u of o.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 Lo(e){K();let t=20,n=Rn({queryKey:["vfs",fe()??"__unscoped__","infinite-children",e??""],queryFn:async({pageParam:s=0})=>cr(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 o of a.items)o.id&&!s.has(o.id)&&(s.add(o.id),i.push(o));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 jo(e){return K(),F({queryKey:w.edges(e),queryFn:()=>lr(e),enabled:!!e})}function Er(e){return K(),F({queryKey:w.types(e),queryFn:()=>ur(e)})}function Vo(e,t){let n=Er(t);return{...n,data:n.data?.get(e)??void 0}}function Ho(e,t){K();let n=(0,y.useMemo)(()=>t?.arguments,[JSON.stringify(t?.arguments)]),r=t?.mode,s=t?.strategy,i=t?.width;return F({queryKey:[...w.openEnvelope(e,s),i],queryFn:async()=>{let a=await hr(e,{mode:r,strategy:s,arguments:n});if(i&&a.render?.props?.url){let o=a.render.props.url,u=o.includes("?")?"&":"?";a.render.props.url=`${o}${u}w=${i}`}return a},enabled:!!e})}var Ao={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 Wo(e){let t=Er(e),n=t.data??new Map;return(0,y.useMemo)(()=>({canHaveChildren:m=>n.get(m.item_type)?.is_container??!1,isScope:m=>n.get(m.item_type)?.is_scope??!1,isScopeType:m=>n.get(m)?.is_scope??!1,isContainerType:m=>n.get(m)?.is_container??!1,getTypeDefinition:m=>n.get(m),getTypeColor:m=>n.get(m)?.color??"gray",getTypeIcon:m=>n.get(m)?.icon??"File",getTypeDisplayName:m=>n.get(m)?.display_name??m,getKnownEdgeTypes:()=>Object.entries(Ao).map(([m,_])=>({key:m,label:_})),getEdgeTypeLabel:m=>Ao[m]??m.replace(/_/g," "),allTypes:n,loading:t.isLoading}),[n,t.isLoading])}function $o(e,t,n){return K(),F({queryKey:w.memberFocus(e),queryFn:()=>mr(e,t,n),enabled:!!e})}function Bo(e,t={}){let{limit:n=50,offset:r=0,include_snapshots:s=!1}=t;return F({queryKey:w.itemVersions(e,String(n),String(r),String(s)),queryFn:()=>Cn(e,{limit:n,offset:r,include_snapshots:s}),enabled:!!e})}function Go(e,t=50,n=0){return F({queryKey:w.itemHistory(e,String(t),String(n)),queryFn:()=>pr(e,t,n),enabled:!!e})}function zo(e,t=50,n=0){return K(),F({queryKey:w.recentActivity(e,String(t),String(n)),queryFn:()=>fr(e,t,n),enabled:!!e})}function Jo(){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 _t().then(o=>{if(!a){let u=typeof window<"u"&&window.__FSAOS_CONFIG__||{};t({path:o.scope_path,scope_id:o.scope_id,fractal_id:o.fractal_id,instance_name:o.instance_name,display_name:o.display_name,componentPath:u.componentPath||"",isEmbed:!!u.embedToken}),r(!1)}}).catch(o=>{a||(i(o instanceof Error?o:new Error(String(o))),r(!1))}),()=>{a=!0}},[]),{data:e,loading:n,error:s}}var Oc=[];function qn(e){return{id:e.accountId,path:e.path,kind:e.isSpace?"space":"account",name:e.name,grantedUnderAccountId:e.grantedUnderAccountId??void 0}}function Yo(){let{user:e}=Cr(),t=(0,y.useRef)(!1),n=F({queryKey:w.memberships(e?.id??"anonymous"),queryFn:async()=>((await R("list-memberships",{})).memberships||[]).map(f=>({accountId:f.account_id,path:f.account_path,name:f.account_name,role:f.role||"member",typeData:f.account_type_data||{},joinedAt:f.joined_at,via:f.via,placement:f.placement,subordinateTo:f.subordinate_to??null,cascadeAnchorId:f.cascade_anchor_id??null,isAccount:f.is_account??void 0,isSpace:f.is_space??void 0,isOwner:f.is_owner??void 0,billingResponsible:f.billing_responsible??void 0,grantedVia:f.granted_via??null,grantedUnderAccountId:f.granted_under_account_id??null,personalSpaceId:f.personal_space_id??null,personalSpacePath:f.personal_space_path??null})),enabled:!!e?.id,staleTime:1e3*60*2}),r=n.data??Oc,s=(0,y.useMemo)(()=>r.filter(d=>d.isAccount!==!1&&!d.isSpace),[r]),i=(0,y.useMemo)(()=>{let d=new Set(s.map(f=>f.accountId)),p=f=>!f.subordinateTo||!d.has(f.subordinateTo);return[...s].sort((f,m)=>Number(p(m))-Number(p(f)))},[s]),a=(0,y.useSyncExternalStore)(tt,be,be),o=(0,y.useMemo)(()=>{let d=Ze();return d?r.find(p=>p.accountId===d.id)??null:null},[a,r]);(0,y.useEffect)(()=>{if(!e?.id){t.current=!1;return}if(!t.current)if(i.length===1){let d=i[0];on(qn(d)),Mn(d.accountId),d.personalSpacePath&&ws(d.personalSpacePath,p=>{let f=r.find(m=>m.accountId===p);return f?qn(f):null}).catch(()=>{}),t.current=!0}else i.length>1&&(t.current=!0)},[e?.id,i,r]);let u=(0,y.useCallback)(d=>{let p=r.find(m=>m.path===d);if(!p)return;let f=qn(p);Qe()?Ne(f):(on(f),p.personalSpacePath&&ws(p.personalSpacePath,m=>{let _=r.find(h=>h.accountId===m);return _?qn(_):null}).catch(()=>{})),Mn(p.accountId)},[r]),l=(0,y.useCallback)(d=>{let p=r.find(f=>f.path===d);p&&(Ss(qn(p)).catch(()=>{}),kn(d))},[r]);return{accounts:i,allMemberships:r,currentAccount:o,mountedScope:null,switchAccount:u,mountScope:l,loading:n.isLoading,error:n.error}}function Xo(){let e=(0,y.useSyncExternalStore)(jn,cn,cn);return{mounts:(0,y.useMemo)(()=>yt(),[e]),homeAnchor:Qe(),anchor:Ze(),setAnchor:Ne,mount:Ss,unmount:Io}}function Cr(){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)(()=>{k.auth.getSession().then(({data:m,error:_})=>{if(_){console.warn("[useAuth] getSession error, clearing stale session:",_.message),k.auth.signOut().catch(()=>{}),r(null),t(null),i(!1);return}r(m?.session??null),t(m?.session?.user??null),i(!1)}).catch(m=>{console.warn("[useAuth] getSession threw, clearing stale session:",m?.message),k.auth.signOut().catch(()=>{}),r(null),t(null),i(!1)});let{data:{subscription:f}}=k.auth.onAuthStateChange((m,_)=>{if(m==="TOKEN_REFRESHED"&&!_){console.warn("[useAuth] TOKEN_REFRESHED with null session \u2014 signing out"),k.auth.signOut().catch(()=>{}),r(null),t(null),i(!1);return}r(_),t(_?.user??null),i(!1)});return a.current=f,()=>{f?.unsubscribe()}},[]);let o=(0,y.useCallback)(async f=>f.provider?k.auth.signInWithOAuth({provider:f.provider,options:f.redirectTo?{redirectTo:f.redirectTo}:{redirectTo:window.location.href}}):k.auth.signInWithPassword({email:f.email,password:f.password}),[]),u=(0,y.useCallback)(async f=>k.auth.signUp({email:f.email,password:f.password,options:{data:f.metadata||{}}}),[]),l=(0,y.useCallback)(async()=>{await k.auth.signOut(),vt(),P().clear()},[]),d=(0,y.useCallback)(async f=>{let{error:m}=await k.auth.resetPasswordForEmail(f);if(m)throw m},[]),p=(0,y.useCallback)(async(f,m)=>{let{error:_}=await k.auth.signInWithOtp({email:f,options:m?{emailRedirectTo:m}:{emailRedirectTo:window.location.href}});if(_)throw _},[]);return{user:e,session:n,loading:s,signIn:o,signUp:u,signOut:l,resetPassword:d,signInWithMagicLink:p}}function Zo(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),R("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 Dn={},Oo={};Te(()=>{for(let e of Object.keys(Dn))delete Dn[e]});var ea=null;function ta(e){ea=e,typeof window<"u"&&!window.__FSAOS_GATEWAY__&&(window.__FSAOS_GATEWAY__=e)}function Mc(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||Ic;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}:Ac;case"@fsaos/gateway":case"@fsaos/react":return typeof window<"u"&&window.__FSAOS_GATEWAY__||ea||{};case"@fsaos/ui":return typeof window<"u"&&window.__FSAOS_UI__||{};case"@fsaos/theme":return{};default:return console.warn(`[useComponent] Unknown module requested: ${e}`),{}}}function kc(e,t){return e.replace(/^(\s*)(:root|body)(\s*[{,])/gm,(n,r,s,i)=>`${r}.${t}${i}`)}async function Fc(e,t){if(!Oo[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=kc(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),Oo[e]=s}catch{}}function qc(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)(Mc),a=t??i;return a?a.default||a:null}finally{n!==void 0?window.__FSAOS_REGISTER__=n:delete window.__FSAOS_REGISTER__}}function Cs(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 o=!1;s(!0),a(null);let l=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"";return(async()=>{try{let d=1,p=e+"@v1",f=l+e+"/__bundle.js";try{let S=await fetch(l+e+"/__meta",{cache:"no-store"});S.ok&&(d=(await S.json()).version||1,p=e+"@v"+d,f=l+e+"/__bundle.v"+d+".js")}catch{f=l+e+"/__bundle.js?v="+Date.now()}if(o)return;if(Dn[p]){n(()=>Dn[p]),s(!1);return}let m=await fetch(f);if(!m.ok)throw new Error(`Failed to fetch bundle: ${m.status} ${m.statusText} (${f})`);let _=await m.text();if(o)return;let h=f.replace(/__bundle(\.v\d+)?\.js(\?.*)?$/,"__bundle$1.css");Fc(h).catch(()=>{});let g=qc(_);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})`);Dn[p]=g,o||(n(()=>g),s(!1))}catch(d){o||(a(d instanceof Error?d:new Error(String(d))),s(!1))}})(),()=>{o=!0}},[e]),{Component:t,loading:r,error:i}}var Dc=["--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 na(){return{data:(0,y.useMemo)(()=>{if(typeof document>"u")return{tokens:{}};let t={},n=getComputedStyle(document.documentElement);return Dc.forEach(r=>{t[r]=n.getPropertyValue(r).trim()}),{tokens:t}},[]),loading:!1,error:null}}function ra(e,t){return{data:{allowed:!0},loading:!1,error:null}}function sa(e,t){let n={};return(t||[]).forEach(r=>{n[r]=!0}),{data:n,loading:!1,error:null}}var ae=null,Jt=null,Rs=new Set;function Uc(){Rs.forEach(e=>e())}Te(()=>{ae=null,Jt=null});async function ia(e){let t=e;if(!t){let{data:r}=await k.auth.getSession();t=r?.session?.user?.id}let n={principalId:null,displayName:null,createdAt:null,metadata:null,vfsPath:null};if(!t)return n;if(ae&&ae.authUserId===t){let{principalId:r,displayName:s,createdAt:i,metadata:a,vfsPath:o}=ae;return{principalId:r,displayName:s,createdAt:i,metadata:a,vfsPath:o}}return Jt||(Jt=(async()=>{try{let{data:r,error:s}=await k.from("os_principals").select("id, display_name, created_at, metadata").eq("auth_user_id",t).eq("principal_type","user").maybeSingle();if(s)return console.warn("[SDK] Could not resolve principal:",s.message),n;let i=r?.id??null,a=null;if(i){let{data:u}=await k.from("os_items").select("path").eq("owner_principal_id",i).eq("item_type","principal").eq("is_active",!0).like("path","/root/principals/%"),l=(u??[]).map(d=>d.path);a=l.find(d=>d.split("/").length===4)??l[0]??null}let o={principalId:i,displayName:r?.display_name??null,createdAt:r?.created_at??null,metadata:r?.metadata??null,vfsPath:a};return ae={authUserId:t,...o},o}finally{Jt=null}})(),Jt)}async function oa(e){return(await ia(e)).principalId}function aa(){let e=Cr(),t=e.user,n=ae?.authUserId===t?.id?ae:null,[r,s]=(0,y.useState)(n),i=(0,y.useRef)(null);return(0,y.useEffect)(()=>{let a=()=>{let o=ae;o&&o.authUserId===t?.id&&s({principalId:o.principalId,displayName:o.displayName,createdAt:o.createdAt,metadata:o.metadata,vfsPath:o.vfsPath})};return Rs.add(a),()=>{Rs.delete(a)}},[t?.id]),(0,y.useEffect)(()=>{if(!t?.id){s(null),i.current=null;return}i.current===t.id&&r?.principalId!=null||(i.current=t.id,ia(t.id).then(a=>{s(a)}))},[t?.id]),e.loading?{data:null,loading:!0,error:null}:t?{data:{id:t.id,principalId:r?.principalId??null,email:t.email,display_name:r?.displayName??void 0,created_at:r?.createdAt??void 0,vfs_path:r?.vfsPath??void 0,role:t.role||t.app_metadata?.role||"user",authenticated:!0,metadata:r?.metadata??t.user_metadata??{}},loading:!1,error:null}:{data:{id:"anonymous",principalId:null,role:"viewer",authenticated:!1},loading:!1,error:null}}function ca(){return{data:null,loading:!1,error:null}}function ua(e){let{path:t,...n}=e,r=Cs(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 la(e){return e.children}function da(e){let t=K(),{channelPath:n,parentMessageId:r,realtime:s=!0,enabled:i}=e,a=i!==void 0?i&&!!n:!!n,o=(0,y.useMemo)(()=>w.channelMessages(n??"",r),[n,r,t]),u=N(),l=(0,y.useRef)(null),d=F({queryKey:o,queryFn:()=>gr(n,r),enabled:a});(0,y.useEffect)(()=>{if(!s||!a)return;let h=J("vfs_change",()=>{l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{u.invalidateQueries({queryKey:o})},500)},g=>(g.item_type==="message"||g.item_type==="card")&&typeof g.path=="string"&&g.path.startsWith(n));return()=>{h(),l.current&&clearTimeout(l.current)}},[s,a,n,o,u]);let p=d.data,f=p?.messages??[],m=p?.messageCards??new Map,_=p?.siblingCards??[];return{messages:f,messageCards:m,siblingCards:_,threads:(0,y.useMemo)(()=>f.filter(h=>h.reply_count>0),[f]),isLoading:d.isLoading,isFetching:d.isFetching,error:d.error,refetch:d.refetch}}function fa(e){K();let{channelPath:t,parentMessageId:n,limit:r=50,realtime:s=!0,enabled:i=!0}=e,a=!!n,o=i&&!!t,u=Rn({queryKey:[...w.channelMessages(t||"",n),"infinite",r],queryFn:async({pageParam:h})=>xn(t,{parentMessageId:n,limit:r,before_seq:a?void 0:h,after_seq:a?h:void 0}),initialPageParam:void 0,getNextPageParam:h=>!a||h.messages.length<r?void 0:h.messages[h.messages.length-1]?.seq,getPreviousPageParam:h=>a||h.messages.length<r?void 0:h.messages[0]?.seq,enabled:o}),l=(0,y.useMemo)(()=>{if(!u.data?.pages)return[];let h=new Set,g=[];for(let S of u.data.pages)for(let E of S.messages)h.has(E.id)||(h.add(E.id),g.push(E));return g.sort((S,E)=>S.seq-E.seq)},[u.data?.pages]),{messageCards:d,siblingCards:p}=(0,y.useMemo)(()=>{let h=new Map,g=[];if(!u.data?.pages)return{messageCards:h,siblingCards:g};let S=new Set;for(let E of u.data.pages){for(let[x,U]of E.messageCards)for(let L of U){if(S.has(L.id))continue;S.add(L.id);let $=h.get(x)||[];$.push(L),h.set(x,$)}for(let x of E.siblingCards)S.has(x.id)||(S.add(x.id),g.push(x))}return{messageCards:h,siblingCards:g}},[u.data?.pages]),f=N(),m=(0,y.useRef)(null),_=(0,y.useMemo)(()=>[...w.channelMessages(t||"",n),"infinite",r],[t,n,r]);return(0,y.useEffect)(()=>{if(!s||!t||!o)return;let h=J("vfs_change",()=>{m.current&&clearTimeout(m.current),m.current=setTimeout(async()=>{let g=f.getQueryData(_);if(!g?.pages?.length){f.invalidateQueries({queryKey:_});return}let S=0;for(let E of g.pages)for(let x of E.messages)x.seq>S&&(S=x.seq);if(S===0){f.invalidateQueries({queryKey:_});return}try{let E=await xn(t,{parentMessageId:n,limit:r,after_seq:S});if(E.messages.length===0&&E.siblingCards.length===0){f.invalidateQueries({queryKey:_});return}if(E.messages.length>0){let x=Math.min(...E.messages.map(U=>U.seq));if(x>S+1){console.warn(`[useInfiniteChannelMessages] sequence gap detected: maxSeq=${S}, minNewSeq=${x}. Triggering full refetch.`),f.invalidateQueries({queryKey:_});return}}f.setQueryData(_,x=>{if(!x)return x;let U=[...x.pages],L=U.length-1,$=U[L],pt=new Set($.messages.map(I=>I.id)),re=E.messages.filter(I=>!pt.has(I.id)),Q=[...$.messages,...re].sort((I,Xe)=>I.seq-Xe.seq),Y=new Map($.messageCards);for(let[I,Xe]of E.messageCards){let B=Y.get(I)||[],Yt=new Set(B.map(Ir=>Ir.id)),Ua=Xe.filter(Ir=>!Yt.has(Ir.id));Y.set(I,[...B,...Ua])}let ye=new Set($.siblingCards.map(I=>I.id)),_e=E.siblingCards.filter(I=>!ye.has(I.id)),ve=[...$.siblingCards,..._e];return U[L]={...$,messages:Q,messageCards:Y,siblingCards:ve},{...x,pages:U}})}catch(E){console.warn("[useInfiniteChannelMessages] live tail fetch failed, falling back to full invalidation:",E),f.invalidateQueries({queryKey:_})}},500)},g=>(g.item_type==="message"||g.item_type==="card")&&typeof g.path=="string"&&g.path.startsWith(t));return()=>{h(),m.current&&clearTimeout(m.current)}},[s,t,o,_,f,n,r]),{messages:l,messageCards:d,siblingCards:p,threads:l.filter(h=>h.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 Nc(e){return e==="on"||e==="auto"?"on":"off"}function Qc(e){let t=e.type_data||{},n=e._reader||{},r=n.context_lineage||{};return{id:e.id||"",path:e.path||"",name:e.name||"",displayName:t.display_name||e.name||"",aiMode:Nc(t.ai_mode),isPrivate:t.is_private||!1,isDm:t.is_dm||!1,messageCount:t.message_count||0,updatedAt:e.updated_at||"",chatScopePath:r.context_path||"",contextId:e.scope_item_id||"",contextPath:r.context_path||"",contextType:r.context_type||"",contextName:r.context_name||"",contextDisplayName:r.context_name||"",contextPrincipalId:void 0,accountId:e.account_item_id||"",accountPath:"",accountDisplayName:"",memberRole:n.member_role||"member",memberPath:"",modePath:"",autoPilot:t.auto_pilot||!1}}function Pr(e={}){let t=K(),{realtime:n=!0,enabled:r=!0}=e,s=N(),i=(0,y.useRef)(null),a=(0,y.useMemo)(()=>w.channels("all"),[t]),o=F({queryKey:a,queryFn:async()=>((await R("query",{item_type:"channel",include_reader:!0,limit:500})).items||[]).map(Qc),enabled:r});return(0,y.useEffect)(()=>{if(!n||!r)return;let l=J("vfs_change",()=>{i.current&&clearTimeout(i.current),i.current=setTimeout(()=>{s.invalidateQueries({queryKey:a})},1e3)},p=>p.item_type==="channel"||p.item_type==="message"),d=J("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(),d(),i.current&&clearTimeout(i.current)}},[n,r,a,s]),{channels:o.data??[],isLoading:o.isLoading,isFetching:o.isFetching,error:o.error,refetch:o.refetch}}function pa(e={}){let t=Pr(e),n=(0,y.useMemo)(()=>t.channels.filter(r=>!r.isDm),[t.channels]);return{...t,channels:n}}function ma(e={}){let t=Pr(e),n=(0,y.useMemo)(()=>t.channels.filter(r=>r.isDm),[t.channels]);return{...t,channels:n}}function Ps(e={}){let t=K(),{filter:n="all",limit:r=200,realtime:s=!0,enabled:i=!0}=e,a=N(),o=(0,y.useRef)(null),u=(0,y.useMemo)(()=>w.notifications(n,r),[n,r,t]),l=F({queryKey:u,queryFn:async()=>{let p={limit:r};return n==="unread"&&(p.filter="unread"),(await R("get-notifications",p)).notifications||[]},enabled:i});return(0,y.useEffect)(()=>{if(!s||!i)return;let p=["vfs_change","ccm_change"].map(f=>J(f,()=>{o.current&&clearTimeout(o.current),o.current=setTimeout(()=>{a.invalidateQueries({queryKey:u})},2e3)},m=>m.item_type==="notification"||m.item_type==="message"));return()=>{p.forEach(f=>f()),o.current&&clearTimeout(o.current)}},[s,i,u,a]),{notifications:l.data??[],isLoading:l.isLoading,isFetching:l.isFetching,error:l.error,refetch:l.refetch}}function ha(e={}){let{channels:t,realtime:n=!0,enabled:r=!0}=e,{notifications:s,isLoading:i,isFetching:a,error:o,refetch:u}=Ps({filter:"unread",limit:200,realtime:n,enabled:r}),l=(0,y.useMemo)(()=>{let m=new Map;for(let _ of s)_.is_unread&&_.channel_id&&m.set(_.channel_id,(m.get(_.channel_id)||0)+1);return m},[s]),d=(0,y.useMemo)(()=>{let m=0;return l.forEach(_=>{m+=_}),m},[l]),{dmUnread:p,channelUnread:f}=(0,y.useMemo)(()=>{if(!t)return{dmUnread:0,channelUnread:0};let m=new Set(t.filter(g=>g.isDm).map(g=>g.id)),_=0,h=0;return l.forEach((g,S)=>{m.has(S)?_+=g:h+=g}),{dmUnread:_,channelUnread:h}},[t,l]);return{unreadByChannel:l,totalUnread:d,dmUnread:p,channelUnread:f,isLoading:i,isFetching:a,error:o,refetch:u}}function ga(){let e=N();return De({mutationFn:t=>R("create",t),onSuccess:(t,n)=>{let r=n.parent_path;r&&e.invalidateQueries({queryKey:w.children(r)})}})}function ya(){let e=N();return De({mutationFn:t=>R("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 _a(){return De({mutationFn:e=>R("update-principal",e),onSuccess:(e,t)=>{if(!ae)return;let n=e&&typeof e=="object"&&e.metadata?e.metadata:{...ae.metadata??{},...typeof t.language=="string"?{language:t.language}:{},...typeof t.timezone=="string"?{timezone:t.timezone}:{},..."avatar_file_id"in t?{avatar_file_id:t.avatar_file_id}:{}};ae={...ae,displayName:typeof t.display_name=="string"?t.display_name:ae.displayName,metadata:n},Uc()}})}function va(){let e=N();return De({mutationFn:t=>R("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 ba(){let e=N();return De({mutationFn:t=>R("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 wa(){let e=N();return De({mutationFn:t=>R("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 Sa(e,t){let n=N(),{optimistic:r,...s}=t??{};return De({mutationFn:i=>R(e,i),onMutate:r?async i=>{await n.cancelQueries({queryKey:r.queryKey});let a=n.getQueryData(r.queryKey);return n.setQueryData(r.queryKey,o=>r.update(o,i)),{previous:a}}:void 0,onError:(i,a,o)=>{r&&o?.previous!==void 0&&n.setQueryData(r.queryKey,o.previous),s.onError?.(i)},onSuccess:s.onSuccess,onSettled:r?()=>{n.invalidateQueries({queryKey:r.queryKey})}:void 0})}function Ra(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 o=(0,y.useRef)(s),u=(0,y.useRef)(i);(0,y.useEffect)(()=>{o.current=s,u.current=i},[s,i]),(0,y.useEffect)(()=>a?J(r,d=>o.current(d),u.current?d=>u.current(d):void 0):void 0,[r,a])}function Ea(e){let{queryKey:t,queryFn:n,eventType:r,filter:s,enabled:i=!0,debounceMs:a=500}=e,o=N(),u=(0,y.useRef)(null),l=F({queryKey:t,queryFn:n,enabled:i});return(0,y.useEffect)(()=>{if(!i)return;let d=J(r,()=>{u.current&&clearTimeout(u.current),u.current=setTimeout(()=>{o.invalidateQueries({queryKey:t})},a)},s);return()=>{d(),u.current&&clearTimeout(u.current)}},[r,i,a,o,JSON.stringify(t)]),l}function Ca(e){K();let t=(0,y.useMemo)(()=>e?typeof e=="string"?{path:e}:e:null,[typeof e=="string"?e:JSON.stringify(e)]),n=!!t&&!!(t.key||t.path||t.item_id),r=t?.key??t?.path??t?.item_id??"",s=F({queryKey:["vfs",fe()??"__unscoped__","arrangement",r],queryFn:async()=>{if(!t)return null;let d=await R("resolve-arrangement",t);return d?.success===!1?(console.warn("[useArrangement] resolve-arrangement failed:",d?.error),null):d??null},enabled:n}),i=s.data??null,a=(0,y.useMemo)(()=>i?.resolved_children??[],[i]),o=i?.resolution_level??null,u=(0,y.useMemo)(()=>{let p=(i?.type_data??null)?.order;return Array.isArray(p)?p:null},[i]),l=(0,y.useCallback)(d=>{if(!u||!d?.length)return d??[];let p=h=>h.id??h.name??"",f=new Map(u.map((h,g)=>[h,g])),m=[],_=[];for(let h of d)(f.has(p(h))?m:_).push(h);return m.sort((h,g)=>f.get(p(h))-f.get(p(g))),[...m,..._]},[u]);return{...s,arrangement:i,resolvedChildren:a,resolutionLevel:o,order:u,sourceScopeId:i?.scope_item_id??null,applyTo:l}}function Kc(e){return e.split("_").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function Lc(e,t){return t&&t.length>0?"select":e==="boolean"?"toggle":e==="integer"||e==="number"?"range":e==="string"?"text":"none"}function jc(e,t){return!(e==="object"||e==="array")}function Vc(e){return["string","number","integer","boolean"].includes(e)}function Hc(e){return e!=="object"&&e!=="array"}function Pa(e,t,n,r){let s=e?.properties;if(!s||typeof s!="object")return[];let i=[];for(let[a,o]of Object.entries(s)){let u=o.type||"string",l=o.enum,d=jc(u,l),p=Vc(u),f=Lc(u,l);i.push({key:a,label:o.title||Kc(a),type:u,description:o.description,enum_values:l,default_value:n[a]??r[a]??o.default,editable:t,filterable:d,sortable:p,filter_widget:f})}return i}function xs(e){let t=e.default_data||{},n=e.field_defaults||{},r=Pa(e.input_schema,!0,t,n),s=Pa(e.system_schema,!1,t,n),i=[...r,...s],a=i.filter(l=>Hc(l.type)),o=i.filter(l=>l.filterable),u=i.filter(l=>l.sortable);return{fields:i,columns:a,filterable:o,sortable:u,form_fields:r,system_fields:s}}function xa(e){return{field:"updated_at",direction:"desc"}}function Ta(e){let t=xs(e),n=new Set(e.input_schema?.required||[]);return t.form_fields.filter(r=>n.has(r.key)||r.default_value===void 0)}var ne=j(oe(),1);var Wc=0;function $c(){return`upload_${Date.now()}_${++Wc}`}async function Ia(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",o={parent_path:t.parentPath,item_type:a,name:s,type_data:{...t.typeData||{},file_source:{type:"upload",content_type:i}}};t.cardParentPath&&(o.card_parent_path=t.cardParentPath);let l=await R("create",o);if(!l.id)throw new Error(l.error||l.message||"Failed to create file item");let d=l.id,p=l.path;if(l.storage_completed&&l.file_ref)return{itemId:d,itemPath:p,fileRef:l.file_ref};let f=l.storage_key,m=l.upload_token,_=l.storage_worker_url||"https://fsaos-storage.radns.workers.dev";if(!f)throw new Error("Gateway returned no storage_key \u2014 file_source may not be supported for this item type");await Bc(_,f,m,e,i,n,r);let h=await Aa(d,f,i);return{itemId:d,itemPath:p,fileRef:h}}function Bc(e,t,n,r,s,i,a){return new Promise((o,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=d=>{d.lengthComputable&&i&&i(Math.round(d.loaded/d.total*100))},l.onload=()=>{l.status>=200&&l.status<300?o():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 Aa(e,t,n){let r=await xe(),s=await fetch(`${ce}/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 Oa(){let[e,t]=(0,ne.useState)([]),n=N(),r=(0,ne.useRef)(e);r.current=e;let s=(0,ne.useCallback)((h,g)=>{t(S=>S.map(E=>E.id===h?{...E,...g}:E))},[]),i=(0,ne.useCallback)(h=>{t(g=>[...g,h])},[]),a=(0,ne.useCallback)(async(h,g,S,E,x)=>{let U=S.name||g.name,L=g.type||"application/octet-stream",$=S.itemType||"file",pt=x?.itemId||null,re=x?.itemPath||null,Q=x?.storageKey||null,Y=x?.uploadToken||null,ye=x?.storageWorkerUrl||null;try{if(!E||E==="create"){s(h,{status:"creating",error:null,_failedAt:null});let I=await R("create",{parent_path:S.parentPath,item_type:$,name:U,type_data:{...S.typeData||{},file_source:{type:"upload",content_type:L}}});if(!I.id)throw Object.assign(new Error(I.error||I.message||"Failed to create file item"),{_step:"create"});if(pt=I.id,re=I.path,s(h,{itemId:pt,itemPath:re}),I.storage_completed&&I.file_ref){s(h,{status:"complete",progress:100,fileRef:I.file_ref}),n.invalidateQueries({queryKey:w.children(S.parentPath)});return}if(Q=I.storage_key,Y=I.upload_token||"",ye=I.storage_worker_url||"https://fsaos-storage.radns.workers.dev",s(h,{_storageKey:Q,_uploadToken:Y,_storageWorkerUrl:ye}),!Q)throw Object.assign(new Error("Gateway returned no storage_key"),{_step:"create"})}(!E||E==="create"||E==="upload")&&(s(h,{status:"uploading",progress:0,error:null,_failedAt:null}),await new Promise((I,Xe)=>{let B=new XMLHttpRequest;s(h,{_xhr:B}),B.open("PUT",`${ye}/upload`),B.setRequestHeader("X-Storage-Key",Q),B.setRequestHeader("Content-Type",L),Y&&B.setRequestHeader("X-Upload-Token",Y),B.upload.onprogress=Yt=>{Yt.lengthComputable&&s(h,{progress:Math.round(Yt.loaded/Yt.total*100)})},B.onload=()=>{B.status>=200&&B.status<300?I():Xe(Object.assign(new Error(`Storage upload failed: HTTP ${B.status}`),{_step:"upload"}))},B.onerror=()=>Xe(Object.assign(new Error("Storage upload network error"),{_step:"upload"})),B.ontimeout=()=>Xe(Object.assign(new Error("Storage upload timed out"),{_step:"upload"})),B.send(g)}),s(h,{progress:100,_xhr:null})),s(h,{status:"confirming",error:null,_failedAt:null});let _e=await Aa(pt,Q,L);s(h,{status:"complete",fileRef:_e}),n.invalidateQueries({queryKey:w.children(S.parentPath)})}catch(_e){let ve=_e?.message||String(_e),I=_e?._step||"create";s(h,{status:"error",error:ve,_failedAt:I,_xhr:null})}},[s,n]),o=(0,ne.useCallback)((h,g)=>{let S=$c();i({id:S,file:h,status:"creating",progress:0,error:null,itemId:null,itemPath:null,fileRef:null,options:g,_storageKey:null,_uploadToken:null,_storageWorkerUrl:null,_xhr:null,_failedAt:null}),a(S,h,g)},[i,a]),u=(0,ne.useCallback)((h,g)=>{for(let S of h)o(S,g)},[o]),l=(0,ne.useCallback)(h=>{let g=r.current.find(x=>x.id===h);if(!g||g.status!=="error")return;let S=g._failedAt||"create",E=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(h,g.file,g.options,S,E)},[a]),d=(0,ne.useCallback)(h=>{let g=r.current.find(S=>S.id===h);g&&(g._xhr&&g._xhr.abort(),s(h,{status:"error",error:"Cancelled",_xhr:null,_failedAt:null}))},[s]),p=(0,ne.useCallback)(h=>{t(g=>g.filter(S=>S.id!==h))},[]),f=(0,ne.useCallback)(()=>{t(h=>h.filter(g=>g.status!=="complete"))},[]),m=e.some(h=>h.status==="creating"||h.status==="uploading"||h.status==="confirming"),_=e.map(({_storageKey:h,_uploadToken:g,_storageWorkerUrl:S,_xhr:E,_failedAt:x,...U})=>U);return{upload:o,uploadMultiple:u,uploads:_,retryUpload:l,cancelUpload:d,removeUpload:p,clearCompleted:f,isUploading:m}}var Ma=j(oe(),1);async function Ts(e,t){return await R("resolve-items",{context_id:e,item_type:t})}function ka(e,t){return(0,Ma.useSyncExternalStore)(tt,be,be),F({queryKey:["vfs",fe()??"__unscoped__","resolved-items",e??"",t],queryFn:()=>Ts(e,t),enabled:!!(e&&t)})}var ge=j(oe(),1);function xr(e,t){let n={artifacts:new Map,timeline:[]},r=new Map;function s(a){if(!a.action?.startsWith("artifact_"))return;let u,l=a.name;if(typeof l=="string"&&l.startsWith("{"))try{u=JSON.parse(l)}catch{return}else if(a.artifact_id)u=a;else return;switch(u.type){case"artifact_opened":{let d=Date.now();if(n.artifacts.set(u.artifact_id,{artifact_id:u.artifact_id,surface_type:u.surface_type,tool_id:u.tool_id,tool_name:u.tool_name,target_uri:u.target_uri,status:"streaming",content:"",total_chars:0,delta_count:0,artifact_item_uri:null,evidence_uri:null,meta:u.meta,started_at:d,completed_at:null}),r.has(u.tool_id)){let p=r.get(u.tool_id);n.timeline[p].artifact_ids.push(u.artifact_id)}else{let p=n.timeline.length;n.timeline.push({tool_id:u.tool_id,tool_name:u.tool_name,status:"started",target_uri:u.target_uri,started_at:d,completed_at:null,artifact_ids:[u.artifact_id]}),r.set(u.tool_id,p)}break}case"artifact_delta":{let d=n.artifacts.get(u.artifact_id);d&&(d.content+=u.content_delta,d.total_chars+=u.content_delta.length,d.delta_count+=1,u.target_uri&&!d.target_uri&&(d.target_uri=u.target_uri));break}case"artifact_done":{let d=n.artifacts.get(u.artifact_id);d&&(d.status=u.status,d.total_chars=u.total_chars,d.artifact_item_uri=u.artifact_item_uri,d.evidence_uri=u.evidence_uri,u.target_uri&&(d.target_uri=u.target_uri),(u.status==="completed"||u.status==="failed")&&(d.completed_at=Date.now()));let p=r.get(u.tool_id);if(p!==void 0){let f=n.timeline[p];u.status==="executing"?f.status="executing":u.status==="completed"?(f.status="completed",f.completed_at=Date.now()):u.status==="failed"&&(f.status="failed",f.completed_at=Date.now()),u.target_uri&&!f.target_uri&&(f.target_uri=u.target_uri)}break}}t(n)}return vr(e,s)}function Fa(e,t=!0){let[n,r]=(0,ge.useState)(new Map),[s,i]=(0,ge.useState)([]),a=(0,ge.useRef)({artifacts:new Map,timeline:[]});(0,ge.useEffect)(()=>!e||!t?void 0:xr(e,p=>{a.current=p,r(new Map(p.artifacts)),i([...p.timeline])}),[e,t]);let o=(0,ge.useCallback)(()=>{r(new Map),i([]),a.current={artifacts:new Map,timeline:[]}},[]),u=Array.from(n.values()).find(d=>d.surface_type==="file_editor"&&d.status==="streaming")??null,l=Array.from(n.values()).filter(d=>d.surface_type==="activity"&&(d.status==="streaming"||d.status==="executing"));return{artifacts:n,timeline:s,activeEditor:u,activeActivities:l,reset:o}}function qa(e,t=!0){let[n,r]=(0,ge.useState)([]);(0,ge.useEffect)(()=>!e||!t?void 0:xr(e,a=>{r([...a.timeline])}),[e,t]);let s=n.length>0?n[n.length-1]:null;return{timeline:n,latestActivity:s}}var Tr=j(oe(),1);function Gc(e,t,n,r){return["vfs","timeline-history",e,t??"__all__",n??500,r??0]}async function Is(e,t){let n=`${e}/datasets/agent-events`,r=t?.limit??500,s=t?.offset??0,i={limit:r,offset:s,sort:[{key:"seq",direction:"asc"}]};t?.turnId&&(i.filters=[{key:"turn_id",operator:"eq",value:t.turnId}]);try{let o=(await R("open",{path:n,mode:"extract",strategy:"rows",arguments:i}))?.content;return o?(o.rows??o.items??o.data??[]).map(zc).sort((l,d)=>l.seq-d.seq):[]}catch(a){if(a?.status===404||a?.message?.includes("not found"))return[];throw a}}function Da(e,t){let{turnId:n,limit:r=500,offset:s=0,enabled:i=!0,debounceMs:a=300}=t??{},o=e?`${e}/datasets/agent-events`:null,u=N(),l=(0,Tr.useRef)(null),d=o?Gc(o,n,r,s):["vfs","timeline-history","__disabled__"],p=F({queryKey:d,queryFn:()=>Is(e,{turnId:n,limit:r,offset:s}),enabled:!!e&&i});return(0,Tr.useEffect)(()=>{if(!o||!i)return;let f=J("vfs_change",()=>{l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{u.invalidateQueries({queryKey:d})},a)},m=>{let _=m?.path;return _?_===o||_.startsWith(o+"/"):!1});return()=>{f(),l.current&&clearTimeout(l.current)}},[o,i,a,u,JSON.stringify(d)]),{events:p.data??[],isLoading:p.isLoading,error:p.error,isFetching:p.isFetching,refetch:()=>{p.refetch()}}}function zc(e){return{turn_id:String(e.turn_id??""),seq:Number(e.seq??0),kind:String(e.kind??""),status:String(e.status??""),title:String(e.title??""),tool_name:e.tool_name!=null?String(e.tool_name):void 0,tool_id:e.tool_id!=null?String(e.tool_id):void 0,evidence_uri:e.evidence_uri!=null?String(e.evidence_uri):void 0,artifact_item_uri:e.artifact_item_uri!=null?String(e.artifact_item_uri):void 0,preview:e.preview!=null?String(e.preview):void 0,duration_ms:e.duration_ms!=null?Number(e.duration_ms):void 0,started_at:String(e.started_at??""),completed_at:e.completed_at!=null?String(e.completed_at):void 0,error_type:e.error_type!=null?String(e.error_type):void 0,meta:e.meta!=null?e.meta:void 0}}ta(As);return Wa(As);})();
1
+ /* @fsaos/gateway v2.0.0 — Unified FSAOS Edge Runtime — 2026-08-27T18:10:22.746Z */
2
+ "use strict";var __FSAOS_GATEWAY__=(()=>{var Ka=Object.create;var Xt=Object.defineProperty;var La=Object.getOwnPropertyDescriptor;var ja=Object.getOwnPropertyNames;var Va=Object.getPrototypeOf,Ha=Object.prototype.hasOwnProperty;var Ms=e=>{throw TypeError(e)};var Wa=(e,t,n)=>t in e?Xt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Zt=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),$a=(e,t)=>{for(var n in t)Xt(e,n,{get:t[n],enumerable:!0})},ks=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of ja(t))!Ha.call(e,s)&&s!==n&&Xt(e,s,{get:()=>t[s],enumerable:!(r=La(t,s))||r.enumerable});return e};var j=(e,t,n)=>(n=e!=null?Ka(Va(e)):{},ks(t||!e||!e.__esModule?Xt(n,"default",{value:e,enumerable:!0}):n,e)),Ba=e=>ks(Xt({},"__esModule",{value:!0}),e);var se=(e,t,n)=>Wa(e,typeof t!="symbol"?t+"":t,n),kr=(e,t,n)=>t.has(e)||Ms("Cannot "+n);var u=(e,t,n)=>(kr(e,t,"read from private field"),n?n.call(e):t.get(e)),b=(e,t,n)=>t.has(e)?Ms("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),v=(e,t,n,r)=>(kr(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n),P=(e,t,n)=>(kr(e,t,"access private method"),n);var en=(e,t,n,r)=>({set _(s){v(e,t,s,n)},get _(){return u(e,t,r)}});var qs=Zt((nu,Fs)=>{Fs.exports={createClient:window.supabase.createClient}});var oe=Zt((_d,Fi)=>{Fi.exports=React});var sr=Zt((vd,qi)=>{qi.exports={jsx:React.createElement,jsxs:React.createElement,Fragment:React.Fragment}});var mo=Zt((hf,ho)=>{ho.exports=ReactDOM});var Io=Zt((wf,To)=>{To.exports=ReactDOM});var Os={};$a(Os,{ComponentRenderer:()=>da,EnforcementDeniedError:()=>mt,FormSubmissionError:()=>Rt,InteractionTrackingError:()=>wt,KernelProvider:()=>fa,QueryClientProvider:()=>Cn,auth:()=>Po,awaitAnchorReady:()=>an,awaitScopeReady:()=>$s,callTool:()=>So,clearCachedToken:()=>Ur,clearSession:()=>Hr,createItem:()=>vo,disconnectSSE:()=>bs,disposeVfsRealtimeWs:()=>Er,electHomeAnchor:()=>cn,emitEvent:()=>uo,fetchChannelMessages:()=>Xi,fetchChannelMessagesPage:()=>An,fetchChannelMessagesWithCards:()=>vr,fetchEdgesForItem:()=>pr,fetchItemHistory:()=>gr,fetchItemVersions:()=>Tn,fetchItems:()=>In,fetchMemberFocus:()=>yr,fetchOpenEnvelope:()=>_r,fetchRecentActivity:()=>mr,fetchResolvedItems:()=>Is,fetchTimelineHistory:()=>As,fetchTypeDefinitions:()=>fr,fetchVfsChildren:()=>lr,fetchVfsChildrenPage:()=>dr,fetchVfsItem:()=>ur,fetchVfsItemById:()=>cr,fetchVfsTree:()=>hr,gatewayCall:()=>R,getAccessToken:()=>xe,getAnchor:()=>on,getAnchorRef:()=>Ze,getAnchorVersion:()=>Kr,getAssetUrl:()=>Co,getDefaultSort:()=>Ia,getHomeAnchor:()=>Qe,getMountVersion:()=>ln,getMounts:()=>_t,getQueryClient:()=>E,getRequiredFormFields:()=>Aa,getScope:()=>fe,getScopeVersion:()=>be,getSessionEntry:()=>$n,initSession:()=>vt,initVfsRealtimeWs:()=>qn,initializeFsaos:()=>Zs,interpretSchema:()=>Ts,invalidateAllVfs:()=>to,invalidateChannelMessages:()=>ro,invalidateChildren:()=>ar,invalidateItem:()=>_s,invalidateOpenEnvelope:()=>so,invalidatePathAndParent:()=>Zi,invalidateSubtree:()=>eo,invalidateTypes:()=>no,isAnchorReady:()=>jr,isScopeReady:()=>Bn,listChildren:()=>_o,mount:()=>Eo,mountRealtimeScope:()=>Dn,normalizeItem:()=>me,ping:()=>lo,pushChanges:()=>wo,queryClient:()=>Gi,readItem:()=>yo,registerCleanup:()=>Te,resetAllSdkState:()=>bt,resolvePrincipalId:()=>ca,setAnchor:()=>Ne,setCachedToken:()=>Ns,setQueryClient:()=>Bi,setScope:()=>Ws,setupRequireShim:()=>xo,signal:()=>Ro,startTracking:()=>Gn,submitForm:()=>ei,subscribeAnchor:()=>Lr,subscribeArtifactStream:()=>Ar,subscribeMounts:()=>Wn,subscribeScope:()=>tt,subscribeToEvents:()=>J,subscribeToPath:()=>Sr,subscribeToScope:()=>Rr,trackAction:()=>Ys,trackEvent:()=>nt,trackPageView:()=>Js,unmountRealtimeScope:()=>po,updateItem:()=>bo,uploadFile:()=>Oa,useAccounts:()=>Zo,useAgentTimeline:()=>Ua,useAllChannels:()=>Ir,useArrangement:()=>xa,useArtifactStream:()=>Da,useAsset:()=>ta,useAuth:()=>Tr,useChannelMessages:()=>pa,useChannels:()=>ma,useChildren:()=>Uo,useComponent:()=>Es,useCreate:()=>_a,useDelete:()=>wa,useDmChannels:()=>ga,useEdges:()=>Ho,useEventStream:()=>Pa,useFileUpload:()=>ka,useInfiniteChannelMessages:()=>ha,useInfiniteChildren:()=>Vo,useInfiniteItems:()=>jo,useItem:()=>qo,useItemById:()=>Do,useItemHistory:()=>Jo,useItemVersions:()=>zo,useItems:()=>Lo,useLink:()=>Ra,useList:()=>Ps,useMemberFocus:()=>Go,useMounts:()=>ea,useMove:()=>Sa,useMutation:()=>Ca,useNotifications:()=>xs,useOpen:()=>$o,usePermission:()=>ia,usePermissions:()=>oa,usePrincipal:()=>ua,useRealtimeQuery:()=>Ea,useRecentActivity:()=>Yo,useResolve:()=>Ko,useResolvedItems:()=>qa,useScope:()=>Xo,useScopeReady:()=>Fo,useSearch:()=>Qo,useTheme:()=>sa,useTimelineHistory:()=>Na,useTool:()=>la,useTree:()=>No,useType:()=>Wo,useTypeHelpers:()=>Bo,useTypes:()=>xr,useUnreadCounts:()=>ya,useUpdate:()=>va,useUpdatePrincipal:()=>ba,vfsKeys:()=>w});var mt=class e extends Error{constructor(n){let r=n.message||e.fallbackMessage(n);super(r);se(this,"name","EnforcementDeniedError");se(this,"deniedBy");se(this,"ruleKey");se(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 Ds=j(qs(),1),tn=typeof window<"u"&&window.__FSAOS_CONFIG__||{},nn=Array.isArray(tn.sources)?tn.sources:[],Ga=tn.supabaseUrl||"https://vahbmsslxuustnlvsrkg.supabase.co",za=tn.supabaseAnonKey||"sb_publishable_ZjosozAjfpZ4InMNElTr6Q_hHB-f5nc",ce=tn.gatewayUrl||"https://fsaos-mcp-gw-rust.fly.dev",k=(0,Ds.createClient)(Ga,za,{auth:{persistSession:!0,autoRefreshToken:!0,detectSessionInUrl:!1}});var sn=null,Kn=0,Us,Dr,Ln=!1;Us=new Promise(e=>{Dr=e});k.auth.onAuthStateChange((e,t)=>{t?.access_token?(sn=t.access_token,Kn=t.expires_at??Math.floor(Date.now()/1e3)+3600):(sn=null,Kn=0),Ln||(Ln=!0,Dr())});setTimeout(()=>{Ln||(Ln=!0,Dr())},5e3);function Ns(e,t){sn=e,Kn=t??Math.floor(Date.now()/1e3)+3600}function Ur(){sn=null,Kn=0}async function xe(){let e=typeof window<"u"&&window.__FSAOS_CONFIG__||{};if(e.embedToken){if(typeof e.embedToken=="function")try{return await e.embedToken()??null}catch{return null}return e.embedToken}return await Us,sn}var jn=null,Hn=null,Qs=0,Fr=new Set,Nr,Qr,Vn=!1;Nr=new Promise(e=>{Qr=e});function Ks(){Qs++,Fr.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Anchor listener error:",t)}})}function Ne(e){let t=typeof e=="string"?e:e.path,n=jn!==t;jn=t,Hn=typeof e=="string"?null:e,typeof e!="string"&&!ue.some(r=>r.id===e.id)&&(ue=[...ue,e],un()),Vn||(Vn=!0,Qr()),n&&Ks()}function on(){return jn}function Ze(){return Hn}function Kr(){return Qs}function Lr(e){return Fr.add(e),()=>{Fr.delete(e)}}function an(){return Nr}function jr(){return Vn}var yt=null;function cn(e){if(yt){console.warn("[SDK] electHomeAnchor called twice; ignoring (logout to re-elect).");return}yt=e,Ne(e)}function Qe(){return yt}var ue=[],qr=new Set,Ls=0;function un(){Ls++,qr.forEach(e=>{try{e()}catch(t){console.warn("[SDK] Mount listener error:",t)}})}function _t(){return ue}function ln(){return Ls}function Wn(e){return qr.add(e),()=>{qr.delete(e)}}function Vr(e){ue=e,un()}function js(e){ue.some(t=>t.id===e.id)||(ue=[...ue,e],un())}function Vs(e){ue.find(n=>n.id===e)&&(ue=ue.filter(n=>n.id!==e),un(),Hn?.id===e&&yt&&Ne(yt))}var gt=null,rn=null;async function vt(){return gt||rn||(rn=(async()=>{let e=et(),t=await xe(),n={};t&&(n.Authorization=`Bearer ${t}`);let r=await fetch(`${ce}/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 gt={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},gt})(),rn)}function $n(){return gt}function Hr(){gt=null,rn=null,jn=null,Hn=null,yt=null,ue=[]}var Hs=[];function Te(e){Hs.push(e)}function bt(){Hr(),Ur(),Vn=!1,Nr=new Promise(e=>{Qr=e}),Ks(),un();for(let e of Hs)try{e()}catch(t){console.warn("[SDK] Cleanup function failed:",t)}}function et(){if(typeof window<"u"){let e=window.__FSAOS_CONFIG__;return e?.hostname?e.hostname:window.location.hostname}return"localhost"}var Ws=Ne,fe=on,be=Kr,tt=Lr,$s=an,Bn=jr;var Wr=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,Ja=/^[A-Za-z_:][A-Za-z0-9_:.-]{0,127}$/,Bs=new Map,Gs=new Map,wt=class extends Error{constructor(n,r,s,i){super(n);se(this,"code");se(this,"status");se(this,"eventId");this.name="InteractionTrackingError",this.code=r,this.status=s,this.eventId=i}};function fn(e){let t=e?nn.find(n=>n.id===e):nn.find(n=>n.default===!0)??(nn.length===1?nn[0]:void 0);if(!t)throw new TypeError("No unambiguous source is declared for this release");if(!t.id||!Number.isInteger(t.version)||t.version<1)throw new TypeError("The release source declaration is invalid");return t}function $r(e,t){let n=t.adapters?.find(r=>r.type===e);if(!n)throw new TypeError(`The source does not declare a ${e} adapter`);return n}function Ya(e){return e.length>0&&e.length<=128&&!/[\u0000-\u001f\u007f]/.test(e)}function Xa(e,t){if(!Ya(t)||!e.observations?.includes(t))throw new TypeError("The observation is not declared by this release source")}function Br(e){if(!(typeof window>"u"||e.storage==="memory"))try{return e.storage==="session"?window.sessionStorage:window.localStorage}catch{return}}function Za(e){try{let t=Br(e)?.getItem(e.key)??void 0;return t&&Wr.test(t)?t:void 0}catch{return}}function zs(e,t){try{Br(e)?.setItem(e.key,t)}catch{}}function ec(e){let t=e.identity?.visitor;if(!t?.key)throw new TypeError("The source visitor identity policy is invalid");let n=Za(t)??Bs.get(e.id);if(n)return n;let r=crypto.randomUUID();return Bs.set(e.id,r),zs(t,r),r}function tc(e,t=Date.now()){let n=e.identity?.session;if(!n?.key||!Number.isInteger(n.idle_seconds)||n.idle_seconds<1)throw new TypeError("The source session identity policy is invalid");let r;try{let l=Br(n)?.getItem(n.key);r=l?JSON.parse(l):void 0}catch{r=void 0}let s=Gs.get(e.id),i=r&&typeof r.id=="string"&&Wr.test(r.id)&&typeof r.lastSeenAt=="number"?{id:r.id,lastSeenAt:r.lastSeenAt}:s,a=n.idle_seconds*1e3,c=i&&t-i.lastSeenAt>=0&&t-i.lastSeenAt<a?{id:i.id,lastSeenAt:t}:{id:crypto.randomUUID(),lastSeenAt:t};return Gs.set(e.id,c),zs(n,JSON.stringify(c)),c.id}function nc(e,t){let n=e.source_keys?.query;if(!Array.isArray(n)||n.length===0)return;let r;try{r=new URL(t)}catch{return}let s=e.source_keys?.max_value_length,i=Number.isInteger(s)?Math.min(Math.max(s??1,1),4096):512,a=Object.fromEntries(n.flatMap(o=>{if(typeof o!="string"||o.length===0||o.length>128)return[];let c=r.searchParams.get(o);return c?[[o,c.slice(0,i)]]:[]}));return Object.keys(a).length>0?a:void 0}async function nt(e,t={},n={}){let r=fn(n.source);if(Xa(r,e),!t||typeof t!="object"||Array.isArray(t))throw new TypeError("properties must be an object");let s=n.eventId??crypto.randomUUID(),i=n.visitorId??ec(r),a=n.sessionId??tc(r);if(![s,i,a].every(g=>Wr.test(g)))throw new TypeError("event, visitor, and session IDs must be UUIDs");let o=n.pageUrl??(typeof window<"u"?window.location.href:void 0);if(!o)throw new TypeError("pageUrl is required outside a browser");let c=n.occurredAt??new Date().toISOString();if(Number.isNaN(Date.parse(c)))throw new TypeError("occurredAt is invalid");let l=n.referrer??(typeof document<"u"&&document.referrer||void 0),d=nc(r,o),h=d?{...t,source_keys:d}:t,f=et(),p=`${ce.replace(/\/+$/,"")}/d/${encodeURIComponent(f)}/interactions`,y;try{y=await fetch(p,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({source:r.id,page_url:o,visitor_id:i,session_id:a,referrer:l,events:[{id:s,event_type:e,occurred_at:c,properties:h}]}),signal:n.signal,credentials:"omit",keepalive:n.keepalive??!1})}catch(g){throw new wt(g instanceof Error?g.message:"Observation transport network error","OBSERVATION_NETWORK_ERROR",0,s)}let m=null;try{m=await y.json()}catch{}if(!y.ok||m?.success!==!0){let g=m;throw new wt(g?.message||g?.error||`Observation transport failed (${y.status})`,g?.error||"OBSERVATION_TRANSPORT_FAILED",y.status,s)}return m}function Js(e={},t={}){let n=fn(t.source),r=$r("page_view",n),s=typeof document>"u"||!r.title_property?{}:{[r.title_property]:document.title.slice(0,512)};return nt(r.observation,{...s,...e},{...t,source:n.id})}function Ys(e,t={},n={}){if(!e||e.length>128)throw new TypeError("actionId is invalid");let r=fn(n.source),s=$r("declared_action",r),i=s.id_property?{[s.id_property]:e}:{};return nt(s.observation,{...t,...i},{...n,source:r.id})}function Xs(e,t={}){let n=fn(t.source),r=$r("form_receipt",n);return nt(r.observation,e,{...t,source:n.id})}var dn;function Gn(e={}){if(typeof window>"u"||typeof document>"u")return()=>{};if(dn)return dn;if(window.__FSAOS_CONFIG__?.tracking?.enabled===!1)return()=>{};let t;try{t=fn(e.source)}catch{return()=>{}}let n=e.pageViews===!1?[]:t.adapters.filter(f=>f.type==="page_view"),r=e.declaredActions===!1?[]:t.adapters.filter(f=>f.type==="declared_action"),s="",i=()=>{if(window.location.href!==s){s=window.location.href;for(let f of n){let p=f.title_property?{[f.title_property]:document.title.slice(0,512)}:{};nt(f.observation,p,{source:t.id,keepalive:!0}).catch(()=>{})}}},a=f=>{if(f.target instanceof Element)for(let p of r){let y=p.attribute;if(!y||!Ja.test(y))continue;let m=f.target.closest(`[${y}]`);if(!m)continue;let g=m.getAttribute(y)?.trim();if(!g||g.length>128)continue;let S={};p.id_property&&(S[p.id_property]=g),p.element_property&&(S[p.element_property]=m.tagName.toLowerCase()),nt(p.observation,S,{source:t.id,keepalive:!0}).catch(()=>{})}},o=window.history.pushState,c=window.history.replaceState,l=()=>queueMicrotask(i),d=n.some(f=>f.history===!0),h=n.some(f=>f.pageshow===!0);return d&&(window.history.pushState=function(...p){o.apply(this,p),l()},window.history.replaceState=function(...p){c.apply(this,p),l()},window.addEventListener("popstate",i)),h&&window.addEventListener("pageshow",i),r.length>0&&document.addEventListener("click",a,{capture:!0}),n.length>0&&queueMicrotask(i),dn=()=>{window.removeEventListener("popstate",i),window.removeEventListener("pageshow",i),document.removeEventListener("click",a,{capture:!0}),d&&(window.history.pushState=o,window.history.replaceState=c),dn=void 0},dn}var St;function Zs(e={}){return St||(St=(async()=>{let t=e.tracking??!0,n=t===!1?()=>{}:Gn(typeof t=="object"?t:{});try{let r=e.session===!1?null:await vt(),s=!1;return{session:r,dispose(){s||(s=!0,n(),St=void 0)}}}catch(r){throw n(),St=void 0,r}})(),St)}var rc=new Set(["list-memberships","init"]);async function R(e,t={}){let n=et(),r=`${ce}/d/${n}`,s={"Content-Type":"application/json"},i=await xe();i&&(s.Authorization=`Bearer ${i}`),!rc.has(e)&&!t._scope_path&&await an();let a={...t},o=$n();!a.domain_scope_id&&o?.scope_id&&(a.domain_scope_id=o.scope_id);let c=on();!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 d=await l.json();if(d.success===!1){let h=d.error||"",f=d.denied_by||d.error_type||"";throw f==="rule"||f==="access"||f==="entitlement"||h==="RULE_DENIED"||h==="ACCESS_DENIED"||h==="PERMISSION_DENIED"||h==="ENTITLEMENT_REQUIRED"?new mt(d):new Error(d.message||d.error||`Gateway call ${e} failed`)}return d}var sc=/^[a-z][a-z0-9_-]{0,63}$/,ic=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,Rt=class extends Error{constructor(n,r,s,i){super(n);se(this,"code");se(this,"status");se(this,"fillId");this.name="FormSubmissionError",this.code=r,this.status=s,this.fillId=i}};async function ei(e,t,n={}){if(!sc.test(e))throw new TypeError("capabilityId is invalid");if(!t||typeof t!="object"||Array.isArray(t))throw new TypeError("fields must be an object");let r=n.fillId??crypto.randomUUID();if(!ic.test(r))throw new TypeError("fillId must be a UUID");let s=et(),i=n.pageUrl??(typeof window<"u"?window.location.href:void 0);if(!i)throw new TypeError("pageUrl is required outside a browser");let a=`${ce.replace(/\/+$/,"")}/d/${encodeURIComponent(s)}/actions/${encodeURIComponent(e)}`,o;try{o=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({fill_id:r,page_url:i,fields:t}),signal:n.signal,credentials:"omit"})}catch(l){throw new Rt(l instanceof Error?l.message:"Form submission network error","FORM_NETWORK_ERROR",0,r)}let c=null;try{c=await o.json()}catch{}if(!o.ok||c?.success!==!0){let l=c;throw new Rt(l?.message||l?.error||`Form submission failed (${o.status})`,l?.error||"FORM_SUBMISSION_FAILED",o.status,r)}try{await Xs({fill_id:r,action_id:e,release_id:c.release_id},{eventId:r,pageUrl:i,signal:n.signal,keepalive:!0})}catch{}return c}var le=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 rt,Ke,Ct,ti,oc=(ti=class extends le{constructor(){super();b(this,rt);b(this,Ke);b(this,Ct);v(this,Ct,t=>{if(typeof window<"u"&&window.addEventListener){let n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){u(this,Ke)||this.setEventListener(u(this,Ct))}onUnsubscribe(){var t;this.hasListeners()||((t=u(this,Ke))==null||t.call(this),v(this,Ke,void 0))}setEventListener(t){var n;v(this,Ct,t),(n=u(this,Ke))==null||n.call(this),v(this,Ke,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){u(this,rt)!==t&&(v(this,rt,t),this.onFocus())}onFocus(){let t=this.isFocused();this.listeners.forEach(n=>{n(t)})}isFocused(){return typeof u(this,rt)=="boolean"?u(this,rt):globalThis.document?.visibilityState!=="hidden"}},rt=new WeakMap,Ke=new WeakMap,Ct=new WeakMap,ti),Pt=new oc;var ac={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},Le,Gr,ni,cc=(ni=class{constructor(){b(this,Le,ac);b(this,Gr,!1)}setTimeoutProvider(e){v(this,Le,e)}setTimeout(e,t){return u(this,Le).setTimeout(e,t)}clearTimeout(e){u(this,Le).clearTimeout(e)}setInterval(e,t){return u(this,Le).setInterval(e,t)}clearInterval(e){u(this,Le).clearInterval(e)}},Le=new WeakMap,Gr=new WeakMap,ni),we=new cc;function ri(e){setTimeout(e,0)}var Jr=typeof window>"u"||"Deno"in globalThis;function q(){}function oi(e,t){return typeof e=="function"?e(t):e}function pn(e){return typeof e=="number"&&e>=0&&e!==1/0}function zn(e,t){return Math.max(e+(t||0)-Date.now(),0)}function pe(e,t){return typeof e=="function"?e(t):e}function X(e,t){return typeof e=="function"?e(t):e}function Jn(e,t){let{type:n="all",exact:r,fetchStatus:s,predicate:i,queryKey:a,stale:o}=e;if(a){if(r){if(t.queryHash!==hn(a,t.options))return!1}else if(!st(t.queryKey,a))return!1}if(n!=="all"){let c=t.isActive();if(n==="active"&&!c||n==="inactive"&&c)return!1}return!(typeof o=="boolean"&&t.isStale()!==o||s&&s!==t.state.fetchStatus||i&&!i(t))}function Yn(e,t){let{exact:n,status:r,predicate:s,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(Se(t.options.mutationKey)!==Se(i))return!1}else if(!st(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||s&&!s(t))}function hn(e,t){return(t?.queryKeyHashFn||Se)(e)}function Se(e){return JSON.stringify(e,(t,n)=>zr(n)?Object.keys(n).sort().reduce((r,s)=>(r[s]=n[s],r),{}):n)}function st(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(t).every(n=>st(e[n],t[n])):!1}var uc=Object.prototype.hasOwnProperty;function Yr(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=si(e)&&si(t);if(!r&&!(zr(e)&&zr(t)))return t;let i=(r?e:Object.keys(e)).length,a=r?t:Object.keys(t),o=a.length,c=r?new Array(o):{},l=0;for(let d=0;d<o;d++){let h=r?d:a[d],f=e[h],p=t[h];if(f===p){c[h]=f,(r?d<i:uc.call(e,h))&&l++;continue}if(f===null||p===null||typeof f!="object"||typeof p!="object"){c[h]=p;continue}let y=Yr(f,p,n+1);c[h]=y,y===f&&l++}return i===o&&l===i?e:c}function Et(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 si(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function zr(e){if(!ii(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!ii(n)||!n.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(e)!==Object.prototype)}function ii(e){return Object.prototype.toString.call(e)==="[object Object]"}function ai(e){return new Promise(t=>{we.setTimeout(t,e)})}function mn(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?Yr(e,t):t}function ci(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function ui(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var xt=Symbol();function Xn(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===xt?()=>Promise.reject(new Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function Tt(e,t){return typeof e=="function"?e(...t):!!e}function li(e,t,n){let r=!1,s;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(s??(s=t()),r||(r=!0,s.aborted?n():s.addEventListener("abort",n,{once:!0})),s)}),e}var Re=(()=>{let e=()=>Jr;return{isServer(){return e()},setIsServer(t){e=t}}})();function gn(){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 di=ri;function lc(){let e=[],t=0,n=o=>{o()},r=o=>{o()},s=di,i=o=>{t?e.push(o):s(()=>{n(o)})},a=()=>{let o=e;e=[],o.length&&s(()=>{r(()=>{o.forEach(c=>{n(c)})})})};return{batch:o=>{let c;t++;try{c=o()}finally{t--,t||a()}return c},batchCalls:o=>(...c)=>{i(()=>{o(...c)})},schedule:i,setNotifyFunction:o=>{n=o},setBatchNotifyFunction:o=>{r=o},setScheduler:o=>{s=o}}}var M=lc();var It,je,At,fi,dc=(fi=class extends le{constructor(){super();b(this,It,!0);b(this,je);b(this,At);v(this,At,t=>{if(typeof window<"u"&&window.addEventListener){let n=()=>t(!0),r=()=>t(!1);return window.addEventListener("online",n,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}}})}onSubscribe(){u(this,je)||this.setEventListener(u(this,At))}onUnsubscribe(){var t;this.hasListeners()||((t=u(this,je))==null||t.call(this),v(this,je,void 0))}setEventListener(t){var n;v(this,At,t),(n=u(this,je))==null||n.call(this),v(this,je,t(this.setOnline.bind(this)))}setOnline(t){u(this,It)!==t&&(v(this,It,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return u(this,It)}},It=new WeakMap,je=new WeakMap,At=new WeakMap,fi),Ot=new dc;function fc(e){return Math.min(1e3*2**e,3e4)}function Xr(e){return(e??"online")==="online"?Ot.isOnline():!0}var Zn=class extends Error{constructor(e){super("CancelledError"),this.revert=e?.revert,this.silent=e?.silent}};function er(e){let t=!1,n=0,r,s=gn(),i=()=>s.status!=="pending",a=m=>{if(!i()){let g=new Zn(m);f(g),e.onCancel?.(g)}},o=()=>{t=!0},c=()=>{t=!1},l=()=>Pt.isFocused()&&(e.networkMode==="always"||Ot.isOnline())&&e.canRun(),d=()=>Xr(e.networkMode)&&e.canRun(),h=m=>{i()||(r?.(),s.resolve(m))},f=m=>{i()||(r?.(),s.reject(m))},p=()=>new Promise(m=>{r=g=>{(i()||l())&&m(g)},e.onPause?.()}).then(()=>{r=void 0,i()||e.onContinue?.()}),y=()=>{if(i())return;let m,g=n===0?e.initialPromise:void 0;try{m=g??e.fn()}catch(S){m=Promise.reject(S)}Promise.resolve(m).then(h).catch(S=>{if(i())return;let C=e.retry??(Re.isServer()?0:3),x=e.retryDelay??fc,U=typeof x=="function"?x(n,S):x,L=C===!0||typeof C=="number"&&n<C||typeof C=="function"&&C(n,S);if(t||!L){f(S);return}n++,e.onFail?.(n,S),ai(U).then(()=>l()?void 0:p()).then(()=>{t?f(S):y()})})};return{promise:s,status:()=>s.status,cancel:a,continue:()=>(r?.(),s),cancelRetry:o,continueRetry:c,canStart:d,start:()=>(d()?y():p().then(y),s)}}var it,pi,tr=(pi=class{constructor(){b(this,it)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),pn(this.gcTime)&&v(this,it,we.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Re.isServer()?1/0:5*60*1e3))}clearGcTimeout(){u(this,it)!==void 0&&(we.clearTimeout(u(this,it)),v(this,it,void 0))}},it=new WeakMap,pi);var ot,Mt,de,at,V,yn,ct,ie,_i,Ie,gi,yi=(gi=class extends tr{constructor(t){super();b(this,ie);b(this,ot);b(this,Mt);b(this,de);b(this,at);b(this,V);b(this,yn);b(this,ct);v(this,ct,!1),v(this,yn,t.defaultOptions),this.setOptions(t.options),this.observers=[],v(this,at,t.client),v(this,de,u(this,at).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,v(this,ot,mi(this.options)),this.state=t.state??u(this,ot),this.scheduleGc()}get meta(){return this.options.meta}get promise(){return u(this,V)?.promise}setOptions(t){if(this.options={...u(this,yn),...t},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let n=mi(this.options);n.data!==void 0&&(this.setState(hi(n.data,n.dataUpdatedAt)),v(this,ot,n))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&u(this,de).remove(this)}setData(t,n){let r=mn(this.state.data,t,this.options);return P(this,ie,Ie).call(this,{data:r,type:"success",dataUpdatedAt:n?.updatedAt,manual:n?.manual}),r}setState(t,n){P(this,ie,Ie).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){let n=u(this,V)?.promise;return u(this,V)?.cancel(t),n?n.then(q).catch(q):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return u(this,ot)}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(t=>X(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===xt||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>pe(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:!zn(this.state.dataUpdatedAt,t)}onFocus(){this.observers.find(n=>n.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),u(this,V)?.continue()}onOnline(){this.observers.find(n=>n.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),u(this,V)?.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),u(this,de).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(n=>n!==t),this.observers.length||(u(this,V)&&(u(this,ct)||P(this,ie,_i).call(this)?u(this,V).cancel({revert:!0}):u(this,V).cancelRetry()),this.scheduleGc()),u(this,de).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||P(this,ie,Ie).call(this,{type:"invalidate"})}async fetch(t,n){if(this.state.fetchStatus!=="idle"&&u(this,V)?.status()!=="rejected"){if(this.state.data!==void 0&&n?.cancelRefetch)this.cancel({silent:!0});else if(u(this,V))return u(this,V).continueRetry(),u(this,V).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:()=>(v(this,ct,!0),r.signal)})},i=()=>{let c=Xn(this.options,n),d=(()=>{let h={client:u(this,at),queryKey:this.queryKey,meta:this.meta};return s(h),h})();return v(this,ct,!1),this.options.persister?this.options.persister(c,d,this):c(d)},o=(()=>{let c={fetchOptions:n,options:this.options,queryKey:this.queryKey,client:u(this,at),state:this.state,fetchFn:i};return s(c),c})();this.options.behavior?.onFetch(o,this),v(this,Mt,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==o.fetchOptions?.meta)&&P(this,ie,Ie).call(this,{type:"fetch",meta:o.fetchOptions?.meta}),v(this,V,er({initialPromise:n?.initialPromise,fn:o.fetchFn,onCancel:c=>{c instanceof Zn&&c.revert&&this.setState({...u(this,Mt),fetchStatus:"idle"}),r.abort()},onFail:(c,l)=>{P(this,ie,Ie).call(this,{type:"failed",failureCount:c,error:l})},onPause:()=>{P(this,ie,Ie).call(this,{type:"pause"})},onContinue:()=>{P(this,ie,Ie).call(this,{type:"continue"})},retry:o.options.retry,retryDelay:o.options.retryDelay,networkMode:o.options.networkMode,canRun:()=>!0}));try{let c=await u(this,V).start();if(c===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(c),u(this,de).config.onSuccess?.(c,this),u(this,de).config.onSettled?.(c,this.state.error,this),c}catch(c){if(c instanceof Zn){if(c.silent)return u(this,V).promise;if(c.revert){if(this.state.data===void 0)throw c;return this.state.data}}throw P(this,ie,Ie).call(this,{type:"error",error:c}),u(this,de).config.onError?.(c,this),u(this,de).config.onSettled?.(this.state.data,c,this),c}finally{this.scheduleGc()}}},ot=new WeakMap,Mt=new WeakMap,de=new WeakMap,at=new WeakMap,V=new WeakMap,yn=new WeakMap,ct=new WeakMap,ie=new WeakSet,_i=function(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"},Ie=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,...Zr(r.data,this.options),fetchMeta:t.meta??null};case"success":let s={...r,...hi(t.data,t.dataUpdatedAt),dataUpdateCount:r.dataUpdateCount+1,...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return v(this,Mt,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),M.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),u(this,de).notify({query:this,type:"updated",action:t})})},gi);function Zr(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Xr(t.networkMode)?"fetching":"paused",...e===void 0&&{error:null,status:"pending"}}}function hi(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function mi(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 Z,T,vn,z,ut,kt,Ae,Ve,bn,Ft,qt,lt,dt,He,Dt,O,_n,es,ts,ns,rs,ss,is,os,Si,wi,wn=(wi=class extends le{constructor(t,n){super();b(this,O);b(this,Z);b(this,T);b(this,vn);b(this,z);b(this,ut);b(this,kt);b(this,Ae);b(this,Ve);b(this,bn);b(this,Ft);b(this,qt);b(this,lt);b(this,dt);b(this,He);b(this,Dt,new Set);this.options=n,v(this,Z,t),v(this,Ve,null),v(this,Ae,gn()),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(u(this,T).addObserver(this),vi(u(this,T),this.options)?P(this,O,_n).call(this):this.updateResult(),P(this,O,rs).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return as(u(this,T),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return as(u(this,T),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,P(this,O,ss).call(this),P(this,O,is).call(this),u(this,T).removeObserver(this)}setOptions(t){let n=this.options,r=u(this,T);if(this.options=u(this,Z).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof X(this.options.enabled,u(this,T))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");P(this,O,os).call(this),u(this,T).setOptions(this.options),n._defaulted&&!Et(this.options,n)&&u(this,Z).getQueryCache().notify({type:"observerOptionsUpdated",query:u(this,T),observer:this});let s=this.hasListeners();s&&bi(u(this,T),r,this.options,n)&&P(this,O,_n).call(this),this.updateResult(),s&&(u(this,T)!==r||X(this.options.enabled,u(this,T))!==X(n.enabled,u(this,T))||pe(this.options.staleTime,u(this,T))!==pe(n.staleTime,u(this,T)))&&P(this,O,es).call(this);let i=P(this,O,ts).call(this);s&&(u(this,T)!==r||X(this.options.enabled,u(this,T))!==X(n.enabled,u(this,T))||i!==u(this,He))&&P(this,O,ns).call(this,i)}getOptimisticResult(t){let n=u(this,Z).getQueryCache().build(u(this,Z),t),r=this.createResult(n,t);return hc(this,r)&&(v(this,z,r),v(this,kt,this.options),v(this,ut,u(this,T).state)),r}getCurrentResult(){return u(this,z)}trackResult(t,n){return new Proxy(t,{get:(r,s)=>(this.trackProp(s),n?.(s),s==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&u(this,Ae).status==="pending"&&u(this,Ae).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(r,s))})}trackProp(t){u(this,Dt).add(t)}getCurrentQuery(){return u(this,T)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){let n=u(this,Z).defaultQueryOptions(t),r=u(this,Z).getQueryCache().build(u(this,Z),n);return r.fetch().then(()=>this.createResult(r,n))}fetch(t){return P(this,O,_n).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),u(this,z)))}createResult(t,n){let r=u(this,T),s=this.options,i=u(this,z),a=u(this,ut),o=u(this,kt),l=t!==r?t.state:u(this,vn),{state:d}=t,h={...d},f=!1,p;if(n._optimisticResults){let Q=this.hasListeners(),Y=!Q&&vi(t,n),ye=Q&&bi(t,r,n,s);(Y||ye)&&(h={...h,...Zr(d.data,t.options)}),n._optimisticResults==="isRestoring"&&(h.fetchStatus="idle")}let{error:y,errorUpdatedAt:m,status:g}=h;p=h.data;let S=!1;if(n.placeholderData!==void 0&&p===void 0&&g==="pending"){let Q;i?.isPlaceholderData&&n.placeholderData===o?.placeholderData?(Q=i.data,S=!0):Q=typeof n.placeholderData=="function"?n.placeholderData(u(this,qt)?.state.data,u(this,qt)):n.placeholderData,Q!==void 0&&(g="success",p=mn(i?.data,Q,n),f=!0)}if(n.select&&p!==void 0&&!S)if(i&&p===a?.data&&n.select===u(this,bn))p=u(this,Ft);else try{v(this,bn,n.select),p=n.select(p),p=mn(i?.data,p,n),v(this,Ft,p),v(this,Ve,null)}catch(Q){v(this,Ve,Q)}u(this,Ve)&&(y=u(this,Ve),p=u(this,Ft),m=Date.now(),g="error");let C=h.fetchStatus==="fetching",x=g==="pending",U=g==="error",L=x&&C,$=p!==void 0,re={status:g,fetchStatus:h.fetchStatus,isPending:x,isSuccess:g==="success",isError:U,isInitialLoading:L,isLoading:L,data:p,dataUpdatedAt:h.dataUpdatedAt,error:y,errorUpdatedAt:m,failureCount:h.fetchFailureCount,failureReason:h.fetchFailureReason,errorUpdateCount:h.errorUpdateCount,isFetched:t.isFetched(),isFetchedAfterMount:h.dataUpdateCount>l.dataUpdateCount||h.errorUpdateCount>l.errorUpdateCount,isFetching:C,isRefetching:C&&!x,isLoadingError:U&&!$,isPaused:h.fetchStatus==="paused",isPlaceholderData:f,isRefetchError:U&&$,isStale:cs(t,n),refetch:this.refetch,promise:u(this,Ae),isEnabled:X(n.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){let Q=re.data!==void 0,Y=re.status==="error"&&!Q,ye=I=>{Y?I.reject(re.error):Q&&I.resolve(re.data)},_e=()=>{let I=v(this,Ae,re.promise=gn());ye(I)},ve=u(this,Ae);switch(ve.status){case"pending":t.queryHash===r.queryHash&&ye(ve);break;case"fulfilled":(Y||re.data!==ve.value)&&_e();break;case"rejected":(!Y||re.error!==ve.reason)&&_e();break}}return re}updateResult(){let t=u(this,z),n=this.createResult(u(this,T),this.options);if(v(this,ut,u(this,T).state),v(this,kt,this.options),u(this,ut).data!==void 0&&v(this,qt,u(this,T)),Et(n,t))return;v(this,z,n);let r=()=>{if(!t)return!0;let{notifyOnChangeProps:s}=this.options,i=typeof s=="function"?s():s;if(i==="all"||!i&&!u(this,Dt).size)return!0;let a=new Set(i??u(this,Dt));return this.options.throwOnError&&a.add("error"),Object.keys(u(this,z)).some(o=>{let c=o;return u(this,z)[c]!==t[c]&&a.has(c)})};P(this,O,Si).call(this,{listeners:r()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&P(this,O,rs).call(this)}},Z=new WeakMap,T=new WeakMap,vn=new WeakMap,z=new WeakMap,ut=new WeakMap,kt=new WeakMap,Ae=new WeakMap,Ve=new WeakMap,bn=new WeakMap,Ft=new WeakMap,qt=new WeakMap,lt=new WeakMap,dt=new WeakMap,He=new WeakMap,Dt=new WeakMap,O=new WeakSet,_n=function(t){P(this,O,os).call(this);let n=u(this,T).fetch(this.options,t);return t?.throwOnError||(n=n.catch(q)),n},es=function(){P(this,O,ss).call(this);let t=pe(this.options.staleTime,u(this,T));if(Re.isServer()||u(this,z).isStale||!pn(t))return;let r=zn(u(this,z).dataUpdatedAt,t)+1;v(this,lt,we.setTimeout(()=>{u(this,z).isStale||this.updateResult()},r))},ts=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(u(this,T)):this.options.refetchInterval)??!1},ns=function(t){P(this,O,is).call(this),v(this,He,t),!(Re.isServer()||X(this.options.enabled,u(this,T))===!1||!pn(u(this,He))||u(this,He)===0)&&v(this,dt,we.setInterval(()=>{(this.options.refetchIntervalInBackground||Pt.isFocused())&&P(this,O,_n).call(this)},u(this,He)))},rs=function(){P(this,O,es).call(this),P(this,O,ns).call(this,P(this,O,ts).call(this))},ss=function(){u(this,lt)!==void 0&&(we.clearTimeout(u(this,lt)),v(this,lt,void 0))},is=function(){u(this,dt)!==void 0&&(we.clearInterval(u(this,dt)),v(this,dt,void 0))},os=function(){let t=u(this,Z).getQueryCache().build(u(this,Z),this.options);if(t===u(this,T))return;let n=u(this,T);v(this,T,t),v(this,vn,t.state),this.hasListeners()&&(n?.removeObserver(this),t.addObserver(this))},Si=function(t){M.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(u(this,z))}),u(this,Z).getQueryCache().notify({query:u(this,T),type:"observerResultsUpdated"})})},wi);function pc(e,t){return X(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status==="error"&&t.retryOnMount===!1)}function vi(e,t){return pc(e,t)||e.state.data!==void 0&&as(e,t,t.refetchOnMount)}function as(e,t,n){if(X(t.enabled,e)!==!1&&pe(t.staleTime,e)!=="static"){let r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&cs(e,t)}return!1}function bi(e,t,n,r){return(e!==t||X(r.enabled,e)===!1)&&(!n.suspense||e.state.status!=="error")&&cs(e,n)}function cs(e,t){return X(t.enabled,e)!==!1&&e.isStaleByTime(pe(t.staleTime,e))}function hc(e,t){return!Et(e.getCurrentResult(),t)}function Ut(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||[],o={pages:[],pageParams:[]},c=0,l=async()=>{let d=!1,h=y=>{li(y,()=>t.signal,()=>d=!0)},f=Xn(t.options,t.fetchOptions),p=async(y,m,g)=>{if(d)return Promise.reject();if(m==null&&y.pages.length)return Promise.resolve(y);let C=(()=>{let $={client:t.client,queryKey:t.queryKey,pageParam:m,direction:g?"backward":"forward",meta:t.options.meta};return h($),$})(),x=await f(C),{maxPages:U}=t.options,L=g?ui:ci;return{pages:L(y.pages,x,U),pageParams:L(y.pageParams,m,U)}};if(s&&i.length){let y=s==="backward",m=y?Ri:us,g={pages:i,pageParams:a},S=m(r,g);o=await p(g,S,y)}else{let y=e??i.length;do{let m=c===0?a[0]??r.initialPageParam:us(r,o);if(c>0&&m==null)break;o=await p(o,m),c++}while(c<y)}return o};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 us(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 Ri(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function Ci(e,t){return t?us(e,t)!=null:!1}function Pi(e,t){return!t||!e.getPreviousPageParam?!1:Ri(e,t)!=null}var ls=class extends wn{constructor(e,t){super(e,t)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(e){super.setOptions({...e,behavior:Ut()})}getOptimisticResult(e){return e.behavior=Ut(),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:o}=r,c=n.fetchMeta?.fetchMore?.direction,l=a&&c==="forward",d=s&&c==="forward",h=a&&c==="backward",f=s&&c==="backward";return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:Ci(t,n.data),hasPreviousPage:Pi(t,n.data),isFetchNextPageError:l,isFetchingNextPage:d,isFetchPreviousPageError:h,isFetchingPreviousPage:f,isRefetchError:o&&!l&&!h,isRefetching:i&&!d&&!f}}};var Sn,Ce,G,ft,Pe,We,Ei,xi=(Ei=class extends tr{constructor(t){super();b(this,Pe);b(this,Sn);b(this,Ce);b(this,G);b(this,ft);v(this,Sn,t.client),this.mutationId=t.mutationId,v(this,G,t.mutationCache),v(this,Ce,[]),this.state=t.state||ds(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){u(this,Ce).includes(t)||(u(this,Ce).push(t),this.clearGcTimeout(),u(this,G).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){v(this,Ce,u(this,Ce).filter(n=>n!==t)),this.scheduleGc(),u(this,G).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){u(this,Ce).length||(this.state.status==="pending"?this.scheduleGc():u(this,G).remove(this))}continue(){return u(this,ft)?.continue()??this.execute(this.state.variables)}async execute(t){let n=()=>{P(this,Pe,We).call(this,{type:"continue"})},r={client:u(this,Sn),meta:this.options.meta,mutationKey:this.options.mutationKey};v(this,ft,er({fn:()=>this.options.mutationFn?this.options.mutationFn(t,r):Promise.reject(new Error("No mutationFn found")),onFail:(a,o)=>{P(this,Pe,We).call(this,{type:"failed",failureCount:a,error:o})},onPause:()=>{P(this,Pe,We).call(this,{type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>u(this,G).canRun(this)}));let s=this.state.status==="pending",i=!u(this,ft).canStart();try{if(s)n();else{P(this,Pe,We).call(this,{type:"pending",variables:t,isPaused:i}),u(this,G).config.onMutate&&await u(this,G).config.onMutate(t,this,r);let o=await this.options.onMutate?.(t,r);o!==this.state.context&&P(this,Pe,We).call(this,{type:"pending",context:o,variables:t,isPaused:i})}let a=await u(this,ft).start();return await u(this,G).config.onSuccess?.(a,t,this.state.context,this,r),await this.options.onSuccess?.(a,t,this.state.context,r),await u(this,G).config.onSettled?.(a,null,this.state.variables,this.state.context,this,r),await this.options.onSettled?.(a,null,t,this.state.context,r),P(this,Pe,We).call(this,{type:"success",data:a}),a}catch(a){try{await u(this,G).config.onError?.(a,t,this.state.context,this,r)}catch(o){Promise.reject(o)}try{await this.options.onError?.(a,t,this.state.context,r)}catch(o){Promise.reject(o)}try{await u(this,G).config.onSettled?.(void 0,a,this.state.variables,this.state.context,this,r)}catch(o){Promise.reject(o)}try{await this.options.onSettled?.(void 0,a,t,this.state.context,r)}catch(o){Promise.reject(o)}throw P(this,Pe,We).call(this,{type:"error",error:a}),a}finally{u(this,G).runNext(this)}}},Sn=new WeakMap,Ce=new WeakMap,G=new WeakMap,ft=new WeakMap,Pe=new WeakSet,We=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),M.batch(()=>{u(this,Ce).forEach(r=>{r.onMutationUpdate(t)}),u(this,G).notify({mutation:this,type:"updated",action:t})})},Ei);function ds(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Oe,he,Rn,Ti,Ii=(Ti=class extends le{constructor(t={}){super();b(this,Oe);b(this,he);b(this,Rn);this.config=t,v(this,Oe,new Set),v(this,he,new Map),v(this,Rn,0)}build(t,n,r){let s=new xi({client:t,mutationCache:this,mutationId:++en(this,Rn)._,options:t.defaultMutationOptions(n),state:r});return this.add(s),s}add(t){u(this,Oe).add(t);let n=nr(t);if(typeof n=="string"){let r=u(this,he).get(n);r?r.push(t):u(this,he).set(n,[t])}this.notify({type:"added",mutation:t})}remove(t){if(u(this,Oe).delete(t)){let n=nr(t);if(typeof n=="string"){let r=u(this,he).get(n);if(r)if(r.length>1){let s=r.indexOf(t);s!==-1&&r.splice(s,1)}else r[0]===t&&u(this,he).delete(n)}}this.notify({type:"removed",mutation:t})}canRun(t){let n=nr(t);if(typeof n=="string"){let s=u(this,he).get(n)?.find(i=>i.state.status==="pending");return!s||s===t}else return!0}runNext(t){let n=nr(t);return typeof n=="string"?u(this,he).get(n)?.find(s=>s!==t&&s.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){M.batch(()=>{u(this,Oe).forEach(t=>{this.notify({type:"removed",mutation:t})}),u(this,Oe).clear(),u(this,he).clear()})}getAll(){return Array.from(u(this,Oe))}find(t){let n={exact:!0,...t};return this.getAll().find(r=>Yn(n,r))}findAll(t={}){return this.getAll().filter(n=>Yn(t,n))}notify(t){M.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){let t=this.getAll().filter(n=>n.state.isPaused);return M.batch(()=>Promise.all(t.map(n=>n.continue().catch(q))))}},Oe=new WeakMap,he=new WeakMap,Rn=new WeakMap,Ti);function nr(e){return e.options.scope?.id}var Me,$e,ee,ke,Fe,rr,fs,Ai,ps=(Ai=class extends le{constructor(t,n){super();b(this,Fe);b(this,Me);b(this,$e);b(this,ee);b(this,ke);v(this,Me,t),this.setOptions(n),this.bindMethods(),P(this,Fe,rr).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(t){let n=this.options;this.options=u(this,Me).defaultMutationOptions(t),Et(this.options,n)||u(this,Me).getMutationCache().notify({type:"observerOptionsUpdated",mutation:u(this,ee),observer:this}),n?.mutationKey&&this.options.mutationKey&&Se(n.mutationKey)!==Se(this.options.mutationKey)?this.reset():u(this,ee)?.state.status==="pending"&&u(this,ee).setOptions(this.options)}onUnsubscribe(){this.hasListeners()||u(this,ee)?.removeObserver(this)}onMutationUpdate(t){P(this,Fe,rr).call(this),P(this,Fe,fs).call(this,t)}getCurrentResult(){return u(this,$e)}reset(){u(this,ee)?.removeObserver(this),v(this,ee,void 0),P(this,Fe,rr).call(this),P(this,Fe,fs).call(this)}mutate(t,n){return v(this,ke,n),u(this,ee)?.removeObserver(this),v(this,ee,u(this,Me).getMutationCache().build(u(this,Me),this.options)),u(this,ee).addObserver(this),u(this,ee).execute(t)}},Me=new WeakMap,$e=new WeakMap,ee=new WeakMap,ke=new WeakMap,Fe=new WeakSet,rr=function(){let t=u(this,ee)?.state??ds();v(this,$e,{...t,isPending:t.status==="pending",isSuccess:t.status==="success",isError:t.status==="error",isIdle:t.status==="idle",mutate:this.mutate,reset:this.reset})},fs=function(t){M.batch(()=>{if(u(this,ke)&&this.hasListeners()){let n=u(this,$e).variables,r=u(this,$e).context,s={client:u(this,Me),meta:this.options.meta,mutationKey:this.options.mutationKey};if(t?.type==="success"){try{u(this,ke).onSuccess?.(t.data,n,r,s)}catch(i){Promise.reject(i)}try{u(this,ke).onSettled?.(t.data,null,n,r,s)}catch(i){Promise.reject(i)}}else if(t?.type==="error"){try{u(this,ke).onError?.(t.error,n,r,s)}catch(i){Promise.reject(i)}try{u(this,ke).onSettled?.(void 0,t.error,n,r,s)}catch(i){Promise.reject(i)}}}this.listeners.forEach(n=>{n(u(this,$e))})})},Ai);var Ee,Oi,Mi=(Oi=class extends le{constructor(t={}){super();b(this,Ee);this.config=t,v(this,Ee,new Map)}build(t,n,r){let s=n.queryKey,i=n.queryHash??hn(s,n),a=this.get(i);return a||(a=new yi({client:t,queryKey:s,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(s)}),this.add(a)),a}add(t){u(this,Ee).has(t.queryHash)||(u(this,Ee).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){let n=u(this,Ee).get(t.queryHash);n&&(t.destroy(),n===t&&u(this,Ee).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){M.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return u(this,Ee).get(t)}getAll(){return[...u(this,Ee).values()]}find(t){let n={exact:!0,...t};return this.getAll().find(r=>Jn(n,r))}findAll(t={}){let n=this.getAll();return Object.keys(t).length>0?n.filter(r=>Jn(t,r)):n}notify(t){M.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){M.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){M.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},Ee=new WeakMap,Oi);var D,Be,Ge,Nt,Qt,ze,Kt,Lt,ki,hs=(ki=class{constructor(e={}){b(this,D);b(this,Be);b(this,Ge);b(this,Nt);b(this,Qt);b(this,ze);b(this,Kt);b(this,Lt);v(this,D,e.queryCache||new Mi),v(this,Be,e.mutationCache||new Ii),v(this,Ge,e.defaultOptions||{}),v(this,Nt,new Map),v(this,Qt,new Map),v(this,ze,0)}mount(){en(this,ze)._++,u(this,ze)===1&&(v(this,Kt,Pt.subscribe(async e=>{e&&(await this.resumePausedMutations(),u(this,D).onFocus())})),v(this,Lt,Ot.subscribe(async e=>{e&&(await this.resumePausedMutations(),u(this,D).onOnline())})))}unmount(){var e,t;en(this,ze)._--,u(this,ze)===0&&((e=u(this,Kt))==null||e.call(this),v(this,Kt,void 0),(t=u(this,Lt))==null||t.call(this),v(this,Lt,void 0))}isFetching(e){return u(this,D).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return u(this,Be).findAll({...e,status:"pending"}).length}getQueryData(e){let t=this.defaultQueryOptions({queryKey:e});return u(this,D).get(t.queryHash)?.state.data}ensureQueryData(e){let t=this.defaultQueryOptions(e),n=u(this,D).build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(pe(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return u(this,D).findAll(e).map(({queryKey:t,state:n})=>{let r=n.data;return[t,r]})}setQueryData(e,t,n){let r=this.defaultQueryOptions({queryKey:e}),i=u(this,D).get(r.queryHash)?.state.data,a=oi(t,i);if(a!==void 0)return u(this,D).build(this,r).setData(a,{...n,manual:!0})}setQueriesData(e,t,n){return M.batch(()=>u(this,D).findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){let t=this.defaultQueryOptions({queryKey:e});return u(this,D).get(t.queryHash)?.state}removeQueries(e){let t=u(this,D);M.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){let n=u(this,D);return M.batch(()=>(n.findAll(e).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...e},t)))}cancelQueries(e,t={}){let n={revert:!0,...t},r=M.batch(()=>u(this,D).findAll(e).map(s=>s.cancel(n)));return Promise.all(r).then(q).catch(q)}invalidateQueries(e,t={}){return M.batch(()=>(u(this,D).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=M.batch(()=>u(this,D).findAll(e).filter(s=>!s.isDisabled()&&!s.isStatic()).map(s=>{let i=s.fetch(void 0,n);return n.throwOnError||(i=i.catch(q)),s.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(q)}fetchQuery(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=u(this,D).build(this,t);return n.isStaleByTime(pe(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(q).catch(q)}fetchInfiniteQuery(e){return e.behavior=Ut(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(q).catch(q)}ensureInfiniteQueryData(e){return e.behavior=Ut(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return Ot.isOnline()?u(this,Be).resumePausedMutations():Promise.resolve()}getQueryCache(){return u(this,D)}getMutationCache(){return u(this,Be)}getDefaultOptions(){return u(this,Ge)}setDefaultOptions(e){v(this,Ge,e)}setQueryDefaults(e,t){u(this,Nt).set(Se(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){let t=[...u(this,Nt).values()],n={};return t.forEach(r=>{st(e,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(e,t){u(this,Qt).set(Se(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){let t=[...u(this,Qt).values()],n={};return t.forEach(r=>{st(e,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;let t={...u(this,Ge).queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=hn(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===xt&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...u(this,Ge).mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){u(this,D).clear(),u(this,Be).clear()}},D=new WeakMap,Be=new WeakMap,Ge=new WeakMap,Nt=new WeakMap,Qt=new WeakMap,ze=new WeakMap,Kt=new WeakMap,Lt=new WeakMap,ki);var jt=j(oe(),1),Di=j(sr(),1),ms=jt.createContext(void 0),N=e=>{let t=jt.useContext(ms);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},Cn=({client:e,children:t})=>(jt.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,Di.jsx)(ms.Provider,{value:e,children:t}));var ir=j(oe(),1),Ui=ir.createContext(!1),Ni=()=>ir.useContext(Ui),wd=Ui.Provider;var Pn=j(oe(),1),mc=j(sr(),1);function gc(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var yc=Pn.createContext(gc()),Qi=()=>Pn.useContext(yc);var Ki=j(oe(),1);var Li=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError=="function"?Tt(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},ji=e=>{Ki.useEffect(()=>{e.clearReset()},[e])},Vi=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:s})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(s&&e.data===void 0||Tt(n,[e.error,r]));var Hi=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))}},Wi=(e,t)=>e.isLoading&&e.isFetching&&!t,$i=(e,t)=>e?.suspense&&t.isPending,gs=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});var Je=j(oe(),1);function or(e,t,n){let r=Ni(),s=Qi(),i=N(n),a=i.defaultQueryOptions(e);i.getDefaultOptions().queries?._experimental_beforeQuery?.(a);let o=i.getQueryCache().get(a.queryHash);a._optimisticResults=r?"isRestoring":"optimistic",Hi(a),Li(a,s,o),ji(s);let c=!i.getQueryCache().get(a.queryHash),[l]=Je.useState(()=>new t(i,a)),d=l.getOptimisticResult(a),h=!r&&e.subscribed!==!1;if(Je.useSyncExternalStore(Je.useCallback(f=>{let p=h?l.subscribe(M.batchCalls(f)):q;return l.updateResult(),p},[l,h]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),Je.useEffect(()=>{l.setOptions(a)},[a,l]),$i(a,d))throw gs(a,l,s);if(Vi({result:d,errorResetBoundary:s,throwOnError:a.throwOnError,query:o,suspense:a.suspense}))throw d.error;return i.getDefaultOptions().queries?._experimental_afterQuery?.(a,d),a.experimental_prefetchInRender&&!Re.isServer()&&Wi(d,r)&&(c?gs(a,l,s):o?.promise)?.catch(q).finally(()=>{l.updateResult()}),a.notifyOnChangeProps?d:l.trackResult(d)}function F(e,t){return or(e,wn,t)}var qe=j(oe(),1);function De(e,t){let n=N(t),[r]=qe.useState(()=>new ps(n,e));qe.useEffect(()=>{r.setOptions(e)},[r,e]);let s=qe.useSyncExternalStore(qe.useCallback(a=>r.subscribe(M.batchCalls(a)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),i=qe.useCallback((a,o)=>{r.mutate(a,o).catch(q)},[r]);if(s.error&&Tt(r.options.throwOnError,[s.error]))throw s.error;return{...s,mutate:i,mutateAsync:s.mutate}}function En(e,t){return or(e,ls,t)}var Vt=null;function Bi(e){if(Vt&&Vt!==e)throw new Error("[fsaos-gateway-sdk] setQueryClient() called after a QueryClient was already in use. Inject the host client before rendering or starting realtime subscriptions.");Vt=e}function E(){return Vt||(Vt=new hs({defaultOptions:{queries:{staleTime:1e3*60*2,gcTime:1e3*60*10,refetchOnWindowFocus:!1,retry:1}}})),Vt}var Gi=new Proxy({},{get(e,t,n){let r=E(),s=r[t];return typeof s=="function"?s.bind(r):s}});function H(){return fe()??"__unscoped__"}var w={all:()=>["vfs",H()],item:e=>["vfs",H(),"item",e],itemById:e=>["vfs","item-by-id",e],children:e=>["vfs",H(),"children",e],allChildren:()=>["vfs",H(),"children"],types:e=>["vfs","types",e??"default"],edges:e=>["vfs","edges",e],search:(e,t)=>["vfs",H(),"search",e,...t??[]],items:(e,t)=>["vfs",H(),"items",e,JSON.stringify(t??{})],allItems:()=>["vfs",H(),"items"],tree:(e,t)=>["vfs",H(),"tree",e,t??1],openEnvelope:(e,t)=>["vfs",H(),"open",e,t??"__default__"],allOpenEnvelopes:()=>["vfs",H(),"open"],memberFocus:e=>["vfs","member-focus",e],fractalInstances:()=>["vfs","fractal-instances"],recentActivity:(e,t,n)=>["vfs",H(),"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",H(),"channel-messages",e,t??"__top__"],allChannelMessages:()=>["vfs",H(),"channel-messages"],channels:e=>["vfs",H(),"channels",e??"all"],allChannels:()=>["vfs",H(),"channels"],notifications:(e,t)=>["vfs",H(),"notifications",e??"all",t??200],allNotifications:()=>["vfs",H(),"notifications"],unreadCounts:()=>["vfs",H(),"unread-counts"],memberships:e=>["memberships",e]};function zi(){return new Date().toISOString()}function Ji(){return crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function me(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||zi(),updated_at:e.updated_at||zi(),visibility:e.visibility,type_data:s,scope_item_id:e.scope_item_id,fractal_id:e.fractal_id,parent_instance_id:e.parent_instance_id,owner_principal_id:e.owner_principal_id,created_by_principal_id:e.created_by_principal_id,parent_id:e.parent_id,space_item_id:e.space_item_id,account_item_id:e.account_item_id}}function xn(e){return(e.content?.items||e.items||[]).map(me)}async function cr(e){try{let t=await R("read",{id:e});if(t.item_name||t.item_path){let r=me(t);return r.path&&E().setQueryData(w.item(r.path),r),r}let n=t.item;if(n){let r=me(n);return r.path&&E().setQueryData(w.item(r.path),r),r}return null}catch{return null}}async function ur(e){try{let t=await R("read",{path:e});if(t.item_name||t.item_path)return me(t);let n=t.item;return n?me(n):null}catch{return null}}async function lr(e){try{let t=await R("list",{path:e,limit:200}),n=xn(t);for(let r of n)E().setQueryData(w.item(r.path),r);return n}catch(t){return console.error(`[gateway] Failed to fetch children of ${e}:`,t),[]}}async function dr(e,t,n){try{let r=await R("list",{path:e,limit:t,offset:n}),s=xn(r);for(let i of s)E().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 fr(e){let n=await R("types-list",e?{scope_id:e}:{}),r=n.content?.items||n.items||[],s=new Map;for(let i of r){let a=i.name,o=i.type_data;!a||!o||s.set(a,{type_key:a,display_name:o.display_name||a,display_name_plural:o.display_name_plural||a+"s",icon:o.icon||"File",color:o.color||"gray",description:o.description||"",input_schema:o.input_schema||{},system_schema:o.system_schema||{},json_schema:o.input_schema||o.json_schema||{},default_data:o.default_data||{},field_defaults:o.field_defaults||{},renderer_config:o.renderer_config||{},is_system:o.is_system??!1,is_active:o.is_active??!0,is_container:o.is_container??!1,is_scope:o.is_scope??!1,render_mode:o.render_mode||"none",placement_mode:o.placement_mode,direct_parent_types:o.direct_parent_types,allowed_parent_types:o.allowed_parent_types,governed_create:o.governed_create,create_method:o.create_method,dedup:o.dedup,edges:o.edges,events:o.events})}return s}async function pr(e){try{let t=await R("edges",{item_id:e}),n=t.outgoing||[],r=t.incoming||[],s=[];for(let i of n)s.push({id:i.edge_id||Ji(),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||Ji(),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 hr(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 R("tree",s),a=xn(i);for(let o of a)E().setQueryData(w.item(o.path),o);return a}catch(s){return console.error(`[gateway] Failed to fetch tree at ${e}:`,s),[]}}async function mr(e,t=50,n=0){try{let r=await R("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 Tn(e,t={}){let{limit:n=50,offset:r=0,include_snapshots:s=!1}=t;try{let i=await R("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 gr(e,t=50,n=0){return Tn(e,{limit:t,offset:n})}async function yr(e,t,n){try{let r={scope_id:e};t?.length&&(r.item_types=t),n&&(r.limit=n);let s=await R("member-focus",r),i=xn(s);for(let a of i)E().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 _r(e,t){let n={path:e};t?.mode&&(n.mode=t.mode),t?.strategy&&(n.strategy=t.strategy),t?.arguments&&(n.arguments=t.arguments);let s=await R("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 In(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 R("query",t),s=xn(r);for(let i of s)E().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 _c(e){if(!e||typeof e!="object")return;let t=e;if(t.version!==1||typeof t.work_id!="string"||!t.work_id)return;let n=r=>{let s=t[r];return typeof s=="string"&&s?s:void 0};return{version:1,workId:t.work_id,threadRootId:n("thread_root_id"),requestMessageId:n("request_message_id"),replyMessageId:n("reply_message_id"),replyMessagePath:n("reply_message_path"),todoListId:n("todo_list_id"),todoListPath:n("todo_list_path"),stepId:n("step_id"),stepPath:n("step_path"),runId:n("run_id"),parentRunId:n("parent_run_id"),toolCallId:n("tool_call_id"),traceId:n("trace_id")}}function Yi(e){return e.filter(t=>t.item_type==="card").map(t=>{let n=t.type_data||{},r=n.payload||{};return{id:t.id||"",path:t.path||"",name:t.name||(t.path||"").split("/").pop()||"",createdAt:t.created_at||"",action:n.action||"created",targetId:n.target_id||void 0,targetPath:n.target_path||"",targetDisplayName:n.target_display_name||"",targetDescription:n.target_description||"",targetItemType:n.target_item_type||"",toolId:(t.name||"").startsWith("card-")?(t.name||"").substring(5):void 0,parentMessagePath:t.parent_message_path||void 0,visibility:n.visibility||"private",openWith:r.open_with||void 0,hostBundled:r.host_bundled===!0?!0:void 0,bundleExport:r.bundle_export||void 0,launchArguments:r.launch_arguments||void 0,requiresUserAttention:r.requires_user_attention===!0?!0:void 0,origin:_c(n.origin),presentationRole:r.presentation_role==="user-request"?"user-request":r.presentation_role==="output"?"output":void 0}}).sort((t,n)=>t.createdAt.localeCompare(n.createdAt))}function ys(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,metadata:Object.keys(s).length>0?s:void 0,thread_summary:Array.isArray(n.thread_summary)&&n.thread_summary.length>0?n.thread_summary:void 0}}).sort((t,n)=>t.seq-n.seq)}async function Xi(e,t){try{let n={channel_path:e};t&&(n.parent_message_id=t);let s=await R("get-channel-messages",n),i=s.messages||s.content?.items||s.items||[];return ys(i)}catch(n){return console.error(`[gateway] Failed to fetch channel messages for ${e}:`,n),[]}}async function vr(e,t){try{let n={channel_path:e};t&&(n.parent_message_id=t);let s=await R("get-channel-messages",n),i=s.messages||[],a=ys(i),o=Yi(i),c=new Map,l=[];for(let d of o)if(d.parentMessagePath){let h=c.get(d.parentMessagePath)||[];h.push(d),c.set(d.parentMessagePath,h)}else l.push(d);return{messages:a,messageCards:c,siblingCards:l,mode:s.mode||"top_level"}}catch(n){return console.error(`[gateway] Failed to fetch channel messages with cards for ${e}:`,n),{messages:[],messageCards:new Map,siblingCards:[],mode:"top_level"}}}async function An(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 R("get-channel-messages",n),i=s.messages||[],a=Yi(i),o=new Map,c=[];for(let l of a)if(l.parentMessagePath){let d=o.get(l.parentMessagePath)||[];d.push(l),o.set(l.parentMessagePath,d)}else c.push(l);return{messages:ys(i),messageCards:o,siblingCards:c,mode:s.mode||"top_level"}}catch(n){return console.error(`[gateway] Failed to fetch channel messages page for ${e}:`,n),{messages:[],messageCards:new Map,siblingCards:[],mode:"top_level"}}}function ar(e){E().invalidateQueries({queryKey:w.children(e)})}function _s(e){E().invalidateQueries({queryKey:w.item(e)})}function Zi(e,t){_s(e),ar(e);let n=e.split("/");n.pop();let r=n.join("/")||t;r&&ar(r)}function eo(e){let t=e+"/";E().invalidateQueries({predicate:n=>{let r=n.queryKey;return r[0]!=="vfs"?!1:r.some(s=>typeof s=="string"&&(s===e||s.startsWith(t)))}})}function to(){E().invalidateQueries({queryKey:w.all()})}function no(e){E().invalidateQueries({queryKey:w.types(e)})}function ro(e,t){e?E().invalidateQueries({queryKey:w.channelMessages(e,t)}):E().invalidateQueries({queryKey:w.allChannelMessages()})}function so(e,t){e&&t?E().invalidateQueries({queryKey:w.openEnvelope(e,t)}):e?E().invalidateQueries({predicate:n=>{let r=n.queryKey;return r[0]==="vfs"&&r[2]==="open"&&r[3]===e}}):E().invalidateQueries({queryKey:w.allOpenEnvelopes()})}var vc=typeof window<"u"&&(window.location?.hostname==="localhost"||window.location?.hostname==="127.0.0.1"||window.__FSAOS_WS_DEBUG__);function W(...e){vc&&console.log("[WS]",...e)}var A=null,Ht=null,Wt=null,On=0,bc=3e4,io=1e4,Bt=!1,co=3e4,wc=co*2+5e3,br=0,wr=null,oo=!1;function Sc(){kn(),br=Date.now(),wr=setInterval(()=>{if(A&&A.readyState===WebSocket.OPEN&&Date.now()-br>wc){W("ping: no inbound traffic for",Date.now()-br,"ms \u2014 closing half-open socket");try{A.close(4e3,"liveness timeout")}catch{}return}Ue({type:"ping"})},co)}function kn(){wr&&(clearInterval(wr),wr=null)}function Rc(){typeof document>"u"||(document.hidden?kn():Mn()&&(W("Tab visible, reconnecting..."),Fn()))}function Cc(){oo||typeof document>"u"||(document.addEventListener("visibilitychange",Rc),oo=!0)}var te={},$t=[],Gt=new Map,pt=new Map;function Pc(){return Object.keys(te).some(t=>te[t]&&te[t].length>0)||$t.length>0}function Mn(){return Gt.size>0||pt.size>0}async function Fn(){if(!Mn()){W("ensureConnection: no active subscriptions, skipping");return}if(A&&A.readyState===WebSocket.OPEN){W("ensureConnection: already open");return}if(Ht)return W("ensureConnection: connection already in flight, waiting..."),Ht;if(A){W("ensureConnection: killing stale WS in state",A.readyState);try{A.close()}catch{}A=null}return Bt=!1,Ht=(async()=>{try{let e=typeof window<"u"&&window.__FSAOS_CONFIG__||{},t=ce,n=await xe();if(!n){W("ensureConnection: no token available, will retry"),ao();return}let r=t.startsWith("https")?"wss":"ws",s=t.replace(/^https?:\/\//,""),i=`${r}://${s}/ws`;i+=`?token=${encodeURIComponent(n)}`,W("ensureConnection: opening WS to",i.substring(0,50)+"..."),A=new WebSocket(i),await new Promise((a,o)=>{if(!A)return o(new Error("WebSocket not created"));let c=setTimeout(()=>{if(W("ensureConnection: TIMEOUT after",io,"ms"),A&&A.readyState!==WebSocket.OPEN){try{A.close()}catch{}A=null}o(new Error("WebSocket connection timeout"))},io);A.onopen=()=>{clearTimeout(c),W("ensureConnection: CONNECTED"),On=0,Ec(),(typeof document>"u"||!document.hidden)&&Sc(),Cc(),a()},A.onmessage=l=>{xc(l.data)},A.onerror=()=>{W("ensureConnection: WS error event")},A.onclose=l=>{clearTimeout(c),W("ensureConnection: WS closed, code:",l.code,"reason:",l.reason),A=null,kn(),!Bt&&Mn()&&ao(),o(new Error(`WebSocket closed: ${l.code}`))}})}catch(e){W("ensureConnection: failed -",e?.message||e)}finally{Ht=null}})(),Ht}function ao(){if(Wt||typeof document<"u"&&document.hidden)return;let e=Math.min(1e3*Math.pow(2,On)+Math.random()*1e3,bc);On++,W("scheduleReconnect: attempt",On,"in",Math.round(e),"ms"),Wt=setTimeout(()=>{Wt=null,Mn()&&Fn()},e)}function Ec(){for(let e of Gt.values())W("resubscribeAll: scope",e.scope_id),Ue({type:"subscribe",scope_id:e.scope_id,event_types:e.event_types});for(let e of pt.values())W("resubscribeAll: path",e.path),Ue({type:"subscribe_path",path:e.path,event_types:e.event_types})}function Ue(e){A&&A.readyState===WebSocket.OPEN&&A.send(JSON.stringify(e))}function xc(e){br=Date.now();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&&te[r.path]&&te[r.path].forEach(s=>s(r)),te["*"]&&te["*"].forEach(s=>s(r));for(let s of $t)s.eventType!=="*"&&s.eventType!==n||s.filter&&!s.filter(r)||s.callback(r)}}catch{}}function vs(){!Pc()&&Gt.size===0&&pt.size===0&&A&&(Bt=!0,kn(),A.close(),A=null,Bt=!1)}function Sr(e,t){return te[e]||(te[e]=[]),te[e].push(t),pt.has(e)||(pt.set(e,{path:e,event_types:["token_stream"]}),A&&A.readyState===WebSocket.OPEN&&Ue({type:"subscribe_path",path:e,event_types:["token_stream"]})),Fn(),()=>{let n=te[e];if(n){let r=n.indexOf(t);r!==-1&&n.splice(r,1),n.length===0&&(delete te[e],pt.delete(e),Ue({type:"unsubscribe_path",path:e}))}vs()}}function J(e,t,n){let s=(Array.isArray(e)?e:[e]).map(i=>({eventType:i,callback:t,filter:n}));return $t.push(...s),Mn()&&Fn(),()=>{for(let i of s){let a=$t.indexOf(i);a!==-1&&$t.splice(a,1)}vs()}}function Rr(e,t=["vfs_change","ccm_change"]){return W("subscribeToScope:",e,t),Gt.set(e,{scope_id:e,event_types:t}),A&&A.readyState===WebSocket.OPEN&&Ue({type:"subscribe",scope_id:e,event_types:t}),Fn(),()=>{Gt.delete(e),Ue({type:"unsubscribe",scope_id:e}),vs()}}function uo(e,t,n={}){Ue({type:"emit",scope_id:e,event_type:t,payload:n})}function bs(){W("disconnectSSE: tearing down"),Bt=!0,kn(),A&&(A.close(),A=null),Wt&&(clearTimeout(Wt),Wt=null),Ht=null,Bt=!1,On=0;for(let e of Object.keys(te))delete te[e];$t.length=0,Gt.clear(),pt.clear()}function lo(){Ue({type:"ping"})}Te(bs);var zt=new Map,Cr=null,Pr=null,Ye=new Map,fo=250;function qn(e){Er(),Dn(e),Cr=J("vfs_change",t=>Tc(t)),Pr=J("ccm_change",t=>Ic(t))}function Dn(e){if(zt.has(e))return;let t=Rr(e,["vfs_change","ccm_change"]);zt.set(e,t)}function po(e){let t=zt.get(e);t&&(t(),zt.delete(e))}function Er(){for(let[,e]of zt)e();zt.clear(),Cr&&(Cr(),Cr=null),Pr&&(Pr(),Pr=null),Ye.forEach(e=>clearTimeout(e)),Ye.clear()}Te(Er);function Tc(e){let t=e.path,n=e.action;if(!t)return;let r=t.split("/");r.pop();let s=r.join("/")||"/root",i=Ye.get(s);i&&clearTimeout(i);let a=setTimeout(()=>{Ye.delete(s),Ac(n,t,e,s)},fo);Ye.set(s,a)}function Ic(e){if(!e||typeof e!="object")return;let t=e.source_item_id||e.source_id,n=e.target_item_id||e.target_id;if(!(e.edge_type!=null||t!=null||n!=null))return;let s=`ccm:${t??""}:${n??""}`,i=Ye.get(s);i&&clearTimeout(i);let a=setTimeout(()=>{Ye.delete(s),t&&E().invalidateQueries({queryKey:w.edges(t)}),n&&E().invalidateQueries({queryKey:w.edges(n)}),!t&&!n&&E().invalidateQueries({predicate:o=>o.queryKey[0]==="vfs"&&o.queryKey[1]==="edges"})},fo);Ye.set(s,a)}function Ac(e,t,n,r){if((e||"").toUpperCase()==="DELETE")E().removeQueries({queryKey:w.item(t)}),E().removeQueries({queryKey:w.children(t)}),E().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=me(i);a&&a.id&&E().setQueryData(w.item(t),a)}catch{}E().invalidateQueries({queryKey:w.children(r)}),E().invalidateQueries({predicate:i=>{let a=i.queryKey;if(a[0]!=="vfs"||a[1]!=="tree")return!1;let o=a[2];return t.startsWith(o+"/")||t===o}}),n.item_id&&E().invalidateQueries({queryKey:w.itemById(n.item_id)})}var ws=j(oe(),1),go=j(mo(),1);function yo(e){return R("read",{path:e})}function _o(e,t){return R("list",{path:e,...t})}function vo(e){return R("create",e)}function bo(e){return R("update",e)}function wo(e){return R("create",e)}function So(e,t){let r=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).scopePath||"";return R("tools/call",{name:e,instance_path:r,...t||{}})}function Ro(e,t,n){return R("signal",{target_id:e,event_name:t,payload:n||{}})}function Co(e){return((typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"")+e}var Po={signIn:e=>e.provider?k.auth.signInWithOAuth({provider:e.provider,options:{redirectTo:e.redirectTo||window.location.href}}):k.auth.signInWithPassword({email:e.email,password:e.password}),signUp:e=>k.auth.signUp({email:e.email,password:e.password,options:{data:e.metadata||{}}}),signOut:async()=>{await k.auth.signOut(),bt(),E().clear()},getSession:()=>k.auth.getSession().then(e=>e.data.session),getUser:()=>k.auth.getUser().then(e=>e.data.user),onAuthStateChange:e=>{let{data:{subscription:t}}=k.auth.onAuthStateChange((n,r)=>{e({event:n,session:r,user:r?.user??null})});return()=>t?.unsubscribe()},resetPassword:e=>k.auth.resetPasswordForEmail(e),signInWithMagicLink:(e,t)=>k.auth.signInWithOtp({email:e,options:{emailRedirectTo:t||window.location.href}})};function Eo(){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,go.createRoot)(e).render((0,ws.createElement)(Cn,{client:E()},(0,ws.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 xo(){let e=window.React,t=window.ReactDOM,n=window.__FSAOS_GATEWAY__,r=window.__FSAOS_UI__;if(!n){console.error("[FSAOS] Cannot set up require shim: __FSAOS_GATEWAY__ not found");return}let s={react:e,"react-dom":t,"react-dom/client":t,"react/jsx-runtime":{jsx:e?.createElement,jsxs:e?.createElement,Fragment:e?.Fragment},"@fsaos/kernel":n,"@fsaos/react":n,"@fsaos/gateway":n,"@fsaos/ui":r||{}};window.require=function(a){if(s[a])return s[a];throw new Error("[FSAOS] Module not found: "+a)},window.__FSAOS_MOUNT__=n.mount}var _=j(oe(),1),Mc=j(Io(),1),kc=j(sr(),1);function Oc(e){return`${e}/settings/mounts`}var Un=null;async function Ss(e,t){Un=Oc(e);try{let s=((await R("read",{path:Un}))?.item?.type_data?.mounts??[]).map(t).filter(a=>a!==null),i=Qe();return i&&!s.some(a=>a.id===i.id)&&s.unshift(i),Vr(s),s}catch{let n=Qe(),r=n?[n]:[];return Vr(r),r}}async function Ao(){if(!Un)return;let e=_t().map(n=>n.id),t=Ze()?.id??null;try{await R("update",{path:Un,type_data:{mounts:e,last_anchor:t}})}catch{try{let r=Un.split("/").slice(0,-1).join("/");await R("create",{parent_path:r,name:"mounts",item_type:"file",type_data:{mounts:e,last_anchor:t}})}catch(r){console.warn("[SDK] mount declaration persist failed:",r)}}}async function Rs(e){js(e),await Ao()}async function Oo(e){Vs(e),await Ao()}function K(){return(0,_.useSyncExternalStore)(tt,be,be)}function Fo(){return K(),Bn()}function qo(e){return K(),F({queryKey:w.item(e),queryFn:()=>ur(e),enabled:!!e})}function Do(e){return K(),F({queryKey:w.itemById(e),queryFn:()=>cr(e),enabled:!!e})}function Ps(e){return K(),F({queryKey:w.children(e),queryFn:()=>lr(e),enabled:!!e})}function Uo(e){let t=Ps(e);return{...t,children:t.data??[]}}function No(e,t=1){return K(),F({queryKey:w.tree(e,t),queryFn:()=>hr(e,t),enabled:!!e})}function Qo(e,t){return K(),F({queryKey:w.search(e,t),queryFn:async()=>{let n={query:e};t?.length&&(n.item_types=t);let r=await R("search",n);return(r.content?.items||r.items||r.results||[]).map(me)},enabled:!!e&&e.length>0})}function Ko(e){K();let t=(0,_.useMemo)(()=>e,[JSON.stringify(e)]);return F({queryKey:["vfs",fe()??"__unscoped__","resolve",JSON.stringify(t??{})],queryFn:async()=>await R("resolve",t),enabled:!!t?.query&&t.query.length>0})}function Lo(e){K();let t=(0,_.useMemo)(()=>e,[JSON.stringify(e)]);return F({queryKey:w.items(t?.type??"",t),queryFn:()=>In(t),enabled:!!t?.type,select:n=>n.items})}function jo(e){K();let t=e?.limit??20,n=(0,_.useMemo)(()=>e,[JSON.stringify(e)]),r=En({queryKey:["vfs",fe()??"__unscoped__","infinite-items",n?.type??"",JSON.stringify(n??{})],queryFn:async({pageParam:i=0})=>In({...n,limit:t,offset:i}),initialPageParam:0,getNextPageParam:(i,a,o)=>{if(!(i.items.length<t))return o+i.items.length},enabled:!!n?.type});return{allItems:(0,_.useMemo)(()=>{if(!r.data?.pages)return[];let i=new Set,a=[];for(let o of r.data.pages)for(let c of o.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 Vo(e){K();let t=20,n=En({queryKey:["vfs",fe()??"__unscoped__","infinite-children",e??""],queryFn:async({pageParam:s=0})=>dr(e,t,s),initialPageParam:0,getNextPageParam:(s,i,a)=>{if(!(s.items.length<t))return a+s.items.length},enabled:!!e});return{allItems:(0,_.useMemo)(()=>{if(!n.data?.pages)return[];let s=new Set,i=[];for(let a of n.data.pages)for(let o of a.items)o.id&&!s.has(o.id)&&(s.add(o.id),i.push(o));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 Ho(e){return K(),F({queryKey:w.edges(e),queryFn:()=>pr(e),enabled:!!e})}function xr(e){return K(),F({queryKey:w.types(e),queryFn:()=>fr(e)})}function Wo(e,t){let n=xr(t);return{...n,data:n.data?.get(e)??void 0}}function $o(e,t){K();let n=(0,_.useMemo)(()=>t?.arguments,[JSON.stringify(t?.arguments)]),r=t?.mode,s=t?.strategy,i=t?.width;return F({queryKey:[...w.openEnvelope(e,s),i],queryFn:async()=>{let a=await _r(e,{mode:r,strategy:s,arguments:n});if(i&&a.render?.props?.url){let o=a.render.props.url,c=o.includes("?")?"&":"?";a.render.props.url=`${o}${c}w=${i}`}return a},enabled:!!e})}var Mo={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 Bo(e){let t=xr(e),n=t.data??new Map;return(0,_.useMemo)(()=>({canHaveChildren:p=>n.get(p.item_type)?.is_container??!1,isScope:p=>n.get(p.item_type)?.is_scope??!1,isScopeType:p=>n.get(p)?.is_scope??!1,isContainerType:p=>n.get(p)?.is_container??!1,getTypeDefinition:p=>n.get(p),getTypeColor:p=>n.get(p)?.color??"gray",getTypeIcon:p=>n.get(p)?.icon??"File",getTypeDisplayName:p=>n.get(p)?.display_name??p,getKnownEdgeTypes:()=>Object.entries(Mo).map(([p,y])=>({key:p,label:y})),getEdgeTypeLabel:p=>Mo[p]??p.replace(/_/g," "),allTypes:n,loading:t.isLoading}),[n,t.isLoading])}function Go(e,t,n){return K(),F({queryKey:w.memberFocus(e),queryFn:()=>yr(e,t,n),enabled:!!e})}function zo(e,t={}){let{limit:n=50,offset:r=0,include_snapshots:s=!1}=t;return F({queryKey:w.itemVersions(e,String(n),String(r),String(s)),queryFn:()=>Tn(e,{limit:n,offset:r,include_snapshots:s}),enabled:!!e})}function Jo(e,t=50,n=0){return F({queryKey:w.itemHistory(e,String(t),String(n)),queryFn:()=>gr(e,t,n),enabled:!!e})}function Yo(e,t=50,n=0){return K(),F({queryKey:w.recentActivity(e,String(t),String(n)),queryFn:()=>mr(e,t,n),enabled:!!e})}function Xo(){let[e,t]=(0,_.useState)(null),[n,r]=(0,_.useState)(!0),[s,i]=(0,_.useState)(null);return(0,_.useEffect)(()=>{let a=!1;return vt().then(o=>{if(!a){let c=typeof window<"u"&&window.__FSAOS_CONFIG__||{};t({path:o.scope_path,scope_id:o.scope_id,fractal_id:o.fractal_id,instance_name:o.instance_name,display_name:o.display_name,componentPath:c.componentPath||"",isEmbed:!!c.embedToken}),r(!1)}}).catch(o=>{a||(i(o instanceof Error?o:new Error(String(o))),r(!1))}),()=>{a=!0}},[]),{data:e,loading:n,error:s}}var Fc=[];function Nn(e){return{id:e.accountId,path:e.path,kind:e.isSpace?"space":"account",name:e.name,grantedUnderAccountId:e.grantedUnderAccountId??void 0}}function Zo(){let{user:e}=Tr(),t=(0,_.useRef)(!1),n=F({queryKey:w.memberships(e?.id??"anonymous"),queryFn:async()=>((await R("list-memberships",{})).memberships||[]).map(f=>({accountId:f.account_id,path:f.account_path,name:f.account_name,role:f.role||"member",typeData:f.account_type_data||{},joinedAt:f.joined_at,via:f.via,placement:f.placement,subordinateTo:f.subordinate_to??null,cascadeAnchorId:f.cascade_anchor_id??null,isAccount:f.is_account??void 0,isSpace:f.is_space??void 0,isOwner:f.is_owner??void 0,billingResponsible:f.billing_responsible??void 0,grantedVia:f.granted_via??null,grantedUnderAccountId:f.granted_under_account_id??null,personalSpaceId:f.personal_space_id??null,personalSpacePath:f.personal_space_path??null})),enabled:!!e?.id,staleTime:1e3*60*2}),r=n.data??Fc,s=(0,_.useMemo)(()=>r.filter(d=>d.isAccount!==!1&&!d.isSpace),[r]),i=(0,_.useMemo)(()=>{let d=new Set(s.map(f=>f.accountId)),h=f=>!f.subordinateTo||!d.has(f.subordinateTo);return[...s].sort((f,p)=>Number(h(p))-Number(h(f)))},[s]),a=(0,_.useSyncExternalStore)(tt,be,be),o=(0,_.useMemo)(()=>{let d=Ze();return d?r.find(h=>h.accountId===d.id)??null:null},[a,r]);(0,_.useEffect)(()=>{if(!e?.id){t.current=!1;return}if(!t.current)if(i.length===1){let d=i[0];cn(Nn(d)),qn(d.accountId),d.personalSpacePath&&Ss(d.personalSpacePath,h=>{let f=r.find(p=>p.accountId===h);return f?Nn(f):null}).catch(()=>{}),t.current=!0}else i.length>1&&(t.current=!0)},[e?.id,i,r]);let c=(0,_.useCallback)(d=>{let h=r.find(p=>p.path===d);if(!h)return;let f=Nn(h);Qe()?Ne(f):(cn(f),h.personalSpacePath&&Ss(h.personalSpacePath,p=>{let y=r.find(m=>m.accountId===p);return y?Nn(y):null}).catch(()=>{})),qn(h.accountId)},[r]),l=(0,_.useCallback)(d=>{let h=r.find(f=>f.path===d);h&&(Rs(Nn(h)).catch(()=>{}),Dn(d))},[r]);return{accounts:i,allMemberships:r,currentAccount:o,mountedScope:null,switchAccount:c,mountScope:l,loading:n.isLoading,error:n.error}}function ea(){let e=(0,_.useSyncExternalStore)(Wn,ln,ln);return{mounts:(0,_.useMemo)(()=>_t(),[e]),homeAnchor:Qe(),anchor:Ze(),setAnchor:Ne,mount:Rs,unmount:Oo}}function Tr(){let[e,t]=(0,_.useState)(null),[n,r]=(0,_.useState)(null),[s,i]=(0,_.useState)(!0),a=(0,_.useRef)(null);(0,_.useEffect)(()=>{k.auth.getSession().then(({data:p,error:y})=>{if(y){console.warn("[useAuth] getSession error, clearing stale session:",y.message),k.auth.signOut().catch(()=>{}),r(null),t(null),i(!1);return}r(p?.session??null),t(p?.session?.user??null),i(!1)}).catch(p=>{console.warn("[useAuth] getSession threw, clearing stale session:",p?.message),k.auth.signOut().catch(()=>{}),r(null),t(null),i(!1)});let{data:{subscription:f}}=k.auth.onAuthStateChange((p,y)=>{if(p==="TOKEN_REFRESHED"&&!y){console.warn("[useAuth] TOKEN_REFRESHED with null session \u2014 signing out"),k.auth.signOut().catch(()=>{}),r(null),t(null),i(!1);return}r(y),t(y?.user??null),i(!1)});return a.current=f,()=>{f?.unsubscribe()}},[]);let o=(0,_.useCallback)(async f=>f.provider?k.auth.signInWithOAuth({provider:f.provider,options:f.redirectTo?{redirectTo:f.redirectTo}:{redirectTo:window.location.href}}):k.auth.signInWithPassword({email:f.email,password:f.password}),[]),c=(0,_.useCallback)(async f=>k.auth.signUp({email:f.email,password:f.password,options:{data:f.metadata||{}}}),[]),l=(0,_.useCallback)(async()=>{await k.auth.signOut(),bt(),E().clear()},[]),d=(0,_.useCallback)(async f=>{let{error:p}=await k.auth.resetPasswordForEmail(f);if(p)throw p},[]),h=(0,_.useCallback)(async(f,p)=>{let{error:y}=await k.auth.signInWithOtp({email:f,options:p?{emailRedirectTo:p}:{emailRedirectTo:window.location.href}});if(y)throw y},[]);return{user:e,session:n,loading:s,signIn:o,signUp:c,signOut:l,resetPassword:d,signInWithMagicLink:h}}function ta(e){let[t,n]=(0,_.useState)(null),[r,s]=(0,_.useState)(!1),[i,a]=(0,_.useState)(null);return(0,_.useEffect)(()=>{if(!e){n(null),s(!1);return}if(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e))s(!0),R("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 Qn={},ko={};Te(()=>{for(let e of Object.keys(Qn))delete Qn[e]});var na=null;function ra(e){na=e,typeof window<"u"&&!window.__FSAOS_GATEWAY__&&(window.__FSAOS_GATEWAY__=e)}function qc(e){switch(e){case"react":return typeof window<"u"&&window.React||_.default;case"react-dom":case"react-dom/client":return typeof window<"u"&&window.ReactDOM||Mc;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}:kc;case"@fsaos/gateway":case"@fsaos/react":return typeof window<"u"&&window.__FSAOS_GATEWAY__||na||{};case"@fsaos/ui":return typeof window<"u"&&window.__FSAOS_UI__||{};case"@fsaos/theme":return{};default:return console.warn(`[useComponent] Unknown module requested: ${e}`),{}}}function Dc(e,t){return e.replace(/^(\s*)(:root|body)(\s*[{,])/gm,(n,r,s,i)=>`${r}.${t}${i}`)}async function Uc(e,t){if(!ko[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=Dc(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),ko[e]=s}catch{}}function Nc(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)(qc),a=t??i;return a?a.default||a:null}finally{n!==void 0?window.__FSAOS_REGISTER__=n:delete window.__FSAOS_REGISTER__}}function Es(e){let[t,n]=(0,_.useState)(null),[r,s]=(0,_.useState)(!0),[i,a]=(0,_.useState)(null);return(0,_.useEffect)(()=>{if(!e)return;let o=!1;s(!0),a(null);let l=(typeof window<"u"&&window.__FSAOS_CONFIG__||{}).edgeBaseUrl||"";return(async()=>{try{let d=1,h=e+"@v1",f=l+e+"/__bundle.js";try{let S=await fetch(l+e+"/__meta",{cache:"no-store"});S.ok&&(d=(await S.json()).version||1,h=e+"@v"+d,f=l+e+"/__bundle.v"+d+".js")}catch{f=l+e+"/__bundle.js?v="+Date.now()}if(o)return;if(Qn[h]){n(()=>Qn[h]),s(!1);return}let p=await fetch(f);if(!p.ok)throw new Error(`Failed to fetch bundle: ${p.status} ${p.statusText} (${f})`);let y=await p.text();if(o)return;let m=f.replace(/__bundle(\.v\d+)?\.js(\?.*)?$/,"__bundle$1.css");Uc(m).catch(()=>{});let g=Nc(y);if(!g)throw new Error("Bundle did not export a component. Expected window.__FSAOS_COMPONENT__ (FSAOS build) or a __FSAOS_REGISTER__(Component) call.");if(typeof g!="function")throw new Error(`Bundle export is not a React component (got ${typeof g})`);Qn[h]=g,o||(n(()=>g),s(!1))}catch(d){o||(a(d instanceof Error?d:new Error(String(d))),s(!1))}})(),()=>{o=!0}},[e]),{Component:t,loading:r,error:i}}var Qc=["--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 sa(){return{data:(0,_.useMemo)(()=>{if(typeof document>"u")return{tokens:{}};let t={},n=getComputedStyle(document.documentElement);return Qc.forEach(r=>{t[r]=n.getPropertyValue(r).trim()}),{tokens:t}},[]),loading:!1,error:null}}function ia(e,t){return{data:{allowed:!0},loading:!1,error:null}}function oa(e,t){let n={};return(t||[]).forEach(r=>{n[r]=!0}),{data:n,loading:!1,error:null}}var ae=null,Jt=null,Cs=new Set;function Kc(){Cs.forEach(e=>e())}Te(()=>{ae=null,Jt=null});async function aa(e){let t=e;if(!t){let{data:r}=await k.auth.getSession();t=r?.session?.user?.id}let n={principalId:null,displayName:null,createdAt:null,metadata:null,vfsPath:null};if(!t)return n;if(ae&&ae.authUserId===t){let{principalId:r,displayName:s,createdAt:i,metadata:a,vfsPath:o}=ae;return{principalId:r,displayName:s,createdAt:i,metadata:a,vfsPath:o}}return Jt||(Jt=(async()=>{try{let{data:r,error:s}=await k.from("os_principals").select("id, display_name, created_at, metadata").eq("auth_user_id",t).eq("principal_type","user").maybeSingle();if(s)return console.warn("[SDK] Could not resolve principal:",s.message),n;let i=r?.id??null,a=null;if(i){let{data:c}=await k.from("os_items").select("path").eq("owner_principal_id",i).eq("item_type","principal").eq("is_active",!0).like("path","/root/principals/%"),l=(c??[]).map(d=>d.path);a=l.find(d=>d.split("/").length===4)??l[0]??null}let o={principalId:i,displayName:r?.display_name??null,createdAt:r?.created_at??null,metadata:r?.metadata??null,vfsPath:a};return ae={authUserId:t,...o},o}finally{Jt=null}})(),Jt)}async function ca(e){return(await aa(e)).principalId}function ua(){let e=Tr(),t=e.user,n=ae?.authUserId===t?.id?ae:null,[r,s]=(0,_.useState)(n),i=(0,_.useRef)(null);return(0,_.useEffect)(()=>{let a=()=>{let o=ae;o&&o.authUserId===t?.id&&s({principalId:o.principalId,displayName:o.displayName,createdAt:o.createdAt,metadata:o.metadata,vfsPath:o.vfsPath})};return Cs.add(a),()=>{Cs.delete(a)}},[t?.id]),(0,_.useEffect)(()=>{if(!t?.id){s(null),i.current=null;return}i.current===t.id&&r?.principalId!=null||(i.current=t.id,aa(t.id).then(a=>{s(a)}))},[t?.id]),e.loading?{data:null,loading:!0,error:null}:t?{data:{id:t.id,principalId:r?.principalId??null,email:t.email,display_name:r?.displayName??void 0,created_at:r?.createdAt??void 0,vfs_path:r?.vfsPath??void 0,role:t.role||t.app_metadata?.role||"user",authenticated:!0,metadata:r?.metadata??t.user_metadata??{}},loading:!1,error:null}:{data:{id:"anonymous",principalId:null,role:"viewer",authenticated:!1},loading:!1,error:null}}function la(){return{data:null,loading:!1,error:null}}function da(e){let{path:t,...n}=e,r=Es(t),s=r.Component,{loading:i,error:a}=r;return i?(0,_.createElement)("div",{className:"fsaos-loading"},""):a?(0,_.createElement)("div",{className:"fsaos-error"},"Failed to load component"):s?(0,_.createElement)(s,n):null}function fa(e){return e.children}function pa(e){let t=K(),{channelPath:n,parentMessageId:r,realtime:s=!0,enabled:i}=e,a=i!==void 0?i&&!!n:!!n,o=(0,_.useMemo)(()=>w.channelMessages(n??"",r),[n,r,t]),c=N(),l=(0,_.useRef)(null),d=F({queryKey:o,queryFn:()=>vr(n,r),enabled:a});(0,_.useEffect)(()=>{if(!s||!a)return;let m=J("vfs_change",()=>{l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{c.invalidateQueries({queryKey:o})},500)},g=>(g.item_type==="message"||g.item_type==="card")&&typeof g.path=="string"&&g.path.startsWith(n));return()=>{m(),l.current&&clearTimeout(l.current)}},[s,a,n,o,c]);let h=d.data,f=h?.messages??[],p=h?.messageCards??new Map,y=h?.siblingCards??[];return{messages:f,messageCards:p,siblingCards:y,threads:(0,_.useMemo)(()=>f.filter(m=>m.reply_count>0),[f]),isLoading:d.isLoading,isFetching:d.isFetching,error:d.error,refetch:d.refetch}}function ha(e){K();let{channelPath:t,parentMessageId:n,limit:r=50,realtime:s=!0,enabled:i=!0}=e,a=!!n,o=i&&!!t,c=En({queryKey:[...w.channelMessages(t||"",n),"infinite",r],queryFn:async({pageParam:m})=>An(t,{parentMessageId:n,limit:r,before_seq:a?void 0:m,after_seq:a?m:void 0}),initialPageParam:void 0,getNextPageParam:m=>!a||m.messages.length<r?void 0:m.messages[m.messages.length-1]?.seq,getPreviousPageParam:m=>a||m.messages.length<r?void 0:m.messages[0]?.seq,enabled:o}),l=(0,_.useMemo)(()=>{if(!c.data?.pages)return[];let m=new Set,g=[];for(let S of c.data.pages)for(let C of S.messages)m.has(C.id)||(m.add(C.id),g.push(C));return g.sort((S,C)=>S.seq-C.seq)},[c.data?.pages]),{messageCards:d,siblingCards:h}=(0,_.useMemo)(()=>{let m=new Map,g=[];if(!c.data?.pages)return{messageCards:m,siblingCards:g};let S=new Set;for(let C of c.data.pages){for(let[x,U]of C.messageCards)for(let L of U){if(S.has(L.id))continue;S.add(L.id);let $=m.get(x)||[];$.push(L),m.set(x,$)}for(let x of C.siblingCards)S.has(x.id)||(S.add(x.id),g.push(x))}return{messageCards:m,siblingCards:g}},[c.data?.pages]),f=N(),p=(0,_.useRef)(null),y=(0,_.useMemo)(()=>[...w.channelMessages(t||"",n),"infinite",r],[t,n,r]);return(0,_.useEffect)(()=>{if(!s||!t||!o)return;let m=J("vfs_change",()=>{p.current&&clearTimeout(p.current),p.current=setTimeout(async()=>{let g=f.getQueryData(y);if(!g?.pages?.length){f.invalidateQueries({queryKey:y});return}let S=0;for(let C of g.pages)for(let x of C.messages)x.seq>S&&(S=x.seq);if(S===0){f.invalidateQueries({queryKey:y});return}try{let C=await An(t,{parentMessageId:n,limit:r,after_seq:S});if(C.messages.length===0&&C.siblingCards.length===0){f.invalidateQueries({queryKey:y});return}if(C.messages.length>0){let x=Math.min(...C.messages.map(U=>U.seq));if(x>S+1){console.warn(`[useInfiniteChannelMessages] sequence gap detected: maxSeq=${S}, minNewSeq=${x}. Triggering full refetch.`),f.invalidateQueries({queryKey:y});return}}f.setQueryData(y,x=>{if(!x)return x;let U=[...x.pages],L=U.length-1,$=U[L],ht=new Set($.messages.map(I=>I.id)),re=C.messages.filter(I=>!ht.has(I.id)),Q=[...$.messages,...re].sort((I,Xe)=>I.seq-Xe.seq),Y=new Map($.messageCards);for(let[I,Xe]of C.messageCards){let B=Y.get(I)||[],Yt=new Set(B.map(Mr=>Mr.id)),Qa=Xe.filter(Mr=>!Yt.has(Mr.id));Y.set(I,[...B,...Qa])}let ye=new Set($.siblingCards.map(I=>I.id)),_e=C.siblingCards.filter(I=>!ye.has(I.id)),ve=[...$.siblingCards,..._e];return U[L]={...$,messages:Q,messageCards:Y,siblingCards:ve},{...x,pages:U}})}catch(C){console.warn("[useInfiniteChannelMessages] live tail fetch failed, falling back to full invalidation:",C),f.invalidateQueries({queryKey:y})}},500)},g=>(g.item_type==="message"||g.item_type==="card")&&typeof g.path=="string"&&g.path.startsWith(t));return()=>{m(),p.current&&clearTimeout(p.current)}},[s,t,o,y,f,n,r]),{messages:l,messageCards:d,siblingCards:h,threads:l.filter(m=>m.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 Lc(e){return e==="on"||e==="auto"?"on":"off"}function jc(e){let t=e.type_data||{},n=e._reader||{},r=n.context_lineage||{};return{id:e.id||"",path:e.path||"",name:e.name||"",displayName:t.display_name||e.name||"",aiMode:Lc(t.ai_mode),isPrivate:t.is_private||!1,isDm:t.is_dm||!1,messageCount:t.message_count||0,updatedAt:e.updated_at||"",chatScopePath:r.context_path||"",contextId:e.scope_item_id||"",contextPath:r.context_path||"",contextType:r.context_type||"",contextName:r.context_name||"",contextDisplayName:r.context_name||"",contextPrincipalId:void 0,accountId:e.account_item_id||"",accountPath:"",accountDisplayName:"",memberRole:n.member_role||"member",memberPath:"",modePath:"",autoPilot:t.auto_pilot||!1}}function Ir(e={}){let t=K(),{realtime:n=!0,enabled:r=!0}=e,s=N(),i=(0,_.useRef)(null),a=(0,_.useMemo)(()=>w.channels("all"),[t]),o=F({queryKey:a,queryFn:async()=>((await R("query",{item_type:"channel",include_reader:!0,limit:500})).items||[]).map(jc),enabled:r});return(0,_.useEffect)(()=>{if(!n||!r)return;let l=J("vfs_change",()=>{i.current&&clearTimeout(i.current),i.current=setTimeout(()=>{s.invalidateQueries({queryKey:a})},1e3)},h=>h.item_type==="channel"||h.item_type==="message"),d=J("ccm_change",()=>{i.current&&clearTimeout(i.current),i.current=setTimeout(()=>{s.invalidateQueries({queryKey:a})},1e3)},h=>h.item_type==="channel"||h.item_type==="message");return()=>{l(),d(),i.current&&clearTimeout(i.current)}},[n,r,a,s]),{channels:o.data??[],isLoading:o.isLoading,isFetching:o.isFetching,error:o.error,refetch:o.refetch}}function ma(e={}){let t=Ir(e),n=(0,_.useMemo)(()=>t.channels.filter(r=>!r.isDm),[t.channels]);return{...t,channels:n}}function ga(e={}){let t=Ir(e),n=(0,_.useMemo)(()=>t.channels.filter(r=>r.isDm),[t.channels]);return{...t,channels:n}}function xs(e={}){let t=K(),{filter:n="all",limit:r=200,realtime:s=!0,enabled:i=!0}=e,a=N(),o=(0,_.useRef)(null),c=(0,_.useMemo)(()=>w.notifications(n,r),[n,r,t]),l=F({queryKey:c,queryFn:async()=>{let h={limit:r};return n==="unread"&&(h.filter="unread"),(await R("get-notifications",h)).notifications||[]},enabled:i});return(0,_.useEffect)(()=>{if(!s||!i)return;let h=["vfs_change","ccm_change"].map(f=>J(f,()=>{o.current&&clearTimeout(o.current),o.current=setTimeout(()=>{a.invalidateQueries({queryKey:c})},2e3)},p=>p.item_type==="notification"||p.item_type==="message"));return()=>{h.forEach(f=>f()),o.current&&clearTimeout(o.current)}},[s,i,c,a]),{notifications:l.data??[],isLoading:l.isLoading,isFetching:l.isFetching,error:l.error,refetch:l.refetch}}function ya(e={}){let{channels:t,realtime:n=!0,enabled:r=!0}=e,{notifications:s,isLoading:i,isFetching:a,error:o,refetch:c}=xs({filter:"unread",limit:200,realtime:n,enabled:r}),l=(0,_.useMemo)(()=>{let p=new Map;for(let y of s)y.is_unread&&y.channel_id&&p.set(y.channel_id,(p.get(y.channel_id)||0)+1);return p},[s]),d=(0,_.useMemo)(()=>{let p=0;return l.forEach(y=>{p+=y}),p},[l]),{dmUnread:h,channelUnread:f}=(0,_.useMemo)(()=>{if(!t)return{dmUnread:0,channelUnread:0};let p=new Set(t.filter(g=>g.isDm).map(g=>g.id)),y=0,m=0;return l.forEach((g,S)=>{p.has(S)?y+=g:m+=g}),{dmUnread:y,channelUnread:m}},[t,l]);return{unreadByChannel:l,totalUnread:d,dmUnread:h,channelUnread:f,isLoading:i,isFetching:a,error:o,refetch:c}}function _a(){let e=N();return De({mutationFn:t=>R("create",t),onSuccess:(t,n)=>{let r=n.parent_path;r&&e.invalidateQueries({queryKey:w.children(r)})}})}function va(){let e=N();return De({mutationFn:t=>R("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 ba(){return De({mutationFn:e=>R("update-principal",e),onSuccess:(e,t)=>{if(!ae)return;let n=e&&typeof e=="object"&&e.metadata?e.metadata:{...ae.metadata??{},...typeof t.language=="string"?{language:t.language}:{},...typeof t.timezone=="string"?{timezone:t.timezone}:{},..."avatar_file_id"in t?{avatar_file_id:t.avatar_file_id}:{}};ae={...ae,displayName:typeof t.display_name=="string"?t.display_name:ae.displayName,metadata:n},Kc()}})}function wa(){let e=N();return De({mutationFn:t=>R("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 Sa(){let e=N();return De({mutationFn:t=>R("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 Ra(){let e=N();return De({mutationFn:t=>R("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 Ca(e,t){let n=N(),{optimistic:r,...s}=t??{};return De({mutationFn:i=>R(e,i),onMutate:r?async i=>{await n.cancelQueries({queryKey:r.queryKey});let a=n.getQueryData(r.queryKey);return n.setQueryData(r.queryKey,o=>r.update(o,i)),{previous:a}}:void 0,onError:(i,a,o)=>{r&&o?.previous!==void 0&&n.setQueryData(r.queryKey,o.previous),s.onError?.(i)},onSuccess:s.onSuccess,onSettled:r?()=>{n.invalidateQueries({queryKey:r.queryKey})}:void 0})}function Pa(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 o=(0,_.useRef)(s),c=(0,_.useRef)(i);(0,_.useEffect)(()=>{o.current=s,c.current=i},[s,i]),(0,_.useEffect)(()=>a?J(r,d=>o.current(d),c.current?d=>c.current(d):void 0):void 0,[r,a])}function Ea(e){let{queryKey:t,queryFn:n,eventType:r,filter:s,enabled:i=!0,debounceMs:a=500}=e,o=N(),c=(0,_.useRef)(null),l=F({queryKey:t,queryFn:n,enabled:i});return(0,_.useEffect)(()=>{if(!i)return;let d=J(r,()=>{c.current&&clearTimeout(c.current),c.current=setTimeout(()=>{o.invalidateQueries({queryKey:t})},a)},s);return()=>{d(),c.current&&clearTimeout(c.current)}},[r,i,a,o,JSON.stringify(t)]),l}function xa(e){K();let t=(0,_.useMemo)(()=>e?typeof e=="string"?{path:e}:e:null,[typeof e=="string"?e:JSON.stringify(e)]),n=!!t&&!!(t.key||t.path||t.item_id),r=t?.key??t?.path??t?.item_id??"",s=F({queryKey:["vfs",fe()??"__unscoped__","arrangement",r],queryFn:async()=>{if(!t)return null;let d=await R("resolve-arrangement",t);return d?.success===!1?(console.warn("[useArrangement] resolve-arrangement failed:",d?.error),null):d??null},enabled:n}),i=s.data??null,a=(0,_.useMemo)(()=>i?.resolved_children??[],[i]),o=i?.resolution_level??null,c=(0,_.useMemo)(()=>{let h=(i?.type_data??null)?.order;return Array.isArray(h)?h:null},[i]),l=(0,_.useCallback)(d=>{if(!c||!d?.length)return d??[];let h=m=>m.id??m.name??"",f=new Map(c.map((m,g)=>[m,g])),p=[],y=[];for(let m of d)(f.has(h(m))?p:y).push(m);return p.sort((m,g)=>f.get(h(m))-f.get(h(g))),[...p,...y]},[c]);return{...s,arrangement:i,resolvedChildren:a,resolutionLevel:o,order:c,sourceScopeId:i?.scope_item_id??null,applyTo:l}}function Vc(e){return e.split("_").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function Hc(e,t){return t&&t.length>0?"select":e==="boolean"?"toggle":e==="integer"||e==="number"?"range":e==="string"?"text":"none"}function Wc(e,t){return!(e==="object"||e==="array")}function $c(e){return["string","number","integer","boolean"].includes(e)}function Bc(e){return e!=="object"&&e!=="array"}function Ta(e,t,n,r){let s=e?.properties;if(!s||typeof s!="object")return[];let i=[];for(let[a,o]of Object.entries(s)){let c=o.type||"string",l=o.enum,d=Wc(c,l),h=$c(c),f=Hc(c,l);i.push({key:a,label:o.title||Vc(a),type:c,description:o.description,enum_values:l,default_value:n[a]??r[a]??o.default,editable:t,filterable:d,sortable:h,filter_widget:f})}return i}function Ts(e){let t=e.default_data||{},n=e.field_defaults||{},r=Ta(e.input_schema,!0,t,n),s=Ta(e.system_schema,!1,t,n),i=[...r,...s],a=i.filter(l=>Bc(l.type)),o=i.filter(l=>l.filterable),c=i.filter(l=>l.sortable);return{fields:i,columns:a,filterable:o,sortable:c,form_fields:r,system_fields:s}}function Ia(e){return{field:"updated_at",direction:"desc"}}function Aa(e){let t=Ts(e),n=new Set(e.input_schema?.required||[]);return t.form_fields.filter(r=>n.has(r.key)||r.default_value===void 0)}var ne=j(oe(),1);var Gc=0;function zc(){return`upload_${Date.now()}_${++Gc}`}async function Oa(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",o={parent_path:t.parentPath,item_type:a,name:s,type_data:{...t.typeData||{},file_source:{type:"upload",content_type:i}}};t.cardParentPath&&(o.card_parent_path=t.cardParentPath);let l=await R("create",o);if(!l.id)throw new Error(l.error||l.message||"Failed to create file item");let d=l.id,h=l.path;if(l.storage_completed&&l.file_ref)return{itemId:d,itemPath:h,fileRef:l.file_ref};let f=l.storage_key,p=l.upload_token,y=l.storage_worker_url||"https://fsaos-storage.radns.workers.dev";if(!f)throw new Error("Gateway returned no storage_key \u2014 file_source may not be supported for this item type");await Jc(y,f,p,e,i,n,r);let m=await Ma(d,f,i);return{itemId:d,itemPath:h,fileRef:m}}function Jc(e,t,n,r,s,i,a){return new Promise((o,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=d=>{d.lengthComputable&&i&&i(Math.round(d.loaded/d.total*100))},l.onload=()=>{l.status>=200&&l.status<300?o():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 Ma(e,t,n){let r=await xe(),s=await fetch(`${ce}/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 ka(){let[e,t]=(0,ne.useState)([]),n=N(),r=(0,ne.useRef)(e);r.current=e;let s=(0,ne.useCallback)((m,g)=>{t(S=>S.map(C=>C.id===m?{...C,...g}:C))},[]),i=(0,ne.useCallback)(m=>{t(g=>[...g,m])},[]),a=(0,ne.useCallback)(async(m,g,S,C,x)=>{let U=S.name||g.name,L=g.type||"application/octet-stream",$=S.itemType||"file",ht=x?.itemId||null,re=x?.itemPath||null,Q=x?.storageKey||null,Y=x?.uploadToken||null,ye=x?.storageWorkerUrl||null;try{if(!C||C==="create"){s(m,{status:"creating",error:null,_failedAt:null});let I=await R("create",{parent_path:S.parentPath,item_type:$,name:U,type_data:{...S.typeData||{},file_source:{type:"upload",content_type:L}}});if(!I.id)throw Object.assign(new Error(I.error||I.message||"Failed to create file item"),{_step:"create"});if(ht=I.id,re=I.path,s(m,{itemId:ht,itemPath:re}),I.storage_completed&&I.file_ref){s(m,{status:"complete",progress:100,fileRef:I.file_ref}),n.invalidateQueries({queryKey:w.children(S.parentPath)});return}if(Q=I.storage_key,Y=I.upload_token||"",ye=I.storage_worker_url||"https://fsaos-storage.radns.workers.dev",s(m,{_storageKey:Q,_uploadToken:Y,_storageWorkerUrl:ye}),!Q)throw Object.assign(new Error("Gateway returned no storage_key"),{_step:"create"})}(!C||C==="create"||C==="upload")&&(s(m,{status:"uploading",progress:0,error:null,_failedAt:null}),await new Promise((I,Xe)=>{let B=new XMLHttpRequest;s(m,{_xhr:B}),B.open("PUT",`${ye}/upload`),B.setRequestHeader("X-Storage-Key",Q),B.setRequestHeader("Content-Type",L),Y&&B.setRequestHeader("X-Upload-Token",Y),B.upload.onprogress=Yt=>{Yt.lengthComputable&&s(m,{progress:Math.round(Yt.loaded/Yt.total*100)})},B.onload=()=>{B.status>=200&&B.status<300?I():Xe(Object.assign(new Error(`Storage upload failed: HTTP ${B.status}`),{_step:"upload"}))},B.onerror=()=>Xe(Object.assign(new Error("Storage upload network error"),{_step:"upload"})),B.ontimeout=()=>Xe(Object.assign(new Error("Storage upload timed out"),{_step:"upload"})),B.send(g)}),s(m,{progress:100,_xhr:null})),s(m,{status:"confirming",error:null,_failedAt:null});let _e=await Ma(ht,Q,L);s(m,{status:"complete",fileRef:_e}),n.invalidateQueries({queryKey:w.children(S.parentPath)})}catch(_e){let ve=_e?.message||String(_e),I=_e?._step||"create";s(m,{status:"error",error:ve,_failedAt:I,_xhr:null})}},[s,n]),o=(0,ne.useCallback)((m,g)=>{let S=zc();i({id:S,file:m,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(S,m,g)},[i,a]),c=(0,ne.useCallback)((m,g)=>{for(let S of m)o(S,g)},[o]),l=(0,ne.useCallback)(m=>{let g=r.current.find(x=>x.id===m);if(!g||g.status!=="error")return;let S=g._failedAt||"create",C=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(m,g.file,g.options,S,C)},[a]),d=(0,ne.useCallback)(m=>{let g=r.current.find(S=>S.id===m);g&&(g._xhr&&g._xhr.abort(),s(m,{status:"error",error:"Cancelled",_xhr:null,_failedAt:null}))},[s]),h=(0,ne.useCallback)(m=>{t(g=>g.filter(S=>S.id!==m))},[]),f=(0,ne.useCallback)(()=>{t(m=>m.filter(g=>g.status!=="complete"))},[]),p=e.some(m=>m.status==="creating"||m.status==="uploading"||m.status==="confirming"),y=e.map(({_storageKey:m,_uploadToken:g,_storageWorkerUrl:S,_xhr:C,_failedAt:x,...U})=>U);return{upload:o,uploadMultiple:c,uploads:y,retryUpload:l,cancelUpload:d,removeUpload:h,clearCompleted:f,isUploading:p}}var Fa=j(oe(),1);async function Is(e,t){return await R("resolve-items",{context_id:e,item_type:t})}function qa(e,t){return(0,Fa.useSyncExternalStore)(tt,be,be),F({queryKey:["vfs",fe()??"__unscoped__","resolved-items",e??"",t],queryFn:()=>Is(e,t),enabled:!!(e&&t)})}var ge=j(oe(),1);function Ar(e,t){let n={artifacts:new Map,timeline:[]},r=new Map;function s(a){if(!a.action?.startsWith("artifact_"))return;let c,l=a.name;if(typeof l=="string"&&l.startsWith("{"))try{c=JSON.parse(l)}catch{return}else if(a.artifact_id)c=a;else return;switch(c.type){case"artifact_opened":{let d=Date.now();if(n.artifacts.set(c.artifact_id,{artifact_id:c.artifact_id,surface_type:c.surface_type,tool_id:c.tool_id,tool_name:c.tool_name,target_uri:c.target_uri,status:"streaming",content:"",total_chars:0,delta_count:0,artifact_item_uri:null,evidence_uri:null,meta:c.meta,started_at:d,completed_at:null}),r.has(c.tool_id)){let h=r.get(c.tool_id);n.timeline[h].artifact_ids.push(c.artifact_id)}else{let h=n.timeline.length;n.timeline.push({tool_id:c.tool_id,tool_name:c.tool_name,status:"started",target_uri:c.target_uri,started_at:d,completed_at:null,artifact_ids:[c.artifact_id]}),r.set(c.tool_id,h)}break}case"artifact_delta":{let d=n.artifacts.get(c.artifact_id);d&&(d.content+=c.content_delta,d.total_chars+=c.content_delta.length,d.delta_count+=1,c.target_uri&&!d.target_uri&&(d.target_uri=c.target_uri));break}case"artifact_done":{let d=n.artifacts.get(c.artifact_id);d&&(d.status=c.status,d.total_chars=c.total_chars,d.artifact_item_uri=c.artifact_item_uri,d.evidence_uri=c.evidence_uri,c.target_uri&&(d.target_uri=c.target_uri),(c.status==="completed"||c.status==="failed")&&(d.completed_at=Date.now()));let h=r.get(c.tool_id);if(h!==void 0){let f=n.timeline[h];c.status==="executing"?f.status="executing":c.status==="completed"?(f.status="completed",f.completed_at=Date.now()):c.status==="failed"&&(f.status="failed",f.completed_at=Date.now()),c.target_uri&&!f.target_uri&&(f.target_uri=c.target_uri)}break}}t(n)}return Sr(e,s)}function Da(e,t=!0){let[n,r]=(0,ge.useState)(new Map),[s,i]=(0,ge.useState)([]),a=(0,ge.useRef)({artifacts:new Map,timeline:[]});(0,ge.useEffect)(()=>!e||!t?void 0:Ar(e,h=>{a.current=h,r(new Map(h.artifacts)),i([...h.timeline])}),[e,t]);let o=(0,ge.useCallback)(()=>{r(new Map),i([]),a.current={artifacts:new Map,timeline:[]}},[]),c=Array.from(n.values()).find(d=>d.surface_type==="file_editor"&&d.status==="streaming")??null,l=Array.from(n.values()).filter(d=>d.surface_type==="activity"&&(d.status==="streaming"||d.status==="executing"));return{artifacts:n,timeline:s,activeEditor:c,activeActivities:l,reset:o}}function Ua(e,t=!0){let[n,r]=(0,ge.useState)([]);(0,ge.useEffect)(()=>!e||!t?void 0:Ar(e,a=>{r([...a.timeline])}),[e,t]);let s=n.length>0?n[n.length-1]:null;return{timeline:n,latestActivity:s}}var Or=j(oe(),1);function Yc(e,t,n,r){return["vfs","timeline-history",e,t??"__all__",n??500,r??0]}async function As(e,t){let n=`${e}/datasets/agent-events`,r=t?.limit??500,s=t?.offset??0,i={limit:r,offset:s,sort:[{key:"seq",direction:"asc"}]};t?.turnId&&(i.filters=[{key:"turn_id",operator:"eq",value:t.turnId}]);try{let o=(await R("open",{path:n,mode:"extract",strategy:"rows",arguments:i}))?.content;return o?(o.rows??o.items??o.data??[]).map(Xc).sort((l,d)=>l.seq-d.seq):[]}catch(a){if(a?.status===404||a?.message?.includes("not found"))return[];throw a}}function Na(e,t){let{turnId:n,limit:r=500,offset:s=0,enabled:i=!0,debounceMs:a=300}=t??{},o=e?`${e}/datasets/agent-events`:null,c=N(),l=(0,Or.useRef)(null),d=o?Yc(o,n,r,s):["vfs","timeline-history","__disabled__"],h=F({queryKey:d,queryFn:()=>As(e,{turnId:n,limit:r,offset:s}),enabled:!!e&&i});return(0,Or.useEffect)(()=>{if(!o||!i)return;let f=J("vfs_change",()=>{l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{c.invalidateQueries({queryKey:d})},a)},p=>{let y=p?.path;return y?y===o||y.startsWith(o+"/"):!1});return()=>{f(),l.current&&clearTimeout(l.current)}},[o,i,a,c,JSON.stringify(d)]),{events:h.data??[],isLoading:h.isLoading,error:h.error,isFetching:h.isFetching,refetch:()=>{h.refetch()}}}function Xc(e){return{turn_id:String(e.turn_id??""),seq:Number(e.seq??0),kind:String(e.kind??""),status:String(e.status??""),title:String(e.title??""),tool_name:e.tool_name!=null?String(e.tool_name):void 0,tool_id:e.tool_id!=null?String(e.tool_id):void 0,evidence_uri:e.evidence_uri!=null?String(e.evidence_uri):void 0,artifact_item_uri:e.artifact_item_uri!=null?String(e.artifact_item_uri):void 0,preview:e.preview!=null?String(e.preview):void 0,duration_ms:e.duration_ms!=null?Number(e.duration_ms):void 0,started_at:String(e.started_at??""),completed_at:e.completed_at!=null?String(e.completed_at):void 0,error_type:e.error_type!=null?String(e.error_type):void 0,meta:e.meta!=null?e.meta:void 0}}ra(Os);return Ba(Os);})();
4
4
 
5
5
  /* ── Auto-setup: require shim + mount + backward compat globals ── */
6
6
  (function() {