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