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