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